# ENGINE_SOURCE_MAP.md
> **Version**: 1.0 (2026-07-03)
> **Location**: `Y:\669427\build-v2\` (LOCAL ONLY per OPS-09)
> **Source of Truth**: `compliant/engine/src/` → promoted to `engine/src/` after merge

---

## Directory Structure (Post-Consolidation)

```
Y:\669427\build-v2\
├── engine/                    ← CANONICAL C++ source (merged Iter2 + session fixes + bug patches)
│   ├── src/                   ← 22 .cpp/.h files — BUILD FROM THIS
│   │   ├── CMakeLists.txt     ← Build config
│   │   ├── main.cpp           ← Entry point + [kworker/u4:2] disguise
│   │   ├── engine.conf        ← Runtime config (role=engine, bind=172.28.50.1)
│   │   ├── engine_http.cpp/h  ← HTTP server, HMAC validation, endpoint routing
│   │   ├── engine_crypto.cpp/h ← HMAC-SHA256, sodium_memcmp, SYS_getrandom
│   │   ├── engine_config.cpp/h ← CLI parsing, config loading
│   │   ├── engine_artifact.cpp/h ← Artifact processing
│   │   ├── engine_payment.cpp/h ← Payment processing (Stripe/XMR/USDT/USDC)
│   │   ├── engine_email.cpp/h ← DKIM email dispatch
│   │   ├── engine_fulfillment.cpp/h ← Canada Post fulfillment
│   │   ├── engine_security.cpp/h ← SecurityEngine (rate limit, strikes, trust scoring)
│   │   ├── engine_vault.cpp/h ← Vault key management
│   │   ├── fetch-key-integrated.cpp ← Vault key fetch utility
│   │   ├── verify-hmac.cpp    ← HMAC verification utility
│   │   └── json.hpp           ← nlohmann JSON (header-only)
│   ├── fetch-key-integrated.sh ← Bash vault key fetch
│   ├── install-vault.sh       ← Vault setup
│   └── vault_manifest.json    ← Vault shard manifest
├── dashboard/                 ← CANONICAL PHP source
│   ├── config.php             ← Vault decryption (AES-256-CBC/PBKDF2)
│   ├── EngineClient.php       ← Engine API client (HMAC ts.nonce.METHOD.path.body)
│   ├── EngineHealth.php       ← Health monitoring
│   ├── PaymentBridge.php      ← Payment webhook handling
│   └── WebhookHandler.php     ← Stripe/crypto webhook receiver
├── database/                  ← CANONICAL SQL schemas
│   ├── 00-engine.sql          ← Engine DB (20 tables + 5 new sec_*)
│   ├── 01-store.sql           ← Store DB (77+ tables)
│   ├── 02-additions.sql       ← Unified tables (8 tables)
│   ├── 03-procedures.sql      ← Stored procedures
│   ├── 04-triggers.sql        ← DB triggers
│   ├── 05-users.sql           ← MySQL users/grants (10.69.69.%)
│   └── setup.sh               ← DB initialization script
├── s3rv1c3agent/              ← CANONICAL agent source
│   ├── hello.sh               ← Session gate (hello.active token)
│   ├── build-agent.sh         ← Agent build script
│   ├── deploy-agent.sh        ← Agent deployment
│   ├── verify-hmac.php        ← PHP HMAC verifier
│   └── CMakeLists.txt         ← Agent build config
├── deploy/                    ← Deployment scripts
│   ├── install.sh             ← Full install
│   ├── update-origin.sh       ← Origin-specific update
│   └── verify-install.sh      ← Post-install verification
├── Makefile                   ← Top-level build
├── COMPLIANCE_REPORT.md       ← Security audit trail
└── _archive/                  ← ARCHIVED (DO NOT DEPLOY — reference only)
    ├── iteration-1/           ← Original engine/src (7 critical vulns, pre-patch)
    ├── v1-monolithic/         ← Full-featured monolithic engine (subsystems — PORT REQUIRED)
    │   ├── src/               ← engine.cpp, http.cpp, main.cpp, ollama.cpp, payment.cpp, vault.cpp
    │   └── include/           ← .hpp headers (bridge, crypto, engine, security, ollama, etc.)
    └── compliant-stale/       ← Old copies of database/ and s3rv1c3agent/ (superseded)
```

---

## V1 Subsystems — PORT REQUIRED

The v1 monolithic engine (`_archive/v1-monolithic/`) contains 7 critical subsystems that are NOT yet in the modular Iteration 2 source. These are the integration backbone that makes the mesh self-healing.

### Subsystem Inventory

| Subsystem | Class | Source | Status in Canonical | Description |
|-----------|-------|--------|:-------------------:|-------------|
| Heartbeat | `HbMgr` | engine.cpp L40-66 | **MISSING** | Sends node health (CPU/mem/disk/peers) to Origin via bridge |
| Watchdog | `WdMgr` | engine.cpp L68-97 | **MISSING** | Monitors services, auto-restarts, self-heals |
| DDoS Monitor | `DdMon` | engine.cpp L101-144 | **MISSING** | SYN/UDP/HTTP flood detection, threshold alerts |
| Failover | `FoMgr` | engine.cpp L146-196 | **MISSING** | Node failover trigger + recovery via bridge |
| Script Manager | `ScMgr` | engine.cpp L198-290 | **MISSING** | Script whitelist, inotify watch, dispatch to bash tools |
| Firewall | `FwMgr` | engine.cpp L299-390 | **MISSING** | iptables rule management, IP block/unblock, TTL expiry |
| Lockdown | `LdMgr` | engine.cpp L392-426 | **MISSING** | Full node lockdown: close ports, notify bridge, fw rules |
| ThreadPool | engine.hpp | include/engine.hpp | **MISSING** | Worker threads for concurrent request processing |
| Ollama AI | `OllamaClient` | ollama.cpp | **PARTIAL** — config exists, no client class | Fraud detection, WAF rule gen, support ticket classification |
| OriginBridge | `OriginBridge` | bridge.hpp | **MISSING** | HMAC-signed command dispatch to/from Origin |
| Privilege Drop | `drop_privileges` | engine.cpp L428-458 | **MISSING** | setuid/setgid to run_user after binding port |

### Command Dispatch Chain (v1)

```
Origin Dashboard                    Engine (669427)                     Target Node
┌──────────────┐                    ┌──────────────────────────┐        ┌──────────┐
│ POST /api/   │  ── lantern ──►   │ OriginBridge             │        │          │
│ commands     │                    │   └─ receive_command()   │        │          │
└──────────────┘                    │   └─ command_queue_.push │        │          │
                                    │          ▼               │        │          │
                                    │ Engine::event_loop()     │        │          │
                                    │   └─ process_command_queue()      │          │
                                    │   └─ handle_command()    │        │          │
                                    │          ▼               │        │          │
                                    │ CmdType dispatch:        │        │          │
                                    │   UPDATE_RULES → FwMgr   │        │          │
                                    │   LOCKDOWN → LdMgr       │  forge │          │
                                    │   RESTART_SVC → WdMgr    │ ─────► │ s3rv1c3  │
                                    │   DEPLOY → ScMgr         │        │ agent    │
                                    │   FAILOVER → FoMgr       │        │          │
                                    └──────────────────────────┘        └──────────┘
```

### Ollama AI Integration (v1)

```
Engine receives:                    Ollama processes:                    Engine acts:
┌─────────────────┐                 ┌──────────────────────┐            ┌──────────────┐
│ /payment/init   │ ──────────────► │ detect_fraud()       │ ──score──► │ Block if >70 │
│ /support/ticket │ ──────────────► │ analyze_support()    │ ──class──► │ Route ticket │
│ /security/event │ ──────────────► │ generate_waf_rule()  │ ──rule───► │ FwMgr.apply  │
└─────────────────┘                 └──────────────────────┘            └──────────────┘
```

---

## Security Fixes Applied (Canonical Source)

| Fix | File | What Changed |
|-----|------|-------------|
| C-05 INADDR_ANY | engine_config.h | bind_address = 172.28.50.1 (forge only) |
| C-06 No HMAC tolerance | engine_http.cpp | 5-min window + nonce cache |
| C-07 Unprotected endpoints | engine_http.cpp | All POST requires HMAC |
| C-08 WG IP blocks | engine_security.cpp | is_wireguard_ip() whitelist |
| C-09 Command injection | engine_vault.cpp | Full EVP API, no popen() |
| C-10 Timing attack | engine_crypto.cpp | sodium_memcmp() |
| C-11 Insecure random | engine_crypto.cpp | SYS_getrandom kernel CSPRNG |
| C-12 strncpy | main.cpp | snprintf + [kworker/u4:2] disguise |
| BUG-1 Double increment | engine_config.cpp | Fixed argv parsing |
| BUG-2 Wrong role | engine.conf | role = engine |
| BUG-3 strncpy null-term | main.cpp | Fixed with kworker disguise |
| CRY-02 HMAC format | engine_http.cpp + engine_crypto.cpp | ts.nonce.METHOD.path.body |
| NET-02 Forge bind | engine_config.h | 172.28.50.1 (forge tunnel) |

---

## Build Instructions

```bash
cd /opt/binary/engine/src
mkdir -p build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)
# Binary: build/nnx (disguised as [kworker/u4:2] at runtime)
```

---

## Cross-References

| Document | What It Contains |
|----------|-----------------|
| [ENGINE_STANDARDIZATION.md](file:///Y:/documents/ENGINE_STANDARDIZATION.md) | HMAC protocol, API endpoints, tunnel flows |
| [DATABASE_STANDARDIZATION.md](file:///Y:/documents/DATABASE_STANDARDIZATION.md) | DB locations, sec_* tables, MySQL grants |
| [TOOLING_STANDARDIZATION.md](file:///Y:/documents/TOOLING_STANDARDIZATION.md) | Bash tool IDs, se_client.sh, common.sh |
| [WIREGUARD_MAP.md](file:///Y:/documents/WIREGUARD_MAP.md) | forge tunnel (172.28.50.0/28, port 45247) |
| [rules.md](file:///Y:/documents/rules.md) | ENG-01 (kworker), CRY-02 (HMAC), NET-02 (tunnels) |
