From 08e0888431a4e1929c30f44d9083279ced8ca175 Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Mon, 24 Aug 2026 08:23:24 +0100 Subject: [PATCH] refactor: migrate repository documentation from Markdown to AsciiDoc --- .migration/PYTHON_TO_RUST_RESCRIPT.adoc | 29 + .migration/PYTHON_TO_RUST_RESCRIPT.md | 28 - ARCHITECTURE-v2.md => ARCHITECTURE-v2.adoc | 403 +++--- ARCHITECTURE.md => ARCHITECTURE.adoc | 399 +++--- CHANGELOG.adoc | 348 +++-- CHANGELOG.md | 203 --- CODE_OF_CONDUCT.adoc | 221 +++ CODE_OF_CONDUCT.md | 206 --- CONTRIBUTING.adoc | 3 + CONTRIBUTING.md | 7 - GOVERNANCE.adoc | 485 +------ GOVERNANCE.md | 60 - MAINTAINERS.adoc | 234 ++- MAINTAINERS.md | 205 --- MANUAL_REVIEW_NEEDED.adoc | 20 + MANUAL_REVIEW_NEEDED.md | 21 - REVERSIBILITY.md => REVERSIBILITY.adoc | 336 +++-- RSR_COMPLIANCE.adoc | 255 ++++ RSR_COMPLIANCE.md | 314 ---- SECURITY.adoc | 178 +++ SECURITY.md | 191 --- TEST-NEEDS.adoc | 30 + TEST-NEEDS.md | 31 - TOPOLOGY.md => TOPOLOGY.adoc | 42 +- .../{DEPLOYMENT.md => DEPLOYMENT.adoc} | 488 ++++--- docs/hardware/SETUP.adoc | 319 +++++ docs/hardware/SETUP.md | 311 ---- docs/tech-debt-2026-05-26.adoc | 67 + docs/tech-debt-2026-05-26.md | 54 - docs/user-guide/USER_MANUAL.adoc | 304 ++++ docs/user-guide/USER_MANUAL.md | 309 ---- docs/white-paper/KALDOR_WHITE_PAPER.adoc | 1232 ++++++++++++++++ docs/white-paper/KALDOR_WHITE_PAPER.md | 1257 ----------------- firmware/README.adoc | 316 +++++ firmware/README.md | 283 ---- llm-warmup-dev.adoc | 19 + llm-warmup-dev.md | 20 - llm-warmup-user.adoc | 19 + llm-warmup-user.md | 20 - 39 files changed, 4327 insertions(+), 4940 deletions(-) create mode 100644 .migration/PYTHON_TO_RUST_RESCRIPT.adoc delete mode 100644 .migration/PYTHON_TO_RUST_RESCRIPT.md rename ARCHITECTURE-v2.md => ARCHITECTURE-v2.adoc (65%) rename ARCHITECTURE.md => ARCHITECTURE.adoc (67%) delete mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.adoc delete mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.adoc delete mode 100644 CONTRIBUTING.md delete mode 100644 GOVERNANCE.md delete mode 100644 MAINTAINERS.md create mode 100644 MANUAL_REVIEW_NEEDED.adoc delete mode 100644 MANUAL_REVIEW_NEEDED.md rename REVERSIBILITY.md => REVERSIBILITY.adoc (51%) create mode 100644 RSR_COMPLIANCE.adoc delete mode 100644 RSR_COMPLIANCE.md create mode 100644 SECURITY.adoc delete mode 100644 SECURITY.md create mode 100644 TEST-NEEDS.adoc delete mode 100644 TEST-NEEDS.md rename TOPOLOGY.md => TOPOLOGY.adoc (88%) rename docs/developer/{DEPLOYMENT.md => DEPLOYMENT.adoc} (55%) create mode 100644 docs/hardware/SETUP.adoc delete mode 100644 docs/hardware/SETUP.md create mode 100644 docs/tech-debt-2026-05-26.adoc delete mode 100644 docs/tech-debt-2026-05-26.md create mode 100644 docs/user-guide/USER_MANUAL.adoc delete mode 100644 docs/user-guide/USER_MANUAL.md create mode 100644 docs/white-paper/KALDOR_WHITE_PAPER.adoc delete mode 100644 docs/white-paper/KALDOR_WHITE_PAPER.md create mode 100644 firmware/README.adoc delete mode 100644 firmware/README.md create mode 100644 llm-warmup-dev.adoc delete mode 100644 llm-warmup-dev.md create mode 100644 llm-warmup-user.adoc delete mode 100644 llm-warmup-user.md diff --git a/.migration/PYTHON_TO_RUST_RESCRIPT.adoc b/.migration/PYTHON_TO_RUST_RESCRIPT.adoc new file mode 100644 index 0000000..a9f3ee2 --- /dev/null +++ b/.migration/PYTHON_TO_RUST_RESCRIPT.adoc @@ -0,0 +1,29 @@ +== Python → Rust/AffineScript Migration Guide + +=== Policy + +This repo contains Python code that should be migrated to: - *Rust* for +systems/ML/backend code - *ReScript* for web/frontend/scripting + +=== Why + +* Python has dynamic typing and runtime errors +* Rust provides memory safety and performance +* ReScript provides type safety and JS interop + +=== Migration Steps + +[arabic] +. Identify Python files by purpose (systems vs web) +. Create equivalent Rust modules in `+src/+` or ReScript in +`+src/*.res+` +. Use `+cargo+` or `+rescript+` build systems +. Remove Python files after migration +. Update CI/CD + +=== Exceptions + +* SaltStack configurations (exempt) +* One-time scripts (convert to shell/Rust) + +=== Status: PENDING MIGRATION diff --git a/.migration/PYTHON_TO_RUST_RESCRIPT.md b/.migration/PYTHON_TO_RUST_RESCRIPT.md deleted file mode 100644 index e172cd9..0000000 --- a/.migration/PYTHON_TO_RUST_RESCRIPT.md +++ /dev/null @@ -1,28 +0,0 @@ - -# Python → Rust/AffineScript Migration Guide - -## Policy -This repo contains Python code that should be migrated to: -- **Rust** for systems/ML/backend code -- **ReScript** for web/frontend/scripting - -## Why -- Python has dynamic typing and runtime errors -- Rust provides memory safety and performance -- ReScript provides type safety and JS interop - -## Migration Steps -1. Identify Python files by purpose (systems vs web) -2. Create equivalent Rust modules in `src/` or ReScript in `src/*.res` -3. Use `cargo` or `rescript` build systems -4. Remove Python files after migration -5. Update CI/CD - -## Exceptions -- SaltStack configurations (exempt) -- One-time scripts (convert to shell/Rust) - -## Status: PENDING MIGRATION diff --git a/ARCHITECTURE-v2.md b/ARCHITECTURE-v2.adoc similarity index 65% rename from ARCHITECTURE-v2.md rename to ARCHITECTURE-v2.adoc index 2b76e26..ca1b921 100644 --- a/ARCHITECTURE-v2.md +++ b/ARCHITECTURE-v2.adoc @@ -1,18 +1,18 @@ - -# Kaldor Community Manufacturing Platform - System Architecture v2.0 +== Kaldor Community Manufacturing Platform - System Architecture v2.0 -**Hyperlocal, Community-Owned Textile Manufacturing Ecosystem** +*Hyperlocal, Community-Owned Textile Manufacturing Ecosystem* -## Vision +=== Vision -Transform spare rooms into a distributed, community-governed manufacturing network for sustainable, local textile production (spinning, weaving, 3D printing) based on Kaldor's Law 2: "The rate of growth in productivity is positively related to the rate of growth of manufacturing output." +Transform spare rooms into a distributed, community-governed +manufacturing network for sustainable, local textile production +(spinning, weaving, 3D printing) based on Kaldor’s Law 2: "`The rate of +growth in productivity is positively related to the rate of growth of +manufacturing output.`" -## System Architecture +=== System Architecture -``` +.... ┌─────────────────────────────────────────────────────────────────────────┐ │ COMMUNITY GOVERNANCE LAYER │ │ │ @@ -79,88 +79,90 @@ Transform spare rooms into a distributed, community-governed manufacturing netwo │ │ • WASM Runtime │ │ • WASM Runtime │ │ • WASM Runtime │ │ │ └────────────────────┘ └────────────────────┘ └──────────────────┘ │ └─────────────────────────────────────────────────────────────────────────┘ -``` - -## Technology Stack - -### Backend Runtime -- **Deno 1.40+** - Secure TypeScript runtime -- **Fresh Framework** - Edge-first web framework -- **Oak** - Middleware framework for HTTP -- **DenoKV** - Built-in key-value store -- **Supabase Deno Client** - PostgreSQL with Deno - -### Frontend -- **ReScript 11+** - Type-safe, functional language compiling to JavaScript -- **ReScript React** - Type-safe React bindings -- **RescriptRelay** - GraphQL client -- **TailwindCSS** - Utility-first CSS - -### WASM Acceleration -- **Rust → WASM** - Performance-critical modules - - Textile pattern generation - - Production scheduling algorithms - - Real-time machine learning for quality control - - Consensus protocol implementation (CURP) -- **AssemblyScript** - TypeScript → WASM for web workers - -### Database -- **TimescaleDB** - Time-series (unchanged, works with Deno) -- **PostgreSQL 15+** - Primary database -- **DenoKV** - Local caching and state -- **Supabase** - Database hosting + real-time subscriptions - -### Edge Devices (RISC-V First) -- **ESP32-C6** - RISC-V + WiFi 6 + Thread/Zigbee -- **ESP32-C3** - RISC-V + WiFi 4 (budget option) -- **SiFive HiFive1** - RISC-V development board -- **Kendryte K210** - RISC-V with AI acceleration -- **WCH CH32V** - Low-cost RISC-V alternative - -### Firmware -- **ESP-IDF** - Official Espressif framework (RISC-V support) -- **Zephyr RTOS** - Open-source RTOS with RISC-V support -- **WASM3** - WebAssembly runtime for embedded devices -- **Matter SDK** - Official Matter protocol implementation - -### Industrial Protocols -- **OPC UA** - Unified Architecture for industrial automation -- **Modbus TCP/RTU** - Legacy SCADA integration -- **Matter** - Smart home/industrial IoT standard -- **Thread** - IPv6-based mesh networking -- **Zigbee** - Low-power mesh (via Matter bridge) - -### Consensus & Governance -- **CURP** - Consistent Unordered Replication Protocol -- **Raft** - Consensus algorithm (fallback) -- **Quadratic Voting** - Community decision weighting -- **Time-locked contracts** - Scheduled governance actions - -## Hyperlocal Manufacturing Topology - -### Space Requirements Per Node - -**Micro Node (1 spare room ~3m x 3m)** -- 1x Spinning station (1.5m²) -- 1x Small loom OR 1x 3D printer (1.5m²) -- Storage: 2m² -- Operator space: 3m² +.... + +=== Technology Stack + +==== Backend Runtime + +* *Deno 1.40+* - Secure TypeScript runtime +* *Fresh Framework* - Edge-first web framework +* *Oak* - Middleware framework for HTTP +* *DenoKV* - Built-in key-value store +* *Supabase Deno Client* - PostgreSQL with Deno + +==== Frontend + +* *ReScript 11+* - Type-safe, functional language compiling to +JavaScript +* *ReScript React* - Type-safe React bindings +* *RescriptRelay* - GraphQL client +* *TailwindCSS* - Utility-first CSS + +==== WASM Acceleration + +* *Rust → WASM* - Performance-critical modules +** Textile pattern generation +** Production scheduling algorithms +** Real-time machine learning for quality control +** Consensus protocol implementation (CURP) +* *AssemblyScript* - TypeScript → WASM for web workers + +==== Database + +* *TimescaleDB* - Time-series (unchanged, works with Deno) +* *PostgreSQL 15+* - Primary database +* *DenoKV* - Local caching and state +* *Supabase* - Database hosting + real-time subscriptions + +==== Edge Devices (RISC-V First) + +* *ESP32-C6* - RISC-V + WiFi 6 + Thread/Zigbee +* *ESP32-C3* - RISC-V + WiFi 4 (budget option) +* *SiFive HiFive1* - RISC-V development board +* *Kendryte K210* - RISC-V with AI acceleration +* *WCH CH32V* - Low-cost RISC-V alternative + +==== Firmware + +* *ESP-IDF* - Official Espressif framework (RISC-V support) +* *Zephyr RTOS* - Open-source RTOS with RISC-V support +* *WASM3* - WebAssembly runtime for embedded devices +* *Matter SDK* - Official Matter protocol implementation + +==== Industrial Protocols + +* *OPC UA* - Unified Architecture for industrial automation +* *Modbus TCP/RTU* - Legacy SCADA integration +* *Matter* - Smart home/industrial IoT standard +* *Thread* - IPv6-based mesh networking +* *Zigbee* - Low-power mesh (via Matter bridge) + +==== Consensus & Governance + +* *CURP* - Consistent Unordered Replication Protocol +* *Raft* - Consensus algorithm (fallback) +* *Quadratic Voting* - Community decision weighting +* *Time-locked contracts* - Scheduled governance actions + +=== Hyperlocal Manufacturing Topology + +==== Space Requirements Per Node + +*Micro Node (1 spare room ~3m x 3m)* - 1x Spinning station (1.5m²) - 1x +Small loom OR 1x 3D printer (1.5m²) - Storage: 2m² - Operator space: 3m² - Total: ~8m² (one spare bedroom) -**Small Node (2 spare rooms)** -- Full spin + weave + print capability -- Distributed across 2 rooms or 1 larger space -- Can operate independently +*Small Node (2 spare rooms)* - Full spin + weave + print capability - +Distributed across 2 rooms or 1 larger space - Can operate independently -**Community Hub (3+ spare rooms or small commercial)** -- Multiple machines of each type -- Training center -- Material storage -- Finishing/distribution center +*Community Hub (3+ spare rooms or small commercial)* - Multiple machines +of each type - Training center - Material storage - +Finishing/distribution center -### Network Topology +==== Network Topology -``` +.... ┌─────────────────────────────────────────────────┐ │ Community Manufacturing Network │ │ │ @@ -178,23 +180,24 @@ Transform spare rooms into a distributed, community-governed manufacturing netwo │ │ Distribution) │ │ │ └──────────────────┘ │ └─────────────────────────────────────────────────┘ -``` +.... -## File Type Schema for Instructables +=== File Type Schema for Instructables -### Production Files (.kaldor format family) +==== Production Files (.kaldor format family) -``` +.... .ksp - Kaldor Spin Pattern .kwp - Kaldor Weave Pattern .k3p - Kaldor 3D Print Pattern .kjob - Kaldor Job Specification (multi-stage) .kmat - Kaldor Material Specification -``` +.... Each file is a JSON/TOML hybrid with embedded metadata: -```toml +[source,toml] +---- # Example: sample-shirt.kjob [metadata] name = "Community Linen Shirt" @@ -234,31 +237,30 @@ material_cost = 12.50 # GBP labor_hours = 10 suggested_price = 65.00 community_share = 0.15 # 15% to commons fund -``` +---- -### Interoperability Standards +==== Interoperability Standards -All `.kaldor` files are: -1. **Human-readable** (TOML/JSON) -2. **Version controlled** (Git-friendly) -3. **Forkable** (Creative Commons licensed) -4. **Composable** (stages can be mixed/matched) -5. **Economically transparent** (costs/pricing included) +All `+.kaldor+` files are: 1. *Human-readable* (TOML/JSON) 2. *Version +controlled* (Git-friendly) 3. *Forkable* (Creative Commons licensed) 4. +*Composable* (stages can be mixed/matched) 5. *Economically transparent* +(costs/pricing included) -## Matter Protocol Integration +=== Matter Protocol Integration -### Why Matter? +==== Why Matter? -1. **Open Standard** - Industry-backed, royalty-free -2. **Secure** - Built-in encryption, authentication -3. **IPv6 Native** - Modern networking -4. **Multi-admin** - Community governance friendly -5. **Thread/WiFi Bridge** - Flexible topology -6. **RISC-V Support** - ESP32-C6 has native Matter support +[arabic] +. *Open Standard* - Industry-backed, royalty-free +. *Secure* - Built-in encryption, authentication +. *IPv6 Native* - Modern networking +. *Multi-admin* - Community governance friendly +. *Thread/WiFi Bridge* - Flexible topology +. *RISC-V Support* - ESP32-C6 has native Matter support -### Matter Device Types for Manufacturing +==== Matter Device Types for Manufacturing -``` +.... Matter Cluster Kaldor Application ───────────────── ────────────────── On/Off Machine power control @@ -267,22 +269,21 @@ Temperature Ambient monitoring Flow Measurement Material throughput Occupancy Sensing Operator presence Power Source Battery/mains status -``` +.... -### Custom Matter Clusters +==== Custom Matter Clusters -We'll define custom clusters for: -- **Textile Production** (cluster ID: 0xKALD0001) -- **Community Governance** (cluster ID: 0xKALD0002) -- **Job Scheduling** (cluster ID: 0xKALD0003) +We’ll define custom clusters for: - *Textile Production* (cluster ID: +0xKALD0001) - *Community Governance* (cluster ID: 0xKALD0002) - *Job +Scheduling* (cluster ID: 0xKALD0003) -## SCADA/DCS Interoperability +=== SCADA/DCS Interoperability -### OPC UA Integration +==== OPC UA Integration Kaldor nodes expose OPC UA server: -``` +.... Server: opc.tcp://node-001.local:4840 Namespace: http://kaldor.community/manufacturing/ @@ -311,13 +312,13 @@ Objects/ ├── ActiveMembers ├── PendingVotes └── CommonsFund -``` +.... -### Modbus RTU/TCP Support +==== Modbus RTU/TCP Support For legacy equipment integration: -``` +.... Holding Registers (Function Code 03) ───────────────────────────────────── Address Description Units @@ -330,41 +331,42 @@ Address Description Units 15 Error Code Enum 20-29 Community metrics 30-39 Job queue status -``` +.... -## RISC-V Architecture Support +=== RISC-V Architecture Support -### Why RISC-V? +==== Why RISC-V? -1. **Open Source** - No licensing fees, fully auditable -2. **Customizable** - Add custom instructions for textile operations -3. **Security** - PMP (Physical Memory Protection), formal verification -4. **Emerging Ecosystem** - ESP32-C6, StarFive, SiFive -5. **Educational** - Universities can teach on actual hardware -6. **Future-proof** - Not controlled by single vendor +[arabic] +. *Open Source* - No licensing fees, fully auditable +. *Customizable* - Add custom instructions for textile operations +. *Security* - PMP (Physical Memory Protection), formal verification +. *Emerging Ecosystem* - ESP32-C6, StarFive, SiFive +. *Educational* - Universities can teach on actual hardware +. *Future-proof* - Not controlled by single vendor -### Supported RISC-V Boards +==== Supported RISC-V Boards -| Board | ISA | Clock | RAM | WiFi | Matter | Cost | -|-------|-----|-------|-----|------|--------|------| -| ESP32-C6 | RV32IMAC | 160MHz | 512KB | WiFi 6 | ✅ | £5 | -| ESP32-C3 | RV32IMC | 160MHz | 400KB | WiFi 4 | ⚠️ | £3 | -| SiFive HiFive1 | RV32IMAC | 320MHz | 16KB | ❌ | ❌ | £60 | -| Kendryte K210 | RV64GC (dual) | 400MHz | 8MB | ❌ | ❌ | £15 | +[cols=",,,,,,",options="header",] +|=== +|Board |ISA |Clock |RAM |WiFi |Matter |Cost +|ESP32-C6 |RV32IMAC |160MHz |512KB |WiFi 6 |✅ |£5 +|ESP32-C3 |RV32IMC |160MHz |400KB |WiFi 4 |⚠️ |£3 +|SiFive HiFive1 |RV32IMAC |320MHz |16KB |❌ |❌ |£60 +|Kendryte K210 |RV64GC (dual) |400MHz |8MB |❌ |❌ |£15 +|=== -**Recommended**: ESP32-C6 (best balance of features, cost, Matter support) +*Recommended*: ESP32-C6 (best balance of features, cost, Matter support) -### WASM on RISC-V +==== WASM on RISC-V -We use **WASM3** interpreter: -- ~65KB code size -- Runs on 64KB+ RAM -- Near-native performance for compute -- Portable across RISC-V variants +We use *WASM3* interpreter: - ~65KB code size - Runs on 64KB+ RAM - +Near-native performance for compute - Portable across RISC-V variants Example: Pattern generation in Rust→WASM running on ESP32-C6: -```rust +[source,rust] +---- // Compiled to WASM, runs on RISC-V #[no_mangle] pub extern "C" fn generate_weave_pattern( @@ -376,56 +378,57 @@ pub extern "C" fn generate_weave_pattern( // Runs 10x faster than interpreted Python // ... } -``` - -## Kaldor's Law Integration - -### Kaldor's Second Law (Verdoorn's Law) - -> "The rate of growth in productivity is positively related to the rate of growth of manufacturing output." - -**Application to Hyperlocal Manufacturing:** - -1. **Increasing Returns to Scale** - - As community adds more nodes, overhead decreases - - Shared knowledge base improves productivity - - Specialized nodes emerge (expert spinners, weavers) - -2. **Learning-by-Doing** - - Platform tracks productivity metrics - - Identifies bottlenecks automatically - - Suggests process improvements via ML - -3. **Measurement Integration** - ```sql - -- Kaldor's Law Dashboard Query - SELECT - time_bucket('1 month', produced_at) as month, - SUM(output_units) as total_output, - SUM(output_units) / SUM(labor_hours) as productivity, - LAG(SUM(output_units) / SUM(labor_hours)) OVER (ORDER BY time_bucket('1 month', produced_at)) as prev_productivity, - ((SUM(output_units) / SUM(labor_hours)) - LAG(SUM(output_units) / SUM(labor_hours)) OVER (ORDER BY time_bucket('1 month', produced_at))) / - LAG(SUM(output_units) / SUM(labor_hours)) OVER (ORDER BY time_bucket('1 month', produced_at)) as productivity_growth - FROM production_records - GROUP BY month - ``` - -4. **Feedback Loop** - - Increased output → More data → Better ML models → Higher productivity → Increased output - -## Next Steps - -See implementation in: -- `backend-deno/` - Deno backend rewrite -- `frontend-rescript/` - ReScript frontend -- `wasm-modules/` - Rust WASM acceleration -- `firmware-riscv/` - RISC-V firmware for ESP32-C6 -- `docs/white-paper/` - Business case and economic analysis -- `docs/wiki/` - Comprehensive community documentation -- `docs/3d-weave-spec/` - 3D weaving technology specification - ---- - -**Version**: 2.0.0 -**License**: MPL-2.0 (software) + CC-BY-SA-4.0 (documentation) -**Last Updated**: 2025-11-22 +---- + +=== Kaldor’s Law Integration + +==== Kaldor’s Second Law (Verdoorn’s Law) + +____ +"`The rate of growth in productivity is positively related to the rate +of growth of manufacturing output.`" +____ + +*Application to Hyperlocal Manufacturing:* + +[arabic] +. *Increasing Returns to Scale* +* As community adds more nodes, overhead decreases +* Shared knowledge base improves productivity +* Specialized nodes emerge (expert spinners, weavers) +. *Learning-by-Doing* +* Platform tracks productivity metrics +* Identifies bottlenecks automatically +* Suggests process improvements via ML +. *Measurement Integration* ++ +[source,sql] +---- +-- Kaldor's Law Dashboard Query +SELECT + time_bucket('1 month', produced_at) as month, + SUM(output_units) as total_output, + SUM(output_units) / SUM(labor_hours) as productivity, + LAG(SUM(output_units) / SUM(labor_hours)) OVER (ORDER BY time_bucket('1 month', produced_at)) as prev_productivity, + ((SUM(output_units) / SUM(labor_hours)) - LAG(SUM(output_units) / SUM(labor_hours)) OVER (ORDER BY time_bucket('1 month', produced_at))) / + LAG(SUM(output_units) / SUM(labor_hours)) OVER (ORDER BY time_bucket('1 month', produced_at)) as productivity_growth +FROM production_records +GROUP BY month +---- +. *Feedback Loop* +* Increased output → More data → Better ML models → Higher productivity +→ Increased output + +=== Next Steps + +See implementation in: - `+backend-deno/+` - Deno backend rewrite - +`+frontend-rescript/+` - ReScript frontend - `+wasm-modules/+` - Rust +WASM acceleration - `+firmware-riscv/+` - RISC-V firmware for ESP32-C6 - +`+docs/white-paper/+` - Business case and economic analysis - +`+docs/wiki/+` - Comprehensive community documentation - +`+docs/3d-weave-spec/+` - 3D weaving technology specification + +''''' + +*Version*: 2.0.0 *License*: MPL-2.0 (software) + CC-BY-SA-4.0 +(documentation) *Last Updated*: 2025-11-22 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.adoc similarity index 67% rename from ARCHITECTURE.md rename to ARCHITECTURE.adoc index 0661bb8..032f7eb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.adoc @@ -1,16 +1,14 @@ - -# Kaldor IIoT System Architecture +== Kaldor IIoT System Architecture -## Overview +=== Overview -The Kaldor IIoT system provides real-time monitoring and analytics for loom Back Beam Width (BBW) measurements, enabling predictive maintenance and quality control. +The Kaldor IIoT system provides real-time monitoring and analytics for +loom Back Beam Width (BBW) measurements, enabling predictive maintenance +and quality control. -## System Components +=== System Components -``` +.... ┌─────────────────────────────────────────────────────────────────┐ │ OPERATOR INTERFACE │ │ │ @@ -83,184 +81,209 @@ The Kaldor IIoT system provides real-time monitoring and analytics for loom Back │ │ └─────────────┘ └──────────────┘ └────────────────┘ │ │ │ └────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ +.... -``` - -## Technology Stack - -### Edge Layer (Firmware) -- **Platform**: ESP32 (dual-core, WiFi/Bluetooth) -- **Framework**: Arduino/ESP-IDF -- **Protocol**: MQTT over TLS -- **Sampling Rate**: 100Hz for sensors, 1Hz for telemetry -- **Storage**: Local buffering on flash (failover) - -### Backend Services -- **API Server**: Node.js (Express.js) -- **Real-time**: WebSocket (Socket.io) -- **Analytics**: Python (NumPy, SciPy, Pandas) -- **Message Broker**: Eclipse Mosquitto (MQTT) -- **Task Queue**: Bull (Redis-based) - -### Data Storage -- **Time-Series**: TimescaleDB (PostgreSQL extension) -- **Relational**: PostgreSQL 15+ -- **Cache**: Redis 7+ -- **Retention**: - - Raw data: 7 days - - Aggregated 1-min: 90 days - - Aggregated 1-hour: 2 years - -### Frontend -- **Framework**: React 18 + TypeScript -- **State Management**: Redux Toolkit -- **Real-time**: Socket.io-client -- **Visualization**: Recharts, D3.js -- **UI Components**: Material-UI - -### Infrastructure -- **Containerization**: Docker + Docker Compose -- **Reverse Proxy**: Nginx -- **SSL/TLS**: Let's Encrypt (Certbot) -- **Monitoring**: Prometheus + Grafana -- **Logging**: ELK Stack (Elasticsearch, Logstash, Kibana) - -## Data Flow - -### 1. Data Acquisition -``` +=== Technology Stack + +==== Edge Layer (Firmware) + +* *Platform*: ESP32 (dual-core, WiFi/Bluetooth) +* *Framework*: Arduino/ESP-IDF +* *Protocol*: MQTT over TLS +* *Sampling Rate*: 100Hz for sensors, 1Hz for telemetry +* *Storage*: Local buffering on flash (failover) + +==== Backend Services + +* *API Server*: Node.js (Express.js) +* *Real-time*: WebSocket (Socket.io) +* *Analytics*: Python (NumPy, SciPy, Pandas) +* *Message Broker*: Eclipse Mosquitto (MQTT) +* *Task Queue*: Bull (Redis-based) + +==== Data Storage + +* *Time-Series*: TimescaleDB (PostgreSQL extension) +* *Relational*: PostgreSQL 15+ +* *Cache*: Redis 7+ +* *Retention*: +** Raw data: 7 days +** Aggregated 1-min: 90 days +** Aggregated 1-hour: 2 years + +==== Frontend + +* *Framework*: React 18 + TypeScript +* *State Management*: Redux Toolkit +* *Real-time*: Socket.io-client +* *Visualization*: Recharts, D3.js +* *UI Components*: Material-UI + +==== Infrastructure + +* *Containerization*: Docker + Docker Compose +* *Reverse Proxy*: Nginx +* *SSL/TLS*: Let’s Encrypt (Certbot) +* *Monitoring*: Prometheus + Grafana +* *Logging*: ELK Stack (Elasticsearch, Logstash, Kibana) + +=== Data Flow + +==== 1. Data Acquisition + +.... Sensors → ESP32 ADC → Signal Processing → MQTT Publish -``` +.... -### 2. Data Ingestion -``` +==== 2. Data Ingestion + +.... MQTT → Message Broker → Data Processor → TimescaleDB → Alert Engine → Notification Service → WebSocket → Dashboard (Real-time) -``` +.... + +==== 3. Data Analytics -### 3. Data Analytics -``` +.... TimescaleDB → Analytics Engine → Statistical Analysis → Anomaly Detection → Predictive Maintenance -``` +.... + +==== 4. User Access -### 4. User Access -``` +.... User → Web Dashboard → REST API → Database → WebSocket → Live Updates -``` - -## Security Architecture - -### Network Security -- TLS 1.3 for all communications -- VPN access for remote monitoring -- Network segmentation (IoT VLAN) -- Firewall rules (allow-list only) - -### Authentication & Authorization -- JWT-based authentication -- Role-based access control (RBAC) -- API key authentication for devices -- Session management with Redis - -### Data Security -- Encryption at rest (AES-256) -- Encryption in transit (TLS) -- Secure credential storage (HashiCorp Vault) -- Audit logging for all access - -## Scalability - -### Horizontal Scaling -- Stateless API servers (load balanced) -- MQTT broker clustering -- Database read replicas -- Redis cluster for caching - -### Performance Targets -- API Response: < 100ms (p95) -- Real-time Latency: < 500ms (sensor to dashboard) -- Concurrent Users: 100+ -- Devices Supported: 1000+ looms -- Data Points: 100M+ per day - -## High Availability - -### Redundancy -- Multi-zone deployment -- Database replication (primary + 2 replicas) -- MQTT broker cluster (3+ nodes) -- Load balancer with health checks - -### Disaster Recovery -- Automated backups (hourly incremental, daily full) -- Point-in-time recovery (PITR) -- Backup retention: 30 days -- RTO: 1 hour, RPO: 15 minutes - -## Monitoring & Observability - -### Metrics -- System metrics (CPU, memory, disk, network) -- Application metrics (request rate, latency, errors) -- Business metrics (active devices, data quality, alerts) -- Custom dashboards in Grafana - -### Alerting -- Infrastructure alerts (Prometheus Alertmanager) -- Application alerts (custom rules) -- Business alerts (SLA violations) -- Multi-channel notifications (email, SMS, Slack) - -### Logging -- Structured logging (JSON format) -- Centralized log aggregation (ELK) -- Log retention: 90 days -- Full-text search capability - -## Development & Deployment - -### CI/CD Pipeline -``` +.... + +=== Security Architecture + +==== Network Security + +* TLS 1.3 for all communications +* VPN access for remote monitoring +* Network segmentation (IoT VLAN) +* Firewall rules (allow-list only) + +==== Authentication & Authorization + +* JWT-based authentication +* Role-based access control (RBAC) +* API key authentication for devices +* Session management with Redis + +==== Data Security + +* Encryption at rest (AES-256) +* Encryption in transit (TLS) +* Secure credential storage (HashiCorp Vault) +* Audit logging for all access + +=== Scalability + +==== Horizontal Scaling + +* Stateless API servers (load balanced) +* MQTT broker clustering +* Database read replicas +* Redis cluster for caching + +==== Performance Targets + +* API Response: < 100ms (p95) +* Real-time Latency: < 500ms (sensor to dashboard) +* Concurrent Users: 100+ +* Devices Supported: 1000+ looms +* Data Points: 100M+ per day + +=== High Availability + +==== Redundancy + +* Multi-zone deployment +* Database replication (primary + 2 replicas) +* MQTT broker cluster (3+ nodes) +* Load balancer with health checks + +==== Disaster Recovery + +* Automated backups (hourly incremental, daily full) +* Point-in-time recovery (PITR) +* Backup retention: 30 days +* RTO: 1 hour, RPO: 15 minutes + +=== Monitoring & Observability + +==== Metrics + +* System metrics (CPU, memory, disk, network) +* Application metrics (request rate, latency, errors) +* Business metrics (active devices, data quality, alerts) +* Custom dashboards in Grafana + +==== Alerting + +* Infrastructure alerts (Prometheus Alertmanager) +* Application alerts (custom rules) +* Business alerts (SLA violations) +* Multi-channel notifications (email, SMS, Slack) + +==== Logging + +* Structured logging (JSON format) +* Centralized log aggregation (ELK) +* Log retention: 90 days +* Full-text search capability + +=== Development & Deployment + +==== CI/CD Pipeline + +.... Git Push → GitHub Actions → Build → Test → Deploy ↓ Docker Registry ↓ Staging Environment → Manual Approval → Production -``` +.... + +==== Environments -### Environments -- **Development**: Local Docker Compose -- **Staging**: Cloud-based (IONOS) -- **Production**: Cloud-based (IONOS) with HA +* *Development*: Local Docker Compose +* *Staging*: Cloud-based (IONOS) +* *Production*: Cloud-based (IONOS) with HA -### Deployment Strategy -- Blue-green deployment -- Rolling updates for zero downtime -- Automated rollback on failure -- Feature flags for gradual rollout +==== Deployment Strategy -## Edge Computing Capabilities +* Blue-green deployment +* Rolling updates for zero downtime +* Automated rollback on failure +* Feature flags for gradual rollout -### On-Device Processing -- Real-time signal filtering -- Edge analytics (moving averages, thresholds) -- Local alerting (critical conditions) -- Data compression before transmission +=== Edge Computing Capabilities -### Offline Operation -- Local buffering (up to 24 hours) -- Automatic sync when connection restored -- Local web interface for diagnostics -- Fallback to default operating parameters +==== On-Device Processing -## Data Model +* Real-time signal filtering +* Edge analytics (moving averages, thresholds) +* Local alerting (critical conditions) +* Data compression before transmission -### Measurement Schema -```sql +==== Offline Operation + +* Local buffering (up to 24 hours) +* Automatic sync when connection restored +* Local web interface for diagnostics +* Fallback to default operating parameters + +=== Data Model + +==== Measurement Schema + +[source,sql] +---- -- Time-series table (TimescaleDB hypertable) CREATE TABLE bbw_measurements ( time TIMESTAMPTZ NOT NULL, @@ -279,12 +302,13 @@ SELECT create_hypertable('bbw_measurements', 'time'); -- Create indexes CREATE INDEX ON bbw_measurements (loom_id, time DESC); CREATE INDEX ON bbw_measurements (sensor_id, time DESC); -``` +---- + +=== API Design -## API Design +==== RESTful Endpoints -### RESTful Endpoints -``` +.... GET /api/v1/looms # List all looms GET /api/v1/looms/{id} # Get loom details GET /api/v1/looms/{id}/measurements # Get measurements @@ -292,37 +316,38 @@ POST /api/v1/looms/{id}/config # Update configuration GET /api/v1/alerts # List alerts POST /api/v1/alerts/{id}/acknowledge # Acknowledge alert GET /api/v1/analytics/summary # Get analytics summary -``` +.... + +==== WebSocket Events -### WebSocket Events -``` +.... connect # Client connection subscribe:loom:{id} # Subscribe to loom updates unsubscribe:loom:{id} # Unsubscribe measurement:update # Real-time measurement alert:new # New alert status:change # Device status change -``` +.... -## Compliance & Standards +=== Compliance & Standards -- **Industrial**: IEC 61131-3 (PLC programming) -- **IoT**: MQTT 5.0, OPC UA -- **Security**: IEC 62443 (industrial cybersecurity) -- **Data**: GDPR compliance (if applicable) -- **Quality**: ISO 9001 alignment +* *Industrial*: IEC 61131-3 (PLC programming) +* *IoT*: MQTT 5.0, OPC UA +* *Security*: IEC 62443 (industrial cybersecurity) +* *Data*: GDPR compliance (if applicable) +* *Quality*: ISO 9001 alignment -## Future Enhancements +=== Future Enhancements -1. **Machine Learning**: Predictive maintenance models -2. **Digital Twin**: Virtual loom simulation -3. **Edge AI**: On-device anomaly detection -4. **AR Interface**: Augmented reality diagnostics -5. **Integration**: ERP/MES system connectivity -6. **Multi-tenancy**: Support for multiple facilities +[arabic] +. *Machine Learning*: Predictive maintenance models +. *Digital Twin*: Virtual loom simulation +. *Edge AI*: On-device anomaly detection +. *AR Interface*: Augmented reality diagnostics +. *Integration*: ERP/MES system connectivity +. *Multi-tenancy*: Support for multiple facilities ---- +''''' -**Document Version**: 1.0 -**Last Updated**: 2025-11-22 -**Status**: Production Ready +*Document Version*: 1.0 *Last Updated*: 2025-11-22 *Status*: Production +Ready diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index b3cd2b5..4e7b6a0 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -1,191 +1,233 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Changelog - -All notable changes to the Kaldor Community Manufacturing Platform will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -== [Unreleased] - -=== Added -- RSR Framework compliance (targeting Platinum level) -- Tri-Perimeter Contribution Framework (TPCF) -- Deno backend with WASM acceleration -- ReScript frontend with sound type system -- Matter protocol integration for IoT devices -- RISC-V firmware support (ESP32-C6) -- SCADA/DCS interoperability (OPC UA, Modbus) -- CRDT-based offline-first architecture -- CURP consensus protocol for community governance -- Comprehensive security policy (RFC 9116) -- .well-known/ directory (security.txt, ai.txt, humans.txt) -- Code of Conduct with Emotional Safety (CCCP) -- Quadratic voting system -- Kaldor's Law 2 economic integration - -=== Changed -- Architecture v2.0: Deno + ReScript + WASM (from Node.js + TypeScript) -- Licensing: Palimpsest v0.8 (from MIT only) -- Governance: TPCF perimeters (from flat model) - -=== Security -- Implemented RFC 9116 security.txt -- Added responsible disclosure policy -- Enabled signed commits requirement -- Added dependency scanning (Dependabot) - -== [2.0.0] - 2025-11-22 - -=== Breaking Changes -- Complete rewrite from Node.js to Deno runtime -- Frontend migrated from React+TypeScript to ReScript -- Database schema redesigned for offline-first CRDTs -- API v2.0 with Matter protocol support - -=== Added -- **Backend**: Deno 1.40+ with Oak framework -- **Frontend**: ReScript 11+ with type-safe React bindings -- **WASM**: Rust-compiled modules for pattern generation and scheduling -- **Firmware**: ESP32-C6 RISC-V support with Matter/Thread -- **Protocols**: Matter, OPC UA, Modbus TCP/RTU -- **Database**: TimescaleDB + Automerge CRDTs -- **Governance**: CURP consensus + quadratic voting -- **Documentation**: White paper, wiki, 3D-weave specification - -=== Improved -- Offline-first operation (works air-gapped) -- Type safety (ReScript + Rust + Deno strict mode) -- Memory safety (zero unsafe blocks in Rust) -- Build reproducibility (Nix flake) -- Test coverage (>80% target) -- Security (OWASP Top 10 compliance) - -== [1.0.0] - 2025-11-22 (Legacy) - -=== Added -- Initial IIoT platform implementation -- Node.js backend with Express.js -- React frontend with Material-UI -- ESP32 firmware (C++) -- TimescaleDB time-series database -- MQTT broker (Mosquitto) -- Docker Compose deployment -- Prometheus + Grafana monitoring - -=== Deprecated -- Node.js backend (replaced by Deno in v2.0) -- TypeScript frontend (replaced by ReScript in v2.0) -- C++ firmware (replaced by Rust in v2.0) - ---- - -== Version History - -| Version | Date | Description | RSR Level | -|---------|------|-------------|-----------| -| 2.0.0 | 2025-11-22 | Complete rewrite for community manufacturing | Platinum (target) | -| 1.0.0 | 2025-11-22 | Initial IIoT platform | Bronze | - -== Upgrade Guide - -=== From 1.0.x to 2.0.0 - -**⚠️ Breaking Changes - Major Migration Required** - -1. **Backend Migration**: - [source,bash] ----- - # Remove Node.js dependencies - rm -rf backend/api/node_modules +== Changelog + +All notable changes to the Kaldor Community Manufacturing Platform will +be documented in this file. + +The format is based on https://keepachangelog.com/en/1.0.0/[Keep a +Changelog], and this project adheres to +https://semver.org/spec/v2.0.0.html[Semantic Versioning]. + +=== [Unreleased] + +=== [0.2.0] - 2026-04-12 + +==== Changed + +* *firmware-zig*: Migrated to Zig 0.15.2 API (`+root_module+` + +`+b.createModule()+`, `+b.graph.host+`) +* *firmware-zig*: Renamed `+OtaUpdater.error+` field to `+last_error+` +(`+error+` is a Zig keyword) +* *firmware-zig*: `+calculateQuality+` signature `+*Self+` → +`+*const Self+` (does not mutate) +* *firmware-zig*: Block comment `+/** */+` → `+//+` line comments (Zig +has no block comments) + +==== Added + +* *firmware-zig*: `+src/all_tests.zig+` — dedicated host-side test root +that imports all submodules with tests (buffer, sensors, mqtt, ota, +wifi) while skipping `+main.zig+`’s freestanding-only `+extern fn+` +stubs +* `+.gitignore+`: `+**/.zig-cache/+` and `+**/zig-out/+` patterns +* `+.machine_readable/6a2/+`: Full content expansion for STATE, META, +ECOSYSTEM, PLAYBOOK, NEUROSYM — all previously stub-only + +==== Fixed + +* *firmware-zig*: All 10 host unit tests now pass on Zig 0.15.2 +(previously failed to compile) +* *NEUROSYM.a2ml*: Removed stale `+report-format = "logtalk"+` (Logtalk +removed from Hypatia 2026-04-12) + +==== Added + +* RSR Framework compliance (targeting Platinum level) +* Tri-Perimeter Contribution Framework (TPCF) +* Deno backend with WASM acceleration +* ReScript frontend with sound type system +* Matter protocol integration for IoT devices +* RISC-V firmware support (ESP32-C6) +* SCADA/DCS interoperability (OPC UA, Modbus) +* CRDT-based offline-first architecture +* CURP consensus protocol for community governance +* Comprehensive security policy (RFC 9116) +* .well-known/ directory (security.txt, ai.txt, humans.txt) +* Code of Conduct with Emotional Safety (CCCP) +* Quadratic voting system +* Kaldor’s Law 2 economic integration + +==== Changed + +* Architecture v2.0: Deno + ReScript + WASM (from Node.js + TypeScript) +* Licensing: Palimpsest v0.8 (from MIT only) +* Governance: TPCF perimeters (from flat model) + +==== Security + +* Implemented RFC 9116 security.txt +* Added responsible disclosure policy +* Enabled signed commits requirement +* Added dependency scanning (Dependabot) + +=== [2.0.0] - 2025-11-22 + +==== Breaking Changes + +* Complete rewrite from Node.js to Deno runtime +* Frontend migrated from React+TypeScript to ReScript +* Database schema redesigned for offline-first CRDTs +* API v2.0 with Matter protocol support + +==== Added + +* *Backend*: Deno 1.40+ with Oak framework +* *Frontend*: ReScript 11+ with type-safe React bindings +* *WASM*: Rust-compiled modules for pattern generation and scheduling +* *Firmware*: ESP32-C6 RISC-V support with Matter/Thread +* *Protocols*: Matter, OPC UA, Modbus TCP/RTU +* *Database*: TimescaleDB + Automerge CRDTs +* *Governance*: CURP consensus + quadratic voting +* *Documentation*: White paper, wiki, 3D-weave specification + +==== Improved + +* Offline-first operation (works air-gapped) +* Type safety (ReScript + Rust + Deno strict mode) +* Memory safety (zero unsafe blocks in Rust) +* Build reproducibility (Nix flake) +* Test coverage (>80% target) +* Security (OWASP Top 10 compliance) - # Install Deno - curl -fsSL https://deno.land/install.sh | sh +=== [1.0.0] - 2025-11-22 (Legacy) - # Run new backend - cd backend-deno - deno task dev - [source,] +==== Added + +* Initial IIoT platform implementation +* Node.js backend with Express.js +* React frontend with Material-UI +* ESP32 firmware (C++) +* TimescaleDB time-series database +* MQTT broker (Mosquitto) +* Docker Compose deployment +* Prometheus + Grafana monitoring + +==== Deprecated + +* Node.js backend (replaced by Deno in v2.0) +* TypeScript frontend (replaced by ReScript in v2.0) +* C++ firmware (replaced by Rust in v2.0) + +''''' + +=== Version History + +[width="100%",cols="24%,15%,33%,28%",options="header",] +|=== +|Version |Date |Description |RSR Level +|2.0.0 |2025-11-22 |Complete rewrite for community manufacturing +|Platinum (target) + +|1.0.0 |2025-11-22 |Initial IIoT platform |Bronze +|=== + +=== Upgrade Guide + +==== From 1.0.x to 2.0.0 + +*⚠️ Breaking Changes - Major Migration Required* + +[arabic] +. *Backend Migration*: ++ +[source,bash] ---- +# Remove Node.js dependencies +rm -rf backend/api/node_modules + +# Install Deno +curl -fsSL https://deno.land/install.sh | sh -2. **Frontend Migration**: - [source,bash] +# Run new backend +cd backend-deno +deno task dev ---- - # Install ReScript - cd frontend-rescript - npm install - npm start - [source,] +. *Frontend Migration*: ++ +[source,bash] ---- - -3. **Database Migration**: - [source,sql] +# Install ReScript +cd frontend-rescript +npm install +npm start ---- - -- Run CRDT migration - \i database/migrations/002_crdt_support.sql - [source,] +. *Database Migration*: ++ +[source,sql] ---- - -4. **Firmware Migration**: - [source,bash] +-- Run CRDT migration +\i database/migrations/002_crdt_support.sql +---- +. *Firmware Migration*: ++ +[source,bash] ---- - # Flash new RISC-V firmware - cd firmware-riscv - idf.py flash monitor - [source,] +# Flash new RISC-V firmware +cd firmware-riscv +idf.py flash monitor ---- -**Data Migration**: Automatic migration tool included: +*Data Migration*: Automatic migration tool included: + [source,bash] ---- deno run --allow-all scripts/migrate-v1-to-v2.ts -[source,] ---- -== Support Policy +=== Support Policy + +[cols=",,,",options="header",] +|=== +|Version |Status |End of Life |Security Fixes +|2.x |✅ Active |TBD |Yes +|1.x |❌ Deprecated |2025-11-22 |Critical only (90 days) +|=== -| Version | Status | End of Life | Security Fixes | -|---------|--------|-------------|----------------| -| 2.x | ✅ Active | TBD | Yes | -| 1.x | ❌ Deprecated | 2025-11-22 | Critical only (90 days) | +=== Contributing -== Contributing +See CONTRIBUTING.md for changelog guidelines. -See [CONTRIBUTING.md](CONTRIBUTING.md) for changelog guidelines. +*Changelog Entry Format*: -**Changelog Entry Format**: [source,markdown] ---- -=== Added +### Added - New feature description (#123) -=== Changed +### Changed - Modified behavior description (#124) -=== Deprecated +### Deprecated - Soon-to-be-removed feature (#125) -=== Removed +### Removed - Deleted feature description (#126) -=== Fixed +### Fixed - Bug fix description (#127) -=== Security +### Security - Vulnerability fix (CVE-YYYY-XXXXX) (#128) -[source,] ---- -== Links +=== Links -- **Repository**: https://github.com/Hyperpolymath/Kaldor-IIoT -- **Releases**: https://github.com/Hyperpolymath/Kaldor-IIoT/releases -- **Security Advisories**: https://github.com/Hyperpolymath/Kaldor-IIoT/security/advisories -- **Issue Tracker**: https://github.com/Hyperpolymath/Kaldor-IIoT/issues +* *Repository*: https://github.com/hyperpolymath/kaldor-iiot +* *Releases*: https://github.com/hyperpolymath/kaldor-iiot/releases +* *Security Advisories*: +https://github.com/hyperpolymath/kaldor-iiot/security/advisories +* *Issue Tracker*: https://github.com/hyperpolymath/kaldor-iiot/issues ---- +''''' -**Maintained by**: Kaldor Community -**Format**: Keep a Changelog v1.1.0 -**Versioning**: Semantic Versioning v2.0.0 +*Maintained by*: Kaldor Community *Format*: Keep a Changelog v1.1.0 +*Versioning*: Semantic Versioning v2.0.0 diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 0b2af56..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,203 +0,0 @@ - -# Changelog - -All notable changes to the Kaldor Community Manufacturing Platform will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [Unreleased] - -## [0.2.0] - 2026-04-12 - -### Changed -- **firmware-zig**: Migrated to Zig 0.15.2 API (`root_module` + `b.createModule()`, `b.graph.host`) -- **firmware-zig**: Renamed `OtaUpdater.error` field to `last_error` (`error` is a Zig keyword) -- **firmware-zig**: `calculateQuality` signature `*Self` → `*const Self` (does not mutate) -- **firmware-zig**: Block comment `/** */` → `//` line comments (Zig has no block comments) - -### Added -- **firmware-zig**: `src/all_tests.zig` — dedicated host-side test root that imports all - submodules with tests (buffer, sensors, mqtt, ota, wifi) while skipping `main.zig`'s - freestanding-only `extern fn` stubs -- `.gitignore`: `**/.zig-cache/` and `**/zig-out/` patterns -- `.machine_readable/6a2/`: Full content expansion for STATE, META, ECOSYSTEM, PLAYBOOK, - NEUROSYM — all previously stub-only - -### Fixed -- **firmware-zig**: All 10 host unit tests now pass on Zig 0.15.2 (previously failed to compile) -- **NEUROSYM.a2ml**: Removed stale `report-format = "logtalk"` (Logtalk removed from Hypatia 2026-04-12) - - - -### Added -- RSR Framework compliance (targeting Platinum level) -- Tri-Perimeter Contribution Framework (TPCF) -- Deno backend with WASM acceleration -- ReScript frontend with sound type system -- Matter protocol integration for IoT devices -- RISC-V firmware support (ESP32-C6) -- SCADA/DCS interoperability (OPC UA, Modbus) -- CRDT-based offline-first architecture -- CURP consensus protocol for community governance -- Comprehensive security policy (RFC 9116) -- .well-known/ directory (security.txt, ai.txt, humans.txt) -- Code of Conduct with Emotional Safety (CCCP) -- Quadratic voting system -- Kaldor's Law 2 economic integration - -### Changed -- Architecture v2.0: Deno + ReScript + WASM (from Node.js + TypeScript) -- Licensing: Palimpsest v0.8 (from MIT only) -- Governance: TPCF perimeters (from flat model) - -### Security -- Implemented RFC 9116 security.txt -- Added responsible disclosure policy -- Enabled signed commits requirement -- Added dependency scanning (Dependabot) - -## [2.0.0] - 2025-11-22 - -### Breaking Changes -- Complete rewrite from Node.js to Deno runtime -- Frontend migrated from React+TypeScript to ReScript -- Database schema redesigned for offline-first CRDTs -- API v2.0 with Matter protocol support - -### Added -- **Backend**: Deno 1.40+ with Oak framework -- **Frontend**: ReScript 11+ with type-safe React bindings -- **WASM**: Rust-compiled modules for pattern generation and scheduling -- **Firmware**: ESP32-C6 RISC-V support with Matter/Thread -- **Protocols**: Matter, OPC UA, Modbus TCP/RTU -- **Database**: TimescaleDB + Automerge CRDTs -- **Governance**: CURP consensus + quadratic voting -- **Documentation**: White paper, wiki, 3D-weave specification - -### Improved -- Offline-first operation (works air-gapped) -- Type safety (ReScript + Rust + Deno strict mode) -- Memory safety (zero unsafe blocks in Rust) -- Build reproducibility (Nix flake) -- Test coverage (>80% target) -- Security (OWASP Top 10 compliance) - -## [1.0.0] - 2025-11-22 (Legacy) - -### Added -- Initial IIoT platform implementation -- Node.js backend with Express.js -- React frontend with Material-UI -- ESP32 firmware (C++) -- TimescaleDB time-series database -- MQTT broker (Mosquitto) -- Docker Compose deployment -- Prometheus + Grafana monitoring - -### Deprecated -- Node.js backend (replaced by Deno in v2.0) -- TypeScript frontend (replaced by ReScript in v2.0) -- C++ firmware (replaced by Rust in v2.0) - ---- - -## Version History - -| Version | Date | Description | RSR Level | -|---------|------|-------------|-----------| -| 2.0.0 | 2025-11-22 | Complete rewrite for community manufacturing | Platinum (target) | -| 1.0.0 | 2025-11-22 | Initial IIoT platform | Bronze | - -## Upgrade Guide - -### From 1.0.x to 2.0.0 - -**⚠️ Breaking Changes - Major Migration Required** - -1. **Backend Migration**: - ```bash - # Remove Node.js dependencies - rm -rf backend/api/node_modules - - # Install Deno - curl -fsSL https://deno.land/install.sh | sh - - # Run new backend - cd backend-deno - deno task dev - ``` - -2. **Frontend Migration**: - ```bash - # Install ReScript - cd frontend-rescript - npm install - npm start - ``` - -3. **Database Migration**: - ```sql - -- Run CRDT migration - \i database/migrations/002_crdt_support.sql - ``` - -4. **Firmware Migration**: - ```bash - # Flash new RISC-V firmware - cd firmware-riscv - idf.py flash monitor - ``` - -**Data Migration**: Automatic migration tool included: -```bash -deno run --allow-all scripts/migrate-v1-to-v2.ts -``` - -## Support Policy - -| Version | Status | End of Life | Security Fixes | -|---------|--------|-------------|----------------| -| 2.x | ✅ Active | TBD | Yes | -| 1.x | ❌ Deprecated | 2025-11-22 | Critical only (90 days) | - -## Contributing - -See [CONTRIBUTING.md](CONTRIBUTING.md) for changelog guidelines. - -**Changelog Entry Format**: -```markdown -### Added -- New feature description (#123) - -### Changed -- Modified behavior description (#124) - -### Deprecated -- Soon-to-be-removed feature (#125) - -### Removed -- Deleted feature description (#126) - -### Fixed -- Bug fix description (#127) - -### Security -- Vulnerability fix (CVE-YYYY-XXXXX) (#128) -``` - -## Links - -- **Repository**: https://github.com/hyperpolymath/kaldor-iiot -- **Releases**: https://github.com/hyperpolymath/kaldor-iiot/releases -- **Security Advisories**: https://github.com/hyperpolymath/kaldor-iiot/security/advisories -- **Issue Tracker**: https://github.com/hyperpolymath/kaldor-iiot/issues - ---- - -**Maintained by**: Kaldor Community -**Format**: Keep a Changelog v1.1.0 -**Versioning**: Semantic Versioning v2.0.0 diff --git a/CODE_OF_CONDUCT.adoc b/CODE_OF_CONDUCT.adoc new file mode 100644 index 0000000..d424e83 --- /dev/null +++ b/CODE_OF_CONDUCT.adoc @@ -0,0 +1,221 @@ +== Contributor Covenant Code of Conduct + +=== Our Pledge + +We as members, contributors, and leaders pledge to make participation in +the Kaldor Community Manufacturing Platform a harassment-free experience +for everyone, regardless of age, body size, visible or invisible +disability, ethnicity, sex characteristics, gender identity and +expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity and +orientation. + +We pledge to act and interact in ways that contribute to an open, +welcoming, diverse, inclusive, and healthy community focused on +*hyperlocal, community-owned manufacturing* and *economic autonomy*. + +=== Our Standards + +==== Positive Behavior + +Examples of behavior that contributes to a positive environment: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our +mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the +overall community and local economies +* *Prioritizing community ownership over individual extraction* +* *Sharing knowledge freely and teaching others* +* *Respecting offline-first and privacy-preserving design* +* *Supporting local, hyperlocal production over centralized +alternatives* + +==== Unacceptable Behavior + +Examples of unacceptable behavior: + +* The use of sexualized language or imagery, and sexual attention or +advances of any kind +* Trolling, insulting or derogatory comments, and personal or political +attacks +* Public or private harassment +* Publishing others’ private information, such as a physical or email +address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting +* *Advocating for centralized, extractive business models* +* *Undermining community governance or TPCF perimeter system* +* *Promoting surveillance capitalism or non-consensual data collection* +* *Discouraging offline-first or local-first approaches* + +=== Emotional Safety (CCCP Integration) + +We recognize that open source contribution can be emotionally taxing. We +commit to: + +[arabic] +. *Reversibility*: All major decisions can be rolled back with community +consensus +. *Low-stakes experimentation*: Perimeter 3 (Community Sandbox) allows +risk-free contribution +. *Anxiety reduction*: Clear contribution paths, no "`gotchas`", +friendly code review +. *Celebration of learning*: Mistakes are learning opportunities, not +failures +. *Transparency*: No hidden agendas, all governance is public + +See our *Emotional Temperature* metrics in +`+docs/community/EMOTIONAL_SAFETY.md+` + +=== Tri-Perimeter Contribution Framework (TPCF) + +We operate a graduated trust system: + +==== Perimeter 3: Community Sandbox (Open) + +* *Access*: Anyone +* *Scope*: Documentation, examples, tutorials, bug reports +* *Risk*: Low +* *Approval*: Self-service, immediate + +==== Perimeter 2: Professional Contributors (Vetted) + +* *Access*: Established contributors (3+ merged PRs) +* *Scope*: Feature development, refactoring, architecture proposals +* *Risk*: Medium +* *Approval*: Maintainer review + +==== Perimeter 1: Core Maintainers (Trusted) + +* *Access*: Long-term contributors (6+ months, 20+ merged PRs) +* *Scope*: Security-critical code, release management, governance +* *Risk*: High +* *Approval*: Consensus of existing Perimeter 1 members + +Progression between perimeters is *merit-based and transparent*. See +`+MAINTAINERS.md+` for current perimeter assignments. + +=== Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our +standards of acceptable behavior and will take appropriate and fair +corrective action in response to any behavior that they deem +inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other +contributions that are not aligned with this Code of Conduct, and will +communicate reasons for moderation decisions when appropriate. + +=== Scope + +This Code of Conduct applies within all community spaces (GitHub, +Matrix, mailing lists, community meetups, conferences), and also applies +when an individual is officially representing the community in public +spaces. + +=== Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may +be reported to the community leaders responsible for enforcement at: + +*conduct@kaldor.community* + +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security +of the reporter of any incident. + +=== Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in +determining the consequences for any action they deem in violation of +this Code of Conduct: + +==== 1. Correction + +*Community Impact*: Use of inappropriate language or other behavior +deemed unprofessional or unwelcome in the community. + +*Consequence*: A private, written warning from community leaders, +providing clarity around the nature of the violation and an explanation +of why the behavior was inappropriate. A public apology may be +requested. + +==== 2. Warning + +*Community Impact*: A violation through a single incident or series of +actions. + +*Consequence*: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, for a specified period of +time. This includes avoiding interactions in community spaces as well as +external channels like social media. Violating these terms may lead to a +temporary or permanent ban. + +==== 3. Temporary Ban + +*Community Impact*: A serious violation of community standards, +including sustained inappropriate behavior. + +*Consequence*: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No +public or private interaction with the people involved, including +unsolicited interaction with those enforcing the Code of Conduct, is +allowed during this period. Violating these terms may lead to a +permanent ban. + +==== 4. Permanent Ban + +*Community Impact*: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of +individuals. + +*Consequence*: A permanent ban from any sort of public interaction +within the community. + +=== Kaldor-Specific Values + +As a community-manufacturing platform, we additionally commit to: + +[arabic] +. *Economic Justice*: No extractive business models +. *Local First*: Prioritize hyperlocal production +. *Shared Ownership*: Community benefit over individual profit +. *Accessibility*: Low barrier to entry (spare room → supply chain) +. *Education*: Teach, don’t gatekeep +. *Sustainability*: Long-term thinking, repair-friendly design +. *Autonomy*: Offline-first, privacy-preserving +. *Transparency*: Open economics, visible costs +. *Federation*: P2P, not client-server hegemony +. *Kaldor’s Law*: Increasing returns to COMMUNITY scale + +=== Attribution + +This Code of Conduct is adapted from the +https://www.contributor-covenant.org[Contributor Covenant], version 2.1, +available at +https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. + +Community Impact Guidelines were inspired by +https://github.com/mozilla/diversity[Mozilla’s code of conduct +enforcement ladder]. + +Emotional Safety principles adapted from the CCCP Manifesto. + +TPCF framework developed specifically for Kaldor Community +Manufacturing. + +=== Questions? + +If you have questions about this Code of Conduct, please contact: +*conduct@kaldor.community* + +''''' + +_Last updated: 2025-11-22_ _Version: 1.0.0_ diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md deleted file mode 100644 index 904f165..0000000 --- a/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,206 +0,0 @@ - -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in the -Kaldor Community Manufacturing Platform a harassment-free experience for everyone, -regardless of age, body size, visible or invisible disability, ethnicity, sex -characteristics, gender identity and expression, level of experience, education, -socio-economic status, nationality, personal appearance, race, religion, or sexual -identity and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community focused on **hyperlocal, community-owned -manufacturing** and **economic autonomy**. - -## Our Standards - -### Positive Behavior - -Examples of behavior that contributes to a positive environment: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community and local economies -* **Prioritizing community ownership over individual extraction** -* **Sharing knowledge freely and teaching others** -* **Respecting offline-first and privacy-preserving design** -* **Supporting local, hyperlocal production over centralized alternatives** - -### Unacceptable Behavior - -Examples of unacceptable behavior: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting -* **Advocating for centralized, extractive business models** -* **Undermining community governance or TPCF perimeter system** -* **Promoting surveillance capitalism or non-consensual data collection** -* **Discouraging offline-first or local-first approaches** - -## Emotional Safety (CCCP Integration) - -We recognize that open source contribution can be emotionally taxing. We commit to: - -1. **Reversibility**: All major decisions can be rolled back with community consensus -2. **Low-stakes experimentation**: Perimeter 3 (Community Sandbox) allows risk-free contribution -3. **Anxiety reduction**: Clear contribution paths, no "gotchas", friendly code review -4. **Celebration of learning**: Mistakes are learning opportunities, not failures -5. **Transparency**: No hidden agendas, all governance is public - -See our **Emotional Temperature** metrics in `docs/community/EMOTIONAL_SAFETY.md` - -## Tri-Perimeter Contribution Framework (TPCF) - -We operate a graduated trust system: - -### Perimeter 3: Community Sandbox (Open) -- **Access**: Anyone -- **Scope**: Documentation, examples, tutorials, bug reports -- **Risk**: Low -- **Approval**: Self-service, immediate - -### Perimeter 2: Professional Contributors (Vetted) -- **Access**: Established contributors (3+ merged PRs) -- **Scope**: Feature development, refactoring, architecture proposals -- **Risk**: Medium -- **Approval**: Maintainer review - -### Perimeter 1: Core Maintainers (Trusted) -- **Access**: Long-term contributors (6+ months, 20+ merged PRs) -- **Scope**: Security-critical code, release management, governance -- **Risk**: High -- **Approval**: Consensus of existing Perimeter 1 members - -Progression between perimeters is **merit-based and transparent**. -See `MAINTAINERS.md` for current perimeter assignments. - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned with this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces (GitHub, Matrix, -mailing lists, community meetups, conferences), and also applies when -an individual is officially representing the community in public spaces. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement at: - -**conduct@kaldor.community** - -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -## Kaldor-Specific Values - -As a community-manufacturing platform, we additionally commit to: - -1. **Economic Justice**: No extractive business models -2. **Local First**: Prioritize hyperlocal production -3. **Shared Ownership**: Community benefit over individual profit -4. **Accessibility**: Low barrier to entry (spare room → supply chain) -5. **Education**: Teach, don't gatekeep -6. **Sustainability**: Long-term thinking, repair-friendly design -7. **Autonomy**: Offline-first, privacy-preserving -8. **Transparency**: Open economics, visible costs -9. **Federation**: P2P, not client-server hegemony -10. **Kaldor's Law**: Increasing returns to COMMUNITY scale - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.1, available at -[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. - -Community Impact Guidelines were inspired by -[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. - -Emotional Safety principles adapted from the CCCP Manifesto. - -TPCF framework developed specifically for Kaldor Community Manufacturing. - -[homepage]: https://www.contributor-covenant.org -[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html -[Mozilla CoC]: https://github.com/mozilla/diversity - -## Questions? - -If you have questions about this Code of Conduct, please contact: -**conduct@kaldor.community** - ---- - -*Last updated: 2025-11-22* -*Version: 1.0.0* diff --git a/CONTRIBUTING.adoc b/CONTRIBUTING.adoc new file mode 100644 index 0000000..dab29bd --- /dev/null +++ b/CONTRIBUTING.adoc @@ -0,0 +1,3 @@ +== Contributing + +See CONTRIBUTING.adoc for full contribution guidelines. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 66fae77..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,7 +0,0 @@ - -# Contributing - -See [CONTRIBUTING.adoc](CONTRIBUTING.adoc) for full contribution guidelines. diff --git a/GOVERNANCE.adoc b/GOVERNANCE.adoc index 6cfd815..9b836fb 100644 --- a/GOVERNANCE.adoc +++ b/GOVERNANCE.adoc @@ -1,469 +1,60 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -// SPDX-FileCopyrightText: 2025 Kaldor Community Manufacturing Platform Contributors -= Kaldor IIoT Governance Model -:toc: left -:toclevels: 3 -:icons: font +== Governance -This document defines the decision-making processes, maintainer succession, financial transparency, and conflict resolution for the Kaldor IIoT project. +=== Overview -== Principles +This project is governed by the following principles and structures to +ensure transparent, inclusive, and effective decision-making. -1. **Decentralized Authority**: No single individual or organization controls the project -2. **Consensus Over Voting**: Seek agreement first, vote only when necessary -3. **Reversibility**: Decisions can be revisited with new evidence -4. **Transparency**: All governance discussions are public (except security/HR issues) -5. **Offline-First**: Governance works without internet connectivity (CURP consensus) +=== Roles and Responsibilities -== Decision-Making Framework +==== Maintainers -=== CURP Consensus Protocol +Maintainers are responsible for: - Reviewing and merging pull requests - +Managing releases and versioning - Ensuring code quality and standards - +Triaging issues and bug reports - Community engagement and support -Kaldor uses **CURP** (Consistent Unordered Replication Protocol) for governance decisions, enabling offline-capable, distributed consensus. +==== Contributors -==== How CURP Works -1. **Proposal**: Maintainer creates proposal with unique ID -2. **Replication**: Proposal synced to all maintainers (even offline nodes) -3. **Voting**: Maintainers vote using quadratic voice credits (offline-capable) -4. **Convergence**: CRDTs resolve conflicts when nodes reconnect -5. **Execution**: Approved proposals execute automatically +Contributors are expected to: - Follow the code of conduct - Submit +well-documented pull requests - Write tests for new functionality - +Maintain existing tests - Update documentation as needed -==== CURP Guarantees -* **Eventual Consistency**: All nodes converge to same decision -* **Partition Tolerance**: Offline nodes catch up when reconnected -* **No Blocking**: No single node failure prevents progress -* **Deterministic**: Same inputs always produce same outcome +=== Decision Making -=== Quadratic Voting +==== Minor Changes -To prevent tyranny of majority and plutocracy, Kaldor uses **quadratic voting** with voice credits. +* Can be made by any maintainer +* Include bug fixes, documentation updates, dependency updates -==== Voice Credit Allocation -[cols="2,1,3"] -|=== -|Action |Credits |Rationale +==== Major Changes -|New member -|10 -|Starting balance for participation +* Require discussion in issues or pull requests +* Include new features, architectural changes, API changes +* Need approval from at least 2 maintainers -|1 month active contribution -|+5 -|Reward sustained engagement +==== Breaking Changes -|1 merged PR (Perimeter 2/1) -|+2 -|Technical contribution value +* Require RFC (Request for Comments) process +* Need approval from majority of maintainers +* Must include migration guide -|Security disclosure -|+10 -|Critical contribution to project safety +=== Code of Conduct -|Mentoring new contributor -|+3 -|Community building +All participants are expected to follow our Code of Conduct. Violations +can be reported to the maintainers. -|**Maximum accumulation** -|**100** -|**Prevents plutocracy** -|=== +=== Communication -==== Voting Cost Formula +* *Issues*: For bug reports and feature requests +* *Discussions*: For questions and general discussion +* *Pull Requests*: For code contributions -To cast `n` votes on a single proposal, you spend `n²` voice credits. +=== Licensing -.Example -* 1 vote = 1² = 1 credit -* 2 votes = 2² = 4 credits -* 3 votes = 3² = 9 credits -* 5 votes = 5² = 25 credits -* 10 votes = 10² = 100 credits (maximum) +All contributions are made under the terms of the repository’s LICENSE +file. By submitting a pull request, you agree to license your +contributions accordingly. -**Effect**: Strong preferences cost exponentially more, encouraging broad consensus. +''''' -==== Approval Thresholds -[cols="2,1,3"] -|=== -|Decision Type |Threshold |Veto Power - -|**Breaking Changes** -|66% approval -|No single veto >25% of total votes - -|**New Perimeter 1 Maintainer** -|75% approval -|Sponsor from different org required - -|**Architecture Decisions** -|66% approval -|ADR documentation required - -|**Security Patches** -|Simple majority (51%) -|Expedited process, post-hoc review - -|**Funding Allocation** -|75% approval -|Financial transparency required - -|**Code of Conduct Enforcement** -|66% approval -|Independent ombudsperson consulted - -|**Project Fork/Archive** -|90% approval -|30-day discussion period -|=== - -==== Vote Delegation -Maintainers can delegate voice credits to trusted proxies: - -[source,bash] ----- -# Delegate 20 credits to proxy -deno run scripts/governance/delegate.ts \ - --credits 20 \ - --proxy alice@example.com \ - --duration 30days ----- - -**Constraints**: -* Cannot delegate >50% of credits -* Delegation expires after specified duration -* Can revoke delegation anytime - -== Roles & Responsibilities - -=== Perimeter 1: Core Maintainers - -**Current Roster**: See link:MAINTAINERS.md[MAINTAINERS.md] - -==== Responsibilities -* Review Perimeter 2/3 contributions (24-48 hour SLA) -* Security incident response (24-hour acknowledgement) -* Release management (semantic versioning) -* Governance participation (quadratic voting) -* Mentor Perimeter 2 contributors -* Financial stewardship (if project funded) - -==== Time Commitment -* **Minimum**: 5 hours/week (review, governance, community) -* **Expected**: 10-15 hours/week for active maintainers -* **Sabbaticals**: 4-week notice, temporary delegation - -==== Becoming a P1 Maintainer -1. **Nomination**: Existing P1 maintainer sponsors candidate -2. **Review**: Public review period (2 weeks) -3. **Voting**: 75% approval via quadratic voting -4. **Onboarding**: 2-week shadowing period with sponsor -5. **Responsibilities**: Sign link:MAINTAINERS.md[MAINTAINERS.md] agreement - -==== Stepping Down -Maintainers can step down anytime with 4-week notice: - -1. Announce intention in governance forum -2. Transfer active responsibilities to other P1s -3. Transition to Perimeter 2 (or leave entirely) -4. Update link:MAINTAINERS.md[MAINTAINERS.md] - -**Emeritus Status**: Long-serving maintainers (>2 years) can request advisory role with voting rights but no review obligations. - -==== Removal Process -If maintainer is unresponsive (>30 days) or violates link:CODE_OF_CONDUCT.md[Code of Conduct]: - -1. Private outreach (ombudsperson) -2. Public discussion (if unresolved) -3. Voting: 66% approval to remove -4. Update link:MAINTAINERS.md[MAINTAINERS.md] - -=== Perimeter 2: Professional Contributors - -==== Responsibilities -* Implement features, fix bugs -* Maintain documentation -* Review Perimeter 3 contributions (optional) -* Participate in technical discussions - -==== Becoming P2 -* 5+ merged PRs in Perimeter 3 -* Demonstrated domain expertise -* Nominated by P1 maintainer -* Consensus approval from P1s - -=== Perimeter 3: Community Contributors - -**Open to Everyone** - -* Self-service sandbox (`sandbox/` directory) -* Learning by doing (no rejection anxiety) -* Pathway to Perimeter 2 - -See link:CONTRIBUTING.adoc[CONTRIBUTING.adoc] for TPCF details. - -== Organizational Structure - -=== Working Groups - -Specialized teams for focus areas: - -[cols="2,2,1"] -|=== -|Working Group |Responsibilities |Lead - -|**Backend** -|Deno server, WASM integration, APIs -|TBD - -|**Frontend** -|ReScript UI, dashboard, governance interface -|TBD - -|**Firmware** -|ESP32-C6, Matter protocol, RISC-V -|TBD - -|**Data & CRDTs** -|TimescaleDB, Automerge, offline-first -|TBD - -|**Community** -|Documentation, onboarding, support -|TBD - -|**Security** -|Vulnerability response, audits, threat modeling -|TBD - -|**Governance** -|Policy, voting, conflict resolution -|TBD -|=== - -**Formation**: Any P1 maintainer can propose new working group (simple majority vote) - -**Meetings**: Asynchronous-first (written proposals), synchronous optional - -=== Advisory Board (Future) - -When project has funding or significant adoption: - -* Domain experts (manufacturing, IoT, economics) -* Community representatives (user organizations) -* Legal/licensing advisors -* No voting power, advisory only - -== Financial Governance - -=== Current Status -Project is unfunded (volunteer-driven). - -=== If Funded (Future) -1. **Transparency**: All financial records public (OpenCollective preferred) -2. **Allocation**: 75% approval via quadratic voting -3. **Priorities**: - - Contributor stipends (>50% of budget) - - Infrastructure costs (hosting, CI/CD, hardware) - - Security audits - - Community events -4. **Prohibited**: No individual salaries >2x median contributor stipend - -=== Funding Sources -See link:FUNDING.yml[FUNDING.yml] for active channels: - -* Individual donations (Liberapay, Open Collective) -* Grants (foundations, government programs) -* Cooperative membership fees (if governance transitions to cooperative) -* Service contracts (support, consulting) - -**Prohibited**: Venture capital, corporate ownership stakes - -== Conflict Resolution - -=== Process - -==== Step 1: Direct Discussion -Parties attempt private resolution (7 days). - -==== Step 2: Mediation -Ombudsperson facilitates discussion (14 days). - -**Ombudsperson**: Rotating role among P1 maintainers (6-month terms). - -==== Step 3: Governance Vote -If unresolved, governance vote (66% approval). - -==== Step 4: External Arbitration -For legal/contractual disputes, binding arbitration (rare). - -=== Code of Conduct Violations - -See link:CODE_OF_CONDUCT.md#enforcement[CODE_OF_CONDUCT.md] for enforcement procedures. - -**Separation**: CoC violations handled by separate committee (not regular governance). - -== Decision Records - -=== Architecture Decision Records (ADRs) - -All architectural changes require ADR in `docs/architecture/adr/`. - -.ADR Template ----- -# ADR-NNN: Title - -**Status**: Proposed | Accepted | Deprecated | Superseded - -**Context**: What is the issue we're addressing? - -**Decision**: What are we doing about it? - -**Consequences**: What are the trade-offs? - -**Alternatives Considered**: What else did we evaluate? ----- - -=== Governance Decision Log - -All governance votes recorded in `docs/governance/decisions/`. - -.Decision Log Format -[source,yaml] ----- -id: GD-2025-001 -date: 2025-11-28 -type: Architecture Decision -proposal: "Adopt CURP consensus for governance" -votes: - - maintainer: alice@example.com - credits_spent: 9 # 3 votes - approve: true - - maintainer: bob@example.com - credits_spent: 4 # 2 votes - approve: true -threshold: 66% -result: Approved (80% approval) ----- - -== Succession Planning - -=== Maintainer Succession - -**Target**: Minimum 5 active P1 maintainers from ≥3 organizations - -**Recruitment**: Annual call for nominations - -**Diversity**: Strive for geographic, organizational, domain diversity - -=== Project Stewardship - -If all P1 maintainers become inactive: - -1. **Automatic Escalation**: P2 contributors inherit P1 responsibilities (temporary) -2. **Emergency Election**: Community votes on new P1 maintainers (simple majority) -3. **Archival**: If no active contributors for 12 months, project archived with clear notice - -=== Fork Rights - -Any contributor can fork project under link:LICENSE.txt[LICENSE.txt] terms: - -* Must preserve attribution (SPDX headers) -* Cannot use "Kaldor IIoT" trademark without permission -* Community may recognize fork as canonical (90% vote) - -== Amendment Process - -This governance document can be amended: - -1. **Proposal**: Any P1 maintainer drafts amendment -2. **Discussion**: 30-day public comment period -3. **Voting**: 75% approval via quadratic voting -4. **Effective Date**: 14 days after approval (allows for objections) - -**Version Control**: All governance changes tracked in Git with rationale in commit messages. - -== Emergency Procedures - -=== Security Incidents -* **Authority**: Security working group + 2 P1 maintainers -* **Timeline**: Immediate action, post-hoc governance review within 7 days -* **Process**: See link:SECURITY.md[SECURITY.md] - -=== Code of Conduct Emergencies -* **Authority**: Ombudsperson + CoC committee -* **Timeline**: 24-hour initial response, 7-day resolution -* **Process**: See link:CODE_OF_CONDUCT.md#enforcement[CODE_OF_CONDUCT.md] - -=== Infrastructure Failures -* **Authority**: Infrastructure working group -* **Timeline**: Immediate triage, 48-hour postmortem -* **Transparency**: Public incident reports (except security-sensitive details) - -== Governance Tooling - -=== Technical Implementation - -[source,typescript] ----- -// scripts/governance/propose.ts -import { Proposal } from "../lib/governance.ts"; - -const proposal = new Proposal({ - title: "Adopt new dependency audit policy", - description: "Require SBOM for all new dependencies", - type: "policy", - threshold: 0.66, // 66% approval -}); - -await proposal.submit(); -// Syncs via CURP to all maintainers (offline-capable) ----- - -[source,typescript] ----- -// scripts/governance/vote.ts -import { vote } from "../lib/governance.ts"; - -await vote({ - proposalId: "GD-2025-001", - credits: 4, // 2 votes (quadratic: 2² = 4) - approve: true, -}); ----- - -=== Offline Voting - -Maintainers can vote offline using CURP: - -[source,bash] ----- -# Sync proposals while online -deno run scripts/governance/sync.ts - -# Go offline, review proposals locally -deno run scripts/governance/list.ts - -# Vote offline (stored in local CRDT) -deno run scripts/governance/vote.ts \ - --proposal GD-2025-001 \ - --credits 4 \ - --approve - -# Reconnect, sync votes (automatic conflict resolution) -deno run scripts/governance/sync.ts ----- - -== Questions & Feedback - -* **Governance Questions**: Open issue with `governance` label -* **Propose Amendment**: Start discussion in governance forum -* **Emergency Contact**: governance@kaldor.community - ---- - -**Document Version**: 1.0.0 + -**Last Updated**: 2025-11-28 + -**Next Review**: 2026-05-28 (6 months) + -**License**: MIT OR Apache-2.0 - -_"Governance is not about control—it's about enabling collective action."_ +_Last updated: 2026-07-18_ diff --git a/GOVERNANCE.md b/GOVERNANCE.md deleted file mode 100644 index e27364c..0000000 --- a/GOVERNANCE.md +++ /dev/null @@ -1,60 +0,0 @@ -# Governance - -## Overview - -This project is governed by the following principles and structures to ensure transparent, inclusive, and effective decision-making. - -## Roles and Responsibilities - -### Maintainers - -Maintainers are responsible for: -- Reviewing and merging pull requests -- Managing releases and versioning -- Ensuring code quality and standards -- Triaging issues and bug reports -- Community engagement and support - -### Contributors - -Contributors are expected to: -- Follow the code of conduct -- Submit well-documented pull requests -- Write tests for new functionality -- Maintain existing tests -- Update documentation as needed - -## Decision Making - -### Minor Changes -- Can be made by any maintainer -- Include bug fixes, documentation updates, dependency updates - -### Major Changes -- Require discussion in issues or pull requests -- Include new features, architectural changes, API changes -- Need approval from at least 2 maintainers - -### Breaking Changes -- Require RFC (Request for Comments) process -- Need approval from majority of maintainers -- Must include migration guide - -## Code of Conduct - -All participants are expected to follow our Code of Conduct. Violations can be reported to the maintainers. - -## Communication - -- **Issues**: For bug reports and feature requests -- **Discussions**: For questions and general discussion -- **Pull Requests**: For code contributions - -## Licensing - -All contributions are made under the terms of the repository's LICENSE file. -By submitting a pull request, you agree to license your contributions accordingly. - ---- - -*Last updated: 2026-07-18* diff --git a/MAINTAINERS.adoc b/MAINTAINERS.adoc index aa23a55..6cb054c 100644 --- a/MAINTAINERS.adoc +++ b/MAINTAINERS.adoc @@ -1,48 +1,220 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Maintainers -:toc: preamble +== Maintainers -This document lists the maintainers of this project and their responsibilities. +This document lists the maintainers of the Kaldor Community +Manufacturing Platform and describes the Tri-Perimeter Contribution +Framework (TPCF). -== Current Maintainers +=== Current Maintainers -[cols="2,3,2",options="header"] +==== Perimeter 1: Core Maintainers (Security-Critical) + +Core maintainers have consensus-based voting rights on security, +governance, and architecture decisions. + +[width="100%",cols="17%,19%,14%,31%,19%",options="header",] +|=== +|Name |GitHub |Role |Focus Areas |Joined +|Hyperpolymath |@Hyperpolymath |Project Lead |Vision, Architecture, +Community |2025-11-22 + +|_[Open for nomination]_ |- |Security Lead |Firmware, Cryptography |- + +|_[Open for nomination]_ |- |Backend Lead |Deno, WASM, OPC UA |- + +|_[Open for nomination]_ |- |Frontend Lead |ReScript, Accessibility |- +|=== + +*Advancement to P1*: Requires 75% community vote (quadratic voting), 6+ +months contribution, 20+ merged PRs, background check for security +roles. + +==== Perimeter 2: Professional Contributors (Vetted) + +Professional contributors have merge rights for feature development +after review. + +[cols=",,,,",options="header",] +|=== +|Name |GitHub |Specialization |Contributions |Joined +|_[Open for applications]_ |- |CRDT/Offline-First |- |- +|_[Open for applications]_ |- |RISC-V Firmware |- |- +|_[Open for applications]_ |- |Matter Protocol |- |- +|_[Open for applications]_ |- |Data Visualization |- |- +|=== + +*Advancement to P2*: Requires 3+ merged PRs in P3, demonstrated +expertise, maintainer endorsement. + +==== Perimeter 3: Community Sandbox (Open) + +All contributors start here. No approval needed for documentation, +examples, bug reports. + +*Current Contributors*: See CONTRIBUTORS.md + +=== Tri-Perimeter Contribution Framework (TPCF) + +==== Perimeter 3: Community Sandbox + +*Access*: Anyone, immediate *Scope*: Low-risk contributions *Examples*: +Documentation, tutorials, bug reports, design mockups *Paths*: - +`+docs/**/*+` - `+examples/**/*+` - `+tutorials/**/*+` - GitHub +Issues/Discussions - Wiki pages + +*Merge Process*: Self-service PR → Automated checks → Maintainer merge +(24-48h) + +==== Perimeter 2: Professional Contributors + +*Access*: Earned through contribution *Scope*: Feature development, +refactoring *Examples*: New features, performance improvements, +architecture changes *Paths*: - `+backend-deno/**/*+` (excluding +security-critical) - `+frontend-rescript/**/*+` - `+wasm-modules/**/*+` +- `+tests/**/*+` + +*Merge Process*: Discussion → PR → 2 maintainer reviews → Tests pass → +Merge + +*Requirements*: - All tests pass (>80% coverage) - Follows coding +standards - Includes documentation - No security regressions + +==== Perimeter 1: Core Maintainers + +*Access*: Consensus vote only *Scope*: Security, cryptography, +governance *Examples*: Firmware updates, consensus algorithms, release +management *Paths*: - `+firmware-riscv/**/*+` - +`+backend-deno/services/consensus.ts+` - +`+backend-deno/middleware/auth.ts+` - Cryptographic implementations - +Release tags + +*Merge Process*: Consensus among P1 → Security audit → Signed commits → +Two-person rule → Canary deployment (24h) → Full deployment + +*Requirements*: - 100% test coverage for security-critical code - +External security review for cryptography - Signed commits (GPG) - No +solo merges (pair programming) + +=== Governance Model + +==== Decision-Making + +[cols=",,",options="header",] +|=== +|Decision Type |Authority |Process +|P3 contribution |Individual maintainer |Review + merge +|P2 feature |2 maintainers |Code review + approval +|P1 security fix |All P1 consensus |Security review + vote +|Architecture change |Community vote |RFC → Discussion → Vote +|Breaking change |Community vote |RFC → Deprecation → Vote +|Perimeter advancement |Quadratic vote |Nomination → Community vote +|Project direction |Quadratic vote |Annual roadmap vote |=== -| Name | Role | Contact -| Jonathan D.A. Jewell -| Lead Maintainer -| https://github.com/hyperpolymath[@hyperpolymath] +==== Voting System + +We use *Quadratic Voting* for major decisions: + +* Each community member gets voice credits (based on contribution) +* Votes cost credits squared (1 vote = 1 credit, 2 votes = 4 credits, +etc.) +* Prevents majority tyranny while respecting expertise +* Calculated via CURP consensus protocol + +==== Community Roles + +Beyond TPCF perimeters: + +[width="100%",cols="19%,48%,33%",options="header",] |=== +|Role |Responsibility |Selection +|*Community Steward* |Facilitates discussions, mediates conflicts +|Community election (annual) + +|*Documentation Lead* |Maintains wikis, tutorials, API docs |Volunteer + +P2 approval + +|*Security Coordinator* |Triages security reports, coordinates +disclosure |P1 appointment + +|*Release Manager* |Manages release process, changelogs |P1 rotation +(quarterly) + +|*Event Organizer* |Community calls, workshops, conferences |Volunteer +|=== + +=== Code Ownership + +==== CODEOWNERS File + +The `+.github/CODEOWNERS+` file specifies mandatory reviewers: + +.... +# Global (all files require at least 1 P1 review) +* @Hyperpolymath + +# Security-critical (require all P1 consensus) +/firmware-riscv/ @Hyperpolymath +/backend-deno/services/consensus.ts @Hyperpolymath +/backend-deno/middleware/auth.ts @Hyperpolymath +/.github/workflows/ @Hyperpolymath + +# Documentation (any P2+ can merge) +/docs/ @Hyperpolymath +/wiki/ @Hyperpolymath +/examples/ @Hyperpolymath +.... + +=== Conflict Resolution + +==== Process + +[arabic] +. *Discussion*: Attempt to reach consensus through discussion +. *Mediation*: Community Steward facilitates neutral mediation +. *Vote*: If no consensus after 2 weeks, initiate quadratic vote +. *Escalation*: For serious disputes, external arbitration (Software +Freedom Conservancy) + +==== Code of Conduct Enforcement + +See CODE_OF_CONDUCT.md for full policy. -== Responsibilities +*Enforcement Team*: Rotating panel of 3 members (1 from each perimeter) +*Contact*: conduct@kaldor.community *Appeals*: External review board -Maintainers are responsible for: +=== Succession Planning -* Reviewing and merging pull requests -* Triaging issues and feature requests -* Ensuring code quality and security standards -* Managing releases and versioning -* Upholding the project's code of conduct +To ensure project continuity: -== Becoming a Maintainer +[arabic] +. *Bus Factor*: Maintain minimum 3 maintainers per perimeter +. *Knowledge Transfer*: Pair programming, documentation, shadowing +. *Backup Maintainers*: Each P1 role has designated backup +. *Emergency Protocol*: If maintainer unreachable for 30 days, backup +assumes role +. *Graceful Exit*: Maintainers stepping down train replacement (3-month +overlap) -Contributors who demonstrate: +=== Contact -* Consistent, high-quality contributions -* Understanding of the project's goals and standards -* Constructive participation in discussions -* Commitment to the project's long-term health +* *Public*: GitHub Issues/Discussions +* *Maintainers*: maintainers@kaldor.community +* *Security*: security@kaldor.community +* *Governance*: governance@kaldor.community +* *Matrix*: `+#kaldor-maintainers:matrix.org+` (P1+ only) -May be invited to become maintainers at the discretion of existing maintainers. +=== Acknowledgments -== Decision Making +This governance model draws inspiration from: -* Routine decisions (bug fixes, minor improvements) can be made by any maintainer -* Significant changes require discussion and consensus among maintainers -* Breaking changes or major features should be discussed in issues before implementation +* *Rust RFC Process*: Structured decision-making +* *Node.js TSC*: Technical Steering Committee model +* *Apache Software Foundation*: Meritocratic advancement +* *Debian Project*: Democratic governance at scale +* *Wikipedia*: Graduated editor privileges +* *Platform Cooperatives*: Distributed ownership -== Contact +''''' -For questions about project governance, open an issue or contact the maintainers listed above. +*Last Updated*: 2025-11-22 *Version*: 1.0.0 *TPCF Framework*: v1.0 +(Rhodium Standard Repository) diff --git a/MAINTAINERS.md b/MAINTAINERS.md deleted file mode 100644 index c56c755..0000000 --- a/MAINTAINERS.md +++ /dev/null @@ -1,205 +0,0 @@ - -# Maintainers - -This document lists the maintainers of the Kaldor Community Manufacturing Platform and describes the Tri-Perimeter Contribution Framework (TPCF). - -## Current Maintainers - -### Perimeter 1: Core Maintainers (Security-Critical) - -Core maintainers have consensus-based voting rights on security, governance, and architecture decisions. - -| Name | GitHub | Role | Focus Areas | Joined | -|------|--------|------|-------------|--------| -| Hyperpolymath | @Hyperpolymath | Project Lead | Vision, Architecture, Community | 2025-11-22 | -| *[Open for nomination]* | - | Security Lead | Firmware, Cryptography | - | -| *[Open for nomination]* | - | Backend Lead | Deno, WASM, OPC UA | - | -| *[Open for nomination]* | - | Frontend Lead | ReScript, Accessibility | - | - -**Advancement to P1**: Requires 75% community vote (quadratic voting), 6+ months contribution, 20+ merged PRs, background check for security roles. - -### Perimeter 2: Professional Contributors (Vetted) - -Professional contributors have merge rights for feature development after review. - -| Name | GitHub | Specialization | Contributions | Joined | -|------|--------|----------------|---------------|--------| -| *[Open for applications]* | - | CRDT/Offline-First | - | - | -| *[Open for applications]* | - | RISC-V Firmware | - | - | -| *[Open for applications]* | - | Matter Protocol | - | - | -| *[Open for applications]* | - | Data Visualization | - | - | - -**Advancement to P2**: Requires 3+ merged PRs in P3, demonstrated expertise, maintainer endorsement. - -### Perimeter 3: Community Sandbox (Open) - -All contributors start here. No approval needed for documentation, examples, bug reports. - -**Current Contributors**: See [CONTRIBUTORS.md](CONTRIBUTORS.md) - -## Tri-Perimeter Contribution Framework (TPCF) - -### Perimeter 3: Community Sandbox - -**Access**: Anyone, immediate -**Scope**: Low-risk contributions -**Examples**: Documentation, tutorials, bug reports, design mockups -**Paths**: -- `docs/**/*` -- `examples/**/*` -- `tutorials/**/*` -- GitHub Issues/Discussions -- Wiki pages - -**Merge Process**: Self-service PR → Automated checks → Maintainer merge (24-48h) - -### Perimeter 2: Professional Contributors - -**Access**: Earned through contribution -**Scope**: Feature development, refactoring -**Examples**: New features, performance improvements, architecture changes -**Paths**: -- `backend-deno/**/*` (excluding security-critical) -- `frontend-rescript/**/*` -- `wasm-modules/**/*` -- `tests/**/*` - -**Merge Process**: Discussion → PR → 2 maintainer reviews → Tests pass → Merge - -**Requirements**: -- All tests pass (>80% coverage) -- Follows coding standards -- Includes documentation -- No security regressions - -### Perimeter 1: Core Maintainers - -**Access**: Consensus vote only -**Scope**: Security, cryptography, governance -**Examples**: Firmware updates, consensus algorithms, release management -**Paths**: -- `firmware-riscv/**/*` -- `backend-deno/services/consensus.ts` -- `backend-deno/middleware/auth.ts` -- Cryptographic implementations -- Release tags - -**Merge Process**: Consensus among P1 → Security audit → Signed commits → Two-person rule → Canary deployment (24h) → Full deployment - -**Requirements**: -- 100% test coverage for security-critical code -- External security review for cryptography -- Signed commits (GPG) -- No solo merges (pair programming) - -## Governance Model - -### Decision-Making - -| Decision Type | Authority | Process | -|---------------|-----------|---------| -| P3 contribution | Individual maintainer | Review + merge | -| P2 feature | 2 maintainers | Code review + approval | -| P1 security fix | All P1 consensus | Security review + vote | -| Architecture change | Community vote | RFC → Discussion → Vote | -| Breaking change | Community vote | RFC → Deprecation → Vote | -| Perimeter advancement | Quadratic vote | Nomination → Community vote | -| Project direction | Quadratic vote | Annual roadmap vote | - -### Voting System - -We use **Quadratic Voting** for major decisions: - -- Each community member gets voice credits (based on contribution) -- Votes cost credits squared (1 vote = 1 credit, 2 votes = 4 credits, etc.) -- Prevents majority tyranny while respecting expertise -- Calculated via CURP consensus protocol - -### Community Roles - -Beyond TPCF perimeters: - -| Role | Responsibility | Selection | -|------|----------------|-----------| -| **Community Steward** | Facilitates discussions, mediates conflicts | Community election (annual) | -| **Documentation Lead** | Maintains wikis, tutorials, API docs | Volunteer + P2 approval | -| **Security Coordinator** | Triages security reports, coordinates disclosure | P1 appointment | -| **Release Manager** | Manages release process, changelogs | P1 rotation (quarterly) | -| **Event Organizer** | Community calls, workshops, conferences | Volunteer | - -## Code Ownership - -### CODEOWNERS File - -The `.github/CODEOWNERS` file specifies mandatory reviewers: - -``` -# Global (all files require at least 1 P1 review) -* @Hyperpolymath - -# Security-critical (require all P1 consensus) -/firmware-riscv/ @Hyperpolymath -/backend-deno/services/consensus.ts @Hyperpolymath -/backend-deno/middleware/auth.ts @Hyperpolymath -/.github/workflows/ @Hyperpolymath - -# Documentation (any P2+ can merge) -/docs/ @Hyperpolymath -/wiki/ @Hyperpolymath -/examples/ @Hyperpolymath -``` - -## Conflict Resolution - -### Process - -1. **Discussion**: Attempt to reach consensus through discussion -2. **Mediation**: Community Steward facilitates neutral mediation -3. **Vote**: If no consensus after 2 weeks, initiate quadratic vote -4. **Escalation**: For serious disputes, external arbitration (Software Freedom Conservancy) - -### Code of Conduct Enforcement - -See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for full policy. - -**Enforcement Team**: Rotating panel of 3 members (1 from each perimeter) -**Contact**: conduct@kaldor.community -**Appeals**: External review board - -## Succession Planning - -To ensure project continuity: - -1. **Bus Factor**: Maintain minimum 3 maintainers per perimeter -2. **Knowledge Transfer**: Pair programming, documentation, shadowing -3. **Backup Maintainers**: Each P1 role has designated backup -4. **Emergency Protocol**: If maintainer unreachable for 30 days, backup assumes role -5. **Graceful Exit**: Maintainers stepping down train replacement (3-month overlap) - -## Contact - -- **Public**: GitHub Issues/Discussions -- **Maintainers**: maintainers@kaldor.community -- **Security**: security@kaldor.community -- **Governance**: governance@kaldor.community -- **Matrix**: `#kaldor-maintainers:matrix.org` (P1+ only) - -## Acknowledgments - -This governance model draws inspiration from: - -- **Rust RFC Process**: Structured decision-making -- **Node.js TSC**: Technical Steering Committee model -- **Apache Software Foundation**: Meritocratic advancement -- **Debian Project**: Democratic governance at scale -- **Wikipedia**: Graduated editor privileges -- **Platform Cooperatives**: Distributed ownership - ---- - -**Last Updated**: 2025-11-22 -**Version**: 1.0.0 -**TPCF Framework**: v1.0 (Rhodium Standard Repository) diff --git a/MANUAL_REVIEW_NEEDED.adoc b/MANUAL_REVIEW_NEEDED.adoc new file mode 100644 index 0000000..c5de166 --- /dev/null +++ b/MANUAL_REVIEW_NEEDED.adoc @@ -0,0 +1,20 @@ +== ⚠️ Large Codebase - Manual Review Required + +This repository has substantial TS/JS code (>5000 lines). + +=== Challenges + +* Large codebase requires careful migration planning +* May have complex type dependencies +* Third-party libraries may need bindings + +=== Recommended Approach + +[arabic] +. *Audit*: Catalog all TS/JS files and dependencies +. *Prioritize*: Identify core vs peripheral code +. *Incremental*: Convert module by module +. *Test*: Ensure each converted module works +. *WASM*: Consider for heavy computation sections + +=== Do NOT attempt automated bulk conversion. diff --git a/MANUAL_REVIEW_NEEDED.md b/MANUAL_REVIEW_NEEDED.md deleted file mode 100644 index 6f78d7b..0000000 --- a/MANUAL_REVIEW_NEEDED.md +++ /dev/null @@ -1,21 +0,0 @@ - -# ⚠️ Large Codebase - Manual Review Required - -This repository has substantial TS/JS code (>5000 lines). - -## Challenges -- Large codebase requires careful migration planning -- May have complex type dependencies -- Third-party libraries may need bindings - -## Recommended Approach -1. **Audit**: Catalog all TS/JS files and dependencies -2. **Prioritize**: Identify core vs peripheral code -3. **Incremental**: Convert module by module -4. **Test**: Ensure each converted module works -5. **WASM**: Consider for heavy computation sections - -## Do NOT attempt automated bulk conversion. diff --git a/REVERSIBILITY.md b/REVERSIBILITY.adoc similarity index 51% rename from REVERSIBILITY.md rename to REVERSIBILITY.adoc index f722ddc..dfeab57 100644 --- a/REVERSIBILITY.md +++ b/REVERSIBILITY.adoc @@ -1,90 +1,98 @@ - -# REVERSIBILITY.md +== REVERSIBILITY.md - +*Version*: 1.0.0 *Last Updated*: 2025-11-28 -**Version**: 1.0.0 -**Last Updated**: 2025-11-28 +=== Purpose -## Purpose +Kaldor IIoT is committed to *reversible decisions* and *low-stakes +experimentation*. Every operation can be undone, every decision can be +revisited with new evidence, and no contributor should fear permanent +mistakes. -Kaldor IIoT is committed to **reversible decisions** and **low-stakes experimentation**. Every operation can be undone, every decision can be revisited with new evidence, and no contributor should fear permanent mistakes. +This document provides procedures for undoing changes, reverting +decisions, and safely experimenting. -This document provides procedures for undoing changes, reverting decisions, and safely experimenting. +=== Principles -## Principles +[arabic] +. *No Permanent Mistakes*: All changes are reversible via version +control, backups, or governance votes +. *Safe Experimentation*: Perimeter 3 (sandbox) encourages learning +without consequences +. *Clear Undo Paths*: Every operation documents its reversal procedure +. *Blameless Culture*: Mistakes are learning opportunities, not grounds +for punishment +. *Right to Disconnect*: Contributors can step back without penalty -1. **No Permanent Mistakes**: All changes are reversible via version control, backups, or governance votes -2. **Safe Experimentation**: Perimeter 3 (sandbox) encourages learning without consequences -3. **Clear Undo Paths**: Every operation documents its reversal procedure -4. **Blameless Culture**: Mistakes are learning opportunities, not grounds for punishment -5. **Right to Disconnect**: Contributors can step back without penalty +=== Code Reversibility -## Code Reversibility +==== Git Operations -### Git Operations +===== Undo Last Commit (Not Pushed) -#### Undo Last Commit (Not Pushed) - -```bash +[source,bash] +---- # Keep changes, undo commit git reset --soft HEAD~1 # Discard changes entirely git reset --hard HEAD~1 -``` +---- -#### Revert Pushed Commit +===== Revert Pushed Commit -```bash +[source,bash] +---- # Create new commit that undoes changes git revert git push origin main -``` +---- -#### Restore Deleted File +===== Restore Deleted File -```bash +[source,bash] +---- # Find when file was deleted git log --all --full-history -- path/to/file # Restore from specific commit git checkout ^ -- path/to/file -``` +---- -#### Undo Merge +===== Undo Merge -```bash +[source,bash] +---- # Find merge commit git log --oneline --graph # Revert merge (use -m 1 for parent branch) git revert -m 1 -``` +---- -### Sandbox Cleanup +==== Sandbox Cleanup -Perimeter 3 (sandbox/) has automated cleanup via RVC (Robot Vacuum Cleaner): +Perimeter 3 (sandbox/) has automated cleanup via RVC (Robot Vacuum +Cleaner): -```bash +[source,bash] +---- # Remove abandoned experiments (>90 days inactive) just sandbox-clean # Restore accidentally deleted sandbox git reflog git checkout -``` +---- -## Data Reversibility +=== Data Reversibility -### Database Operations +==== Database Operations -#### Rollback Migration +===== Rollback Migration -```bash +[source,bash] +---- # List migrations just db-migrations @@ -93,43 +101,47 @@ just db-rollback # Rollback to specific version just db-rollback --to 20250101120000 -``` +---- -#### Point-in-Time Recovery (Production) +===== Point-in-Time Recovery (Production) -```bash +[source,bash] +---- # TimescaleDB continuous backups # Restore to 2 hours ago just db-restore --timestamp "2025-11-28 14:00:00" -``` +---- -#### CRDT Conflict Resolution +===== CRDT Conflict Resolution CRDTs automatically resolve conflicts, but you can inspect history: -```bash +[source,bash] +---- # View Automerge change history deno run scripts/crdt/history.ts --doc # Restore to previous state (creates new state, preserves history) deno run scripts/crdt/restore.ts --doc --timestamp "2025-11-28T14:00:00Z" -``` +---- -### Configuration Reversibility +==== Configuration Reversibility -#### Environment Variables +===== Environment Variables -```bash +[source,bash] +---- # Backup current .env cp .env .env.backup.$(date +%Y%m%d) # Restore previous .env cp .env.backup.20251128 .env -``` +---- -#### Nix Configuration +===== Nix Configuration -```bash +[source,bash] +---- # Rollback to previous Nix generation nix-env --rollback @@ -138,21 +150,23 @@ nix-env --list-generations # Switch to specific generation nix-env --switch-generation 42 -``` +---- -## Governance Reversibility +=== Governance Reversibility -### Revisiting Decisions +==== Revisiting Decisions Any governance decision can be revisited if: -1. **New Evidence**: Material facts change since original decision -2. **Unintended Consequences**: Decision had unforeseen negative impacts -3. **Community Consensus**: 66% vote to reconsider +[arabic] +. *New Evidence*: Material facts change since original decision +. *Unintended Consequences*: Decision had unforeseen negative impacts +. *Community Consensus*: 66% vote to reconsider -**Procedure**: +*Procedure*: -```bash +[source,bash] +---- # Propose reconsideration deno run scripts/governance/reconsider.ts \ --decision-id GD-2025-001 \ @@ -160,36 +174,39 @@ deno run scripts/governance/reconsider.ts \ # Vote (same threshold as original decision) # If approved, original decision is marked "superseded" -``` +---- -### Maintainer Decisions +==== Maintainer Decisions Perimeter 1 maintainers can self-correct: -```bash +[source,bash] +---- # Revert approved PR (creates new PR) gh pr create --title "Revert #123: Reason for revert" \ --body "Discovered issue XYZ after merge" # No approval needed for immediate bug fixes # Post-hoc review within 7 days -``` +---- -## Deployment Reversibility +=== Deployment Reversibility -### Rollback Release +==== Rollback Release -```bash +[source,bash] +---- # Rollback to previous version just deploy-rollback # Deploy specific version just deploy --version v1.2.3 -``` +---- -### Blue-Green Deployment +==== Blue-Green Deployment -```bash +[source,bash] +---- # Production runs v2.0.0 (blue) # Deploy v2.1.0 to green environment just deploy-green --version v2.1.0 @@ -202,73 +219,79 @@ just switch-to-green # If issues, instant rollback to blue just switch-to-blue -``` +---- -### Canary Rollback +==== Canary Rollback -```bash +[source,bash] +---- # 10% traffic on v2.1.0 canary just deploy-canary --version v2.1.0 --traffic 10% # Errors detected, rollback immediately just canary-rollback -``` +---- -## Hardware Reversibility +=== Hardware Reversibility -### Firmware Updates +==== Firmware Updates ESP32-C6 firmware supports rollback: -```bash +[source,bash] +---- # OTA update with automatic rollback on boot failure pio run --target upload-ota --environment esp32c6 # If new firmware fails to boot (3 attempts), ESP32 auto-rolls back # Manual rollback: pio run --target upload-ota --environment esp32c6 --upload-port --project-option "firmware_version=v1.0.0" -``` +---- -### Factory Reset +==== Factory Reset -```bash +[source,bash] +---- # Reset ESP32 to factory defaults (preserves backup partition) deno run scripts/firmware/factory-reset.ts --device loom-001 # Restore from backup deno run scripts/firmware/restore.ts --device loom-001 --backup 20251128 -``` +---- -## Community Reversibility +=== Community Reversibility -### Stepping Down +==== Stepping Down Contributors can step back anytime: -```bash +[source,bash] +---- # Announce in governance forum (optional but appreciated) # No minimum notice for Perimeter 2/3 # 4 weeks notice appreciated for Perimeter 1 (see GOVERNANCE.adoc) # Transfer responsibilities just handoff --to alice@example.com -``` +---- -### Rejoining +==== Rejoining Former contributors can return anytime: -- **Perimeter 3**: Immediate (no approval needed) -- **Perimeter 2**: Re-nomination if inactive >12 months -- **Perimeter 1**: Re-election if inactive >6 months +* *Perimeter 3*: Immediate (no approval needed) +* *Perimeter 2*: Re-nomination if inactive >12 months +* *Perimeter 1*: Re-election if inactive >6 months -## Emotional Safety Mechanisms +=== Emotional Safety Mechanisms -### Low-Stakes Contribution +==== Low-Stakes Contribution -**Perimeter 3 (Sandbox)**: Experiments auto-merge if CI passes. No human review = no rejection anxiety. +*Perimeter 3 (Sandbox)*: Experiments auto-merge if CI passes. No human +review = no rejection anxiety. -```bash +[source,bash] +---- # Create sandbox experiment git checkout -b sandbox/my-idea mkdir -p sandbox/my-idea @@ -278,102 +301,109 @@ git push # Auto-merges if tests pass # Can delete anytime, no questions asked -``` +---- -### Reversible Commits +==== Reversible Commits -Commit early, commit often. Commits are cheap, reversible, and aid learning: +Commit early, commit often. Commits are cheap, reversible, and aid +learning: -```bash +[source,bash] +---- # Experimental commit with clear reversibility git commit -m "experiment: trying alternative algorithm [REVERSIBLE]" # Tag helps identify safe-to-revert commits -``` +---- -### Blameless Postmortems +==== Blameless Postmortems When production incidents occur: -1. **Focus on Systems**: What processes failed, not who made mistake -2. **Document Learnings**: Update runbooks, add monitoring -3. **No Punishment**: Mistakes are learning opportunities -4. **Appreciation**: Thank responders for quick resolution +[arabic] +. *Focus on Systems*: What processes failed, not who made mistake +. *Document Learnings*: Update runbooks, add monitoring +. *No Punishment*: Mistakes are learning opportunities +. *Appreciation*: Thank responders for quick resolution -Template: `docs/postmortems/YYYY-MM-DD-incident-title.md` +Template: `+docs/postmortems/YYYY-MM-DD-incident-title.md+` -## Conflict Resolution Reversibility +=== Conflict Resolution Reversibility Code of Conduct enforcement decisions can be appealed: -1. **Internal Appeal**: Ombudsperson reviews (14 days) -2. **Governance Review**: Community vote (66% to overturn) -3. **External Mediation**: Third-party mediator (rare) +[arabic] +. *Internal Appeal*: Ombudsperson reviews (14 days) +. *Governance Review*: Community vote (66% to overturn) +. *External Mediation*: Third-party mediator (rare) -See [CODE_OF_CONDUCT.md#appeals](CODE_OF_CONDUCT.md#appeals) for details. +See CODE_OF_CONDUCT.md#appeals for details. -## Non-Reversible Actions (Rare) +=== Non-Reversible Actions (Rare) Some actions are difficult or impossible to reverse: -### Security Disclosures +==== Security Disclosures -- Published CVEs cannot be unpublished (only corrected) -- Coordinate carefully before disclosure (see [SECURITY.md](SECURITY.md)) +* Published CVEs cannot be unpublished (only corrected) +* Coordinate carefully before disclosure (see SECURITY.md) -### Public Communications +==== Public Communications -- Press releases, blog posts persist via web archives -- Draft carefully, review with 2+ maintainers before publishing +* Press releases, blog posts persist via web archives +* Draft carefully, review with 2+ maintainers before publishing -### Legal Agreements +==== Legal Agreements -- Contracts, license changes may be legally binding -- Require governance vote + legal review +* Contracts, license changes may be legally binding +* Require governance vote + legal review -### Data Deletion (GDPR) +==== Data Deletion (GDPR) -- Right to be forgotten requests are permanent -- Automated backups purged after 90 days +* Right to be forgotten requests are permanent +* Automated backups purged after 90 days -## Undo Checklist +=== Undo Checklist When reverting any change: -- [ ] Document reason for revert (commit message or ADR) -- [ ] Notify affected contributors (GitHub mentions) -- [ ] Update CHANGELOG.md -- [ ] Run full test suite after revert -- [ ] Check for dependent changes that also need reverting -- [ ] Post-mortem if production issue (not for experiments) +* [ ] Document reason for revert (commit message or ADR) +* [ ] Notify affected contributors (GitHub mentions) +* [ ] Update CHANGELOG.md +* [ ] Run full test suite after revert +* [ ] Check for dependent changes that also need reverting +* [ ] Post-mortem if production issue (not for experiments) -## Emergency Undo Procedures +=== Emergency Undo Procedures -### Production Outage +==== Production Outage -```bash +[source,bash] +---- # Immediate rollback authority (no approval needed) # Security WG + 2 P1 maintainers just deploy-rollback # Post-hoc governance review within 7 days -``` +---- -### Security Incident +==== Security Incident -```bash +[source,bash] +---- # Revert compromised code immediately git revert git push origin main --force-with-lease # Force-push permitted ONLY for security incidents # Document in incident report -``` +---- -### Compromised Credentials +==== Compromised Credentials -```bash +[source,bash] +---- # Rotate all secrets immediately just secrets-rotate @@ -381,13 +411,14 @@ just secrets-rotate just audit-access --since 24h # Notify users if data exposed (see SECURITY.md) -``` +---- -## Reversibility Testing +=== Reversibility Testing Regularly test undo procedures: -```bash +[source,bash] +---- # Quarterly disaster recovery drill just dr-drill @@ -396,18 +427,19 @@ just dr-drill # - Firmware rollback # - Deployment rollback # - CRDT conflict resolution -``` +---- -## Questions & Feedback +=== Questions & Feedback -- **Stuck undoing something?**: Open issue with `reversibility` label -- **Propose new undo mechanism**: Start discussion in governance forum -- **Emergency undo assistance**: governance@kaldor.community +* *Stuck undoing something?*: Open issue with `+reversibility+` label +* *Propose new undo mechanism*: Start discussion in governance forum +* *Emergency undo assistance*: governance@kaldor.community ---- +''''' -**Remember**: If you can break it, you can fix it. If you can deploy it, you can rollback it. If you can join, you can leave. **Reversibility enables fearless innovation.** +*Remember*: If you can break it, you can fix it. If you can deploy it, +you can rollback it. If you can join, you can leave. *Reversibility +enables fearless innovation.* -**Last Updated**: 2025-11-28 -**Document Version**: 1.0.0 -**License**: MIT OR Apache-2.0 +*Last Updated*: 2025-11-28 *Document Version*: 1.0.0 *License*: MIT OR +Apache-2.0 diff --git a/RSR_COMPLIANCE.adoc b/RSR_COMPLIANCE.adoc new file mode 100644 index 0000000..7a92977 --- /dev/null +++ b/RSR_COMPLIANCE.adoc @@ -0,0 +1,255 @@ +== RSR Framework Compliance Report + +== Kaldor Community Manufacturing Platform + +*Date*: 2025-11-22 *Version*: 2.0.0 *Target Compliance Level*: Gold +*Current Compliance Level*: Bronze (Partial) + +=== RSR 11-Category Audit + +==== 1. Type Safety ⚠️ PARTIAL + +*Current State*: Mixed - ✅ ReScript frontend (sound type system) - ✅ +Deno backend (TypeScript with strict mode) - ⚠️ Firmware (C++ - no +formal verification) - ❌ Analytics (Python - dynamic typing) + +*Gold Level Requirements*: - [ ] All components use sound type systems - +[ ] No `+any+` types in TypeScript/Deno - [ ] Formal verification for +critical paths - [ ] Property-based testing + +*Actions Required*: 1. Convert Python analytics to Rust or OCaml 2. Add +SPARK Ada for firmware critical sections 3. Enable +`+deno check --strict+` everywhere 4. Add Deno’s `+@ts-strict+` +decorators + +''''' + +==== 2. Memory Safety ⚠️ PARTIAL + +*Current State*: Mixed - ✅ Deno (garbage collected, safe) - ✅ ReScript +(garbage collected, safe) - ⚠️ Firmware (C++ with manual memory +management) - ❌ No unsafe block auditing + +*Gold Level Requirements*: - [ ] Zero unsafe blocks (or audited + +justified) - [ ] No manual memory management in critical paths - [ ] +AddressSanitizer/Valgrind clean - [ ] Ownership model enforced + +*Actions Required*: 1. Rewrite firmware in Rust (zero unsafe blocks) 2. +Add memory sanitizer checks to CI/CD 3. Document all memory allocation +patterns + +''''' + +==== 3. Offline-First ❌ FAILED + +*Current State*: Heavy cloud dependencies - ❌ Requires internet for +MQTT broker - ❌ Database requires network connection - ❌ Frontend +assumes API availability - ❌ No local-first CRDT implementation + +*Gold Level Requirements*: - [ ] Works completely air-gapped - [ ] Local +database replication (CRDTs) - [ ] P2P mesh networking fallback - [ ] +Service Worker for offline frontend + +*Actions Required*: 1. Implement CRDT-based local-first database +(Automerge) 2. Add Matter Thread mesh for offline operation 3. Implement +Service Worker with offline cache 4. Add local DenoKV for edge caching +5. Build P2P sync protocol (Hypercore, IPFS, or custom) + +''''' + +==== 4. Documentation ⚠️ PARTIAL + +*Current State*: Good but incomplete - ✅ README.md - ✅ ARCHITECTURE.md +- ✅ User manual - ❌ Missing: SECURITY.md - ❌ Missing: CONTRIBUTING.md +- ❌ Missing: CODE_OF_CONDUCT.md - ❌ Missing: MAINTAINERS.md - ❌ +Missing: CHANGELOG.md + +*Gold Level Requirements*: - [ ] All standard files present - [ ] API +documentation (100% coverage) - [ ] Architecture Decision Records (ADRs) +- [ ] .well-known/ directory + +*Actions Required*: 1. Add missing governance documents 2. Create +.well-known/ directory 3. Generate comprehensive API docs 4. Add ADR +directory + +''''' + +==== 5. Build Reproducibility ❌ FAILED + +*Current State*: Docker only - ✅ Docker Compose - ❌ No Nix flake - ❌ +No deterministic builds - ❌ No build hash verification + +*Gold Level Requirements*: - [ ] Nix flake.nix with locked dependencies +- [ ] Reproducible builds (bit-for-bit) - [ ] SBOM (Software Bill of +Materials) - [ ] Signed releases + +*Actions Required*: 1. Create flake.nix for entire project 2. Add Nix +development environment 3. Generate SBOM with CycloneDX 4. Implement +reproducible Docker builds 5. Add GPG signing for releases + +''''' + +==== 6. Testing ⚠️ PARTIAL + +*Current State*: Some tests - ✅ Backend unit tests (partial) - ❌ No +integration tests - ❌ No property-based tests - ❌ No mutation testing +- ❌ Coverage < 80% + +*Gold Level Requirements*: - [ ] 100% test pass rate - [ ] >80% code +coverage - [ ] Property-based testing (QuickCheck) - [ ] Mutation +testing - [ ] Fuzz testing for parsers + +*Actions Required*: 1. Add comprehensive test suite 2. Implement +property-based tests with fast-check 3. Add mutation testing with +Stryker 4. Achieve 80%+ coverage 5. Add fuzz testing for file parsers + +''''' + +==== 7. TPCF (Tri-Perimeter Framework) ❌ NOT IMPLEMENTED + +*Current State*: No perimeter system - ❌ No perimeter definitions - ❌ +No graduated contribution model - ❌ No MAINTAINERS.md with perimeters + +*Gold Level Requirements*: - [ ] Three perimeters defined +(Core/Professional/Community) - [ ] Clear access control per perimeter - +[ ] Documented contribution paths - [ ] Automated perimeter enforcement + +*Actions Required*: 1. Define three perimeters for Kaldor project 2. +Create MAINTAINERS.md with perimeter assignments 3. Implement automated +checks for perimeter violations 4. Document contribution graduation +process + +''''' + +==== 8. Licensing ⚠️ PARTIAL + +*Current State*: Mixed licenses - ✅ License files present - ⚠️ Not +using Palimpsest License - ❌ No license verification in CI + +*Gold Level Requirements*: - [ ] Palimpsest v0.8 dual-license +(MIT/Apache-2.0 fallback) - [ ] All dependencies license-compatible - [ +] REUSE.software compliant - [ ] License headers in all files + +*Actions Required*: 1. Adopt Palimpsest License v0.8 2. Add license +headers to all source files 3. Run REUSE linter in CI/CD 4. Create +LICENSE.txt with full text 5. Add license-checker to build + +''''' + +==== 9. Security ❌ INCOMPLETE + +*Current State*: Basic security - ✅ JWT authentication - ✅ Input +validation - ❌ No SECURITY.md - ❌ No security.txt (RFC 9116) - ❌ No +dependency scanning - ❌ No CVE monitoring + +*Gold Level Requirements*: - [ ] SECURITY.md with disclosure policy - [ +] .well-known/security.txt (RFC 9116) - [ ] Automated dependency +scanning - [ ] Regular security audits - [ ] Signed commits enforcement + +*Actions Required*: 1. Create SECURITY.md with responsible disclosure 2. +Add .well-known/security.txt 3. Implement Dependabot/Renovate 4. Add +OWASP dependency checker 5. Enable signed commits requirement + +''''' + +==== 10. Multi-Language Verification (iSOS) ❌ NOT IMPLEMENTED + +*Current State*: No cross-language verification - ❌ No formal contracts +at FFI boundaries - ❌ No WASM sandboxing verification - ❌ No +compositional correctness proofs + +*Gold Level Requirements*: - [ ] FFI contracts verified - [ ] WASM +module sandboxing - [ ] Type-safe language boundaries - [ ] Formal +proofs for critical components + +*Actions Required*: 1. Add WASM sandboxing with wasmtime 2. Define FFI +contracts with wit-bindgen 3. Add SPARK Ada for firmware critical +sections 4. Implement boundary type checking + +''''' + +==== 11. Offline-First State Management (CRDTs) ❌ NOT IMPLEMENTED + +*Current State*: Client-server only - ❌ No CRDT implementation - ❌ No +conflict-free replication - ❌ No P2P sync + +*Gold Level Requirements*: - [ ] CRDT-based data structures - [ ] +Automerge or Yjs integration - [ ] Conflict-free collaborative editing - +[ ] Eventual consistency guarantees + +*Actions Required*: 1. Implement Automerge for production data 2. Add +Y-CRDT for collaborative editing 3. Build sync protocol with libp2p 4. +Add offline queue with sync reconciliation + +''''' + +=== Compliance Summary + +[cols=",,,",options="header",] +|=== +|Category |Current |Target |Gap +|Type Safety |Bronze |Gold |Medium +|Memory Safety |Bronze |Gold |Medium +|Offline-First |None |Gold |*Critical* +|Documentation |Bronze |Gold |Low +|Build Reproducibility |None |Gold |*Critical* +|Testing |Bronze |Gold |Medium +|TPCF |None |Gold |*Critical* +|Licensing |Bronze |Gold |Low +|Security |Bronze |Gold |Medium +|iSOS |None |Gold |High +|CRDTs |None |Gold |*Critical* +|=== + +*Overall Compliance*: 35% (Bronze/Partial) *Target*: 100% (Gold) + +''''' + +=== Priority Implementation Order + +==== Phase 1: Critical Foundations (Week 1-2) + +[arabic] +. *Offline-First Architecture* - CRDT implementation +. *TPCF Setup* - Define perimeters, MAINTAINERS.md +. *Build Reproducibility* - Nix flake +. *Documentation* - All missing governance docs + +==== Phase 2: Type & Memory Safety (Week 3-4) + +[arabic, start=5] +. *Rewrite firmware in Rust* - Memory safety +. *Convert analytics to Rust/OCaml* - Type safety +. *Add formal verification* - SPARK Ada critical sections + +==== Phase 3: Testing & Security (Week 5-6) + +[arabic, start=8] +. *Comprehensive test suite* - >80% coverage +. *Security audit* - SECURITY.md, security.txt +. *Dependency scanning* - Automated CVE checks + +==== Phase 4: Polish & Verification (Week 7-8) + +[arabic, start=11] +. *iSOS implementation* - FFI contracts +. *License compliance* - Palimpsest adoption +. *Final RSR verification* - rhodium-init self-check + +''''' + +=== Immediate Actions (Next 24 Hours) + +[arabic] +. Create all missing governance documents +. Set up .well-known/ directory +. Implement basic CRDT support +. Add Nix flake.nix +. Define TPCF perimeters +. Add Palimpsest License + +''''' + +*Next Update*: After Phase 1 completion *Responsible*: Claude (automated +implementation) *Review*: Human approval required for perimeter +assignments diff --git a/RSR_COMPLIANCE.md b/RSR_COMPLIANCE.md deleted file mode 100644 index a768c7b..0000000 --- a/RSR_COMPLIANCE.md +++ /dev/null @@ -1,314 +0,0 @@ - -# RSR Framework Compliance Report -# Kaldor Community Manufacturing Platform - -**Date**: 2025-11-22 -**Version**: 2.0.0 -**Target Compliance Level**: Gold -**Current Compliance Level**: Bronze (Partial) - -## RSR 11-Category Audit - -### 1. Type Safety ⚠️ PARTIAL -**Current State**: Mixed -- ✅ ReScript frontend (sound type system) -- ✅ Deno backend (TypeScript with strict mode) -- ⚠️ Firmware (C++ - no formal verification) -- ❌ Analytics (Python - dynamic typing) - -**Gold Level Requirements**: -- [ ] All components use sound type systems -- [ ] No `any` types in TypeScript/Deno -- [ ] Formal verification for critical paths -- [ ] Property-based testing - -**Actions Required**: -1. Convert Python analytics to Rust or OCaml -2. Add SPARK Ada for firmware critical sections -3. Enable `deno check --strict` everywhere -4. Add Deno's `@ts-strict` decorators - ---- - -### 2. Memory Safety ⚠️ PARTIAL -**Current State**: Mixed -- ✅ Deno (garbage collected, safe) -- ✅ ReScript (garbage collected, safe) -- ⚠️ Firmware (C++ with manual memory management) -- ❌ No unsafe block auditing - -**Gold Level Requirements**: -- [ ] Zero unsafe blocks (or audited + justified) -- [ ] No manual memory management in critical paths -- [ ] AddressSanitizer/Valgrind clean -- [ ] Ownership model enforced - -**Actions Required**: -1. Rewrite firmware in Rust (zero unsafe blocks) -2. Add memory sanitizer checks to CI/CD -3. Document all memory allocation patterns - ---- - -### 3. Offline-First ❌ FAILED -**Current State**: Heavy cloud dependencies -- ❌ Requires internet for MQTT broker -- ❌ Database requires network connection -- ❌ Frontend assumes API availability -- ❌ No local-first CRDT implementation - -**Gold Level Requirements**: -- [ ] Works completely air-gapped -- [ ] Local database replication (CRDTs) -- [ ] P2P mesh networking fallback -- [ ] Service Worker for offline frontend - -**Actions Required**: -1. Implement CRDT-based local-first database (Automerge) -2. Add Matter Thread mesh for offline operation -3. Implement Service Worker with offline cache -4. Add local DenoKV for edge caching -5. Build P2P sync protocol (Hypercore, IPFS, or custom) - ---- - -### 4. Documentation ⚠️ PARTIAL -**Current State**: Good but incomplete -- ✅ README.md -- ✅ ARCHITECTURE.md -- ✅ User manual -- ❌ Missing: SECURITY.md -- ❌ Missing: CONTRIBUTING.md -- ❌ Missing: CODE_OF_CONDUCT.md -- ❌ Missing: MAINTAINERS.md -- ❌ Missing: CHANGELOG.md - -**Gold Level Requirements**: -- [ ] All standard files present -- [ ] API documentation (100% coverage) -- [ ] Architecture Decision Records (ADRs) -- [ ] .well-known/ directory - -**Actions Required**: -1. Add missing governance documents -2. Create .well-known/ directory -3. Generate comprehensive API docs -4. Add ADR directory - ---- - -### 5. Build Reproducibility ❌ FAILED -**Current State**: Docker only -- ✅ Docker Compose -- ❌ No Nix flake -- ❌ No deterministic builds -- ❌ No build hash verification - -**Gold Level Requirements**: -- [ ] Nix flake.nix with locked dependencies -- [ ] Reproducible builds (bit-for-bit) -- [ ] SBOM (Software Bill of Materials) -- [ ] Signed releases - -**Actions Required**: -1. Create flake.nix for entire project -2. Add Nix development environment -3. Generate SBOM with CycloneDX -4. Implement reproducible Docker builds -5. Add GPG signing for releases - ---- - -### 6. Testing ⚠️ PARTIAL -**Current State**: Some tests -- ✅ Backend unit tests (partial) -- ❌ No integration tests -- ❌ No property-based tests -- ❌ No mutation testing -- ❌ Coverage < 80% - -**Gold Level Requirements**: -- [ ] 100% test pass rate -- [ ] >80% code coverage -- [ ] Property-based testing (QuickCheck) -- [ ] Mutation testing -- [ ] Fuzz testing for parsers - -**Actions Required**: -1. Add comprehensive test suite -2. Implement property-based tests with fast-check -3. Add mutation testing with Stryker -4. Achieve 80%+ coverage -5. Add fuzz testing for file parsers - ---- - -### 7. TPCF (Tri-Perimeter Framework) ❌ NOT IMPLEMENTED -**Current State**: No perimeter system -- ❌ No perimeter definitions -- ❌ No graduated contribution model -- ❌ No MAINTAINERS.md with perimeters - -**Gold Level Requirements**: -- [ ] Three perimeters defined (Core/Professional/Community) -- [ ] Clear access control per perimeter -- [ ] Documented contribution paths -- [ ] Automated perimeter enforcement - -**Actions Required**: -1. Define three perimeters for Kaldor project -2. Create MAINTAINERS.md with perimeter assignments -3. Implement automated checks for perimeter violations -4. Document contribution graduation process - ---- - -### 8. Licensing ⚠️ PARTIAL -**Current State**: Mixed licenses -- ✅ License files present -- ⚠️ Not using Palimpsest License -- ❌ No license verification in CI - -**Gold Level Requirements**: -- [ ] Palimpsest v0.8 dual-license (MIT/Apache-2.0 fallback) -- [ ] All dependencies license-compatible -- [ ] REUSE.software compliant -- [ ] License headers in all files - -**Actions Required**: -1. Adopt Palimpsest License v0.8 -2. Add license headers to all source files -3. Run REUSE linter in CI/CD -4. Create LICENSE.txt with full text -5. Add license-checker to build - ---- - -### 9. Security ❌ INCOMPLETE -**Current State**: Basic security -- ✅ JWT authentication -- ✅ Input validation -- ❌ No SECURITY.md -- ❌ No security.txt (RFC 9116) -- ❌ No dependency scanning -- ❌ No CVE monitoring - -**Gold Level Requirements**: -- [ ] SECURITY.md with disclosure policy -- [ ] .well-known/security.txt (RFC 9116) -- [ ] Automated dependency scanning -- [ ] Regular security audits -- [ ] Signed commits enforcement - -**Actions Required**: -1. Create SECURITY.md with responsible disclosure -2. Add .well-known/security.txt -3. Implement Dependabot/Renovate -4. Add OWASP dependency checker -5. Enable signed commits requirement - ---- - -### 10. Multi-Language Verification (iSOS) ❌ NOT IMPLEMENTED -**Current State**: No cross-language verification -- ❌ No formal contracts at FFI boundaries -- ❌ No WASM sandboxing verification -- ❌ No compositional correctness proofs - -**Gold Level Requirements**: -- [ ] FFI contracts verified -- [ ] WASM module sandboxing -- [ ] Type-safe language boundaries -- [ ] Formal proofs for critical components - -**Actions Required**: -1. Add WASM sandboxing with wasmtime -2. Define FFI contracts with wit-bindgen -3. Add SPARK Ada for firmware critical sections -4. Implement boundary type checking - ---- - -### 11. Offline-First State Management (CRDTs) ❌ NOT IMPLEMENTED -**Current State**: Client-server only -- ❌ No CRDT implementation -- ❌ No conflict-free replication -- ❌ No P2P sync - -**Gold Level Requirements**: -- [ ] CRDT-based data structures -- [ ] Automerge or Yjs integration -- [ ] Conflict-free collaborative editing -- [ ] Eventual consistency guarantees - -**Actions Required**: -1. Implement Automerge for production data -2. Add Y-CRDT for collaborative editing -3. Build sync protocol with libp2p -4. Add offline queue with sync reconciliation - ---- - -## Compliance Summary - -| Category | Current | Target | Gap | -|----------|---------|--------|-----| -| Type Safety | Bronze | Gold | Medium | -| Memory Safety | Bronze | Gold | Medium | -| Offline-First | None | Gold | **Critical** | -| Documentation | Bronze | Gold | Low | -| Build Reproducibility | None | Gold | **Critical** | -| Testing | Bronze | Gold | Medium | -| TPCF | None | Gold | **Critical** | -| Licensing | Bronze | Gold | Low | -| Security | Bronze | Gold | Medium | -| iSOS | None | Gold | High | -| CRDTs | None | Gold | **Critical** | - -**Overall Compliance**: 35% (Bronze/Partial) -**Target**: 100% (Gold) - ---- - -## Priority Implementation Order - -### Phase 1: Critical Foundations (Week 1-2) -1. **Offline-First Architecture** - CRDT implementation -2. **TPCF Setup** - Define perimeters, MAINTAINERS.md -3. **Build Reproducibility** - Nix flake -4. **Documentation** - All missing governance docs - -### Phase 2: Type & Memory Safety (Week 3-4) -5. **Rewrite firmware in Rust** - Memory safety -6. **Convert analytics to Rust/OCaml** - Type safety -7. **Add formal verification** - SPARK Ada critical sections - -### Phase 3: Testing & Security (Week 5-6) -8. **Comprehensive test suite** - >80% coverage -9. **Security audit** - SECURITY.md, security.txt -10. **Dependency scanning** - Automated CVE checks - -### Phase 4: Polish & Verification (Week 7-8) -11. **iSOS implementation** - FFI contracts -12. **License compliance** - Palimpsest adoption -13. **Final RSR verification** - rhodium-init self-check - ---- - -## Immediate Actions (Next 24 Hours) - -1. Create all missing governance documents -2. Set up .well-known/ directory -3. Implement basic CRDT support -4. Add Nix flake.nix -5. Define TPCF perimeters -6. Add Palimpsest License - ---- - -**Next Update**: After Phase 1 completion -**Responsible**: Claude (automated implementation) -**Review**: Human approval required for perimeter assignments diff --git a/SECURITY.adoc b/SECURITY.adoc new file mode 100644 index 0000000..8a791f9 --- /dev/null +++ b/SECURITY.adoc @@ -0,0 +1,178 @@ +== Security Policy + +=== Supported Versions + +We actively support the following versions with security updates: + +[cols=",,",options="header",] +|=== +|Version |Supported |End of Life +|2.0.x |:white_check_mark: |TBD +|1.0.x |:x: |2025-11-22 +|=== + +=== Reporting a Vulnerability + +*DO NOT* report security vulnerabilities through public GitHub issues. + +==== Responsible Disclosure + +We follow a 90-day coordinated disclosure policy. Please report security +vulnerabilities to: + +*Primary Contact*: security@kaldor.community *PGP Key*: See +`+.well-known/security.txt+` *Response Time*: Within 48 hours + +==== What to Include + +Please include the following information: + +[arabic] +. *Type of vulnerability* (e.g., RCE, XSS, authentication bypass) +. *Affected component* (firmware, backend, frontend, etc.) +. *Impact assessment* (CVSS score if available) +. *Reproduction steps* (detailed, step-by-step) +. *Proof of concept* (code, screenshots, video) +. *Suggested fix* (optional but appreciated) + +==== Disclosure Timeline + +* *Day 0*: Vulnerability report received +* *Day 1-2*: Acknowledgment sent to reporter +* *Day 3-14*: Vulnerability verified and severity assessed +* *Day 15-60*: Fix developed and tested +* *Day 61-75*: Security advisory drafted +* *Day 76-90*: Coordinated public disclosure +** CVE assigned (if applicable) +** Security advisory published +** Credit given to reporter (unless anonymity requested) + +==== Scope + +*In Scope*: - Authentication bypass - Authorization issues - Remote code +execution (RCE) - SQL injection, XSS, CSRF - Firmware vulnerabilities - +MQTT/Matter protocol attacks - OPC UA security issues - CRDT convergence +failures - Memory safety violations - Cryptographic vulnerabilities + +*Out of Scope*: - Social engineering attacks - Physical attacks on +hardware - Denial of Service (DoS) - unless amplification factor >100x - +Issues in third-party dependencies (report to upstream) - Issues +requiring physical access to devices - Theoretical vulnerabilities +without proof of concept + +=== Security Architecture + +==== Defense in Depth + +The Kaldor platform implements multiple security layers: + +[arabic] +. *Network Layer* +* TLS 1.3 for all connections +* Matter protocol encryption +* Thread mesh network security +* mTLS for MQTT +. *Application Layer* +* JWT-based authentication +* Role-based access control (RBAC) +* Input validation (Zod schemas) +* Rate limiting +* CSRF protection +. *Data Layer* +* Encryption at rest (AES-256-GCM) +* PostgreSQL row-level security +* Encrypted backups +* CRDT signed operations +. *Firmware Layer* +* Secure boot (ESP32-C6) +* OTA signature verification +* WASM sandboxing +* Memory protection (RISC-V PMP) + +==== Threat Model + +See `+docs/security/THREAT_MODEL.md+` for detailed threat analysis. + +*Key Threats Addressed*: - Unauthorized machine control - Production +data tampering - Community governance manipulation - Supply chain +attacks - Insider threats (TPCF perimeters) + +=== Security Hardening Checklist + +==== Production Deployment + +* [ ] Change all default passwords +* [ ] Generate unique JWT secret (min 32 bytes) +* [ ] Enable HTTPS with valid certificates +* [ ] Configure firewall rules (allow-list only) +* [ ] Enable audit logging +* [ ] Set up intrusion detection (fail2ban) +* [ ] Implement backup encryption +* [ ] Configure RBAC policies +* [ ] Enable signed commits requirement +* [ ] Run dependency scanner (weekly) +* [ ] Perform security audit (annually) + +==== Device Security + +* [ ] Flash firmware with secure boot enabled +* [ ] Set unique device certificates +* [ ] Disable debug interfaces in production +* [ ] Enable Matter commissioner authentication +* [ ] Configure OTA signature verification +* [ ] Set up device attestation +* [ ] Implement certificate rotation (90 days) + +=== Security Tools + +We use the following tools for security assurance: + +* *SAST*: Deno’s built-in linter, Rust Clippy +* *Dependency Scanning*: Dependabot, `+deno outdated+` +* *Secrets Detection*: GitGuardian, gitleaks +* *Container Scanning*: Trivy, Docker Scout +* *Fuzzing*: AFL++ for C/C++ firmware +* *Penetration Testing*: Annual third-party audit + +=== Known Vulnerabilities + +Current known vulnerabilities are tracked at: +https://github.com/Hyperpolymath/Kaldor-IIoT/security/advisories + +=== Security Contact + +* *Email*: security@kaldor.community +* *PGP Key Fingerprint*: See `+.well-known/security.txt+` +* *Security Advisory Feed*: RSS available at +`+/security/advisories.rss+` + +=== Bounty Program + +We do not currently offer a bug bounty program, but we: + +[arabic] +. Publicly acknowledge security researchers (with permission) +. Prioritize security fixes above all other work +. Provide CVE credit where applicable +. Are exploring community-funded bounty options + +=== Compliance + +This security policy aligns with: + +* *OWASP Top 10* (2021) +* *CWE Top 25* (2024) +* *NIST Cybersecurity Framework* +* *IEC 62443* (Industrial cybersecurity) +* *RFC 9116* (security.txt) + +=== Updates + +This policy was last updated: 2025-11-22 + +Subscribe to security notifications: +https://github.com/Hyperpolymath/Kaldor-IIoT/security/advisories + +''''' + +_Thank you for helping keep Kaldor and our community safe!_ diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index de06127..0000000 --- a/SECURITY.md +++ /dev/null @@ -1,191 +0,0 @@ - -# Security Policy - -## Supported Versions - -We actively support the following versions with security updates: - -| Version | Supported | End of Life | -| ------- | ------------------ | ----------- | -| 2.0.x | :white_check_mark: | TBD | -| 1.0.x | :x: | 2025-11-22 | - -## Reporting a Vulnerability - -**DO NOT** report security vulnerabilities through public GitHub issues. - -### Responsible Disclosure - -We follow a 90-day coordinated disclosure policy. Please report security vulnerabilities to: - -**Primary Contact**: security@kaldor.community -**PGP Key**: See `.well-known/security.txt` -**Response Time**: Within 48 hours - -### What to Include - -Please include the following information: - -1. **Type of vulnerability** (e.g., RCE, XSS, authentication bypass) -2. **Affected component** (firmware, backend, frontend, etc.) -3. **Impact assessment** (CVSS score if available) -4. **Reproduction steps** (detailed, step-by-step) -5. **Proof of concept** (code, screenshots, video) -6. **Suggested fix** (optional but appreciated) - -### Disclosure Timeline - -- **Day 0**: Vulnerability report received -- **Day 1-2**: Acknowledgment sent to reporter -- **Day 3-14**: Vulnerability verified and severity assessed -- **Day 15-60**: Fix developed and tested -- **Day 61-75**: Security advisory drafted -- **Day 76-90**: Coordinated public disclosure - - CVE assigned (if applicable) - - Security advisory published - - Credit given to reporter (unless anonymity requested) - -### Scope - -**In Scope**: -- Authentication bypass -- Authorization issues -- Remote code execution (RCE) -- SQL injection, XSS, CSRF -- Firmware vulnerabilities -- MQTT/Matter protocol attacks -- OPC UA security issues -- CRDT convergence failures -- Memory safety violations -- Cryptographic vulnerabilities - -**Out of Scope**: -- Social engineering attacks -- Physical attacks on hardware -- Denial of Service (DoS) - unless amplification factor >100x -- Issues in third-party dependencies (report to upstream) -- Issues requiring physical access to devices -- Theoretical vulnerabilities without proof of concept - -## Security Architecture - -### Defense in Depth - -The Kaldor platform implements multiple security layers: - -1. **Network Layer** - - TLS 1.3 for all connections - - Matter protocol encryption - - Thread mesh network security - - mTLS for MQTT - -2. **Application Layer** - - JWT-based authentication - - Role-based access control (RBAC) - - Input validation (Zod schemas) - - Rate limiting - - CSRF protection - -3. **Data Layer** - - Encryption at rest (AES-256-GCM) - - PostgreSQL row-level security - - Encrypted backups - - CRDT signed operations - -4. **Firmware Layer** - - Secure boot (ESP32-C6) - - OTA signature verification - - WASM sandboxing - - Memory protection (RISC-V PMP) - -### Threat Model - -See `docs/security/THREAT_MODEL.md` for detailed threat analysis. - -**Key Threats Addressed**: -- Unauthorized machine control -- Production data tampering -- Community governance manipulation -- Supply chain attacks -- Insider threats (TPCF perimeters) - -## Security Hardening Checklist - -### Production Deployment - -- [ ] Change all default passwords -- [ ] Generate unique JWT secret (min 32 bytes) -- [ ] Enable HTTPS with valid certificates -- [ ] Configure firewall rules (allow-list only) -- [ ] Enable audit logging -- [ ] Set up intrusion detection (fail2ban) -- [ ] Implement backup encryption -- [ ] Configure RBAC policies -- [ ] Enable signed commits requirement -- [ ] Run dependency scanner (weekly) -- [ ] Perform security audit (annually) - -### Device Security - -- [ ] Flash firmware with secure boot enabled -- [ ] Set unique device certificates -- [ ] Disable debug interfaces in production -- [ ] Enable Matter commissioner authentication -- [ ] Configure OTA signature verification -- [ ] Set up device attestation -- [ ] Implement certificate rotation (90 days) - -## Security Tools - -We use the following tools for security assurance: - -- **SAST**: Deno's built-in linter, Rust Clippy -- **Dependency Scanning**: Dependabot, `deno outdated` -- **Secrets Detection**: GitGuardian, gitleaks -- **Container Scanning**: Trivy, Docker Scout -- **Fuzzing**: AFL++ for C/C++ firmware -- **Penetration Testing**: Annual third-party audit - -## Known Vulnerabilities - -Current known vulnerabilities are tracked at: -https://github.com/Hyperpolymath/Kaldor-IIoT/security/advisories - -## Security Contact - -- **Email**: security@kaldor.community -- **PGP Key Fingerprint**: See `.well-known/security.txt` -- **Security Advisory Feed**: RSS available at `/security/advisories.rss` - -## Bounty Program - -We do not currently offer a bug bounty program, but we: - -1. Publicly acknowledge security researchers (with permission) -2. Prioritize security fixes above all other work -3. Provide CVE credit where applicable -4. Are exploring community-funded bounty options - -## Compliance - -This security policy aligns with: - -- **OWASP Top 10** (2021) -- **CWE Top 25** (2024) -- **NIST Cybersecurity Framework** -- **IEC 62443** (Industrial cybersecurity) -- **RFC 9116** (security.txt) - -## Updates - -This policy was last updated: 2025-11-22 - -Subscribe to security notifications: -https://github.com/Hyperpolymath/Kaldor-IIoT/security/advisories - ---- - -*Thank you for helping keep Kaldor and our community safe!* diff --git a/TEST-NEEDS.adoc b/TEST-NEEDS.adoc new file mode 100644 index 0000000..4a14a60 --- /dev/null +++ b/TEST-NEEDS.adoc @@ -0,0 +1,30 @@ +== TEST-NEEDS.md — kaldor-iiot + +=== CRG Grade: C — ACHIEVED 2026-04-04 + +=== Current Test State + +[cols=",,",options="header",] +|=== +|Category |Count |Notes +|Test files |1 |Current state +|=== + +=== What’s Covered + +* [x] 1 existing test file(s) +* [x] TypeScript/JavaScript tests + +=== Still Missing (for CRG B+) + +* [ ] Zig FFI tests (if applicable) +* [ ] CI/CD test automation +* [ ] Property-based tests +* [ ] Edge case coverage + +=== Run Tests + +[source,bash] +---- +npm test +---- diff --git a/TEST-NEEDS.md b/TEST-NEEDS.md deleted file mode 100644 index 56ee4f0..0000000 --- a/TEST-NEEDS.md +++ /dev/null @@ -1,31 +0,0 @@ - -# TEST-NEEDS.md — kaldor-iiot - -## CRG Grade: C — ACHIEVED 2026-04-04 - -## Current Test State - -| Category | Count | Notes | -|----------|-------|-------| -| Test files | 1 | Current state | - -## What's Covered - -- [x] 1 existing test file(s) -- [x] TypeScript/JavaScript tests - -## Still Missing (for CRG B+) - -- [ ] Zig FFI tests (if applicable) -- [ ] CI/CD test automation -- [ ] Property-based tests -- [ ] Edge case coverage - -## Run Tests - -```bash -npm test -``` diff --git a/TOPOLOGY.md b/TOPOLOGY.adoc similarity index 88% rename from TOPOLOGY.md rename to TOPOLOGY.adoc index 6ddbba4..6737c5f 100644 --- a/TOPOLOGY.md +++ b/TOPOLOGY.adoc @@ -1,15 +1,8 @@ - - - +== Kaldor IIoT — Project Topology -# Kaldor IIoT — Project Topology +=== System Architecture -## System Architecture - -``` +.... ┌─────────────────────────────────────────┐ │ COMMUNITY MAKERS │ │ (Mobile App / Web Dashboard) │ @@ -48,11 +41,11 @@ Copyright (c) Jonathan D.A. Jewell │ Nix / flake.nix .machine_readable/ │ │ Justfile / Cargo 0-AI-MANIFEST.a2ml │ └─────────────────────────────────────────┘ -``` +.... -## Completion Dashboard +=== Completion Dashboard -``` +.... COMPONENT STATUS NOTES ───────────────────────────────── ────────────────── ───────────────────────────────── USER INTERFACES @@ -77,25 +70,26 @@ REPO INFRASTRUCTURE ───────────────────────────────────────────────────────────────────────────── OVERALL: ████████░░ ~80% v2.0.0 Active Development -``` +.... -## Key Dependencies +=== Key Dependencies -``` +.... Matter Mesh ──────► Deno Backend ──────► Automerge ──────► ReScript UI │ │ │ │ ▼ ▼ ▼ ▼ RISC-V Edge ──────► WASM Logic ───────► TimescaleDB ───► Governance -``` +.... -## Update Protocol +=== Update Protocol This file is maintained by both humans and AI agents. When updating: -1. **After completing a component**: Change its bar and percentage -2. **After adding a component**: Add a new row in the appropriate section -3. **After architectural changes**: Update the ASCII diagram -4. **Date**: Update the `Last updated` comment at the top of this file +[arabic] +. *After completing a component*: Change its bar and percentage +. *After adding a component*: Add a new row in the appropriate section +. *After architectural changes*: Update the ASCII diagram +. *Date*: Update the `+Last updated+` comment at the top of this file -Progress bars use: `█` (filled) and `░` (empty), 10 characters wide. -Percentages: 0%, 10%, 20%, ... 100% (in 10% increments). +Progress bars use: `+█+` (filled) and `+░+` (empty), 10 characters wide. +Percentages: 0%, 10%, 20%, … 100% (in 10% increments). diff --git a/docs/developer/DEPLOYMENT.md b/docs/developer/DEPLOYMENT.adoc similarity index 55% rename from docs/developer/DEPLOYMENT.md rename to docs/developer/DEPLOYMENT.adoc index 1323fc0..6dea346 100644 --- a/docs/developer/DEPLOYMENT.md +++ b/docs/developer/DEPLOYMENT.adoc @@ -1,104 +1,100 @@ - -# Kaldor IIoT - Deployment Guide +== Kaldor IIoT - Deployment Guide -## Table of Contents +=== Table of Contents -1. [Prerequisites](#prerequisites) -2. [Local Development](#local-development) -3. [Production Deployment](#production-deployment) -4. [IONOS Deploy Now](#ionos-deploy-now) -5. [Docker Deployment](#docker-deployment) -6. [Kubernetes Deployment](#kubernetes-deployment) -7. [Security Hardening](#security-hardening) -8. [Monitoring Setup](#monitoring-setup) -9. [Backup and Recovery](#backup-and-recovery) +[arabic] +. link:#prerequisites[Prerequisites] +. link:#local-development[Local Development] +. link:#production-deployment[Production Deployment] +. link:#ionos-deploy-now[IONOS Deploy Now] +. link:#docker-deployment[Docker Deployment] +. link:#kubernetes-deployment[Kubernetes Deployment] +. link:#security-hardening[Security Hardening] +. link:#monitoring-setup[Monitoring Setup] +. link:#backup-and-recovery[Backup and Recovery] -## Prerequisites +=== Prerequisites -### Required Software +==== Required Software -- Docker 20.10+ -- Docker Compose 2.0+ -- Git 2.30+ -- Node.js 18+ (for development) -- Python 3.9+ (for analytics) +* Docker 20.10+ +* Docker Compose 2.0+ +* Git 2.30+ +* Node.js 18+ (for development) +* Python 3.9+ (for analytics) -### Required Accounts +==== Required Accounts -- IONOS account (for Deploy Now) -- SMTP server (for email alerts) -- Twilio account (optional, for SMS) -- Domain name with SSL certificate +* IONOS account (for Deploy Now) +* SMTP server (for email alerts) +* Twilio account (optional, for SMS) +* Domain name with SSL certificate -### Hardware Requirements +==== Hardware Requirements -**Minimum (Development)** -- 4 CPU cores -- 8 GB RAM -- 50 GB storage -- 100 Mbps network +*Minimum (Development)* - 4 CPU cores - 8 GB RAM - 50 GB storage - 100 +Mbps network -**Recommended (Production)** -- 8 CPU cores -- 16 GB RAM -- 200 GB SSD storage -- 1 Gbps network -- UPS backup power +*Recommended (Production)* - 8 CPU cores - 16 GB RAM - 200 GB SSD +storage - 1 Gbps network - UPS backup power -## Local Development +=== Local Development -### 1. Clone Repository +==== 1. Clone Repository -```bash +[source,bash] +---- git clone https://github.com/your-org/kaldor-iiot.git cd kaldor-iiot -``` +---- -### 2. Configure Environment +==== 2. Configure Environment -```bash +[source,bash] +---- cp .env.example .env # Edit .env with your settings nano .env -``` +---- -### 3. Start Development Environment +==== 3. Start Development Environment -```bash +[source,bash] +---- docker-compose up -d -``` +---- -### 4. Initialize Database +==== 4. Initialize Database -```bash +[source,bash] +---- docker-compose exec timescaledb psql -U kaldor -d kaldor_iiot -f /docker-entrypoint-initdb.d/001_initial_schema.sql -``` +---- -### 5. Access Services +==== 5. Access Services -- Frontend: http://localhost -- API: http://localhost:3000 -- API Docs: http://localhost:3000/api-docs -- Grafana: http://localhost:3001 +* Frontend: http://localhost +* API: http://localhost:3000 +* API Docs: http://localhost:3000/api-docs +* Grafana: http://localhost:3001 -## Production Deployment +=== Production Deployment -### Automated Deployment +==== Automated Deployment Use the deployment script: -```bash +[source,bash] +---- ./scripts/deployment/deploy.sh -``` +---- -### Manual Deployment +==== Manual Deployment -#### 1. Prepare Server +===== 1. Prepare Server -```bash +[source,bash] +---- # Update system sudo apt update && sudo apt upgrade -y @@ -109,11 +105,12 @@ sudo sh get-docker.sh # Install Docker Compose sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose -``` +---- -#### 2. Configure Firewall +===== 2. Configure Firewall -```bash +[source,bash] +---- # Allow HTTP/HTTPS sudo ufw allow 80/tcp sudo ufw allow 443/tcp @@ -124,77 +121,85 @@ sudo ufw allow 8883/tcp # Enable firewall sudo ufw enable -``` +---- -#### 3. Setup SSL Certificates +===== 3. Setup SSL Certificates -```bash +[source,bash] +---- # Using Let's Encrypt sudo apt install certbot sudo certbot certonly --standalone -d your-domain.com -``` +---- -#### 4. Configure Environment +===== 4. Configure Environment -```bash +[source,bash] +---- # Production environment variables nano .env -``` +---- Required production settings: -```env + +[source,env] +---- NODE_ENV=production DB_PASSWORD= REDIS_PASSWORD= JWT_SECRET= -``` +---- -#### 5. Deploy Application +===== 5. Deploy Application -```bash +[source,bash] +---- docker-compose -f docker-compose.prod.yml up -d -``` +---- -## IONOS Deploy Now +=== IONOS Deploy Now -### Setup +==== Setup -1. Fork the repository on GitHub -2. Go to IONOS Deploy Now -3. Connect your GitHub account -4. Select the Kaldor-IIoT repository -5. Configure build settings: - - Build command: `npm run build` - - Output directory: `dist` +[arabic] +. Fork the repository on GitHub +. Go to IONOS Deploy Now +. Connect your GitHub account +. Select the Kaldor-IIoT repository +. Configure build settings: +* Build command: `+npm run build+` +* Output directory: `+dist+` -### GitHub Secrets +==== GitHub Secrets Add these secrets to your repository: -``` +.... IONOS_API_KEY= IONOS_PROJECT_ID= DB_PASSWORD= JWT_SECRET= -``` +.... -### Deploy +==== Deploy Push to main branch: -```bash +[source,bash] +---- git push origin main -``` +---- Deployment happens automatically via GitHub Actions. -## Docker Deployment +=== Docker Deployment -### Production Docker Compose +==== Production Docker Compose -Create `docker-compose.prod.yml`: +Create `+docker-compose.prod.yml+`: -```yaml +[source,yaml] +---- version: '3.8' services: @@ -209,19 +214,21 @@ services: - kaldor-network # ... other services -``` +---- -### Best Practices +==== Best Practices -1. **Use specific image tags** (not `latest`) -2. **Set restart policies** (`restart: unless-stopped`) -3. **Use Docker volumes** for persistent data -4. **Enable health checks** for all services -5. **Resource limits** to prevent resource exhaustion +[arabic] +. *Use specific image tags* (not `+latest+`) +. *Set restart policies* (`+restart: unless-stopped+`) +. *Use Docker volumes* for persistent data +. *Enable health checks* for all services +. *Resource limits* to prevent resource exhaustion Example resource limits: -```yaml +[source,yaml] +---- services: api: deploy: @@ -232,19 +239,20 @@ services: reservations: cpus: '1' memory: 1G -``` +---- -## Kubernetes Deployment +=== Kubernetes Deployment -### Prerequisites +==== Prerequisites -- Kubernetes cluster (1.24+) -- kubectl configured -- Helm 3+ +* Kubernetes cluster (1.24+) +* kubectl configured +* Helm 3+ -### Deploy with Helm +==== Deploy with Helm -```bash +[source,bash] +---- # Add Kaldor IIoT Helm repo helm repo add kaldor https://charts.kaldor-iiot.example.com @@ -254,11 +262,12 @@ helm install kaldor-iiot kaldor/kaldor-iiot \ --create-namespace \ --set database.password= \ --set jwt.secret= -``` +---- -### Manual Deployment +==== Manual Deployment -```bash +[source,bash] +---- # Apply configurations kubectl apply -f k8s/namespace.yaml kubectl apply -f k8s/secrets.yaml @@ -266,24 +275,26 @@ kubectl apply -f k8s/configmaps.yaml kubectl apply -f k8s/deployments/ kubectl apply -f k8s/services/ kubectl apply -f k8s/ingress.yaml -``` +---- -## Security Hardening +=== Security Hardening -### 1. Change Default Credentials +==== 1. Change Default Credentials -```sql +[source,sql] +---- -- Change admin password UPDATE users SET password_hash = crypt('NewSecurePassword', gen_salt('bf')) WHERE username = 'admin'; -``` +---- -### 2. Configure SSL/TLS +==== 2. Configure SSL/TLS -Update `nginx.conf`: +Update `+nginx.conf+`: -```nginx +[source,nginx] +---- server { listen 443 ssl http2; ssl_certificate /etc/nginx/ssl/cert.pem; @@ -293,52 +304,57 @@ server { # ... rest of config } -``` +---- -### 3. Enable MQTT Authentication +==== 3. Enable MQTT Authentication -Update `mosquitto.conf`: +Update `+mosquitto.conf+`: -```conf +[source,conf] +---- allow_anonymous false password_file /mosquitto/config/password.txt -``` +---- Create password file: -```bash +[source,bash] +---- mosquitto_passwd -c password.txt device_user -``` +---- -### 4. Database Security +==== 4. Database Security -```sql +[source,sql] +---- -- Create read-only user for analytics CREATE USER analytics_ro WITH PASSWORD 'secure_password'; GRANT SELECT ON ALL TABLES IN SCHEMA public TO analytics_ro; -- Revoke unnecessary permissions REVOKE ALL ON SCHEMA public FROM PUBLIC; -``` +---- -### 5. Rate Limiting +==== 5. Rate Limiting -Already configured in `server.js`: +Already configured in `+server.js+`: -```javascript +[source,javascript] +---- const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }); -``` +---- -## Monitoring Setup +=== Monitoring Setup -### Prometheus Configuration +==== Prometheus Configuration -File: `infrastructure/monitoring/prometheus.yml` +File: `+infrastructure/monitoring/prometheus.yml+` -```yaml +[source,yaml] +---- global: scrape_interval: 15s @@ -350,21 +366,23 @@ scrape_configs: - job_name: 'timescaledb' static_configs: - targets: ['timescaledb:9187'] -``` +---- -### Grafana Dashboards +==== Grafana Dashboards Import dashboards: -1. Login to Grafana (http://localhost:3001) -2. Go to Dashboards → Import -3. Import from `infrastructure/monitoring/grafana/dashboards/` +[arabic] +. Login to Grafana (http://localhost:3001) +. Go to Dashboards → Import +. Import from `+infrastructure/monitoring/grafana/dashboards/+` -### Alerting Rules +==== Alerting Rules Configure in Prometheus: -```yaml +[source,yaml] +---- groups: - name: kaldor_alerts rules: @@ -373,22 +391,24 @@ groups: for: 10m annotations: summary: "High error rate detected" -``` +---- -## Backup and Recovery +=== Backup and Recovery -### Database Backup +==== Database Backup -#### Automated Daily Backup +===== Automated Daily Backup -```bash +[source,bash] +---- # Add to crontab 0 2 * * * /usr/local/bin/backup-kaldor-db.sh -``` +---- Backup script: -```bash +[source,bash] +---- #!/bin/bash BACKUP_DIR=/var/backups/kaldor DATE=$(date +%Y%m%d_%H%M%S) @@ -398,53 +418,62 @@ docker-compose exec -T timescaledb pg_dump -U kaldor kaldor_iiot | \ # Keep only last 30 days find $BACKUP_DIR -name "*.sql.gz" -mtime +30 -delete -``` +---- -#### Restore from Backup +===== Restore from Backup -```bash +[source,bash] +---- gunzip < backup.sql.gz | \ docker-compose exec -T timescaledb psql -U kaldor -d kaldor_iiot -``` +---- -### Configuration Backup +==== Configuration Backup -```bash +[source,bash] +---- # Backup all configurations tar -czf config-backup.tar.gz \ .env \ infrastructure/ \ database/schemas/ -``` - -### Disaster Recovery - -1. **Stop all services**: - ```bash - docker-compose down - ``` - -2. **Restore database**: - ```bash - gunzip < latest-backup.sql.gz | \ - docker-compose exec -T timescaledb psql -U kaldor -d kaldor_iiot - ``` +---- -3. **Restore configurations**: - ```bash - tar -xzf config-backup.tar.gz - ``` +==== Disaster Recovery -4. **Restart services**: - ```bash - docker-compose up -d - ``` +[arabic] +. *Stop all services*: ++ +[source,bash] +---- +docker-compose down +---- +. *Restore database*: ++ +[source,bash] +---- +gunzip < latest-backup.sql.gz | \ + docker-compose exec -T timescaledb psql -U kaldor -d kaldor_iiot +---- +. *Restore configurations*: ++ +[source,bash] +---- +tar -xzf config-backup.tar.gz +---- +. *Restart services*: ++ +[source,bash] +---- +docker-compose up -d +---- -## Health Checks +=== Health Checks -### Automated Health Monitoring +==== Automated Health Monitoring -```bash +[source,bash] +---- #!/bin/bash # health-check.sh @@ -457,19 +486,21 @@ fi if ! docker-compose exec timescaledb pg_isready -U kaldor > /dev/null 2>&1; then echo "Database is down!" | mail -s "Kaldor IIoT Alert" admin@example.com fi -``` +---- Add to crontab: -```bash +[source,bash] +---- */5 * * * * /usr/local/bin/health-check.sh -``` +---- -## Performance Optimization +=== Performance Optimization -### Database Optimization +==== Database Optimization -```sql +[source,sql] +---- -- Create indexes CREATE INDEX CONCURRENTLY idx_measurements_loom_time ON bbw_measurements (loom_id, time DESC); @@ -479,19 +510,21 @@ ANALYZE bbw_measurements; -- Vacuum VACUUM ANALYZE; -``` +---- -### Redis Configuration +==== Redis Configuration -```redis +[source,redis] +---- # memory optimization maxmemory 256mb maxmemory-policy allkeys-lru -``` +---- -### Nginx Caching +==== Nginx Caching -```nginx +[source,nginx] +---- proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=1g; location /api/ { @@ -499,13 +532,14 @@ location /api/ { proxy_cache_valid 200 5m; proxy_cache_key "$request_uri"; } -``` +---- -## Troubleshooting Deployments +=== Troubleshooting Deployments -### Container Won't Start +==== Container Won’t Start -```bash +[source,bash] +---- # Check logs docker-compose logs @@ -514,30 +548,33 @@ docker stats # Inspect container docker inspect -``` +---- -### Database Connection Issues +==== Database Connection Issues -```bash +[source,bash] +---- # Test connection docker-compose exec api node -e "const { Pool } = require('pg'); const pool = new Pool({ host: 'timescaledb' }); pool.query('SELECT NOW()').then(console.log).catch(console.error);" -``` +---- -### SSL Certificate Issues +==== SSL Certificate Issues -```bash +[source,bash] +---- # Verify certificate openssl x509 -in cert.pem -text -noout # Test SSL connection openssl s_client -connect your-domain.com:443 -``` +---- -## Rollback Procedure +=== Rollback Procedure -### Docker Compose Rollback +==== Docker Compose Rollback -```bash +[source,bash] +---- # Stop current version docker-compose down @@ -547,24 +584,23 @@ git checkout # Rebuild and start docker-compose build docker-compose up -d -``` +---- -### Database Rollback +==== Database Rollback -```bash +[source,bash] +---- # Restore previous backup gunzip < previous-backup.sql.gz | \ docker-compose exec -T timescaledb psql -U kaldor -d kaldor_iiot -``` +---- -## Support +=== Support -For deployment issues: -- Email: devops@kaldor-iiot.example.com -- Documentation: https://docs.kaldor-iiot.example.com -- GitHub Issues: Technical problems +For deployment issues: - Email: devops@kaldor-iiot.example.com - +Documentation: https://docs.kaldor-iiot.example.com - GitHub Issues: +Technical problems ---- +''''' -**Document Version**: 1.0 -**Last Updated**: 2025-11-22 +*Document Version*: 1.0 *Last Updated*: 2025-11-22 diff --git a/docs/hardware/SETUP.adoc b/docs/hardware/SETUP.adoc new file mode 100644 index 0000000..f42455c --- /dev/null +++ b/docs/hardware/SETUP.adoc @@ -0,0 +1,319 @@ +== Kaldor IIoT - Hardware Setup Guide + +Complete guide for assembling and configuring the BBW sensor board. + +=== Table of Contents + +[arabic] +. link:#bill-of-materials[Bill of Materials] +. link:#pcb-assembly[PCB Assembly] +. link:#sensor-installation[Sensor Installation] +. link:#power-supply[Power Supply] +. link:#network-configuration[Network Configuration] +. link:#firmware-installation[Firmware Installation] +. link:#calibration[Calibration] +. link:#troubleshooting[Troubleshooting] + +=== Bill of Materials + +==== Core Components + +[width="100%",cols="24%,25%,19%,19%,13%",options="header",] +|=== +|Component |Part Number |Quantity |Supplier |Notes +|ESP32 Dev Board |ESP32-WROOM-32 |1 |Espressif |Main microcontroller +|Ultrasonic Sensor |HC-SR04 |1 |Generic |Distance measurement +|Temperature/Humidity |DHT22 |1 |Adafruit |Environmental monitoring +|Accelerometer |ADXL345 |1 |Adafruit |Vibration detection +|Voltage Regulator |LM7805 |1 |Texas Instruments |5V regulation +|Power Jack |DC-005 |1 |Generic |5.5mm x 2.1mm +|=== + +==== Passive Components + +[cols=",,,",options="header",] +|=== +|Component |Value |Quantity |Notes +|Capacitor |100µF 25V |2 |Power filtering +|Capacitor |10µF 16V |4 |Bypass capacitors +|Resistor |10kΩ |4 |Pull-up resistors +|Resistor |330Ω |3 |LED current limiting +|LED |Red |1 |Status indicator +|LED |Green |1 |WiFi indicator +|LED |Blue |1 |MQTT indicator +|=== + +==== Connectors & Hardware + +* JST-XH 2.54mm connectors (4-pin) x 3 +* Dupont wire set +* M3 standoffs and screws +* Enclosure (IP65 rated) +* Cable glands + +=== PCB Assembly + +==== Step 1: Component Placement + +[arabic] +. *Inspect PCB*: Check for defects or damage +. *Solder Power Components*: +* Install voltage regulator (LM7805) +* Add power capacitors (100µF near input/output) +* Install power jack +. *Install ESP32*: +* Use pin headers for removable mounting +* Ensure proper alignment +* Test continuity +. *Add Passive Components*: +* Solder resistors first +* Then capacitors +* Finally LEDs (observe polarity!) + +==== Step 2: Sensor Connections + +===== Ultrasonic Sensor (HC-SR04) + +.... +ESP32 Pin HC-SR04 Pin +--------- ----------- +GPIO 25 → TRIG +GPIO 26 ← ECHO +5V → VCC +GND → GND +.... + +===== Temperature Sensor (DHT22) + +.... +ESP32 Pin DHT22 Pin +--------- --------- +GPIO 27 → DATA +3.3V → VCC +GND → GND +.... + +===== Accelerometer (ADXL345) + +.... +ESP32 Pin ADXL345 Pin +--------- ----------- +GPIO 21 ←→ SDA +GPIO 22 → SCL +3.3V → VCC +GND → GND +.... + +=== Sensor Installation + +==== Mounting the Ultrasonic Sensor + +[arabic] +. *Position*: Mount perpendicular to beam surface +. *Distance*: 100-300mm from target +. *Alignment*: Use laser level for accuracy +. *Securing*: Use vibration-dampening mounts + +==== Installing Temperature Sensor + +[arabic] +. Mount away from heat sources +. Ensure good air circulation +. Protect from direct sunlight +. Secure cable to prevent movement + +==== Accelerometer Mounting + +[arabic] +. Mount directly on loom frame +. Ensure rigid attachment +. Align axes with machine directions +. Use threadlocker on mounting screws + +=== Power Supply + +==== Requirements + +* Input: 12V DC, 2A minimum +* Consumption: ~500mA typical, 1A peak +* Connector: 5.5mm x 2.1mm barrel jack +* Protection: Reverse polarity protection recommended + +==== Wiring + +.... +Power Supply BBW Board +------------ --------- ++12V (Red) → Power Jack Center Pin +GND (Black) → Power Jack Outer Shell +.... + +==== Power Quality + +* Use filtered power supply +* Add ferrite beads on power cable +* Keep power cables away from sensor cables +* Ground enclosure to earth ground + +=== Network Configuration + +==== WiFi Setup + +[arabic] +. On first boot, device creates AP: `+Kaldor-BBW-XXXXXX+` +. Connect to AP (password: `+kaldor2024+`) +. Navigate to `+http://192.168.4.1+` +. Enter your WiFi credentials +. Save and reboot + +==== Static IP (Optional) + +Edit `+include/config.h+`: + +[source,cpp] +---- +#define USE_STATIC_IP true +#define STATIC_IP IPAddress(192, 168, 1, 100) +#define GATEWAY IPAddress(192, 168, 1, 1) +#define SUBNET IPAddress(255, 255, 255, 0) +---- + +=== Firmware Installation + +==== Using PlatformIO + +[arabic] +. *Install PlatformIO*: https://platformio.org/install +. *Open project*: ++ +[source,bash] +---- +cd firmware +pio run +---- +. *Connect ESP32* via USB +. *Upload firmware*: ++ +[source,bash] +---- +pio run --target upload +---- +. *Monitor output*: ++ +[source,bash] +---- +pio device monitor +---- + +==== Using Arduino IDE + +[arabic] +. Install ESP32 board support +. Open `+firmware/src/main.cpp+` +. Select board: "`ESP32 Dev Module`" +. Set upload speed: 921600 +. Configure WiFi credentials in `+config.h+` +. Upload + +=== Calibration + +==== Ultrasonic Sensor Calibration + +[arabic] +. *Prepare reference*: +* Place flat target at exactly 100mm +* Use calibrated ruler or gauge block +. *Run calibration*: +* Connect to serial monitor +* Send command: `+CAL_START+` +* Wait for 100 readings +* Note calibration factor +. *Update firmware*: ++ +[source,cpp] +---- +// In config.h +#define BBW_CALIBRATION_SCALE 1.0234 // Your factor +#define BBW_CALIBRATION_OFFSET 0.0 +---- +. *Verify*: +* Test at 50mm, 100mm, 150mm +* Error should be < ±1mm + +==== Temperature Calibration + +[arabic] +. Use reference thermometer +. Compare readings at 20°C, 25°C, 30°C +. Apply offset if needed: ++ +[source,cpp] +---- +#define TEMP_CALIBRATION_OFFSET -0.5 // °C +---- + +=== Installation Checklist + +* [ ] All components soldered correctly +* [ ] No solder bridges or cold joints +* [ ] Power supply voltage verified (5V at ESP32) +* [ ] Sensor connections tested +* [ ] Firmware uploaded successfully +* [ ] WiFi connection established +* [ ] MQTT broker connection verified +* [ ] Sensors calibrated +* [ ] LEDs functioning correctly +* [ ] Enclosure properly sealed +* [ ] Mounting secure and stable +* [ ] Cable management complete +* [ ] Documentation updated with serial number + +=== Troubleshooting + +==== ESP32 Won’t Boot + +* Check power supply voltage (should be 5V) +* Verify USB cable (use data cable, not charge-only) +* Press BOOT button during upload +* Check for shorts on power rails + +==== WiFi Connection Fails + +* Verify SSID and password +* Check 2.4GHz band (ESP32 doesn’t support 5GHz) +* Move closer to access point +* Check WiFi signal strength (RSSI > -80 dBm) + +==== Sensor Reading Invalid + +* *Ultrasonic*: Check wiring, ensure clear line of sight +* *DHT22*: Verify pull-up resistor (10kΩ) +* *ADXL345*: Check I2C address (0x53), verify SDA/SCL + +==== MQTT Not Connecting + +* Verify broker address and port +* Check firewall rules +* Ensure credentials are correct +* Test with mosquitto_sub tool + +=== Safety Warnings + +⚠️ *Electrical Safety* - Always disconnect power before making changes - +Use appropriate fuse ratings - Ensure proper grounding + +⚠️ *Mechanical Safety* - Secure all mounting hardware - Use +vibration-resistant connectors - Protect cables from moving parts + +⚠️ *Environmental* - Verify IP rating matches environment - Protect from +excessive heat/cold - Keep away from moisture + +=== Support + +For technical support: - Email: hardware@kaldor-iiot.example.com - +Documentation: https://docs.kaldor-iiot.example.com - GitHub Issues: +Report hardware problems + +''''' + +*Document Version*: 1.0 *Last Updated*: 2025-11-22 diff --git a/docs/hardware/SETUP.md b/docs/hardware/SETUP.md deleted file mode 100644 index 4a18952..0000000 --- a/docs/hardware/SETUP.md +++ /dev/null @@ -1,311 +0,0 @@ - -# Kaldor IIoT - Hardware Setup Guide - -Complete guide for assembling and configuring the BBW sensor board. - -## Table of Contents - -1. [Bill of Materials](#bill-of-materials) -2. [PCB Assembly](#pcb-assembly) -3. [Sensor Installation](#sensor-installation) -4. [Power Supply](#power-supply) -5. [Network Configuration](#network-configuration) -6. [Firmware Installation](#firmware-installation) -7. [Calibration](#calibration) -8. [Troubleshooting](#troubleshooting) - -## Bill of Materials - -### Core Components - -| Component | Part Number | Quantity | Supplier | Notes | -|-----------|-------------|----------|----------|-------| -| ESP32 Dev Board | ESP32-WROOM-32 | 1 | Espressif | Main microcontroller | -| Ultrasonic Sensor | HC-SR04 | 1 | Generic | Distance measurement | -| Temperature/Humidity | DHT22 | 1 | Adafruit | Environmental monitoring | -| Accelerometer | ADXL345 | 1 | Adafruit | Vibration detection | -| Voltage Regulator | LM7805 | 1 | Texas Instruments | 5V regulation | -| Power Jack | DC-005 | 1 | Generic | 5.5mm x 2.1mm | - -### Passive Components - -| Component | Value | Quantity | Notes | -|-----------|-------|----------|-------| -| Capacitor | 100µF 25V | 2 | Power filtering | -| Capacitor | 10µF 16V | 4 | Bypass capacitors | -| Resistor | 10kΩ | 4 | Pull-up resistors | -| Resistor | 330Ω | 3 | LED current limiting | -| LED | Red | 1 | Status indicator | -| LED | Green | 1 | WiFi indicator | -| LED | Blue | 1 | MQTT indicator | - -### Connectors & Hardware - -- JST-XH 2.54mm connectors (4-pin) x 3 -- Dupont wire set -- M3 standoffs and screws -- Enclosure (IP65 rated) -- Cable glands - -## PCB Assembly - -### Step 1: Component Placement - -1. **Inspect PCB**: Check for defects or damage -2. **Solder Power Components**: - - Install voltage regulator (LM7805) - - Add power capacitors (100µF near input/output) - - Install power jack - -3. **Install ESP32**: - - Use pin headers for removable mounting - - Ensure proper alignment - - Test continuity - -4. **Add Passive Components**: - - Solder resistors first - - Then capacitors - - Finally LEDs (observe polarity!) - -### Step 2: Sensor Connections - -#### Ultrasonic Sensor (HC-SR04) - -``` -ESP32 Pin HC-SR04 Pin ---------- ----------- -GPIO 25 → TRIG -GPIO 26 ← ECHO -5V → VCC -GND → GND -``` - -#### Temperature Sensor (DHT22) - -``` -ESP32 Pin DHT22 Pin ---------- --------- -GPIO 27 → DATA -3.3V → VCC -GND → GND -``` - -#### Accelerometer (ADXL345) - -``` -ESP32 Pin ADXL345 Pin ---------- ----------- -GPIO 21 ←→ SDA -GPIO 22 → SCL -3.3V → VCC -GND → GND -``` - -## Sensor Installation - -### Mounting the Ultrasonic Sensor - -1. **Position**: Mount perpendicular to beam surface -2. **Distance**: 100-300mm from target -3. **Alignment**: Use laser level for accuracy -4. **Securing**: Use vibration-dampening mounts - -### Installing Temperature Sensor - -1. Mount away from heat sources -2. Ensure good air circulation -3. Protect from direct sunlight -4. Secure cable to prevent movement - -### Accelerometer Mounting - -1. Mount directly on loom frame -2. Ensure rigid attachment -3. Align axes with machine directions -4. Use threadlocker on mounting screws - -## Power Supply - -### Requirements - -- Input: 12V DC, 2A minimum -- Consumption: ~500mA typical, 1A peak -- Connector: 5.5mm x 2.1mm barrel jack -- Protection: Reverse polarity protection recommended - -### Wiring - -``` -Power Supply BBW Board ------------- --------- -+12V (Red) → Power Jack Center Pin -GND (Black) → Power Jack Outer Shell -``` - -### Power Quality - -- Use filtered power supply -- Add ferrite beads on power cable -- Keep power cables away from sensor cables -- Ground enclosure to earth ground - -## Network Configuration - -### WiFi Setup - -1. On first boot, device creates AP: `Kaldor-BBW-XXXXXX` -2. Connect to AP (password: `kaldor2024`) -3. Navigate to `http://192.168.4.1` -4. Enter your WiFi credentials -5. Save and reboot - -### Static IP (Optional) - -Edit `include/config.h`: - -```cpp -#define USE_STATIC_IP true -#define STATIC_IP IPAddress(192, 168, 1, 100) -#define GATEWAY IPAddress(192, 168, 1, 1) -#define SUBNET IPAddress(255, 255, 255, 0) -``` - -## Firmware Installation - -### Using PlatformIO - -1. **Install PlatformIO**: https://platformio.org/install -2. **Open project**: - ```bash - cd firmware - pio run - ``` -3. **Connect ESP32** via USB -4. **Upload firmware**: - ```bash - pio run --target upload - ``` -5. **Monitor output**: - ```bash - pio device monitor - ``` - -### Using Arduino IDE - -1. Install ESP32 board support -2. Open `firmware/src/main.cpp` -3. Select board: "ESP32 Dev Module" -4. Set upload speed: 921600 -5. Configure WiFi credentials in `config.h` -6. Upload - -## Calibration - -### Ultrasonic Sensor Calibration - -1. **Prepare reference**: - - Place flat target at exactly 100mm - - Use calibrated ruler or gauge block - -2. **Run calibration**: - - Connect to serial monitor - - Send command: `CAL_START` - - Wait for 100 readings - - Note calibration factor - -3. **Update firmware**: - ```cpp - // In config.h - #define BBW_CALIBRATION_SCALE 1.0234 // Your factor - #define BBW_CALIBRATION_OFFSET 0.0 - ``` - -4. **Verify**: - - Test at 50mm, 100mm, 150mm - - Error should be < ±1mm - -### Temperature Calibration - -1. Use reference thermometer -2. Compare readings at 20°C, 25°C, 30°C -3. Apply offset if needed: - ```cpp - #define TEMP_CALIBRATION_OFFSET -0.5 // °C - ``` - -## Installation Checklist - -- [ ] All components soldered correctly -- [ ] No solder bridges or cold joints -- [ ] Power supply voltage verified (5V at ESP32) -- [ ] Sensor connections tested -- [ ] Firmware uploaded successfully -- [ ] WiFi connection established -- [ ] MQTT broker connection verified -- [ ] Sensors calibrated -- [ ] LEDs functioning correctly -- [ ] Enclosure properly sealed -- [ ] Mounting secure and stable -- [ ] Cable management complete -- [ ] Documentation updated with serial number - -## Troubleshooting - -### ESP32 Won't Boot - -- Check power supply voltage (should be 5V) -- Verify USB cable (use data cable, not charge-only) -- Press BOOT button during upload -- Check for shorts on power rails - -### WiFi Connection Fails - -- Verify SSID and password -- Check 2.4GHz band (ESP32 doesn't support 5GHz) -- Move closer to access point -- Check WiFi signal strength (RSSI > -80 dBm) - -### Sensor Reading Invalid - -- **Ultrasonic**: Check wiring, ensure clear line of sight -- **DHT22**: Verify pull-up resistor (10kΩ) -- **ADXL345**: Check I2C address (0x53), verify SDA/SCL - -### MQTT Not Connecting - -- Verify broker address and port -- Check firewall rules -- Ensure credentials are correct -- Test with mosquitto_sub tool - -## Safety Warnings - -⚠️ **Electrical Safety** -- Always disconnect power before making changes -- Use appropriate fuse ratings -- Ensure proper grounding - -⚠️ **Mechanical Safety** -- Secure all mounting hardware -- Use vibration-resistant connectors -- Protect cables from moving parts - -⚠️ **Environmental** -- Verify IP rating matches environment -- Protect from excessive heat/cold -- Keep away from moisture - -## Support - -For technical support: -- Email: hardware@kaldor-iiot.example.com -- Documentation: https://docs.kaldor-iiot.example.com -- GitHub Issues: Report hardware problems - ---- - -**Document Version**: 1.0 -**Last Updated**: 2025-11-22 diff --git a/docs/tech-debt-2026-05-26.adoc b/docs/tech-debt-2026-05-26.adoc new file mode 100644 index 0000000..05dd067 --- /dev/null +++ b/docs/tech-debt-2026-05-26.adoc @@ -0,0 +1,67 @@ +== Tech-Debt Audit — kaldor-iiot — 2026-05-26 + +*Source:* estate-wide automated scan 2026-05-26. *Companion:* +https://github.com/hyperpolymath/standards/tree/main/docs/audits[`+hyperpolymath/standards+` +2026-05-26-estate-*-debt audits]. *Combined severity:* `+LOW+`. + +This file records the _raw findings_ — it does not by itself fix the +debt. Each section ends with a '`Recommended next move`' line; closing +the debt is follow-up work. + +=== 1. Proof debt + +No proof-bearing files (`+*.v+`, `+*.lean+`, `+*.agda+`, `+*.idr+`, +`+*.idr2+`, `+*.fst+`, `+*.dfy+`, `+*.tla+`, `+*.ads+`, `+*.adb+`) found +in this repo. + +*Recommended next move:* none. + +=== 2. Licence debt + +[cols=",",options="header",] +|=== +|Field |Value +|LICENSE file |`+LICENSE+` +|SPDX header |`+MPL-2.0+` +|Manifest licence |`+NONE+` +|Body classifier |`+Palimp-MPL-2.0+` +|Severity |`+ok+` +|=== + +*Recommended next move:* none for licence. + +=== 3. Documentation debt + +[cols=",",options="header",] +|=== +|Field |Value +|README lines |285 +|`+docs/+` files |7 +|`+docs/+` LoC |2727 +|CHANGELOG.md |Y +|CONTRIBUTING.md |Y +|CODE_OF_CONDUCT.md |Y +|SECURITY.md |Y +|Severity |`+LOW+` +|=== + +*Recommended next move:* `+docs/+` has only 7 file(s). Aim for ≥10 +organised docs (architecture, usage, contributing-guide, +troubleshooting, design-decisions). The user’s bar for a +"`heavily-developed and well-organised wiki`" is ≥10 files with topical +organisation. + +=== Cross-references + +* Estate proof-debt audit: +`+hyperpolymath/standards/docs/audits/2026-05-26-estate-proof-debt.md+` +* Estate licence-debt audit: +`+hyperpolymath/standards/docs/audits/2026-05-26-estate-licence-debt.md+` +* Estate documentation-debt audit: +`+hyperpolymath/standards/docs/audits/2026-05-26-estate-documentation-debt.md+` + +''''' + +🤖 Generated by Claude Code estate-wide tech-debt scan (2026-05-26). +This file is informational — closing the debt is follow-up work owned by +the maintainer. diff --git a/docs/tech-debt-2026-05-26.md b/docs/tech-debt-2026-05-26.md deleted file mode 100644 index 3e11c28..0000000 --- a/docs/tech-debt-2026-05-26.md +++ /dev/null @@ -1,54 +0,0 @@ - -# Tech-Debt Audit — kaldor-iiot — 2026-05-26 - -**Source:** estate-wide automated scan 2026-05-26. -**Companion:** [`hyperpolymath/standards` 2026-05-26-estate-*-debt audits](https://github.com/hyperpolymath/standards/tree/main/docs/audits). -**Combined severity:** `LOW`. - -This file records the *raw findings* — it does not by itself fix the debt. Each section ends with a 'Recommended next move' line; closing the debt is follow-up work. - -## 1. Proof debt - -No proof-bearing files (`*.v`, `*.lean`, `*.agda`, `*.idr`, `*.idr2`, `*.fst`, `*.dfy`, `*.tla`, `*.ads`, `*.adb`) found in this repo. - -**Recommended next move:** none. - -## 2. Licence debt - -| Field | Value | -|---|---| -| LICENSE file | `LICENSE` | -| SPDX header | `MPL-2.0` | -| Manifest licence | `NONE` | -| Body classifier | `Palimp-MPL-2.0` | -| Severity | `ok` | - -**Recommended next move:** none for licence. - -## 3. Documentation debt - -| Field | Value | -|---|---| -| README lines | 285 | -| `docs/` files | 7 | -| `docs/` LoC | 2727 | -| CHANGELOG.md | Y | -| CONTRIBUTING.md | Y | -| CODE_OF_CONDUCT.md | Y | -| SECURITY.md | Y | -| Severity | `LOW` | - -**Recommended next move:** `docs/` has only 7 file(s). Aim for ≥10 organised docs (architecture, usage, contributing-guide, troubleshooting, design-decisions). The user's bar for a "heavily-developed and well-organised wiki" is ≥10 files with topical organisation. - -## Cross-references - -- Estate proof-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-proof-debt.md` -- Estate licence-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-licence-debt.md` -- Estate documentation-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-documentation-debt.md` - ---- - -🤖 Generated by Claude Code estate-wide tech-debt scan (2026-05-26). This file is informational — closing the debt is follow-up work owned by the maintainer. diff --git a/docs/user-guide/USER_MANUAL.adoc b/docs/user-guide/USER_MANUAL.adoc new file mode 100644 index 0000000..5b74260 --- /dev/null +++ b/docs/user-guide/USER_MANUAL.adoc @@ -0,0 +1,304 @@ +== Kaldor IIoT - User Manual + +=== Table of Contents + +[arabic] +. link:#introduction[Introduction] +. link:#getting-started[Getting Started] +. link:#dashboard-overview[Dashboard Overview] +. link:#monitoring-looms[Monitoring Looms] +. link:#alerts-and-notifications[Alerts and Notifications] +. link:#analytics[Analytics] +. link:#configuration[Configuration] +. link:#troubleshooting[Troubleshooting] + +=== Introduction + +Kaldor IIoT is an advanced monitoring system designed to track and +analyze the Back Beam Width (BBW) of industrial looms in real-time. The +system provides: + +* *Real-time monitoring* of BBW measurements +* *Automated alerts* for out-of-range conditions +* *Historical data analysis* and trends +* *Predictive maintenance* recommendations +* *Quality reporting* for production runs + +=== Getting Started + +==== Logging In + +[arabic] +. Navigate to the dashboard URL (e.g., `+http://kaldor-iiot.local+`) +. Enter your username and password +. Click "`Sign In`" + +*Default Credentials* (Change immediately after first login): - +Username: `+admin+` - Password: `+admin123+` + +==== First Time Setup + +After logging in for the first time: + +[arabic] +. Change your password in Settings +. Verify all looms are showing in the dashboard +. Check that all sensors are reporting data +. Configure alert thresholds for your production requirements + +=== Dashboard Overview + +The main dashboard displays: + +==== Summary Cards + +* *Total Looms*: Number of looms being monitored +* *Active Looms*: Looms currently in production +* *Alerts*: Number of unacknowledged alerts +* *System Health*: Overall system health percentage + +==== Loom Status Grid + +Each loom card shows: - Loom name and location - Current status (Active, +Idle, Warning, Error) - Model information - Quick status indicator + +Click on any loom card to view detailed information. + +=== Monitoring Looms + +==== Loom Detail View + +The loom detail page provides: + +===== Real-Time Metrics + +* *BBW (Current)*: Current back beam width measurement +* *Temperature*: Current environmental temperature +* *Vibration*: Vibration level (acceleration) +* *Quality*: Signal quality percentage + +===== Historical Trends + +* 24-hour BBW trend graph +* Min/max/average values +* Standard deviation over time + +==== Understanding Measurements + +*BBW (Back Beam Width)* - Normal range: 50-200 mm (configurable) - +Tolerance: ±2 mm typical - Update frequency: 1 second + +*Temperature* - Normal range: 15-35°C - High temperature alert: > 35°C - +Critical alert: > 40°C + +*Vibration* - Normal: < 1.0 g - Warning: 1.0-3.0 g - Critical: > 3.0 g + +=== Alerts and Notifications + +==== Alert Types + +[arabic] +. *BBW Out of Range*: Measurement outside configured thresholds +. *High Temperature*: Environmental temperature too high +. *Excessive Vibration*: Abnormal vibration detected +. *Sensor Failure*: Sensor malfunction or communication loss +. *Device Offline*: Loom sensor board not responding + +==== Alert Severity Levels + +* *Critical* (Red): Immediate action required +* *Warning* (Yellow): Attention needed soon +* *Info* (Blue): Informational only + +==== Managing Alerts + +To acknowledge an alert: + +[arabic] +. Go to the Alerts page +. Find the alert in the list +. Click "`Acknowledge`" button +. Add a comment (optional) + +==== Notification Settings + +Configure notifications in Settings: + +* *Email Alerts*: Receive emails for critical alerts +* *SMS Alerts*: Text messages for urgent issues +* *Notification Schedule*: Set quiet hours + +=== Analytics + +==== Quality Reports + +Generate quality reports for production runs: + +[arabic] +. Navigate to Analytics +. Select loom and time period +. Click "`Generate Report`" +. View or download PDF + +Reports include: - Average BBW measurements - Standard deviation - +Min/max values - Quality score - Recommendations + +==== Predictive Maintenance + +The system analyzes historical data to predict maintenance needs: + +* *Health Score*: 0-100 scale of loom condition +* *Trend Analysis*: Increasing/decreasing variability +* *Recommendations*: Suggested maintenance actions +* *Urgency Level*: Low/Medium/High priority + +==== Anomaly Detection + +Automatic detection of unusual patterns: + +* Statistical analysis (z-score > 3) +* Trend changes +* Unexpected variations +* Pattern recognition + +=== Configuration + +==== Loom Configuration + +To configure a loom: + +[arabic] +. Go to loom detail page +. Click "`Configure`" button +. Adjust settings: +* BBW thresholds (min/max) +* Sampling rate +* Alert sensitivity +* Temperature limits +* Vibration thresholds +. Click "`Save`" + +Configuration is sent to the device in real-time. + +==== User Management + +Administrators can: + +[arabic] +. Add new users (Settings → Users → Add User) +. Assign roles (Admin, Operator, Viewer) +. Manage permissions +. Reset passwords + +==== System Settings + +* *Data Retention*: How long to keep historical data +* *Update Frequency*: Dashboard refresh rate +* *Display Units*: Metric/Imperial +* *Time Zone*: Local time zone +* *Language*: Interface language (if supported) + +=== Troubleshooting + +==== Loom Shows "`Offline`" + +[arabic] +. Check physical power to sensor board +. Verify network connection (WiFi/Ethernet) +. Check MQTT broker status +. View device logs for errors + +==== Inaccurate Readings + +[arabic] +. Verify sensor calibration +. Check sensor mounting and alignment +. Clean sensor lenses +. Inspect cables for damage +. Recalibrate if necessary + +==== No Alerts Received + +[arabic] +. Check alert threshold configuration +. Verify notification settings (email/SMS) +. Check spam folder for email alerts +. Verify SMTP/Twilio configuration + +==== Dashboard Not Updating + +[arabic] +. Check internet connection +. Refresh browser page +. Clear browser cache +. Try different browser +. Check for system maintenance + +==== Cannot Login + +[arabic] +. Verify username and password +. Check Caps Lock is off +. Try password reset +. Contact administrator +. Check browser cookies enabled + +=== Best Practices + +==== Daily Operations + +* Check dashboard at start of shift +* Acknowledge all alerts promptly +* Monitor trends for gradual changes +* Report anomalies to maintenance + +==== Weekly Tasks + +* Review weekly quality reports +* Check predictive maintenance scores +* Verify all looms reporting correctly +* Update configurations as needed + +==== Monthly Maintenance + +* Clean all sensors +* Verify calibration +* Review alert thresholds +* Update firmware if available +* Backup configuration settings + +=== Support + +==== Getting Help + +* *User Manual*: This document +* *FAQ*: See FAQ.md +* *Technical Support*: support@kaldor-iiot.example.com +* *Phone*: +1-234-567-8900 +* *Hours*: Monday-Friday, 8AM-5PM EST + +==== Reporting Issues + +When reporting an issue, include: + +[arabic] +. Loom ID and device ID +. Description of problem +. Steps to reproduce +. Screenshots if applicable +. Time and date of occurrence + +=== Glossary + +* *BBW*: Back Beam Width +* *IIoT*: Industrial Internet of Things +* *MQTT*: Message Queuing Telemetry Transport +* *Sensor Board*: ESP32-based measurement device +* *Threshold*: Min/max acceptable value +* *Telemetry*: Remote measurement data +* *OTA*: Over-The-Air (firmware update) + +''''' + +*Document Version*: 1.0 *Last Updated*: 2025-11-22 *For*: Kaldor IIoT +v1.0.0 diff --git a/docs/user-guide/USER_MANUAL.md b/docs/user-guide/USER_MANUAL.md deleted file mode 100644 index 9ff193c..0000000 --- a/docs/user-guide/USER_MANUAL.md +++ /dev/null @@ -1,309 +0,0 @@ - -# Kaldor IIoT - User Manual - -## Table of Contents - -1. [Introduction](#introduction) -2. [Getting Started](#getting-started) -3. [Dashboard Overview](#dashboard-overview) -4. [Monitoring Looms](#monitoring-looms) -5. [Alerts and Notifications](#alerts-and-notifications) -6. [Analytics](#analytics) -7. [Configuration](#configuration) -8. [Troubleshooting](#troubleshooting) - -## Introduction - -Kaldor IIoT is an advanced monitoring system designed to track and analyze the Back Beam Width (BBW) of industrial looms in real-time. The system provides: - -- **Real-time monitoring** of BBW measurements -- **Automated alerts** for out-of-range conditions -- **Historical data analysis** and trends -- **Predictive maintenance** recommendations -- **Quality reporting** for production runs - -## Getting Started - -### Logging In - -1. Navigate to the dashboard URL (e.g., `http://kaldor-iiot.local`) -2. Enter your username and password -3. Click "Sign In" - -**Default Credentials** (Change immediately after first login): -- Username: `admin` -- Password: `admin123` - -### First Time Setup - -After logging in for the first time: - -1. Change your password in Settings -2. Verify all looms are showing in the dashboard -3. Check that all sensors are reporting data -4. Configure alert thresholds for your production requirements - -## Dashboard Overview - -The main dashboard displays: - -### Summary Cards - -- **Total Looms**: Number of looms being monitored -- **Active Looms**: Looms currently in production -- **Alerts**: Number of unacknowledged alerts -- **System Health**: Overall system health percentage - -### Loom Status Grid - -Each loom card shows: -- Loom name and location -- Current status (Active, Idle, Warning, Error) -- Model information -- Quick status indicator - -Click on any loom card to view detailed information. - -## Monitoring Looms - -### Loom Detail View - -The loom detail page provides: - -#### Real-Time Metrics - -- **BBW (Current)**: Current back beam width measurement -- **Temperature**: Current environmental temperature -- **Vibration**: Vibration level (acceleration) -- **Quality**: Signal quality percentage - -#### Historical Trends - -- 24-hour BBW trend graph -- Min/max/average values -- Standard deviation over time - -### Understanding Measurements - -**BBW (Back Beam Width)** -- Normal range: 50-200 mm (configurable) -- Tolerance: ±2 mm typical -- Update frequency: 1 second - -**Temperature** -- Normal range: 15-35°C -- High temperature alert: > 35°C -- Critical alert: > 40°C - -**Vibration** -- Normal: < 1.0 g -- Warning: 1.0-3.0 g -- Critical: > 3.0 g - -## Alerts and Notifications - -### Alert Types - -1. **BBW Out of Range**: Measurement outside configured thresholds -2. **High Temperature**: Environmental temperature too high -3. **Excessive Vibration**: Abnormal vibration detected -4. **Sensor Failure**: Sensor malfunction or communication loss -5. **Device Offline**: Loom sensor board not responding - -### Alert Severity Levels - -- **Critical** (Red): Immediate action required -- **Warning** (Yellow): Attention needed soon -- **Info** (Blue): Informational only - -### Managing Alerts - -To acknowledge an alert: - -1. Go to the Alerts page -2. Find the alert in the list -3. Click "Acknowledge" button -4. Add a comment (optional) - -### Notification Settings - -Configure notifications in Settings: - -- **Email Alerts**: Receive emails for critical alerts -- **SMS Alerts**: Text messages for urgent issues -- **Notification Schedule**: Set quiet hours - -## Analytics - -### Quality Reports - -Generate quality reports for production runs: - -1. Navigate to Analytics -2. Select loom and time period -3. Click "Generate Report" -4. View or download PDF - -Reports include: -- Average BBW measurements -- Standard deviation -- Min/max values -- Quality score -- Recommendations - -### Predictive Maintenance - -The system analyzes historical data to predict maintenance needs: - -- **Health Score**: 0-100 scale of loom condition -- **Trend Analysis**: Increasing/decreasing variability -- **Recommendations**: Suggested maintenance actions -- **Urgency Level**: Low/Medium/High priority - -### Anomaly Detection - -Automatic detection of unusual patterns: - -- Statistical analysis (z-score > 3) -- Trend changes -- Unexpected variations -- Pattern recognition - -## Configuration - -### Loom Configuration - -To configure a loom: - -1. Go to loom detail page -2. Click "Configure" button -3. Adjust settings: - - BBW thresholds (min/max) - - Sampling rate - - Alert sensitivity - - Temperature limits - - Vibration thresholds - -4. Click "Save" - -Configuration is sent to the device in real-time. - -### User Management - -Administrators can: - -1. Add new users (Settings → Users → Add User) -2. Assign roles (Admin, Operator, Viewer) -3. Manage permissions -4. Reset passwords - -### System Settings - -- **Data Retention**: How long to keep historical data -- **Update Frequency**: Dashboard refresh rate -- **Display Units**: Metric/Imperial -- **Time Zone**: Local time zone -- **Language**: Interface language (if supported) - -## Troubleshooting - -### Loom Shows "Offline" - -1. Check physical power to sensor board -2. Verify network connection (WiFi/Ethernet) -3. Check MQTT broker status -4. View device logs for errors - -### Inaccurate Readings - -1. Verify sensor calibration -2. Check sensor mounting and alignment -3. Clean sensor lenses -4. Inspect cables for damage -5. Recalibrate if necessary - -### No Alerts Received - -1. Check alert threshold configuration -2. Verify notification settings (email/SMS) -3. Check spam folder for email alerts -4. Verify SMTP/Twilio configuration - -### Dashboard Not Updating - -1. Check internet connection -2. Refresh browser page -3. Clear browser cache -4. Try different browser -5. Check for system maintenance - -### Cannot Login - -1. Verify username and password -2. Check Caps Lock is off -3. Try password reset -4. Contact administrator -5. Check browser cookies enabled - -## Best Practices - -### Daily Operations - -- Check dashboard at start of shift -- Acknowledge all alerts promptly -- Monitor trends for gradual changes -- Report anomalies to maintenance - -### Weekly Tasks - -- Review weekly quality reports -- Check predictive maintenance scores -- Verify all looms reporting correctly -- Update configurations as needed - -### Monthly Maintenance - -- Clean all sensors -- Verify calibration -- Review alert thresholds -- Update firmware if available -- Backup configuration settings - -## Support - -### Getting Help - -- **User Manual**: This document -- **FAQ**: See FAQ.md -- **Technical Support**: support@kaldor-iiot.example.com -- **Phone**: +1-234-567-8900 -- **Hours**: Monday-Friday, 8AM-5PM EST - -### Reporting Issues - -When reporting an issue, include: - -1. Loom ID and device ID -2. Description of problem -3. Steps to reproduce -4. Screenshots if applicable -5. Time and date of occurrence - -## Glossary - -- **BBW**: Back Beam Width -- **IIoT**: Industrial Internet of Things -- **MQTT**: Message Queuing Telemetry Transport -- **Sensor Board**: ESP32-based measurement device -- **Threshold**: Min/max acceptable value -- **Telemetry**: Remote measurement data -- **OTA**: Over-The-Air (firmware update) - ---- - -**Document Version**: 1.0 -**Last Updated**: 2025-11-22 -**For**: Kaldor IIoT v1.0.0 diff --git a/docs/white-paper/KALDOR_WHITE_PAPER.adoc b/docs/white-paper/KALDOR_WHITE_PAPER.adoc new file mode 100644 index 0000000..54891ac --- /dev/null +++ b/docs/white-paper/KALDOR_WHITE_PAPER.adoc @@ -0,0 +1,1232 @@ +== Kaldor Community Manufacturing Platform + +=== White Paper: Hyperlocal Textile Production as Economic Infrastructure + +*Version*: 1.0.0 *Date*: November 2025 *Authors*: Kaldor Community +Platform Team *License*: CC-BY-SA-4.0 *DOI*: [Pending] + +''''' + +=== Executive Summary + +The *Kaldor Community Manufacturing Platform* transforms spare rooms +into a distributed, community-owned textile manufacturing network. By +applying *Kaldor’s Second Law* (Verdoorn’s Law) - "`the rate of growth +in productivity is positively related to the rate of growth of +manufacturing output`" - at the _community level_ rather than corporate +level, we create increasing returns to scale for local economies. + +*Key Findings*: + +* *Economic*: £65,000+ annual revenue potential from 3 spare rooms (spin ++ weave + print) +* *Social*: 15-20 local jobs created per community cluster (25 +households) +* *Environmental*: 60-80% reduction in carbon vs. centralized +manufacturing +* *Kaldor’s Law*: 2.3x productivity multiplier observed in pilot +communities +* *Accessibility*: £8,000-£12,000 initial investment per room (payback +<18 months) + +*Business Models Supported*: 8 sectors from household to commons +(excluding corporate extraction) + +''''' + +=== Table of Contents + +[arabic] +. link:#1-the-problem[The Problem: Centralized Manufacturing] +. link:#2-the-solution[The Solution: Hyperlocal Networks] +. link:#3-kaldors-law[Kaldor’s Law 2: Theoretical Foundation] +. link:#4-technical-architecture[Technical Architecture] +. link:#5-economic-models[Economic Models (1st-8th Sector)] +. link:#6-financial-projections[Financial Projections] +. link:#7-community-governance[Community Governance] +. link:#8-environmental-impact[Environmental Impact] +. link:#9-risk-analysis[Risk Analysis] +. link:#10-implementation-roadmap[Implementation Roadmap] +. link:#11-case-studies[Case Studies] +. link:#12-appendices[Appendices] + +''''' + +=== 1. The Problem: Centralized Manufacturing + +==== 1.1 Economic Extraction + +Global textile manufacturing is concentrated in: - *Geographic +monopolies*: 60% of global textile production in China, Bangladesh, +Vietnam - *Corporate consolidation*: Top 10 companies control 45% of +market - *Value extraction*: £1 shirt costs £0.15 to make, sells for +£15-25 (100x markup) - *Wage suppression*: Race to bottom ($68/month +Bangladesh minimum wage) + +==== 1.2 Supply Chain Fragility + +COVID-19 exposed vulnerabilities: - *Lead times*: 6-12 months for custom +orders - *Inventory risk*: £billions in unsold stock - *Transportation*: +30-40% of product cost - *Quality control*: Disconnection between +designer and producer + +==== 1.3 Environmental Costs + +Textile industry accounts for: - *10% of global carbon emissions* (more +than aviation + shipping combined) - *20% of industrial water pollution* +- *92 million tonnes* of textile waste annually - *Average garment +travels 20,000 km* from fiber to consumer + +==== 1.4 Community Deskilling + +Historical loss of local manufacturing knowledge: - *1970*: UK had 1.5M +textile workers - *2023*: <100,000 remain (93% decline) - *Skills gap*: +2-3 generations lost craft knowledge - *Dependency*: Communities now +reliant on distant supply chains + +*The Core Problem*: Centralized manufacturing creates economic +extraction, environmental harm, supply chain fragility, and community +deskilling. + +''''' + +=== 2. The Solution: Hyperlocal Networks + +==== 2.1 The Spare Room Economy + +*Insight*: 8.2 million UK households have at least one spare room (ONS, +2021). + +*Opportunity*: - *Unutilized capital*: Spare rooms average 10-15m² of +unused space - *Sunk costs*: Already paid for (mortgage/rent), heating, +electricity infrastructure - *Accessibility*: Lower barrier than +standalone premises - *Distributed*: Natural mesh topology across +communities + +==== 2.2 Three-Node Minimum Viable Network + +A hyperlocal textile supply chain requires three stations: + +===== *Node 1: Spinning Station* (Fiber → Yarn) + +* *Space*: 1.5m x 1.5m (2.25m²) +* *Equipment*: Electric spinner, fiber prep tools, storage +* *Output*: 2-5 kg yarn/day (depending on fiber) +* *Skill*: Beginner-friendly (2-week training) +* *Investment*: £2,500-£4,000 + +===== *Node 2: Weaving Station* (Yarn → Fabric) + +* *Space*: 2m x 1.5m (3m²) +* *Equipment*: Table loom (4-8 shaft), warping board, shuttle +* *Output*: 3-8 meters fabric/day +* *Skill*: Intermediate (1-month training) +* *Investment*: £3,500-£6,000 + +===== *Node 3: 3D Print/Finishing* (Fabric → Product) + +* *Space*: 1.5m x 1.5m (2.25m²) +* *Equipment*: Textile 3D printer OR sewing station + laser cutter +* *Output*: 5-15 products/day +* *Skill*: Beginner to intermediate +* *Investment*: £2,000-£4,000 + +*Total Network*: 7.5m² (~80 sq ft), £8,000-£14,000 investment + +==== 2.3 Network Topology + +.... + House A House B House C + ┌───────────┐ ┌───────────┐ ┌───────────┐ + │ Spinning │───────▶│ Weaving │───────▶│ Printing │ + │ Station │ │ Station │ │ Station │ + └───────────┘ └───────────┘ └───────────┘ + │ │ │ + └────────────────────┴────────────────────┘ + │ + ┌────────▼────────┐ + │ Community Hub │ + │ (Finishing & │ + │ Distribution) │ + └─────────────────┘ +.... + +*Scaling*: Each node can serve multiple neighbors, creating mesh +resilience. + +''''' + +=== 3. Kaldor’s Law 2: Theoretical Foundation + +==== 3.1 Verdoorn’s Law (Kaldor’s Second Law) + +*Original Formulation* (Nicholas Kaldor, 1966): + +____ +"`The rate of growth in productivity (p) is positively related to the +rate of growth of manufacturing output (q)`" +____ + +Mathematically: + +.... +p = a + bq + +Where: + p = productivity growth rate + q = output growth rate + a = autonomous productivity growth (technology, skills) + b = Verdoorn coefficient (typically 0.45-0.50) +.... + +*Implication*: Doubling manufacturing output increases productivity by +45-50%, creating increasing returns to scale. + +==== 3.2 Application to Hyperlocal Manufacturing + +*Traditional Interpretation* (Corporate): - Centralized factories +achieve economies of scale - Productivity increases with factory size - +Justifies geographic consolidation + +*Kaldor Community Interpretation* (Network): - *Distributed scale*: Sum +of network nodes, not single factory - *Learning-by-doing*: Shared +knowledge base across community - *Specialization*: Nodes develop +expertise (expert spinner, expert weaver) - *Coordination efficiency*: +Local = lower transaction costs + +*Key Difference*: We achieve Verdoorn returns through _network effects_, +not _factory size_. + +==== 3.3 Empirical Evidence + +Pilot study (N=12 households, 6-month period): + +[cols=",,,,",options="header",] +|=== +|Metric |Month 1 |Month 3 |Month 6 |Growth +|Output (meters/day) |2.3 |4.1 |5.8 |152% +|Productivity (m/hour) |0.8 |1.4 |2.2 |175% +|Defect rate |12% |6% |3% |-75% +|Setup time (min) |45 |25 |15 |-67% +|=== + +*Verdoorn coefficient (b)*: 0.52 (consistent with Kaldor’s predictions) + +*Mechanism Analysis*: 1. *Month 1-2*: Learning phase, high variability +2. *Month 3-4*: Specialization emerges, knowledge sharing accelerates 3. +*Month 5-6*: Process optimization, standardization benefits + +*Conclusion*: Kaldor’s Law holds at community scale when network effects +replace factory scale. + +''''' + +=== 4. Technical Architecture + +See link:../../ARCHITECTURE-v2.md[ARCHITECTURE-v2.md] for complete +technical specification. + +*Key Technical Innovations*: + +[arabic] +. *Offline-First CRDTs*: Production continues without internet +. *Matter Protocol*: Open standard for device interoperability +. *RISC-V Firmware*: Open-source hardware platform (ESP32-C6) +. *WASM Acceleration*: Near-native performance for pattern generation +. *OPC UA/Modbus*: Integration with existing industrial equipment +. *CURP Consensus*: Community governance without central authority + +*Technology Stack*: - *Backend*: Deno (secure TypeScript runtime) - +*Frontend*: ReScript (sound type system) - *WASM*: Rust (memory-safe, +high-performance) - *Firmware*: Rust on RISC-V (zero unsafe blocks) - +*Database*: TimescaleDB + Automerge (offline-first) + +''''' + +=== 5. Economic Models (1st-8th Sector) + +We support *8 alternative economic models*, deliberately excluding +extractive corporate structures: + +==== 5.1 First Sector: Household/Family + +*Model*: Personal/family production for own use or barter + +*Example*: Retired couple with spare room, making textiles for family + +*Economics*: - *Investment*: £3,000-£5,000 (one station) - *Revenue*: £0 +(gift economy) - *Value*: £8,000-£12,000/year equivalent (saved +purchases) - *Tax*: None (personal use exempt) + +*Kaldor Platform Support*: - Pattern library (free templates) - +Equipment subsidies (community tool library) - Training workshops +(peer-to-peer) - No transaction fees + +*Legal Structure*: None required + +''''' + +==== 5.2 Second Sector: Social Enterprise + +*Model*: Community Interest Company (CIC) or Community Benefit Society + +*Example*: 25-household neighborhood cooperative + +*Economics*: - *Investment*: £25,000-£40,000 (3-node network + hub) - +*Revenue*: £45,000-£75,000/year (custom orders + workshop fees) - +*Surplus*: Reinvested in community (55% asset lock) - *Jobs*: 3-5 +part-time positions (living wage) + +*Kaldor Platform Support*: - Governance templates (quadratic voting) - +Accounting integration (transparent finances) - Job scheduler (fair work +distribution) - Skills marketplace + +*Legal Structures*: - *CIC* (Community Interest Company): UK limited +company with asset lock - *Community Benefit Society*: Co-operative +ownership - *Charitable Incorporated Organisation* (CIO): If primarily +educational + +*Tax Benefits*: - CIC: Corporation tax relief on community benefit +activities - CBS: Potential charity status (zero corporation tax) + +''''' + +==== 5.3 Third Sector: Charity/Non-Profit + +*Model*: Registered charity with textile production as social mission + +*Example*: "`ThreadCare`" - textile training for unemployed youth + +*Economics*: - *Investment*: £50,000-£80,000 (grants + donations) - +*Revenue*: £60,000-£90,000/year (80% grants, 20% sales) - +*Beneficiaries*: 30-50 trainees/year - *Jobs*: 2-3 staff + 10-15 +trainees + +*Kaldor Platform Support*: - Grant application templates - Impact +measurement tools - Trainee progress tracking - Certification pathways + +*Legal Structure*: Registered Charity (England & Wales Charity +Commission) + +*Tax Benefits*: - Zero corporation tax - Gift Aid on donations (25% +uplift) - Business rate exemption (80-100%) - VAT exemption on education + +*Eligibility*: Must demonstrate public benefit (Charity Commission test) + +''''' + +==== 5.4 Fourth Sector: Worker Cooperative + +*Model*: Worker-owned cooperative (1 member = 1 vote) + +*Example*: 7 makers form "`LocalLooms Co-op`" + +*Economics*: - *Investment*: £12,000-£18,000 (member equity + loan) - +*Revenue*: £85,000-£120,000/year - *Distribution*: Patronage dividends +based on hours worked - *Jobs*: 7 full-time equivalents + +*Kaldor Platform Support*: - Democratic governance tools (Loomio +integration) - Transparent accounting (OpenCollective) - Fair +compensation algorithms - Conflict resolution protocols + +*Legal Structure*: Cooperative Society (registered with FCA) + +*Tax Benefits*: - Corporation tax relief on member bonuses - Shared +ownership relief (SEIS/EIS eligible) + +*Governance*: - 1 member = 1 vote - Surplus distributed by patronage +(hours worked) - Open membership (vetted) + +''''' + +==== 5.5 Fifth Sector: Platform Cooperative + +*Model*: Multi-stakeholder cooperative (producers + consumers) + +*Example*: "`FairThread`" - 200 makers + 5,000 customers + +*Economics*: - *Investment*: £150,000-£250,000 (platform development + +local hubs) - *Revenue*: £850,000-£1.2M/year - *Distribution*: 40% +makers, 40% reinvestment, 20% customer dividends - *Jobs*: 50-80 makers, +10-15 staff + +*Kaldor Platform Support*: - Marketplace infrastructure (no fees to +Kaldor) - Supply chain coordination - Demand aggregation - Quality +assurance + +*Legal Structure*: Multi-stakeholder Cooperative + +*Governance*: - 40% makers (1 maker = 1 vote) - 30% customers (quadratic +voting) - 20% workers (staff) - 10% community (local councils, +charities) + +*Revenue Model*: - 5% transaction fee (covers platform costs only) - +£2/month pro membership (optional, premium features) + +''''' + +==== 5.6 Sixth Sector: Community Land Trust (CLT) + +*Model*: Non-profit owns premises, leases to makers at below-market +rates + +*Example*: "`Mill Commons CLT`" - owns building, 12 maker spaces + +*Economics*: - *Investment*: £400,000-£800,000 (property acquisition + +fit-out) - *Revenue*: £48,000-£72,000/year (below-market rents) - +*Leases*: £200-£400/month per space (50-70% below market) - *Asset +appreciation*: Locked in trust (no speculation) + +*Kaldor Platform Support*: - Property assessment tools - Lease templates +- Maintenance scheduling - Shared equipment booking + +*Legal Structure*: Community Benefit Society (asset-locked) + +*Tax Benefits*: - Business rate relief (discretionary, up to 100%) - VAT +exemption on rent (if charitable) - Capital Gains Tax exemption (if +reinvested in community) + +*Land Ownership*: - CLT owns freehold in perpetuity - 99-year leases to +makers - Resale formula caps price (prevents speculation) - Community +has first right of refusal + +''''' + +==== 5.7 Seventh Sector: Mutual Aid Network + +*Model*: Gift economy + time banking, no money exchange + +*Example*: "`ThreadBank`" - 50 members exchange textile services for +time credits + +*Economics*: - *Investment*: £0 (borrowed/donated equipment) - +*Revenue*: £0 (no monetary transactions) - *Value*: 2,000-3,000 +hours/year exchanged - *Equivalence*: £25,000-£40,000 of services (if +monetized) + +*Kaldor Platform Support*: - Time banking ledger (automatic) - Skill +matching algorithm - Reputation system (without coercion) - Conflict +mediation tools + +*Legal Structure*: Unincorporated association (no formal registration +needed) + +*Tax*: None (mutual aid exempt as non-commercial) + +*Time Banking Rates*: - 1 hour spinning = 1 credit - 1 hour weaving = 1 +credit - 1 hour teaching = 1 credit - *No skill hierarchy* (all labor +valued equally) + +''''' + +==== 5.8 Eighth Sector: Commons/Public Goods + +*Model*: Public ownership (council/government), free access + +*Example*: "`Manchester Textile Commons`" - council-owned, free +equipment access + +*Economics*: - *Investment*: £200,000-£400,000 (public funding) - +*Revenue*: £0 (free to residents) - *Usage*: 500-800 users/year - +*Value*: £180,000-£300,000 public benefit/year + +*Kaldor Platform Support*: - Booking system (fair allocation) - +Maintenance tracking - Usage analytics (demonstrate public value) - +Safety compliance + +*Legal Structure*: - Local authority asset - Managed by council or +delegated to trust - Free access (or nominal fee for materials only) + +*Funding*: - Council budget allocation - Levelling Up Fund - UK Shared +Prosperity Fund - Arts Council England + +*Access Policy*: - Priority: Local residents, low-income, students - +Booking: Max 4 hours/week to ensure fair access - Training: Mandatory +safety induction (free) + +''''' + +==== 5.9 Sector Comparison Matrix + +[width="100%",cols="12%,13%,18%,16%,21%,20%",options="header",] +|=== +|Sector |Ownership |Profit Motive |Tax Benefits |Barrier to Entry |Scale +Potential +|1. Household |Family |None (gift) |Exempt |Very Low |Individual + +|2. Social Enterprise |Community |Capped |Moderate |Low |Neighborhood + +|3. Charity |Public trust |Zero |Highest |Medium |Regional + +|4. Worker Coop |Workers |Shared |Moderate |Low |Local-Regional + +|5. Platform Coop |Multi-stake |Shared |Moderate |Medium |National + +|6. CLT |Community |Zero (land) |High |High |Neighborhood + +|7. Mutual Aid |None |Zero |Exempt |Very Low |Local + +|8. Commons |Public |Zero |N/A (public) |None (users) |Municipal +|=== + +*Deliberately Excluded: Corporate (9th Sector)* - *Why*: Extractive +profit motive incompatible with community benefit - *Risk*: Shareholder +primacy → wage suppression, community exploitation - *Alternative*: If +commercial scale needed, use Platform Cooperative (5th sector) + +''''' + +=== 6. Financial Projections + +==== 6.1 Single-Node Economics (One Spare Room) + +*Scenario*: Household spinning station, part-time operation + +*Initial Investment*: + +.... +Electric spinner: £1,800 +Fiber prep tools: £400 +Storage/shelving: £200 +Materials (startup): £300 +Training course: £250 +Insurance: £150 +───────────────────────────── +TOTAL: £3,100 +.... + +*Monthly Operating Costs*: + +.... +Fiber (2 kg/day x 20 days): £240 +Electricity (additional): £25 +Equipment maintenance: £15 +Insurance: £15 +Platform fees: £5 +───────────────────────────── +TOTAL: £300 +.... + +*Revenue* (Part-time: 3 days/week, 4 hours/day): + +.... +Output: 2 kg yarn/day x 12 days/month = 24 kg/month +Selling price: £28/kg (artisan wool yarn) +Revenue: 24 kg x £28 = £672/month +.... + +*Profitability*: + +.... +Monthly revenue: £672 +Monthly costs: £300 +Monthly profit: £372 +Annual profit: £4,464 + +Payback period: £3,100 ÷ £372 = 8.3 months +ROI (Year 1): 44% +.... + +''''' + +==== 6.2 Three-Node Network Economics + +*Scenario*: 3 households (spin + weave + print), coordinated production + +*Combined Investment*: + +.... +Spinning station: £3,100 +Weaving station: £4,800 +3D print/finishing: £3,200 +Shared tools: £1,200 +Community hub setup: £2,500 +───────────────────────────── +TOTAL: £14,800 +.... + +*Monthly Operating Costs*: + +.... +Materials (all stations): £850 +Utilities: £120 +Equipment maintenance: £80 +Insurance: £60 +Platform/software: £20 +Marketing: £50 +───────────────────────────── +TOTAL: £1,180 +.... + +*Revenue* (Full-time equivalent: 160 hours/month): + +.... +Products sold: + - 15 custom shirts @ £65 = £975 + - 8 meters fabric @ £45 = £360 + - 12 accessories @ £25 = £300 + - 5 custom orders @ £120 = £600 + - Workshop fees (4 sessions): £320 +──────────────────────────────────── +Monthly revenue: £2,555 +.... + +*Profitability*: + +.... +Monthly revenue: £2,555 +Monthly costs: £1,180 +Monthly profit: £1,375 +Annual profit: £16,500 + +Payback period: £14,800 ÷ £1,375 = 10.7 months +ROI (Year 1): 11% +ROI (Year 2): 111% (no capital costs) +.... + +*Distribution (Worker Coop Model)*: + +.... +3 households: + - £5,500/year each (part-time income) + - 10-15 hours/week commitment + - Equivalent to £11-12/hour + +Reinvestment fund: + - £1,000/year equipment upgrades +.... + +''''' + +==== 6.3 Community Hub Economics (25 Households) + +*Scenario*: Neighborhood-scale production, CIC structure + +*Investment*: + +.... +Property lease (year 1): £12,000 +Equipment (12 stations): £45,000 +Hub infrastructure: £8,000 +IT/software: £3,000 +Legal/registration: £1,500 +Working capital: £5,000 +───────────────────────────────────── +TOTAL: £74,500 +.... + +*Revenue Streams*: + +.... +Product sales (wholesale + retail): £48,000/year +Custom orders (B2B): £18,000/year +Workshop/training fees: £12,000/year +Equipment rental (external): £3,600/year +Grants (social impact): £6,000/year +───────────────────────────────────────────── +TOTAL: £87,600/year +.... + +*Operating Costs*: + +.... +Rent: £12,000 +Salaries (3 FTE): £36,000 +Materials: £14,400 +Utilities: £3,600 +Marketing: £2,400 +Insurance: £1,800 +Maintenance: £2,400 +Admin/legal: £1,200 +──────────────────────────────────── +TOTAL: £73,800/year +.... + +*Financial Performance*: + +.... +Revenue: £87,600 +Costs: £73,800 +Surplus: £13,800 + +Asset lock (55% CIC): £7,590 → community reinvestment +Distributable: £6,210 → member dividends + +ROI: 18.5% (Year 1) +Jobs created: 18-22 (3 FTE + 15-19 part-time) +.... + +''''' + +==== 6.4 Sensitivity Analysis + +*Risk Factors*: + +[cols=",,,,",options="header",] +|=== +|Variable |Base Case |Pessimistic |Optimistic |Impact on ROI +|Material costs |£850/mo |£1,100 (+29%) |£700 (-18%) |±8% +|Selling price |£28/kg |£22 (-21%) |£35 (+25%) |±15% +|Output (kg/day) |2.0 |1.5 (-25%) |2.8 (+40%) |±12% +|Defect rate |5% |12% (+140%) |2% (-60%) |±4% +|Demand |High |Medium |Very High |±20% +|=== + +*Break-even Analysis* (3-node network): + +.... +Fixed costs: £14,800 (initial) +Variable costs: £1,180/month +Contribution margin: 54% (£1,375 profit ÷ £2,555 revenue) + +Break-even time: 12.5 months (worst case) + 8.2 months (best case) +.... + +*Stress Test*: Platform survives: - ✅ 30% drop in demand (still +profitable) - ✅ 40% increase in material costs (breakeven) - ⚠️ 50% +drop in selling prices (loss-making → reduce hours or seek grants) + +''''' + +=== 7. Community Governance + +==== 7.1 CURP Consensus Protocol + +*CURP* (Consistent Unordered Replication Protocol) enables decentralized +decision-making without central authority. + +*How It Works*: 1. *Proposal*: Member submits governance proposal (e.g., +"`Add new node to network`") 2. *Replication*: Proposal distributed to +all nodes (offline-capable via CRDTs) 3. *Voting*: Quadratic voting +(voice credits based on contribution) 4. *Consensus*: Requires 66% +approval + no single blocking vote >25% 5. *Execution*: Automated via +smart contracts (local, not blockchain) + +*Advantages Over Blockchain*: - ✅ Works offline (no internet required) +- ✅ Zero transaction fees - ✅ Energy efficient (no proof-of-work) - ✅ +Human-readable audit trail + +*Example Vote*: + +.... +Proposal: "Purchase shared laser cutter (£2,400)" +Votes: + - Alice: 9 credits FOR (cost: 81 credits) + - Bob: 4 credits FOR (cost: 16 credits) + - Carol: 2 credits AGAINST (cost: 4 credits) + - Dave: 5 credits FOR (cost: 25 credits) + +Result: 18 FOR vs 2 AGAINST = 90% approval → PASSED +.... + +==== 7.2 Quadratic Voting Mathematics + +*Why Quadratic?* - Prevents majority tyranny (passionate minority can +block) - Incentivizes coalition-building (cheaper to persuade than +outbid) - Respects expertise (earned voice credits) + +*Voice Credit Allocation*: + +.... +New member: 10 credits +1 month contribution: +5 credits +1 merged PR: +2 credits +1 workshop taught: +3 credits +1 year membership: +20 credits + +Max accumulation: 100 credits (prevents plutocracy) +Credits decay: -10% per year (encourages active participation) +.... + +==== 7.3 Dispute Resolution + +*Three-Tier System*: + +[arabic] +. *Tier 1: Mediation* (Community Steward) +* Voluntary, non-binding +* 80% of disputes resolved here +* Free, 2-week timeline +. *Tier 2: Arbitration* (Elected Panel) +* Binding decision +* Panel of 3 (1 from each TPCF perimeter) +* £50 filing fee (refunded if upheld) +* 4-week timeline +. *Tier 3: External Review* (Software Freedom Conservancy) +* Appeals only +* Legal expert panel +* Costs shared by parties +* 8-week timeline + +*Statistics* (pilot program): - 94% disputes resolved in Tier 1 - 5% +escalated to Tier 2 - <1% required external review - Average resolution +time: 9 days + +''''' + +=== 8. Environmental Impact + +==== 8.1 Carbon Footprint Comparison + +*Conventional Textile Supply Chain* (1 shirt): + +.... +Cotton farming: 1.2 kg CO₂ +Spinning (China): 0.8 kg CO₂ +Weaving (Bangladesh): 0.6 kg CO₂ +Dyeing: 1.5 kg CO₂ +Cutting/sewing: 0.4 kg CO₂ +Transport (sea): 2.1 kg CO₂ +Retail distribution: 0.9 kg CO₂ +───────────────────────────── +TOTAL: 7.5 kg CO₂ +.... + +*Kaldor Hyperlocal* (1 shirt): + +.... +Organic fiber (local): 0.3 kg CO₂ +Spinning (spare room): 0.2 kg CO₂ +Weaving (neighbor): 0.2 kg CO₂ +Natural dyeing: 0.1 kg CO₂ +Cutting/sewing: 0.2 kg CO₂ +Local delivery (bike): 0.1 kg CO₂ +───────────────────────────── +TOTAL: 1.1 kg CO₂ +.... + +*Reduction: 85%* (6.4 kg CO₂ saved per shirt) + +*Annual Impact* (25-household hub, 800 shirts/year): - CO₂ saved: 5,120 +kg (5.1 tonnes) - Equivalent to: 23,000 km car travel avoided - Trees +planted equivalent: 230 trees/year + +==== 8.2 Water Usage + +*Conventional*: - 2,700 liters per shirt (cotton farming + processing) - +Chemical pollution: 20% of global industrial wastewater + +*Kaldor Hyperlocal*: - 180 liters per shirt (local fiber, natural +dyeing) - Zero chemical discharge (natural dyes, local treatment) + +*Reduction: 93%* (2,520 liters saved) + +==== 8.3 Waste Reduction + +*Conventional*: - 15% fabric waste (cutting inefficiency) - 85% textiles +end up in landfill (fast fashion) - Microplastic shedding: 700,000 +fibers per wash + +*Kaldor Hyperlocal*: - 3% fabric waste (custom sizing, zero-waste +patterns) - 90% products designed for repair/reuse - Natural fibers: +biodegradable + +*Circular Economy Integration*: - Fabric scraps → stuffing for cushions +- Worn-out garments → fiber reclamation - Dye baths → composted (natural +dyes only) + +''''' + +=== 9. Risk Analysis + +==== 9.1 Market Risks + +[width="99%",cols="17%,31%,21%,31%",options="header",] +|=== +|Risk |Likelihood |Impact |Mitigation +|Low demand |Medium |High |Diversified revenue (products + workshops + +rentals) + +|Price competition |High |Medium |Premium positioning (artisan, local, +sustainable) + +|Material cost spike |Medium |Medium |Bulk buying co-op, local fiber +sourcing + +|Fashion trend shift |Low |Low |Timeless designs, custom orders +|=== + +*Market Validation*: - 72% of UK consumers willing to pay 20-40% premium +for local, sustainable textiles (Which?, 2023) - £4.2B UK market for +artisan/craft goods (Crafts Council, 2022) + +==== 9.2 Operational Risks + +[width="99%",cols="17%,31%,21%,31%",options="header",] +|=== +|Risk |Likelihood |Impact |Mitigation +|Equipment failure |Medium |Medium |Maintenance schedules, equipment +pool, insurance + +|Quality control |Medium |High |Training programs, peer review, standard +templates + +|Key person dependency |Low |High |Cross-training, documentation, +succession planning + +|Supply chain (materials) |Low |Medium |Multiple suppliers, local +sourcing, stockpiling +|=== + +*Operational Metrics* (pilot data): - Equipment uptime: 96.2% - Defect +rate: 3.1% (below 5% target) - On-time delivery: 94% + +==== 9.3 Regulatory Risks + +[width="99%",cols="17%,31%,21%,31%",options="header",] +|=== +|Risk |Likelihood |Impact |Mitigation +|Planning permission |Low |Medium |Residential use compliant (no +structural changes) + +|Health & safety |Low |High |Safety training, equipment guards, +insurance + +|Tax compliance |Low |High |Transparent accounting, professional advice + +|Intellectual property |Very Low |Low |Open-source patterns, CC +licensing +|=== + +*Legal Compliance*: - ✅ UK planning: Spare room use falls under +"`incidental use`" (no permission needed if <50% floor area) - ✅ +Insurance: Home-based business coverage (£150-300/year) - ✅ Tax: HMRC +Trading Allowance (£1,000 tax-free) or full registration + +==== 9.4 Social Risks + +[width="99%",cols="17%,31%,21%,31%",options="header",] +|=== +|Risk |Likelihood |Impact |Mitigation +|Conflict between members |Medium |Medium |Clear governance (TPCF), +mediation protocols + +|Burnout |Medium |High |Part-time model, rotation, emotional safety +(CCCP) + +|Gentrification pressure |Low |Medium |CLT model (land locked), +affordable access policies + +|Skill shortage |Medium |Medium |Apprenticeship programs, peer teaching, +wiki resources +|=== + +*Social Capital Building*: - Monthly community gatherings - +Skill-sharing workshops (free) - Intergenerational programs (elder +artisans + youth) + +''''' + +=== 10. Implementation Roadmap + +==== 10.1 Phase 1: Pilot (Months 1-6) + +*Objectives*: - Validate technology stack (Deno, ReScript, WASM, Matter) +- Prove economic model (3-node network) - Establish governance (TPCF, +CURP) - Develop training materials + +*Activities*: - Recruit 12 pilot households (4 clusters x 3 nodes) - +Provide equipment grants (£20,000 total, £1,667/household) - Weekly +check-ins, monthly retrospectives - Measure productivity growth +(Kaldor’s Law validation) + +*Success Criteria*: - [ ] 80% equipment uptime - [ ] Positive cashflow +by month 4 - [ ] Verdoorn coefficient (b) > 0.40 - [ ] 90% participant +satisfaction + +*Budget*: £65,000 - Equipment grants: £20,000 - Platform development: +£25,000 - Training/facilitation: £12,000 - Evaluation/research: £8,000 + +''''' + +==== 10.2 Phase 2: Expansion (Months 7-18) + +*Objectives*: - Scale to 100 households (35 clusters) - Establish 5 +regional hubs - Launch platform cooperative - Achieve financial +sustainability + +*Activities*: - Open enrollment (rolling basis) - Regional training +centers (Birmingham, Manchester, Bristol, Glasgow, Cardiff) - Develop +supply chain partnerships (local fiber farms) - Launch e-commerce +marketplace + +*Success Criteria*: - [ ] 100 active households - [ ] £450,000 annual +GMV (Gross Merchandise Value) - [ ] 50 full-time equivalent jobs - [ ] +Platform breakeven (no ongoing grants) + +*Budget*: £280,000 - Equipment grants (60 new households): £100,000 - +Hub infrastructure (5 locations): £80,000 - Platform scaling: £50,000 - +Marketing/outreach: £30,000 - Operations: £20,000 + +*Funding Sources*: - Lottery Community Fund: £120,000 - Esmée Fairbairn +Foundation: £80,000 - Innovate UK: £50,000 - Crowdfunding: £30,000 + +''''' + +==== 10.3 Phase 3: Maturity (Months 19-36) + +*Objectives*: - National network (500+ households) - International +replication (3 countries) - Spin-off innovations (3D weaving, +bio-textiles) - Policy advocacy (UK Textile Strategy) + +*Activities*: - Franchise model (license platform to regional groups) - +International partnerships (India, Kenya, Peru) - R&D program (3D +weaving tech, bio-fabrication) - Lobby for policy changes +(apprenticeship funding, business rate relief) + +*Success Criteria*: - [ ] 500 UK households, 150 international - [ ] +£2.5M annual GMV - [ ] 250 FTE jobs - [ ] 1 national policy change +enacted + +*Budget*: £850,000 - Network expansion: £300,000 - International +programs: £200,000 - R&D (3D weaving): £180,000 - Policy/advocacy: +£100,000 - Operations: £70,000 + +*Funding Sources*: - Platform revenue (5% transaction fees): +£125,000/year - Social investment (SITR-eligible): £400,000 - EU Horizon +grants: £200,000 - Corporate partnerships: £125,000 + +''''' + +=== 11. Case Studies + +==== 11.1 The Hebden Bridge Textile Commons (Pilot) + +*Location*: Hebden Bridge, West Yorkshire *Model*: Community Benefit +Society *Started*: March 2025 *Participants*: 18 households + +*Setup*: - 6 three-node clusters (spin + weave + finishing) - Shared +community hub (former mill building) - Focus: Organic wool from local +farms + +*Results (6 months)*: | Metric | Value | |——–|——-| | Total output | 420 +meters fabric, 180 garments | | Revenue | £32,400 | | Jobs created | 8 +part-time (4 FTE) | | Carbon saved | 3.2 tonnes CO₂ | | Kaldor +coefficient (b) | 0.48 | + +*Challenges*: - Initial quality variability (solved with peer mentoring) +- Equipment breakdown (pooled maintenance fund established) - Seasonal +demand fluctuations (workshops filled gaps) + +*Quote*: _"`We’ve reclaimed a skill our grandparents had. It’s not just +income, it’s community.`"_ - Sarah T., spinner + +''''' + +==== 11.2 Birmingham Urban Looms (Charity Model) + +*Location*: Sparkbrook, Birmingham *Model*: CIO (Charitable Incorporated +Organisation) *Started*: May 2025 *Beneficiaries*: 35 unemployed youth +(16-24) + +*Mission*: Textile training as pathway to employment + +*Results (4 months)*: | Metric | Value | |——–|——-| | Trainees | 35 +enrolled, 28 completed | | Employment outcomes | 19 employed (68% job +placement) | | Social value | £47,000 (SROI calculation) | | Grant +funding secured | £68,000 (Big Lottery Fund) | + +*Outcomes*: - 19 trainees hired by local textile businesses - 6 started +own micro-businesses - 3 progressed to further education +(fashion/design) + +*Quote*: _"`I was unemployed for 2 years. Now I run my own custom shirt +business from my living room.`"_ - Marcus J., trainee + +''''' + +==== 11.3 Rural Sutherland Wool Network (Mutual Aid Model) + +*Location*: Sutherland, Scottish Highlands *Model*: Time bank + gift +economy *Started*: April 2025 *Members*: 12 households (5 crofts + 7 +village) + +*Structure*: - No money exchanged (pure time banking) - 1 hour labor = 1 +credit (all skills valued equally) - Focus: Processing local sheep wool + +*Results (5 months)*: | Metric | Value | |——–|——-| | Hours exchanged | +680 hours | | Equivalent value | £8,500 (if monetized) | | Wool +processed | 120 kg (from 40 local sheep) | | Products made | 85 +(blankets, sweaters, hats) | + +*Social Impact*: - Reduced isolation (monthly gatherings) - +Intergenerational knowledge transfer (elders teaching youth) - +Strengthened food network (time credits used for eggs, vegetables) + +*Quote*: _"`Money doesn’t reach us here. But time? We’ve always had +that.`"_ - Morag M., crofter + +''''' + +=== 12. Appendices + +==== Appendix A: Technical Specifications + +See link:../../ARCHITECTURE-v2.md[ARCHITECTURE-v2.md] for complete +technical details. + +*Key Technical Metrics*: - Backend uptime: 99.7% (pilot period) - +WebSocket latency: <50ms (p95) - WASM performance: 12x faster than +JavaScript for pattern generation - Offline capability: 48+ hours +without sync - CRDT convergence: <2 seconds for 100 nodes + +''''' + +==== Appendix B: Equipment Specifications + +*Spinning Station*: - Electric spinner: Ashford Joy 2 or Louët S10 - +Fiber prep: Drum carder, hackle, lazy kate - Storage: Bins for roving, +bobbins - Total cost: £2,500-£4,000 + +*Weaving Station*: - Loom: Ashford 8-shaft table loom or rigid heddle + +extensions - Warping: Warping board, raddle, lease sticks - Tools: +Shuttles (3-5), bobbin winder, threading hook - Total cost: +£3,500-£6,000 + +*3D Print/Finishing Station*: - 3D textile printer: Electroloom (or +equiv) OR - Sewing machine: Industrial straight stitch + overlocker - +Laser cutter: 40W CO₂ (optional, for patterns) - Total cost: +£2,000-£4,000 (sewing), £8,000-£12,000 (3D print) + +''''' + +==== Appendix C: Training Curriculum + +*Spinning (2-week course, 20 hours)*: - Week 1: Fiber prep, drafting +technique, wheel mechanics - Week 2: Plying, tension control, fiber +blending, troubleshooting + +*Weaving (4-week course, 40 hours)*: - Week 1-2: Loom setup, warping, +plain weave - Week 3: Twill patterns, color blending - Week 4: Advanced +techniques, quality control, finishing + +*Finishing (1-week course, 10 hours)*: - Cutting (zero-waste patterns) - +Sewing (basic construction) - Quality control (inspection, repair) + +''''' + +==== Appendix D: Legal Templates + +Available at: `+docs/wiki/legal-templates/+` + +* CIC Articles of Association +* Community Benefit Society Rules +* CIO Constitution +* Worker Cooperative Bylaws +* Platform Cooperative Governance +* CLT Lease Agreement +* Time Bank Membership Agreement +* Equipment Loan Agreement + +''''' + +==== Appendix E: Financial Models (Spreadsheets) + +Download: `+docs/white-paper/financial-models/+` + +* Single node calculator (.xlsx) +* Three-node network model (.xlsx) +* Community hub projections (.xlsx) +* Grant application budgets (.xlsx) +* SROI (Social Return on Investment) calculator (.xlsx) + +''''' + +==== Appendix F: Environmental Impact Methodology + +*Life Cycle Assessment (LCA)* based on: - ISO 14040:2006 (LCA +principles) - GHG Protocol (carbon accounting) - Water Footprint Network +(water usage) - Ellen MacArthur Foundation (circular economy) + +*Data Sources*: - Textile Exchange (fiber carbon) - DEFRA (UK +electricity carbon intensity) - Academic studies (transport, processing) + +''''' + +==== Appendix G: References + +[arabic] +. Kaldor, N. (1966). "`Causes of the Slow Rate of Economic Growth of the +United Kingdom`". _Cambridge University Press_. +. Verdoorn, P. J. (1949). "`Fattori che Regolano lo Sviluppo della +Produttività del Lavoro`". _L’Industria_. +. Ostrom, E. (1990). "`Governing the Commons`". _Cambridge University +Press_. +. Beer, S. (1972). "`Brain of the Firm`". _Wiley_. +. Schumacher, E. F. (1973). "`Small Is Beautiful: Economics as if People +Mattered`". _Blond & Briggs_. +. Scholz, T. (2016). "`Platform Cooperativism: Challenging the Corporate +Sharing Economy`". _Rosa Luxemburg Foundation_. +. Transition Network (2010). "`The Transition Handbook`". _Green Books_. +. Open Source Ecology (2019). "`Global Village Construction Set`". +_opensourceecology.org_ +. UK Office for National Statistics (2021). "`Housing Statistics`". +. WRAP (2022). "`Textiles 2030 Impact Report`". + +''''' + +==== Appendix H: Glossary + +* *BBW*: Back Beam Width +* *CIC*: Community Interest Company +* *CLT*: Community Land Trust +* *CRDT*: Conflict-Free Replicated Data Type +* *CURP*: Consistent Unordered Replication Protocol +* *Matter*: Open IoT connectivity standard +* *OPC UA*: Open Platform Communications Unified Architecture +* *RISC-V*: Open instruction set architecture +* *TPCF*: Tri-Perimeter Contribution Framework +* *WASM*: WebAssembly + +''''' + +=== Conclusion + +The Kaldor Community Manufacturing Platform demonstrates that *Kaldor’s +Second Law* - productivity growth through manufacturing output growth - +applies at the _community scale_ when enabled by appropriate technology +and governance. + +*Key Findings*: + +[arabic] +. *Economic Viability*: £4,500-£16,500 annual surplus achievable from +spare rooms +. *Kaldor’s Law Validated*: Verdoorn coefficient of 0.48-0.52 in pilot +communities +. *Environmental Impact*: 85% carbon reduction vs. conventional +manufacturing +. *Social Benefit*: 50+ jobs per 100 households, strengthened community +ties +. *Scalability*: 8 economic models support diverse communities +(household → commons) + +*This is not just a business model. It’s economic infrastructure for +community autonomy.* + +By transforming spare rooms into a distributed manufacturing network, +we: - ✅ Reclaim lost craft knowledge - ✅ Reduce environmental impact +by 85% - ✅ Create dignified local employment - ✅ Strengthen community +resilience - ✅ Prove community scale beats factory scale (with the +right tools) + +*The future of manufacturing isn’t bigger factories. It’s distributed +networks of community-owned spare rooms.* + +''''' + +*For More Information*: - Website: https://kaldor.community - Email: +info@kaldor.community - GitHub: +https://github.com/Hyperpolymath/Kaldor-IIoT - Matrix: +#kaldor:matrix.org + +*License*: CC-BY-SA-4.0 *Citation*: Kaldor Community Platform Team +(2025). "`Kaldor Community Manufacturing Platform: Hyperlocal Textile +Production as Economic Infrastructure`". White Paper v1.0. + +''''' + +_This white paper was written with human oversight and AI assistance +(Claude, Anthropic). All economic projections are based on pilot data +and should be independently verified for your specific context._ diff --git a/docs/white-paper/KALDOR_WHITE_PAPER.md b/docs/white-paper/KALDOR_WHITE_PAPER.md deleted file mode 100644 index 5706dd1..0000000 --- a/docs/white-paper/KALDOR_WHITE_PAPER.md +++ /dev/null @@ -1,1257 +0,0 @@ - -# Kaldor Community Manufacturing Platform -## White Paper: Hyperlocal Textile Production as Economic Infrastructure - -**Version**: 1.0.0 -**Date**: November 2025 -**Authors**: Kaldor Community Platform Team -**License**: CC-BY-SA-4.0 -**DOI**: [Pending] - ---- - -## Executive Summary - -The **Kaldor Community Manufacturing Platform** transforms spare rooms into a distributed, community-owned textile manufacturing network. By applying **Kaldor's Second Law** (Verdoorn's Law) - "the rate of growth in productivity is positively related to the rate of growth of manufacturing output" - at the *community level* rather than corporate level, we create increasing returns to scale for local economies. - -**Key Findings**: - -- **Economic**: £65,000+ annual revenue potential from 3 spare rooms (spin + weave + print) -- **Social**: 15-20 local jobs created per community cluster (25 households) -- **Environmental**: 60-80% reduction in carbon vs. centralized manufacturing -- **Kaldor's Law**: 2.3x productivity multiplier observed in pilot communities -- **Accessibility**: £8,000-£12,000 initial investment per room (payback <18 months) - -**Business Models Supported**: 8 sectors from household to commons (excluding corporate extraction) - ---- - -## Table of Contents - -1. [The Problem: Centralized Manufacturing](#1-the-problem) -2. [The Solution: Hyperlocal Networks](#2-the-solution) -3. [Kaldor's Law 2: Theoretical Foundation](#3-kaldors-law) -4. [Technical Architecture](#4-technical-architecture) -5. [Economic Models (1st-8th Sector)](#5-economic-models) -6. [Financial Projections](#6-financial-projections) -7. [Community Governance](#7-community-governance) -8. [Environmental Impact](#8-environmental-impact) -9. [Risk Analysis](#9-risk-analysis) -10. [Implementation Roadmap](#10-implementation-roadmap) -11. [Case Studies](#11-case-studies) -12. [Appendices](#12-appendices) - ---- - -## 1. The Problem: Centralized Manufacturing - -### 1.1 Economic Extraction - -Global textile manufacturing is concentrated in: -- **Geographic monopolies**: 60% of global textile production in China, Bangladesh, Vietnam -- **Corporate consolidation**: Top 10 companies control 45% of market -- **Value extraction**: £1 shirt costs £0.15 to make, sells for £15-25 (100x markup) -- **Wage suppression**: Race to bottom ($68/month Bangladesh minimum wage) - -### 1.2 Supply Chain Fragility - -COVID-19 exposed vulnerabilities: -- **Lead times**: 6-12 months for custom orders -- **Inventory risk**: £billions in unsold stock -- **Transportation**: 30-40% of product cost -- **Quality control**: Disconnection between designer and producer - -### 1.3 Environmental Costs - -Textile industry accounts for: -- **10% of global carbon emissions** (more than aviation + shipping combined) -- **20% of industrial water pollution** -- **92 million tonnes** of textile waste annually -- **Average garment travels 20,000 km** from fiber to consumer - -### 1.4 Community Deskilling - -Historical loss of local manufacturing knowledge: -- **1970**: UK had 1.5M textile workers -- **2023**: <100,000 remain (93% decline) -- **Skills gap**: 2-3 generations lost craft knowledge -- **Dependency**: Communities now reliant on distant supply chains - -**The Core Problem**: Centralized manufacturing creates economic extraction, environmental harm, supply chain fragility, and community deskilling. - ---- - -## 2. The Solution: Hyperlocal Networks - -### 2.1 The Spare Room Economy - -**Insight**: 8.2 million UK households have at least one spare room (ONS, 2021). - -**Opportunity**: -- **Unutilized capital**: Spare rooms average 10-15m² of unused space -- **Sunk costs**: Already paid for (mortgage/rent), heating, electricity infrastructure -- **Accessibility**: Lower barrier than standalone premises -- **Distributed**: Natural mesh topology across communities - -### 2.2 Three-Node Minimum Viable Network - -A hyperlocal textile supply chain requires three stations: - -#### **Node 1: Spinning Station** (Fiber → Yarn) -- **Space**: 1.5m x 1.5m (2.25m²) -- **Equipment**: Electric spinner, fiber prep tools, storage -- **Output**: 2-5 kg yarn/day (depending on fiber) -- **Skill**: Beginner-friendly (2-week training) -- **Investment**: £2,500-£4,000 - -#### **Node 2: Weaving Station** (Yarn → Fabric) -- **Space**: 2m x 1.5m (3m²) -- **Equipment**: Table loom (4-8 shaft), warping board, shuttle -- **Output**: 3-8 meters fabric/day -- **Skill**: Intermediate (1-month training) -- **Investment**: £3,500-£6,000 - -#### **Node 3: 3D Print/Finishing** (Fabric → Product) -- **Space**: 1.5m x 1.5m (2.25m²) -- **Equipment**: Textile 3D printer OR sewing station + laser cutter -- **Output**: 5-15 products/day -- **Skill**: Beginner to intermediate -- **Investment**: £2,000-£4,000 - -**Total Network**: 7.5m² (~80 sq ft), £8,000-£14,000 investment - -### 2.3 Network Topology - -``` - House A House B House C - ┌───────────┐ ┌───────────┐ ┌───────────┐ - │ Spinning │───────▶│ Weaving │───────▶│ Printing │ - │ Station │ │ Station │ │ Station │ - └───────────┘ └───────────┘ └───────────┘ - │ │ │ - └────────────────────┴────────────────────┘ - │ - ┌────────▼────────┐ - │ Community Hub │ - │ (Finishing & │ - │ Distribution) │ - └─────────────────┘ -``` - -**Scaling**: Each node can serve multiple neighbors, creating mesh resilience. - ---- - -## 3. Kaldor's Law 2: Theoretical Foundation - -### 3.1 Verdoorn's Law (Kaldor's Second Law) - -**Original Formulation** (Nicholas Kaldor, 1966): - -> "The rate of growth in productivity (p) is positively related to the rate of growth of manufacturing output (q)" - -Mathematically: -``` -p = a + bq - -Where: - p = productivity growth rate - q = output growth rate - a = autonomous productivity growth (technology, skills) - b = Verdoorn coefficient (typically 0.45-0.50) -``` - -**Implication**: Doubling manufacturing output increases productivity by 45-50%, creating increasing returns to scale. - -### 3.2 Application to Hyperlocal Manufacturing - -**Traditional Interpretation** (Corporate): -- Centralized factories achieve economies of scale -- Productivity increases with factory size -- Justifies geographic consolidation - -**Kaldor Community Interpretation** (Network): -- **Distributed scale**: Sum of network nodes, not single factory -- **Learning-by-doing**: Shared knowledge base across community -- **Specialization**: Nodes develop expertise (expert spinner, expert weaver) -- **Coordination efficiency**: Local = lower transaction costs - -**Key Difference**: We achieve Verdoorn returns through *network effects*, not *factory size*. - -### 3.3 Empirical Evidence - -Pilot study (N=12 households, 6-month period): - -| Metric | Month 1 | Month 3 | Month 6 | Growth | -|--------|---------|---------|---------|--------| -| Output (meters/day) | 2.3 | 4.1 | 5.8 | 152% | -| Productivity (m/hour) | 0.8 | 1.4 | 2.2 | 175% | -| Defect rate | 12% | 6% | 3% | -75% | -| Setup time (min) | 45 | 25 | 15 | -67% | - -**Verdoorn coefficient (b)**: 0.52 (consistent with Kaldor's predictions) - -**Mechanism Analysis**: -1. **Month 1-2**: Learning phase, high variability -2. **Month 3-4**: Specialization emerges, knowledge sharing accelerates -3. **Month 5-6**: Process optimization, standardization benefits - -**Conclusion**: Kaldor's Law holds at community scale when network effects replace factory scale. - ---- - -## 4. Technical Architecture - -See [ARCHITECTURE-v2.md](../../ARCHITECTURE-v2.md) for complete technical specification. - -**Key Technical Innovations**: - -1. **Offline-First CRDTs**: Production continues without internet -2. **Matter Protocol**: Open standard for device interoperability -3. **RISC-V Firmware**: Open-source hardware platform (ESP32-C6) -4. **WASM Acceleration**: Near-native performance for pattern generation -5. **OPC UA/Modbus**: Integration with existing industrial equipment -6. **CURP Consensus**: Community governance without central authority - -**Technology Stack**: -- **Backend**: Deno (secure TypeScript runtime) -- **Frontend**: ReScript (sound type system) -- **WASM**: Rust (memory-safe, high-performance) -- **Firmware**: Rust on RISC-V (zero unsafe blocks) -- **Database**: TimescaleDB + Automerge (offline-first) - ---- - -## 5. Economic Models (1st-8th Sector) - -We support **8 alternative economic models**, deliberately excluding extractive corporate structures: - -### 5.1 First Sector: Household/Family - -**Model**: Personal/family production for own use or barter - -**Example**: Retired couple with spare room, making textiles for family - -**Economics**: -- **Investment**: £3,000-£5,000 (one station) -- **Revenue**: £0 (gift economy) -- **Value**: £8,000-£12,000/year equivalent (saved purchases) -- **Tax**: None (personal use exempt) - -**Kaldor Platform Support**: -- Pattern library (free templates) -- Equipment subsidies (community tool library) -- Training workshops (peer-to-peer) -- No transaction fees - -**Legal Structure**: None required - ---- - -### 5.2 Second Sector: Social Enterprise - -**Model**: Community Interest Company (CIC) or Community Benefit Society - -**Example**: 25-household neighborhood cooperative - -**Economics**: -- **Investment**: £25,000-£40,000 (3-node network + hub) -- **Revenue**: £45,000-£75,000/year (custom orders + workshop fees) -- **Surplus**: Reinvested in community (55% asset lock) -- **Jobs**: 3-5 part-time positions (living wage) - -**Kaldor Platform Support**: -- Governance templates (quadratic voting) -- Accounting integration (transparent finances) -- Job scheduler (fair work distribution) -- Skills marketplace - -**Legal Structures**: -- **CIC** (Community Interest Company): UK limited company with asset lock -- **Community Benefit Society**: Co-operative ownership -- **Charitable Incorporated Organisation** (CIO): If primarily educational - -**Tax Benefits**: -- CIC: Corporation tax relief on community benefit activities -- CBS: Potential charity status (zero corporation tax) - ---- - -### 5.3 Third Sector: Charity/Non-Profit - -**Model**: Registered charity with textile production as social mission - -**Example**: "ThreadCare" - textile training for unemployed youth - -**Economics**: -- **Investment**: £50,000-£80,000 (grants + donations) -- **Revenue**: £60,000-£90,000/year (80% grants, 20% sales) -- **Beneficiaries**: 30-50 trainees/year -- **Jobs**: 2-3 staff + 10-15 trainees - -**Kaldor Platform Support**: -- Grant application templates -- Impact measurement tools -- Trainee progress tracking -- Certification pathways - -**Legal Structure**: Registered Charity (England & Wales Charity Commission) - -**Tax Benefits**: -- Zero corporation tax -- Gift Aid on donations (25% uplift) -- Business rate exemption (80-100%) -- VAT exemption on education - -**Eligibility**: Must demonstrate public benefit (Charity Commission test) - ---- - -### 5.4 Fourth Sector: Worker Cooperative - -**Model**: Worker-owned cooperative (1 member = 1 vote) - -**Example**: 7 makers form "LocalLooms Co-op" - -**Economics**: -- **Investment**: £12,000-£18,000 (member equity + loan) -- **Revenue**: £85,000-£120,000/year -- **Distribution**: Patronage dividends based on hours worked -- **Jobs**: 7 full-time equivalents - -**Kaldor Platform Support**: -- Democratic governance tools (Loomio integration) -- Transparent accounting (OpenCollective) -- Fair compensation algorithms -- Conflict resolution protocols - -**Legal Structure**: Cooperative Society (registered with FCA) - -**Tax Benefits**: -- Corporation tax relief on member bonuses -- Shared ownership relief (SEIS/EIS eligible) - -**Governance**: -- 1 member = 1 vote -- Surplus distributed by patronage (hours worked) -- Open membership (vetted) - ---- - -### 5.5 Fifth Sector: Platform Cooperative - -**Model**: Multi-stakeholder cooperative (producers + consumers) - -**Example**: "FairThread" - 200 makers + 5,000 customers - -**Economics**: -- **Investment**: £150,000-£250,000 (platform development + local hubs) -- **Revenue**: £850,000-£1.2M/year -- **Distribution**: 40% makers, 40% reinvestment, 20% customer dividends -- **Jobs**: 50-80 makers, 10-15 staff - -**Kaldor Platform Support**: -- Marketplace infrastructure (no fees to Kaldor) -- Supply chain coordination -- Demand aggregation -- Quality assurance - -**Legal Structure**: Multi-stakeholder Cooperative - -**Governance**: -- 40% makers (1 maker = 1 vote) -- 30% customers (quadratic voting) -- 20% workers (staff) -- 10% community (local councils, charities) - -**Revenue Model**: -- 5% transaction fee (covers platform costs only) -- £2/month pro membership (optional, premium features) - ---- - -### 5.6 Sixth Sector: Community Land Trust (CLT) - -**Model**: Non-profit owns premises, leases to makers at below-market rates - -**Example**: "Mill Commons CLT" - owns building, 12 maker spaces - -**Economics**: -- **Investment**: £400,000-£800,000 (property acquisition + fit-out) -- **Revenue**: £48,000-£72,000/year (below-market rents) -- **Leases**: £200-£400/month per space (50-70% below market) -- **Asset appreciation**: Locked in trust (no speculation) - -**Kaldor Platform Support**: -- Property assessment tools -- Lease templates -- Maintenance scheduling -- Shared equipment booking - -**Legal Structure**: Community Benefit Society (asset-locked) - -**Tax Benefits**: -- Business rate relief (discretionary, up to 100%) -- VAT exemption on rent (if charitable) -- Capital Gains Tax exemption (if reinvested in community) - -**Land Ownership**: -- CLT owns freehold in perpetuity -- 99-year leases to makers -- Resale formula caps price (prevents speculation) -- Community has first right of refusal - ---- - -### 5.7 Seventh Sector: Mutual Aid Network - -**Model**: Gift economy + time banking, no money exchange - -**Example**: "ThreadBank" - 50 members exchange textile services for time credits - -**Economics**: -- **Investment**: £0 (borrowed/donated equipment) -- **Revenue**: £0 (no monetary transactions) -- **Value**: 2,000-3,000 hours/year exchanged -- **Equivalence**: £25,000-£40,000 of services (if monetized) - -**Kaldor Platform Support**: -- Time banking ledger (automatic) -- Skill matching algorithm -- Reputation system (without coercion) -- Conflict mediation tools - -**Legal Structure**: Unincorporated association (no formal registration needed) - -**Tax**: None (mutual aid exempt as non-commercial) - -**Time Banking Rates**: -- 1 hour spinning = 1 credit -- 1 hour weaving = 1 credit -- 1 hour teaching = 1 credit -- **No skill hierarchy** (all labor valued equally) - ---- - -### 5.8 Eighth Sector: Commons/Public Goods - -**Model**: Public ownership (council/government), free access - -**Example**: "Manchester Textile Commons" - council-owned, free equipment access - -**Economics**: -- **Investment**: £200,000-£400,000 (public funding) -- **Revenue**: £0 (free to residents) -- **Usage**: 500-800 users/year -- **Value**: £180,000-£300,000 public benefit/year - -**Kaldor Platform Support**: -- Booking system (fair allocation) -- Maintenance tracking -- Usage analytics (demonstrate public value) -- Safety compliance - -**Legal Structure**: -- Local authority asset -- Managed by council or delegated to trust -- Free access (or nominal fee for materials only) - -**Funding**: -- Council budget allocation -- Levelling Up Fund -- UK Shared Prosperity Fund -- Arts Council England - -**Access Policy**: -- Priority: Local residents, low-income, students -- Booking: Max 4 hours/week to ensure fair access -- Training: Mandatory safety induction (free) - ---- - -### 5.9 Sector Comparison Matrix - -| Sector | Ownership | Profit Motive | Tax Benefits | Barrier to Entry | Scale Potential | -|--------|-----------|---------------|--------------|------------------|-----------------| -| 1. Household | Family | None (gift) | Exempt | Very Low | Individual | -| 2. Social Enterprise | Community | Capped | Moderate | Low | Neighborhood | -| 3. Charity | Public trust | Zero | Highest | Medium | Regional | -| 4. Worker Coop | Workers | Shared | Moderate | Low | Local-Regional | -| 5. Platform Coop | Multi-stake | Shared | Moderate | Medium | National | -| 6. CLT | Community | Zero (land) | High | High | Neighborhood | -| 7. Mutual Aid | None | Zero | Exempt | Very Low | Local | -| 8. Commons | Public | Zero | N/A (public) | None (users) | Municipal | - -**Deliberately Excluded: Corporate (9th Sector)** -- **Why**: Extractive profit motive incompatible with community benefit -- **Risk**: Shareholder primacy → wage suppression, community exploitation -- **Alternative**: If commercial scale needed, use Platform Cooperative (5th sector) - ---- - -## 6. Financial Projections - -### 6.1 Single-Node Economics (One Spare Room) - -**Scenario**: Household spinning station, part-time operation - -**Initial Investment**: -``` -Electric spinner: £1,800 -Fiber prep tools: £400 -Storage/shelving: £200 -Materials (startup): £300 -Training course: £250 -Insurance: £150 -───────────────────────────── -TOTAL: £3,100 -``` - -**Monthly Operating Costs**: -``` -Fiber (2 kg/day x 20 days): £240 -Electricity (additional): £25 -Equipment maintenance: £15 -Insurance: £15 -Platform fees: £5 -───────────────────────────── -TOTAL: £300 -``` - -**Revenue** (Part-time: 3 days/week, 4 hours/day): -``` -Output: 2 kg yarn/day x 12 days/month = 24 kg/month -Selling price: £28/kg (artisan wool yarn) -Revenue: 24 kg x £28 = £672/month -``` - -**Profitability**: -``` -Monthly revenue: £672 -Monthly costs: £300 -Monthly profit: £372 -Annual profit: £4,464 - -Payback period: £3,100 ÷ £372 = 8.3 months -ROI (Year 1): 44% -``` - ---- - -### 6.2 Three-Node Network Economics - -**Scenario**: 3 households (spin + weave + print), coordinated production - -**Combined Investment**: -``` -Spinning station: £3,100 -Weaving station: £4,800 -3D print/finishing: £3,200 -Shared tools: £1,200 -Community hub setup: £2,500 -───────────────────────────── -TOTAL: £14,800 -``` - -**Monthly Operating Costs**: -``` -Materials (all stations): £850 -Utilities: £120 -Equipment maintenance: £80 -Insurance: £60 -Platform/software: £20 -Marketing: £50 -───────────────────────────── -TOTAL: £1,180 -``` - -**Revenue** (Full-time equivalent: 160 hours/month): -``` -Products sold: - - 15 custom shirts @ £65 = £975 - - 8 meters fabric @ £45 = £360 - - 12 accessories @ £25 = £300 - - 5 custom orders @ £120 = £600 - - Workshop fees (4 sessions): £320 -──────────────────────────────────── -Monthly revenue: £2,555 -``` - -**Profitability**: -``` -Monthly revenue: £2,555 -Monthly costs: £1,180 -Monthly profit: £1,375 -Annual profit: £16,500 - -Payback period: £14,800 ÷ £1,375 = 10.7 months -ROI (Year 1): 11% -ROI (Year 2): 111% (no capital costs) -``` - -**Distribution (Worker Coop Model)**: -``` -3 households: - - £5,500/year each (part-time income) - - 10-15 hours/week commitment - - Equivalent to £11-12/hour - -Reinvestment fund: - - £1,000/year equipment upgrades -``` - ---- - -### 6.3 Community Hub Economics (25 Households) - -**Scenario**: Neighborhood-scale production, CIC structure - -**Investment**: -``` -Property lease (year 1): £12,000 -Equipment (12 stations): £45,000 -Hub infrastructure: £8,000 -IT/software: £3,000 -Legal/registration: £1,500 -Working capital: £5,000 -───────────────────────────────────── -TOTAL: £74,500 -``` - -**Revenue Streams**: -``` -Product sales (wholesale + retail): £48,000/year -Custom orders (B2B): £18,000/year -Workshop/training fees: £12,000/year -Equipment rental (external): £3,600/year -Grants (social impact): £6,000/year -───────────────────────────────────────────── -TOTAL: £87,600/year -``` - -**Operating Costs**: -``` -Rent: £12,000 -Salaries (3 FTE): £36,000 -Materials: £14,400 -Utilities: £3,600 -Marketing: £2,400 -Insurance: £1,800 -Maintenance: £2,400 -Admin/legal: £1,200 -──────────────────────────────────── -TOTAL: £73,800/year -``` - -**Financial Performance**: -``` -Revenue: £87,600 -Costs: £73,800 -Surplus: £13,800 - -Asset lock (55% CIC): £7,590 → community reinvestment -Distributable: £6,210 → member dividends - -ROI: 18.5% (Year 1) -Jobs created: 18-22 (3 FTE + 15-19 part-time) -``` - ---- - -### 6.4 Sensitivity Analysis - -**Risk Factors**: - -| Variable | Base Case | Pessimistic | Optimistic | Impact on ROI | -|----------|-----------|-------------|------------|---------------| -| Material costs | £850/mo | £1,100 (+29%) | £700 (-18%) | ±8% | -| Selling price | £28/kg | £22 (-21%) | £35 (+25%) | ±15% | -| Output (kg/day) | 2.0 | 1.5 (-25%) | 2.8 (+40%) | ±12% | -| Defect rate | 5% | 12% (+140%) | 2% (-60%) | ±4% | -| Demand | High | Medium | Very High | ±20% | - -**Break-even Analysis** (3-node network): -``` -Fixed costs: £14,800 (initial) -Variable costs: £1,180/month -Contribution margin: 54% (£1,375 profit ÷ £2,555 revenue) - -Break-even time: 12.5 months (worst case) - 8.2 months (best case) -``` - -**Stress Test**: Platform survives: -- ✅ 30% drop in demand (still profitable) -- ✅ 40% increase in material costs (breakeven) -- ⚠️ 50% drop in selling prices (loss-making → reduce hours or seek grants) - ---- - -## 7. Community Governance - -### 7.1 CURP Consensus Protocol - -**CURP** (Consistent Unordered Replication Protocol) enables decentralized decision-making without central authority. - -**How It Works**: -1. **Proposal**: Member submits governance proposal (e.g., "Add new node to network") -2. **Replication**: Proposal distributed to all nodes (offline-capable via CRDTs) -3. **Voting**: Quadratic voting (voice credits based on contribution) -4. **Consensus**: Requires 66% approval + no single blocking vote >25% -5. **Execution**: Automated via smart contracts (local, not blockchain) - -**Advantages Over Blockchain**: -- ✅ Works offline (no internet required) -- ✅ Zero transaction fees -- ✅ Energy efficient (no proof-of-work) -- ✅ Human-readable audit trail - -**Example Vote**: -``` -Proposal: "Purchase shared laser cutter (£2,400)" -Votes: - - Alice: 9 credits FOR (cost: 81 credits) - - Bob: 4 credits FOR (cost: 16 credits) - - Carol: 2 credits AGAINST (cost: 4 credits) - - Dave: 5 credits FOR (cost: 25 credits) - -Result: 18 FOR vs 2 AGAINST = 90% approval → PASSED -``` - -### 7.2 Quadratic Voting Mathematics - -**Why Quadratic?** -- Prevents majority tyranny (passionate minority can block) -- Incentivizes coalition-building (cheaper to persuade than outbid) -- Respects expertise (earned voice credits) - -**Voice Credit Allocation**: -``` -New member: 10 credits -1 month contribution: +5 credits -1 merged PR: +2 credits -1 workshop taught: +3 credits -1 year membership: +20 credits - -Max accumulation: 100 credits (prevents plutocracy) -Credits decay: -10% per year (encourages active participation) -``` - -### 7.3 Dispute Resolution - -**Three-Tier System**: - -1. **Tier 1: Mediation** (Community Steward) - - Voluntary, non-binding - - 80% of disputes resolved here - - Free, 2-week timeline - -2. **Tier 2: Arbitration** (Elected Panel) - - Binding decision - - Panel of 3 (1 from each TPCF perimeter) - - £50 filing fee (refunded if upheld) - - 4-week timeline - -3. **Tier 3: External Review** (Software Freedom Conservancy) - - Appeals only - - Legal expert panel - - Costs shared by parties - - 8-week timeline - -**Statistics** (pilot program): -- 94% disputes resolved in Tier 1 -- 5% escalated to Tier 2 -- <1% required external review -- Average resolution time: 9 days - ---- - -## 8. Environmental Impact - -### 8.1 Carbon Footprint Comparison - -**Conventional Textile Supply Chain** (1 shirt): -``` -Cotton farming: 1.2 kg CO₂ -Spinning (China): 0.8 kg CO₂ -Weaving (Bangladesh): 0.6 kg CO₂ -Dyeing: 1.5 kg CO₂ -Cutting/sewing: 0.4 kg CO₂ -Transport (sea): 2.1 kg CO₂ -Retail distribution: 0.9 kg CO₂ -───────────────────────────── -TOTAL: 7.5 kg CO₂ -``` - -**Kaldor Hyperlocal** (1 shirt): -``` -Organic fiber (local): 0.3 kg CO₂ -Spinning (spare room): 0.2 kg CO₂ -Weaving (neighbor): 0.2 kg CO₂ -Natural dyeing: 0.1 kg CO₂ -Cutting/sewing: 0.2 kg CO₂ -Local delivery (bike): 0.1 kg CO₂ -───────────────────────────── -TOTAL: 1.1 kg CO₂ -``` - -**Reduction: 85%** (6.4 kg CO₂ saved per shirt) - -**Annual Impact** (25-household hub, 800 shirts/year): -- CO₂ saved: 5,120 kg (5.1 tonnes) -- Equivalent to: 23,000 km car travel avoided -- Trees planted equivalent: 230 trees/year - -### 8.2 Water Usage - -**Conventional**: -- 2,700 liters per shirt (cotton farming + processing) -- Chemical pollution: 20% of global industrial wastewater - -**Kaldor Hyperlocal**: -- 180 liters per shirt (local fiber, natural dyeing) -- Zero chemical discharge (natural dyes, local treatment) - -**Reduction: 93%** (2,520 liters saved) - -### 8.3 Waste Reduction - -**Conventional**: -- 15% fabric waste (cutting inefficiency) -- 85% textiles end up in landfill (fast fashion) -- Microplastic shedding: 700,000 fibers per wash - -**Kaldor Hyperlocal**: -- 3% fabric waste (custom sizing, zero-waste patterns) -- 90% products designed for repair/reuse -- Natural fibers: biodegradable - -**Circular Economy Integration**: -- Fabric scraps → stuffing for cushions -- Worn-out garments → fiber reclamation -- Dye baths → composted (natural dyes only) - ---- - -## 9. Risk Analysis - -### 9.1 Market Risks - -| Risk | Likelihood | Impact | Mitigation | -|------|------------|--------|------------| -| Low demand | Medium | High | Diversified revenue (products + workshops + rentals) | -| Price competition | High | Medium | Premium positioning (artisan, local, sustainable) | -| Material cost spike | Medium | Medium | Bulk buying co-op, local fiber sourcing | -| Fashion trend shift | Low | Low | Timeless designs, custom orders | - -**Market Validation**: -- 72% of UK consumers willing to pay 20-40% premium for local, sustainable textiles (Which?, 2023) -- £4.2B UK market for artisan/craft goods (Crafts Council, 2022) - -### 9.2 Operational Risks - -| Risk | Likelihood | Impact | Mitigation | -|------|------------|--------|------------| -| Equipment failure | Medium | Medium | Maintenance schedules, equipment pool, insurance | -| Quality control | Medium | High | Training programs, peer review, standard templates | -| Key person dependency | Low | High | Cross-training, documentation, succession planning | -| Supply chain (materials) | Low | Medium | Multiple suppliers, local sourcing, stockpiling | - -**Operational Metrics** (pilot data): -- Equipment uptime: 96.2% -- Defect rate: 3.1% (below 5% target) -- On-time delivery: 94% - -### 9.3 Regulatory Risks - -| Risk | Likelihood | Impact | Mitigation | -|------|------------|--------|------------| -| Planning permission | Low | Medium | Residential use compliant (no structural changes) | -| Health & safety | Low | High | Safety training, equipment guards, insurance | -| Tax compliance | Low | High | Transparent accounting, professional advice | -| Intellectual property | Very Low | Low | Open-source patterns, CC licensing | - -**Legal Compliance**: -- ✅ UK planning: Spare room use falls under "incidental use" (no permission needed if <50% floor area) -- ✅ Insurance: Home-based business coverage (£150-300/year) -- ✅ Tax: HMRC Trading Allowance (£1,000 tax-free) or full registration - -### 9.4 Social Risks - -| Risk | Likelihood | Impact | Mitigation | -|------|------------|--------|------------| -| Conflict between members | Medium | Medium | Clear governance (TPCF), mediation protocols | -| Burnout | Medium | High | Part-time model, rotation, emotional safety (CCCP) | -| Gentrification pressure | Low | Medium | CLT model (land locked), affordable access policies | -| Skill shortage | Medium | Medium | Apprenticeship programs, peer teaching, wiki resources | - -**Social Capital Building**: -- Monthly community gatherings -- Skill-sharing workshops (free) -- Intergenerational programs (elder artisans + youth) - ---- - -## 10. Implementation Roadmap - -### 10.1 Phase 1: Pilot (Months 1-6) - -**Objectives**: -- Validate technology stack (Deno, ReScript, WASM, Matter) -- Prove economic model (3-node network) -- Establish governance (TPCF, CURP) -- Develop training materials - -**Activities**: -- Recruit 12 pilot households (4 clusters x 3 nodes) -- Provide equipment grants (£20,000 total, £1,667/household) -- Weekly check-ins, monthly retrospectives -- Measure productivity growth (Kaldor's Law validation) - -**Success Criteria**: -- [ ] 80% equipment uptime -- [ ] Positive cashflow by month 4 -- [ ] Verdoorn coefficient (b) > 0.40 -- [ ] 90% participant satisfaction - -**Budget**: £65,000 -- Equipment grants: £20,000 -- Platform development: £25,000 -- Training/facilitation: £12,000 -- Evaluation/research: £8,000 - ---- - -### 10.2 Phase 2: Expansion (Months 7-18) - -**Objectives**: -- Scale to 100 households (35 clusters) -- Establish 5 regional hubs -- Launch platform cooperative -- Achieve financial sustainability - -**Activities**: -- Open enrollment (rolling basis) -- Regional training centers (Birmingham, Manchester, Bristol, Glasgow, Cardiff) -- Develop supply chain partnerships (local fiber farms) -- Launch e-commerce marketplace - -**Success Criteria**: -- [ ] 100 active households -- [ ] £450,000 annual GMV (Gross Merchandise Value) -- [ ] 50 full-time equivalent jobs -- [ ] Platform breakeven (no ongoing grants) - -**Budget**: £280,000 -- Equipment grants (60 new households): £100,000 -- Hub infrastructure (5 locations): £80,000 -- Platform scaling: £50,000 -- Marketing/outreach: £30,000 -- Operations: £20,000 - -**Funding Sources**: -- Lottery Community Fund: £120,000 -- Esmée Fairbairn Foundation: £80,000 -- Innovate UK: £50,000 -- Crowdfunding: £30,000 - ---- - -### 10.3 Phase 3: Maturity (Months 19-36) - -**Objectives**: -- National network (500+ households) -- International replication (3 countries) -- Spin-off innovations (3D weaving, bio-textiles) -- Policy advocacy (UK Textile Strategy) - -**Activities**: -- Franchise model (license platform to regional groups) -- International partnerships (India, Kenya, Peru) -- R&D program (3D weaving tech, bio-fabrication) -- Lobby for policy changes (apprenticeship funding, business rate relief) - -**Success Criteria**: -- [ ] 500 UK households, 150 international -- [ ] £2.5M annual GMV -- [ ] 250 FTE jobs -- [ ] 1 national policy change enacted - -**Budget**: £850,000 -- Network expansion: £300,000 -- International programs: £200,000 -- R&D (3D weaving): £180,000 -- Policy/advocacy: £100,000 -- Operations: £70,000 - -**Funding Sources**: -- Platform revenue (5% transaction fees): £125,000/year -- Social investment (SITR-eligible): £400,000 -- EU Horizon grants: £200,000 -- Corporate partnerships: £125,000 - ---- - -## 11. Case Studies - -### 11.1 The Hebden Bridge Textile Commons (Pilot) - -**Location**: Hebden Bridge, West Yorkshire -**Model**: Community Benefit Society -**Started**: March 2025 -**Participants**: 18 households - -**Setup**: -- 6 three-node clusters (spin + weave + finishing) -- Shared community hub (former mill building) -- Focus: Organic wool from local farms - -**Results (6 months)**: -| Metric | Value | -|--------|-------| -| Total output | 420 meters fabric, 180 garments | -| Revenue | £32,400 | -| Jobs created | 8 part-time (4 FTE) | -| Carbon saved | 3.2 tonnes CO₂ | -| Kaldor coefficient (b) | 0.48 | - -**Challenges**: -- Initial quality variability (solved with peer mentoring) -- Equipment breakdown (pooled maintenance fund established) -- Seasonal demand fluctuations (workshops filled gaps) - -**Quote**: *"We've reclaimed a skill our grandparents had. It's not just income, it's community."* - Sarah T., spinner - ---- - -### 11.2 Birmingham Urban Looms (Charity Model) - -**Location**: Sparkbrook, Birmingham -**Model**: CIO (Charitable Incorporated Organisation) -**Started**: May 2025 -**Beneficiaries**: 35 unemployed youth (16-24) - -**Mission**: Textile training as pathway to employment - -**Results (4 months)**: -| Metric | Value | -|--------|-------| -| Trainees | 35 enrolled, 28 completed | -| Employment outcomes | 19 employed (68% job placement) | -| Social value | £47,000 (SROI calculation) | -| Grant funding secured | £68,000 (Big Lottery Fund) | - -**Outcomes**: -- 19 trainees hired by local textile businesses -- 6 started own micro-businesses -- 3 progressed to further education (fashion/design) - -**Quote**: *"I was unemployed for 2 years. Now I run my own custom shirt business from my living room."* - Marcus J., trainee - ---- - -### 11.3 Rural Sutherland Wool Network (Mutual Aid Model) - -**Location**: Sutherland, Scottish Highlands -**Model**: Time bank + gift economy -**Started**: April 2025 -**Members**: 12 households (5 crofts + 7 village) - -**Structure**: -- No money exchanged (pure time banking) -- 1 hour labor = 1 credit (all skills valued equally) -- Focus: Processing local sheep wool - -**Results (5 months)**: -| Metric | Value | -|--------|-------| -| Hours exchanged | 680 hours | -| Equivalent value | £8,500 (if monetized) | -| Wool processed | 120 kg (from 40 local sheep) | -| Products made | 85 (blankets, sweaters, hats) | - -**Social Impact**: -- Reduced isolation (monthly gatherings) -- Intergenerational knowledge transfer (elders teaching youth) -- Strengthened food network (time credits used for eggs, vegetables) - -**Quote**: *"Money doesn't reach us here. But time? We've always had that."* - Morag M., crofter - ---- - -## 12. Appendices - -### Appendix A: Technical Specifications - -See [ARCHITECTURE-v2.md](../../ARCHITECTURE-v2.md) for complete technical details. - -**Key Technical Metrics**: -- Backend uptime: 99.7% (pilot period) -- WebSocket latency: <50ms (p95) -- WASM performance: 12x faster than JavaScript for pattern generation -- Offline capability: 48+ hours without sync -- CRDT convergence: <2 seconds for 100 nodes - ---- - -### Appendix B: Equipment Specifications - -**Spinning Station**: -- Electric spinner: Ashford Joy 2 or Louët S10 -- Fiber prep: Drum carder, hackle, lazy kate -- Storage: Bins for roving, bobbins -- Total cost: £2,500-£4,000 - -**Weaving Station**: -- Loom: Ashford 8-shaft table loom or rigid heddle + extensions -- Warping: Warping board, raddle, lease sticks -- Tools: Shuttles (3-5), bobbin winder, threading hook -- Total cost: £3,500-£6,000 - -**3D Print/Finishing Station**: -- 3D textile printer: Electroloom (or equiv) OR -- Sewing machine: Industrial straight stitch + overlocker -- Laser cutter: 40W CO₂ (optional, for patterns) -- Total cost: £2,000-£4,000 (sewing), £8,000-£12,000 (3D print) - ---- - -### Appendix C: Training Curriculum - -**Spinning (2-week course, 20 hours)**: -- Week 1: Fiber prep, drafting technique, wheel mechanics -- Week 2: Plying, tension control, fiber blending, troubleshooting - -**Weaving (4-week course, 40 hours)**: -- Week 1-2: Loom setup, warping, plain weave -- Week 3: Twill patterns, color blending -- Week 4: Advanced techniques, quality control, finishing - -**Finishing (1-week course, 10 hours)**: -- Cutting (zero-waste patterns) -- Sewing (basic construction) -- Quality control (inspection, repair) - ---- - -### Appendix D: Legal Templates - -Available at: `docs/wiki/legal-templates/` - -- CIC Articles of Association -- Community Benefit Society Rules -- CIO Constitution -- Worker Cooperative Bylaws -- Platform Cooperative Governance -- CLT Lease Agreement -- Time Bank Membership Agreement -- Equipment Loan Agreement - ---- - -### Appendix E: Financial Models (Spreadsheets) - -Download: `docs/white-paper/financial-models/` - -- Single node calculator (.xlsx) -- Three-node network model (.xlsx) -- Community hub projections (.xlsx) -- Grant application budgets (.xlsx) -- SROI (Social Return on Investment) calculator (.xlsx) - ---- - -### Appendix F: Environmental Impact Methodology - -**Life Cycle Assessment (LCA)** based on: -- ISO 14040:2006 (LCA principles) -- GHG Protocol (carbon accounting) -- Water Footprint Network (water usage) -- Ellen MacArthur Foundation (circular economy) - -**Data Sources**: -- Textile Exchange (fiber carbon) -- DEFRA (UK electricity carbon intensity) -- Academic studies (transport, processing) - ---- - -### Appendix G: References - -1. Kaldor, N. (1966). "Causes of the Slow Rate of Economic Growth of the United Kingdom". *Cambridge University Press*. - -2. Verdoorn, P. J. (1949). "Fattori che Regolano lo Sviluppo della Produttività del Lavoro". *L'Industria*. - -3. Ostrom, E. (1990). "Governing the Commons". *Cambridge University Press*. - -4. Beer, S. (1972). "Brain of the Firm". *Wiley*. - -5. Schumacher, E. F. (1973). "Small Is Beautiful: Economics as if People Mattered". *Blond & Briggs*. - -6. Scholz, T. (2016). "Platform Cooperativism: Challenging the Corporate Sharing Economy". *Rosa Luxemburg Foundation*. - -7. Transition Network (2010). "The Transition Handbook". *Green Books*. - -8. Open Source Ecology (2019). "Global Village Construction Set". *opensourceecology.org* - -9. UK Office for National Statistics (2021). "Housing Statistics". - -10. WRAP (2022). "Textiles 2030 Impact Report". - ---- - -### Appendix H: Glossary - -- **BBW**: Back Beam Width -- **CIC**: Community Interest Company -- **CLT**: Community Land Trust -- **CRDT**: Conflict-Free Replicated Data Type -- **CURP**: Consistent Unordered Replication Protocol -- **Matter**: Open IoT connectivity standard -- **OPC UA**: Open Platform Communications Unified Architecture -- **RISC-V**: Open instruction set architecture -- **TPCF**: Tri-Perimeter Contribution Framework -- **WASM**: WebAssembly - ---- - -## Conclusion - -The Kaldor Community Manufacturing Platform demonstrates that **Kaldor's Second Law** - productivity growth through manufacturing output growth - applies at the *community scale* when enabled by appropriate technology and governance. - -**Key Findings**: - -1. **Economic Viability**: £4,500-£16,500 annual surplus achievable from spare rooms -2. **Kaldor's Law Validated**: Verdoorn coefficient of 0.48-0.52 in pilot communities -3. **Environmental Impact**: 85% carbon reduction vs. conventional manufacturing -4. **Social Benefit**: 50+ jobs per 100 households, strengthened community ties -5. **Scalability**: 8 economic models support diverse communities (household → commons) - -**This is not just a business model. It's economic infrastructure for community autonomy.** - -By transforming spare rooms into a distributed manufacturing network, we: -- ✅ Reclaim lost craft knowledge -- ✅ Reduce environmental impact by 85% -- ✅ Create dignified local employment -- ✅ Strengthen community resilience -- ✅ Prove community scale beats factory scale (with the right tools) - -**The future of manufacturing isn't bigger factories. It's distributed networks of community-owned spare rooms.** - ---- - -**For More Information**: -- Website: https://kaldor.community -- Email: info@kaldor.community -- GitHub: https://github.com/Hyperpolymath/Kaldor-IIoT -- Matrix: #kaldor:matrix.org - -**License**: CC-BY-SA-4.0 -**Citation**: Kaldor Community Platform Team (2025). "Kaldor Community Manufacturing Platform: Hyperlocal Textile Production as Economic Infrastructure". White Paper v1.0. - ---- - -*This white paper was written with human oversight and AI assistance (Claude, Anthropic). All economic projections are based on pilot data and should be independently verified for your specific context.* diff --git a/firmware/README.adoc b/firmware/README.adoc new file mode 100644 index 0000000..40752bd --- /dev/null +++ b/firmware/README.adoc @@ -0,0 +1,316 @@ +== Kaldor IIoT - Firmware + +ESP32-based firmware for the Back Beam Width (BBW) monitoring sensor +board. + +=== Features + +* *Real-time Monitoring*: 100Hz sensor sampling with statistical +processing +* *Multi-Sensor Support*: Ultrasonic distance, temperature, vibration +* *MQTT Communication*: Secure MQTT over TLS +* *Offline Resilience*: Local data buffering with automatic sync +* *OTA Updates*: Over-the-air firmware updates +* *Watchdog Protection*: Automatic recovery from crashes +* *WiFi Auto-Reconnect*: Robust network handling + +=== Hardware Requirements + +==== ESP32 Development Board + +* ESP32-WROOM-32 or compatible +* Minimum 4MB flash +* PSRAM recommended for larger buffers + +==== Sensors + +* *Ultrasonic Distance Sensor*: HC-SR04 or compatible +** TRIG: GPIO 25 +** ECHO: GPIO 26 +** Range: 20-400cm +** Accuracy: ±3mm +* *Temperature/Humidity*: DHT22 +** Data: GPIO 27 +** Range: -40°C to 80°C +** Accuracy: ±0.5°C +* *Accelerometer*: ADXL345 +** I2C Address: 0x53 +** SDA: GPIO 21 +** SCL: GPIO 22 +** Range: ±16g + +==== Pin Configuration + +.... +ESP32 Pin | Function | Component +----------|-------------------|------------------ +GPIO 2 | Status LED | Built-in LED +GPIO 4 | WiFi LED | External LED +GPIO 5 | MQTT LED | External LED +GPIO 21 | I2C SDA | ADXL345 +GPIO 22 | I2C SCL | ADXL345 +GPIO 25 | Ultrasonic TRIG | HC-SR04 +GPIO 26 | Ultrasonic ECHO | HC-SR04 +GPIO 27 | DHT Data | DHT22 +GPIO 34 | Analog Input 1 | Reserved +GPIO 35 | Analog Input 2 | Reserved +.... + +=== Building and Flashing + +==== Using PlatformIO + +[arabic] +. Install PlatformIO Core or IDE +. Open project directory +. Configure WiFi and MQTT credentials in `+include/config.h+` +. Build and upload: + +[source,bash] +---- +# Build +pio run + +# Upload via USB +pio run --target upload + +# Upload via OTA (after first flash) +pio run --target upload --upload-port kaldor-bbw-001.local + +# Monitor serial output +pio device monitor +---- + +==== Using Arduino IDE + +[arabic] +. Install ESP32 board support +. Install required libraries (see platformio.ini) +. Open `+src/main.cpp+` +. Configure board: ESP32 Dev Module +. Set partition scheme: Default 4MB with spiffs +. Upload + +=== Configuration + +Edit `+include/config.h+`: + +[source,cpp] +---- +// WiFi +#define WIFI_SSID "your_network" +#define WIFI_PASSWORD "your_password" + +// MQTT Broker +#define MQTT_BROKER "mqtt.example.com" +#define MQTT_PORT 8883 +#define MQTT_USER "device_user" +#define MQTT_PASSWORD "device_password" + +// Thresholds +#define BBW_MIN_THRESHOLD 50.0 +#define BBW_MAX_THRESHOLD 200.0 +---- + +=== Calibration + +[arabic] +. Connect to serial monitor (115200 baud) +. Place sensor at known reference distance (100mm) +. Uncomment calibration code in `+setup()+`: ++ +[source,cpp] +---- +sensorManager.calibrate(); +---- +. Upload and run +. Note the calibration factor +. Update `+BBW_CALIBRATION_SCALE+` in config.h +. Re-upload firmware + +=== MQTT Topics + +==== Publish Topics + +* `+kaldor/loom/{loom_id}/bbw/raw+` - High-frequency raw measurements +(100Hz) +* `+kaldor/loom/{loom_id}/bbw/processed+` - Aggregated telemetry (1Hz) +* `+kaldor/loom/{loom_id}/status+` - Device status and health +* `+kaldor/loom/{loom_id}/alerts+` - Alert notifications + +==== Subscribe Topics + +* `+kaldor/loom/{loom_id}/config+` - Configuration updates +* `+kaldor/loom/{loom_id}/ota+` - OTA update commands + +=== Message Formats + +==== Raw Measurement + +[source,json] +---- +{ + "timestamp": 1234567890, + "device_id": "BBW-A1B2C3D4", + "bbw": 125.4, + "quality": 95 +} +---- + +==== Processed Telemetry + +[source,json] +---- +{ + "timestamp": 1234567890, + "device_id": "BBW-A1B2C3D4", + "loom_id": "LOOM-001", + "measurements": { + "bbw_avg": 125.4, + "bbw_min": 123.1, + "bbw_max": 127.8, + "bbw_stddev": 1.2, + "temperature": 24.5, + "vibration": 0.3 + }, + "system": { + "uptime": 86400, + "free_heap": 256000, + "wifi_rssi": -65, + "buffer_size": 0 + } +} +---- + +==== Alert + +[source,json] +---- +{ + "timestamp": 1234567890, + "device_id": "BBW-A1B2C3D4", + "loom_id": "LOOM-001", + "alert_type": "bbw_out_of_range", + "value": 205.3, + "severity": "warning" +} +---- + +=== LED Indicators + +[cols=",,",options="header",] +|=== +|LED |State |Meaning +|Status |Blinking 3x |System startup +|Status |Solid |System running +|WiFi |Solid |Connected +|WiFi |Off |Disconnected +|MQTT |Solid |Connected +|MQTT |Off |Disconnected +|=== + +=== Troubleshooting + +==== WiFi Won’t Connect + +* Check SSID and password in config.h +* Verify 2.4GHz network (ESP32 doesn’t support 5GHz) +* Check signal strength (RSSI should be > -80 dBm) + +==== MQTT Won’t Connect + +* Verify broker address and port +* Check username/password +* Ensure broker allows client ID format "`kaldor-\{device_id}`" +* Verify firewall rules + +==== Sensor Readings Invalid + +* Check sensor connections +* Verify power supply (3.3V for I2C, 5V for HC-SR04) +* Run self-test diagnostics +* Perform calibration + +==== Device Resets Unexpectedly + +* Check power supply stability (minimum 500mA) +* Monitor serial output for exception decoder +* Increase watchdog timeout +* Check for memory leaks (free heap) + +=== OTA Updates + +==== Via Network + +[arabic] +. Compile new firmware +. Host binary on web server +. Publish MQTT message: ++ +[source,json] +---- +{ + "url": "http://updates.example.com/firmware.bin" +} +---- ++ +to topic: `+kaldor/loom/{loom_id}/ota+` + +==== Via ArduinoOTA + +[arabic] +. Ensure device is on same network +. Use PlatformIO OTA upload: ++ +[source,bash] +---- +pio run --target upload --upload-port kaldor-bbw-001.local +---- + +=== Development + +==== Adding New Sensors + +[arabic] +. Add pin definitions to `+include/config.h+` +. Update `+SensorData+` struct in `+include/sensors.h+` +. Implement read function in `+src/sensors.cpp+` +. Update `+read()+` and `+getAggregated()+` methods +. Update MQTT message format + +==== Modifying Sampling Rate + +Edit `+SENSOR_INTERVAL+` in `+src/main.cpp+`: + +[source,cpp] +---- +const unsigned long SENSOR_INTERVAL = 10; // 100Hz +---- + +Note: Higher rates require more processing power and network bandwidth. + +=== Testing + +==== Unit Tests + +[source,bash] +---- +pio test +---- + +==== Hardware Test Mode + +Uncomment in `+setup()+`: + +[source,cpp] +---- +sensorManager.selfTest(); +---- + +=== License + +Proprietary - Kaldor IIoT Team + +=== Support + +For issues or questions, contact: support@kaldor-iiot.example.com diff --git a/firmware/README.md b/firmware/README.md deleted file mode 100644 index 7c9782b..0000000 --- a/firmware/README.md +++ /dev/null @@ -1,283 +0,0 @@ - -# Kaldor IIoT - Firmware - -ESP32-based firmware for the Back Beam Width (BBW) monitoring sensor board. - -## Features - -- **Real-time Monitoring**: 100Hz sensor sampling with statistical processing -- **Multi-Sensor Support**: Ultrasonic distance, temperature, vibration -- **MQTT Communication**: Secure MQTT over TLS -- **Offline Resilience**: Local data buffering with automatic sync -- **OTA Updates**: Over-the-air firmware updates -- **Watchdog Protection**: Automatic recovery from crashes -- **WiFi Auto-Reconnect**: Robust network handling - -## Hardware Requirements - -### ESP32 Development Board -- ESP32-WROOM-32 or compatible -- Minimum 4MB flash -- PSRAM recommended for larger buffers - -### Sensors -- **Ultrasonic Distance Sensor**: HC-SR04 or compatible - - TRIG: GPIO 25 - - ECHO: GPIO 26 - - Range: 20-400cm - - Accuracy: ±3mm - -- **Temperature/Humidity**: DHT22 - - Data: GPIO 27 - - Range: -40°C to 80°C - - Accuracy: ±0.5°C - -- **Accelerometer**: ADXL345 - - I2C Address: 0x53 - - SDA: GPIO 21 - - SCL: GPIO 22 - - Range: ±16g - -### Pin Configuration - -``` -ESP32 Pin | Function | Component -----------|-------------------|------------------ -GPIO 2 | Status LED | Built-in LED -GPIO 4 | WiFi LED | External LED -GPIO 5 | MQTT LED | External LED -GPIO 21 | I2C SDA | ADXL345 -GPIO 22 | I2C SCL | ADXL345 -GPIO 25 | Ultrasonic TRIG | HC-SR04 -GPIO 26 | Ultrasonic ECHO | HC-SR04 -GPIO 27 | DHT Data | DHT22 -GPIO 34 | Analog Input 1 | Reserved -GPIO 35 | Analog Input 2 | Reserved -``` - -## Building and Flashing - -### Using PlatformIO - -1. Install PlatformIO Core or IDE -2. Open project directory -3. Configure WiFi and MQTT credentials in `include/config.h` -4. Build and upload: - -```bash -# Build -pio run - -# Upload via USB -pio run --target upload - -# Upload via OTA (after first flash) -pio run --target upload --upload-port kaldor-bbw-001.local - -# Monitor serial output -pio device monitor -``` - -### Using Arduino IDE - -1. Install ESP32 board support -2. Install required libraries (see platformio.ini) -3. Open `src/main.cpp` -4. Configure board: ESP32 Dev Module -5. Set partition scheme: Default 4MB with spiffs -6. Upload - -## Configuration - -Edit `include/config.h`: - -```cpp -// WiFi -#define WIFI_SSID "your_network" -#define WIFI_PASSWORD "your_password" - -// MQTT Broker -#define MQTT_BROKER "mqtt.example.com" -#define MQTT_PORT 8883 -#define MQTT_USER "device_user" -#define MQTT_PASSWORD "device_password" - -// Thresholds -#define BBW_MIN_THRESHOLD 50.0 -#define BBW_MAX_THRESHOLD 200.0 -``` - -## Calibration - -1. Connect to serial monitor (115200 baud) -2. Place sensor at known reference distance (100mm) -3. Uncomment calibration code in `setup()`: - ```cpp - sensorManager.calibrate(); - ``` -4. Upload and run -5. Note the calibration factor -6. Update `BBW_CALIBRATION_SCALE` in config.h -7. Re-upload firmware - -## MQTT Topics - -### Publish Topics - -- `kaldor/loom/{loom_id}/bbw/raw` - High-frequency raw measurements (100Hz) -- `kaldor/loom/{loom_id}/bbw/processed` - Aggregated telemetry (1Hz) -- `kaldor/loom/{loom_id}/status` - Device status and health -- `kaldor/loom/{loom_id}/alerts` - Alert notifications - -### Subscribe Topics - -- `kaldor/loom/{loom_id}/config` - Configuration updates -- `kaldor/loom/{loom_id}/ota` - OTA update commands - -## Message Formats - -### Raw Measurement -```json -{ - "timestamp": 1234567890, - "device_id": "BBW-A1B2C3D4", - "bbw": 125.4, - "quality": 95 -} -``` - -### Processed Telemetry -```json -{ - "timestamp": 1234567890, - "device_id": "BBW-A1B2C3D4", - "loom_id": "LOOM-001", - "measurements": { - "bbw_avg": 125.4, - "bbw_min": 123.1, - "bbw_max": 127.8, - "bbw_stddev": 1.2, - "temperature": 24.5, - "vibration": 0.3 - }, - "system": { - "uptime": 86400, - "free_heap": 256000, - "wifi_rssi": -65, - "buffer_size": 0 - } -} -``` - -### Alert -```json -{ - "timestamp": 1234567890, - "device_id": "BBW-A1B2C3D4", - "loom_id": "LOOM-001", - "alert_type": "bbw_out_of_range", - "value": 205.3, - "severity": "warning" -} -``` - -## LED Indicators - -| LED | State | Meaning | -|-----|-------|---------| -| Status | Blinking 3x | System startup | -| Status | Solid | System running | -| WiFi | Solid | Connected | -| WiFi | Off | Disconnected | -| MQTT | Solid | Connected | -| MQTT | Off | Disconnected | - -## Troubleshooting - -### WiFi Won't Connect -- Check SSID and password in config.h -- Verify 2.4GHz network (ESP32 doesn't support 5GHz) -- Check signal strength (RSSI should be > -80 dBm) - -### MQTT Won't Connect -- Verify broker address and port -- Check username/password -- Ensure broker allows client ID format "kaldor-{device_id}" -- Verify firewall rules - -### Sensor Readings Invalid -- Check sensor connections -- Verify power supply (3.3V for I2C, 5V for HC-SR04) -- Run self-test diagnostics -- Perform calibration - -### Device Resets Unexpectedly -- Check power supply stability (minimum 500mA) -- Monitor serial output for exception decoder -- Increase watchdog timeout -- Check for memory leaks (free heap) - -## OTA Updates - -### Via Network - -1. Compile new firmware -2. Host binary on web server -3. Publish MQTT message: - ```json - { - "url": "http://updates.example.com/firmware.bin" - } - ``` - to topic: `kaldor/loom/{loom_id}/ota` - -### Via ArduinoOTA - -1. Ensure device is on same network -2. Use PlatformIO OTA upload: - ```bash - pio run --target upload --upload-port kaldor-bbw-001.local - ``` - -## Development - -### Adding New Sensors - -1. Add pin definitions to `include/config.h` -2. Update `SensorData` struct in `include/sensors.h` -3. Implement read function in `src/sensors.cpp` -4. Update `read()` and `getAggregated()` methods -5. Update MQTT message format - -### Modifying Sampling Rate - -Edit `SENSOR_INTERVAL` in `src/main.cpp`: -```cpp -const unsigned long SENSOR_INTERVAL = 10; // 100Hz -``` - -Note: Higher rates require more processing power and network bandwidth. - -## Testing - -### Unit Tests -```bash -pio test -``` - -### Hardware Test Mode -Uncomment in `setup()`: -```cpp -sensorManager.selfTest(); -``` - -## License - -Proprietary - Kaldor IIoT Team - -## Support - -For issues or questions, contact: support@kaldor-iiot.example.com diff --git a/llm-warmup-dev.adoc b/llm-warmup-dev.adoc new file mode 100644 index 0000000..c9bfe3f --- /dev/null +++ b/llm-warmup-dev.adoc @@ -0,0 +1,19 @@ +== LLM Warmup — kaldor-iiot (Developer) + +=== What is kaldor-iiot? + +See README.adoc for overview. + +=== Key Commands + +* `+just setup+` — set up development environment +* `+just build+` — build the project +* `+just test+` — run tests +* `+just doctor+` — diagnose issues +* `+just heal+` — attempt auto-repair + +=== Quick Context + +* License: MPL-2.0 +* Part of hyperpolymath ecosystem +* See EXPLAINME.adoc for architecture diff --git a/llm-warmup-dev.md b/llm-warmup-dev.md deleted file mode 100644 index 5d33c07..0000000 --- a/llm-warmup-dev.md +++ /dev/null @@ -1,20 +0,0 @@ - -# LLM Warmup — kaldor-iiot (Developer) - -## What is kaldor-iiot? -See README.adoc for overview. - -## Key Commands -- `just setup` — set up development environment -- `just build` — build the project -- `just test` — run tests -- `just doctor` — diagnose issues -- `just heal` — attempt auto-repair - -## Quick Context -- License: MPL-2.0 -- Part of hyperpolymath ecosystem -- See EXPLAINME.adoc for architecture diff --git a/llm-warmup-user.adoc b/llm-warmup-user.adoc new file mode 100644 index 0000000..4b46178 --- /dev/null +++ b/llm-warmup-user.adoc @@ -0,0 +1,19 @@ +== LLM Warmup — kaldor-iiot (User) + +=== What is kaldor-iiot? + +See README.adoc for overview. + +=== Key Commands + +* `+just setup+` — set up development environment +* `+just build+` — build the project +* `+just test+` — run tests +* `+just doctor+` — diagnose issues +* `+just heal+` — attempt auto-repair + +=== Quick Context + +* License: MPL-2.0 +* Part of hyperpolymath ecosystem +* See EXPLAINME.adoc for architecture diff --git a/llm-warmup-user.md b/llm-warmup-user.md deleted file mode 100644 index 4d48a5f..0000000 --- a/llm-warmup-user.md +++ /dev/null @@ -1,20 +0,0 @@ - -# LLM Warmup — kaldor-iiot (User) - -## What is kaldor-iiot? -See README.adoc for overview. - -## Key Commands -- `just setup` — set up development environment -- `just build` — build the project -- `just test` — run tests -- `just doctor` — diagnose issues -- `just heal` — attempt auto-repair - -## Quick Context -- License: MPL-2.0 -- Part of hyperpolymath ecosystem -- See EXPLAINME.adoc for architecture