Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions .claude/settings.local.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"permissions": {
"allow": [
"Bash(/home/diamondnode/venv312/bin/python scripts/mycelial_qubo.py --shots 512 --outer-rounds 3 --json)",
"Bash(/home/diamondnode/venv312/bin/python scripts/benchmark.py --suite gpu,cudaq,qubo --json)",
"Bash(python3 -c ' *)",
"Bash(/home/diamondnode/venv312/bin/python scripts/benchmark.py --suite all)",
"Bash(/home/diamondnode/venv312/bin/python scripts/llm_interpret.py)",
"Bash(gh --version)",
"Bash(gh auth *)",
"Bash(curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg)",
"Bash(sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg)",
"Bash(dpkg --print-architecture)",
"Bash(echo \"deb [arch=$\\(dpkg --print-architecture\\) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main\")",
"Bash(sudo tee /etc/apt/sources.list.d/github-cli.list)",
"Bash(sudo apt-get update -qq)",
"Bash(sudo apt-get install -y -qq gh)",
"Bash(curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o /tmp/ghkey.gpg)",
"Bash(sudo mv /tmp/ghkey.gpg /usr/share/keyrings/githubcli-archive-keyring.gpg)",
"Bash(git init *)",
"Bash(git config *)",
"Bash(git add *)",
"Bash(git branch *)",
"Bash(git commit -m ' *)",
"Bash(export PATH=\"$PATH:/home/diamondnode/.local/bin\")",
"Bash(npm list *)",
"Bash(/home/diamondnode/.local/bin/vibe --help)",
"Bash(/home/diamondnode/.local/bin/vibe *)"
]
Comment on lines +3 to +29
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-critical critical

The allow list contains several overly permissive commands that use wildcards (*). This creates significant security risks, especially for an automated agent.

Specifically:

  • Bash(python3 -c ' *) (line 6) allows arbitrary Python code execution.
  • Bash(git ... *) (lines 20-24) allows broad git operations that could manipulate the repository state unexpectedly.
  • Bash(gh auth *) (line 10) could expose or manipulate GitHub authentication.
  • Bash(/home/diamondnode/.local/bin/vibe *) (line 28) is an unrestricted command.

It is highly recommended to replace these wildcard permissions with more specific, narrowly-scoped commands to reduce the attack surface. For example, instead of git add *, specify the exact files or directories that can be added.

}
}
166 changes: 166 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
# Copilot Instructions for diamond-node

Genesis Conductor audit-node — QUBO simulation engine + Cloudflare Worker identity layer

## Build, Test, and Lint

```bash
# Install dependencies
npm ci

# Type checking
npm run typecheck

# Run all tests
npm test

# Run specific test file
npx vitest run test/health.test.ts

# Deploy (dry run)
npm run deploy:dry

# Deploy to Cloudflare Workers
npm run deploy

# Generate Ed25519 identity keypair
npm run gen-identity
```

## Python Scripts

**Critical:** All CUDA-Q and numpy scripts **must** use the dedicated venv:

```bash
/home/diamondnode/venv312/bin/python
```

System Python lacks `cudaq`, `numpy`, `cupy`, `scipy`, and `jax`.

```bash
# Run one QUBO iteration
/home/diamondnode/venv312/bin/python scripts/mycelial_qubo.py [--shots 512] [--outer-rounds 3] [--json]

# Run benchmark suite
/home/diamondnode/venv312/bin/python scripts/benchmark.py [--suite all|qubo|llm|gpu|cudaq] [--json]

# Daily health check (GPU + Ollama status)
/home/diamondnode/venv312/bin/python scripts/daily_health.py

# LLM interpretation of network state
/home/diamondnode/venv312/bin/python scripts/llm_interpret.py
```

## Architecture

### Two-Layer Design

1. **TypeScript Worker Layer** (src/)
- Cloudflare Worker serving identity and audit endpoints
- Routes: `/healthz`, `/.well-known/diamond-node.json`, `/audit/replay`
- Ed25519 signatures for all audit events
- Types defined in `src/types.ts`
- AppSignal monitoring (optional, enabled via `APPSIGNAL_KEY`)

2. **Python Simulation Layer** (scripts/)
- CUDA-Q QAOA optimizer running on GTX 1650 (4 GB VRAM)
- State persisted to `state/mycelial_state.json`
- Checkpointing to `state/mycelial_checkpoint.json` on energy improvements

### Core Simulation: Mycelial QUBO

**Problem:** Models fungal hyphal-network growth as QUBO over edge variables on a 16-node 4×4 grid

**QUBO Objective:**
- `lam_dist=0.4`: Distance penalty for long edges
- `lam_redund=-0.2`: Redundancy reward for existing edges (multi-path bonus)
- `lam_resource=-0.8`: Reward for edges near resource nodes (0 and 15)

**Solving Strategy:**
- Split into subspaces of ~10 edges each
- Each subspace solved by 1-layer QAOA circuit (`cudaq.sample`)
- QAOA params: `gamma=0.3`, `beta=0.2`
- Best assignments stitched back into global edge vector

**Double-Loopback Resilience:**
- **Inner loopback:** If `cudaq.sample` fails, retry once; fall back to random on second failure
- **Outer loopback:** When candidate energy beats `state.best_energy`, checkpoint to `state/mycelial_checkpoint.json`

**State Model:** `MycelialState` dataclass carries:
- `active_edges`, `energy_history`, `best_energy`, `best_edges`
- `node_positions`, `resource_nodes`, `run_log`
- Serialized to JSON after every iteration

### Benchmark Suite

Five benchmarks in `benchmark.py` each return:
```python
{
"name": str,
"passed": bool,
"duration_s": float,
"value": Optional[float],
"unit": Optional[str],
"threshold": Optional[float],
"notes": str
}
```

Reports saved to `reports/benchmark-<UTC timestamp>.json`. Exit code 0 only when all pass.

## Key Conventions

### Environment Variables

**Cloudflare Secrets** (set via `wrangler secret put`):
- `DIAMOND_NODE_ED25519_PRIV` — base64 PKCS#8 private key
- `DIAMOND_NODE_ED25519_PUB` — base64 SPKI public key
- `DIAMOND_VAULT_AUDIT_URL` — upstream audit endpoint (optional)
- `APPSIGNAL_KEY` — AppSignal API key (optional)

**Worker vars** (in `wrangler.toml`):
- `NODE_VERSION`, `NODE_ID`, `KEY_ID`

**Python path overrides** (optional):
- `DIAMOND_STATE_DIR` — override `state/` directory
- `DIAMOND_LOG_DIR` — override `logs/` directory
- `DIAMOND_VENV` — override venv path

### Hardware Constraints

- **GPU:** NVIDIA GTX 1650, 4 GB VRAM
- **Thermal threshold:** 89.6 °C (see `bench_gpu_telemetry`)
- **LLM:** Ollama at `/usr/local/bin/ollama` with `llama3.2:3b` (2 GB)

### Python Packages in venv

- `cudaq 0.14.2`
- `numpy 2.4.4`
- `cupy-cuda13x`
- `jax/jaxlib 0.10.0`
- `scipy 1.17.1`

### Identity & Signatures

All audit events are Ed25519-signed. The signature flow:
1. Build event object (sans `sig` field) via `makeEvent()`
2. Sign with `signEvent()` using imported private key
3. Append to in-memory ring buffer (max 100 events)
4. Optionally emit to upstream vault via `emitToVault()`

### State Persistence

- **Primary state:** `state/mycelial_state.json` — written after every iteration
- **Checkpoint:** `state/mycelial_checkpoint.json` — written only on new best energy
- **LLM logs:** `logs/llm-interpretations.jsonl` — appended by `llm_interpret.py`
- **Benchmark reports:** `reports/benchmark-<timestamp>.json`

### CUDA-Q Backend

All QAOA circuits use `qpp-cpu` backend (CPU simulator) since GTX 1650 lacks direct CUDA-Q kernel support. Future GPU acceleration would require migration to `nvidia` backend with compatible hardware.

## Disambiguation

- **NOT** `Diamond-V` (vault repo)
- **NOT** `diamondvault.io` (separate domain)
- This is specifically the `diamond-node` audit/simulation node in the Genesis Conductor 7-agent topology
68 changes: 25 additions & 43 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,43 +1,25 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

# Tencent Cloud Edge Functions
.env
.edgeone
edgeone.json

content.txt
node_modules/
dist/
.wrangler/
*.env
.env*
!.env.example
*.local

# State files (generated at runtime)
state/mycelial_state.json
state/mycelial_checkpoint.json
.claude/scheduled_tasks.lock

# Logs (append-only, generated)
logs/llm-interpretations.jsonl
logs/*.log

# Benchmark results (generated)
benchmark_results/*.json
reports/benchmark-*.json
reports/health-*.json

# Node modules
node_modules/
package-lock.json
Comment on lines +23 to +25
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There are a couple of issues in this section:

  1. The # Node modules section and node_modules/ entry are duplicates of line 1.
  2. package-lock.json should generally not be ignored. Committing this file is crucial for ensuring reproducible builds by locking dependency versions across different environments (local development, CI, production). Please consider removing package-lock.json from this file.

10 changes: 10 additions & 0 deletions .well-known/diamond-node.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"_comment": "Template — populated at runtime by the Worker. The identity_pubkey field is populated after running: node scripts/gen-identity.mjs && wrangler secret put DIAMOND_NODE_ED25519_PUB",
"node_id": "diamond-node",
"key_id": "dn-2026-05",
"identity_pubkey": "",
"version": "0.1.0",
"deploy_url": "https://dn.genesisconductor.io",
"repo": "https://github.com/Genesis-Conductor-Engine/diamond-node",
"audit_replay": "https://dn.genesisconductor.io/audit/replay"
}
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Changelog

## [0.1.0] — 2026-05-11

### Added
- Cloudflare Worker identity layer (`src/index.ts`, `src/health.ts`, `src/identity.ts`, `src/audit.ts`)
- `GET /healthz` endpoint — liveness + pubkey + version
- `GET /.well-known/diamond-node.json` — identity manifest
- `GET /audit/replay` — in-memory ring buffer of last 100 signed events
- Ed25519 signing via WebCrypto; `node.online` event emitted on first healthz per isolate
- `scripts/gen-identity.mjs` — offline keypair generator
- QUBO simulation engine (`scripts/mycelial_qubo.py`) — mycelial hyphal-network optimizer using CUDA-Q QAOA
- Benchmark suite (`scripts/benchmark.py`) — gpu, cudaq, qubo, llm, state_persistence
- LLM interpretation pass (`scripts/llm_interpret.py`) — Ollama llama3.2:3b network analyst
- Daily health check (`scripts/daily_health.py`)
- Phase 1 repo scaffold per HAVIS v2.0 plan (deploy URL: `dn.genesisconductor.io`)
15 changes: 15 additions & 0 deletions CITATION.cff
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
cff-version: 1.2.0
message: "If you use diamond-node in research, please cite it as below."
type: software
title: diamond-node
version: 0.1.0
date-released: "2026-05-11"
license: Apache-2.0
repository-code: https://github.com/Genesis-Conductor-Engine/diamond-node
url: https://dn.genesisconductor.io
abstract: >
Genesis Conductor audit-node combining a QUBO-based mycelial network optimizer
(CUDA-Q QAOA on NVIDIA GTX 1650) with a Cloudflare Worker identity layer
providing Ed25519-signed audit events.
authors:
- name: "Kovach Enterprises / Genesis Conductor"
70 changes: 70 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Environment

All CUDA-Q and numpy work must use the dedicated venv:

```
/home/diamondnode/venv312/bin/python
```

System Python lacks `cudaq`, `numpy`, `cupy`, `scipy`, and `jax`. Key packages in the venv: `cudaq 0.14.2`, `numpy 2.4.4`, `cupy-cuda13x`, `jax/jaxlib 0.10.0`, `scipy 1.17.1`.

Hardware: NVIDIA GTX 1650, 4 GB VRAM. Thermal threshold 89.6 °C (see `bench_gpu_telemetry`).

Ollama is at `/usr/local/bin/ollama` with `llama3.2:3b` (2 GB) loaded.

Path overrides via env vars: `DIAMOND_STATE_DIR`, `DIAMOND_LOG_DIR`, `DIAMOND_VENV`.

## Commands

Run one QUBO iteration (uses venv python internally):
```bash
/home/diamondnode/venv312/bin/python scripts/mycelial_qubo.py [--shots 512] [--outer-rounds 3] [--json]
```

Run the full benchmark suite (saves report to `reports/`):
```bash
/home/diamondnode/venv312/bin/python scripts/benchmark.py [--suite all|qubo|llm|gpu|cudaq] [--json]
```

Daily health check (GPU telemetry + ttectra + ollama status):
```bash
/home/diamondnode/venv312/bin/python scripts/daily_health.py
```

LLM interpretation of current network state (appends to `logs/llm-interpretations.jsonl`):
```bash
/home/diamondnode/venv312/bin/python scripts/llm_interpret.py
```

CUDA-Q smoke test (256 shots of a Bell circuit on `qpp-cpu`):
```bash
/home/diamondnode/venv312/bin/python scripts/_cudaq_probe.py
```

## Architecture

**Core simulation — `mycelial_qubo.py`**

Models fungal hyphal-network growth as a QUBO over edge variables on a 16-node 4×4 grid. The QUBO diagonal encodes three competing terms: distance penalty (`lam_dist=0.4`), redundancy reward for already-active edges (`lam_redund=-0.2`), and resource-proximity reward for edges incident to resource nodes 0 and 15 (`lam_resource=-0.8`).

Solving is split into subspaces of 10 edges each. Each subspace is solved by a 1-layer QAOA circuit via `cudaq.sample` (gamma=0.3, beta=0.2). Subspace assignments are stitched back into the global edge vector, and the best global assignment is kept across `outer_rounds`.

**Double-loopback resilience**:
- *Inner loopback*: if `cudaq.sample` raises, retries once; falls back to random assignment on second failure.
- *Outer loopback*: whenever a candidate energy beats `state.best_energy`, state is checkpointed to `state/mycelial_checkpoint.json`. This checkpoint is the recovery target if outer rounds diverge.

**State persistence**

`MycelialState` (dataclass) is serialised to `state/mycelial_state.json` after every iteration and to `state/mycelial_checkpoint.json` on any new best energy. The state carries `active_edges`, `energy_history`, `best_energy`/`best_edges`, node positions, and a full `run_log`.

**Benchmark runner — `benchmark.py`**

Five benchmarks (`gpu_telemetry`, `cudaq_probe`, `qubo_iteration`, `state_persistence`, `llm_latency`) each return a uniform dict `{name, passed, duration_s, value?, unit?, threshold?, notes}`. Results are saved as JSON to `reports/benchmark-<UTC timestamp>.json`. Exit code is 0 only when all selected benchmarks pass.

**LLM interpretation — `llm_interpret.py`**

Reads `state/mycelial_state.json`, builds a one-sentence summary (node count, active edges, best energy, trend, resource nodes, iteration), and sends it to `ollama run llama3.2:3b` asking for a 3–4 sentence assessment and a single parameter-change recommendation. Output appended as JSONL to `logs/llm-interpretations.jsonl`.
Loading