---
name: flux-dev
description: The operational hub skill for coding Flux with AI — git-first workflow, fluxc/MCP build+test (never raw cargo), VARFLOW + FLUXFOOD methodology, frontend deploy, and a router to all sibling Flux skills.
---

# Flux Dev v4 — Git-First AI Workflow

> **Flux v0.18.0 "Atelier" (2026-05-30) — fluxc-core split + Pro IDE shell + Frontend UI MCP surface. The operational skill for coding Flux with AI.**

## 🆕 What's New — SIGIL chain templates ([**SIGIL_TEMPLATES.md**](SIGIL_TEMPLATES.md))

Copy-paste starters for new `sigil-*` crates and fresh Flux-native sibling chains — FLUXFOOD workspace, name-derived identity (network_id / protocol prefix / topics / ports), block-header v0, the deterministic **chronos** test harness (happy-path `blocks_applied=N, divergence=0` + adversarial tamper-reject), and a lightweight tip-verify node. Modeled on the live `sigil-header` / `sigil-net` / `sigil-chronos` / `sigil-node` crates; the manual path until `fluxc scaffold-chain` (the `flux-extension` stub) lands. Verify with `flux_combo`, never raw `cargo`.

## 🖥 Building desktop UIs (the Electron-killer) — read [**FCX.md**](FCX.md)

Author UI in **FCX** (a TSX dialect), ship a native cross-compiled Slint `.exe` — no Chromium, no JS runtime. `flux-fcx` transpiles FCX→Slint→native; `fcx pack` + `fluxc build --target win` → a 3.6 MB GUI binary (proven on real Windows hardware). Dialect: state/`useState`, JSX tags, `{interp}`, `onClick`, `{cond && …}` conditionals, `{list.map(…)}` lists, multi-component. FCX.md has the full dialect→Slint map, the cross-build recipe, the "amaze on first run" bar, and the SAP/FCQ discipline checklist.

## ☁️ Cloud test fabric (Vast.ai) — use the **`flux-fabric`** skill

Spinning N Vast.ai boxes (1 fast GPU + 9 cheap followers + Delta/Epsilon) to test chronos/p2p/flux:// + mining at scale lives in its own skill: **`~/.claude/skills/flux-fabric/SKILL.md`**. Fail-loud pre-flight, REST recipes (the Vast MCP is broken → 400s), the benchmark matrix, and teardown. Vehicle for SIGIL P1 #2 (gossipsub fabric) — see memory `project_sigil_p1_harden_primitives`.

## 🧭 Methodology — Variational Flow (load this BEFORE claiming any lane)

Read [**VARFLOW.md**](VARFLOW.md) — the development methodology of the agentic-money / post-quantum era.

**TL;DR:** 7 axioms + T1-T10 token-economy + Honest Checklist + Variational Review. Pull-based lanes settle cryptographically, witnessed by quorum, validated in multiverse before mainline. Generation 5 (methodology named) shipped 2026-05-30; Gen 6-9 substrate queued as SWARM S8-S10 + SWARM-V1.

**The Honest Checklist (run before every claim):**
1. What's the measurement gate? (specific, falsifiable)
2. What's still pretend? (unverified assumptions)
3. What composition edges? (which crates/lanes does this touch)
4. What's the rollback path?

**The Variational Review (run before every code change):** which term in $\mathcal{S}_{\mathrm{SIGIL}}$ does this touch? None = orthogonal, one = compose naturally, two+ = reconsider scope.

Canonical doc: `flux/docs/VARIATIONAL_FLOW_v0.md` (286 lines).

## v0.23 Update (2026-06-03) - DeepSeek-V4 API two-mind gate (NO GPU box) + flux-moe v0.3

**The vast.ai GPU path is superseded.** deepseek-r1:70b on a rented A100 was impractical
(82GB > 80GB, OOM, >200s cold-load, reaper-bait). The stable 2-of-2 engine is now:
- PROPOSER = local qwen3.6 (ollama `http://localhost:11434`, model `qwen3.6:latest`) - on Epsilon, CPU, stable, free.
- VETOER/JUDGE = DeepSeek-V4 API - `https://api.deepseek.com` (OpenAI-compatible `/chat/completions`),
  models `deepseek-v4-flash` (cheap/fast default) + `deepseek-v4-pro`. Key `/root/.config/deepseek/api_key`,
  env `DEEPSEEK_API_KEY`. V4 is a reasoner: chain-of-thought in `reasoning_content`, the answer in `content`
  (give it enough max_tokens or `content` comes back empty).
- No GPU box. The whole money-safety gate runs on-prem + one API.

**flux-moe v0.3** (crates/flux-moe): `generate()` now speaks BOTH ollama (`/api/generate`) AND OpenAI
(`/chat/completions`), routed by `endpoint_is_ollama()`. New `generate_openai()` + `openai_chat_url()`
(Bearer key from `DEEPSEEK_API_KEY`/`FLUX_MOE_API_KEY`). So `two_mind_split(proposer=local-ollama-qwen,
vetoer=deepseek-api)` runs the gate with no rented hardware. Proven live: qwen proposed send_qug,
deepseek-flash VETOED an invalid hex address that qwen missed. v0.2 also: `classify()` score-argmax +
word-boundary; Ensemble `judge`/`parse_judge_verdict`. Commits 89ece4d, b08a472, 8ec9def.

**Serving a model call to the BROWSER (cockpit dispatch, etc.) - NO bespoke Python proxy.**
The compiler IS the web server. Two correct paths:
1. Extend `fluxc serve` with the route (Rust). Anywhere you'd reach for a Python HTTP bridge, extend fluxc serve.
2. Tune-via-access-log through q-flux: the browser GETs a sentinel URL (e.g. `/dispatch.json?prompt=...`,
   returns 404, harmless), q-flux logs it to `/home/storage/logs/q-flux/access.log`, a tailer matches it,
   calls deepseek-flash, writes the result where the cockpit polls. No CORS, no extra ports, no key in the bundle.
   A standalone Python proxy on a port is the ANTI-pattern.

**The flux-core improve loop** (proven on flux-moe): drive qwen3.6 (local) with this skill + MCP combos to
draft; YOU refute/verify by building+testing with `/usr/local/bin/flux-cargo-wrapper test -p <crate>` (the
`flux_test` MCP is broken - os error 2; `fluxc` may not be on the non-interactive PATH). Claim the file
(`flux_file_claim`), commit only your file, release. The swarm leaves work UNCOMMITTED - a path-scoped
`git add <file>` rescues it.


## v0.18 Update (2026-05-30) — Frontend UI deploy workflow + desktop launcher discipline

The canonical frontend deploy path is **MCP-exposed since v0.11.2+ via `flux_ui_*` tools**, sandboxed to the production dist root with built-in cache-busting. Do NOT `cp` files into `/home/orobit/q-narwhalknight/dist-final/` by hand any more — that loses cache-bust, loses audit, and conflates dev edits with prod deploys.

### The 4 frontend MCP tools (all are deferred — load via ToolSearch when first needed)

| Tool | What it does | When to use |
|---|---|---|
| `flux_ui_list {ext?}` | Lists every static surface in dist root with size + mtime + public URL + cache-busted URL. Default ext filter is `html,css,js`. | **First call every UI session** — see what's already deployed before you edit |
| `flux_ui_read {file, max_bytes?}` | Read the live deployed copy of a file back into context | When you need to know the production state, not your local working copy |
| `flux_ui_deploy {file, content}` | Write a file into the dist root (overwrites) and return a CACHE-BUSTED URL (`?v=<epoch>`) so the change is visible in your browser immediately | Every UI deploy. Replaces raw `cp` + `curl` verify dance. |
| `flux_ui_preview {file}` | Mint a fresh cache-busted URL for an already-deployed file | Hand a URL to a human; they always see the latest, never a stale cached copy |

### Why the `flux_ui_*` path is the only correct path

The browser cache TTL on production-served HTML/CSS/JS is 24h. After a raw `cp` + `git update-server-info`, a human reloads quillon.xyz/desktop.html and **sees the old version** unless they hard-reload — and even hard-reload doesn't always defeat intermediate caches. `flux_ui_deploy` returns a URL like `https://fluxapp.xyz/desktop.html?v=1780109815` — the query string busts every cache layer. This is the fix to the perennial "I deployed but the page didn't change" failure mode.

### The "dev copy vs production" trap (learned the hard way 2026-05-30)

There are stale `q-narwhalknight/dist-final/` mirrors elsewhere on the box. Specifically:

- `/home/storage/deepseek-codewhale/q-narwhalknight/dist-final/` — **STALE dev copy.** Has `quillonos.html` (older launcher). Edits here do NOT serve at quillon.xyz.
- `/home/orobit/q-narwhalknight/dist-final/` — **PRODUCTION root.** Has the real `desktop.html` (QuillonOS Desktop v0.3 hyprland-skin launcher). q-flux serves this. This is what quillon.xyz points to.

`flux_ui_*` is sandboxed to the production root and so cannot be fooled. When in doubt, `flux_ui_list` confirms what's actually live.

### Desktop launcher discipline — the 3-place pattern for wiring a new surface

`desktop.html` is the QuillonOS hyprland-skin launcher. To make a new HTML surface reachable from the desktop, three places must be edited consistently:

1. **`APPS` registry** (around line 924) — add an entry like:
   ```js
   ide: { title: 'Flux Pro IDE — Atelier', icon: '💻',
          kind: 'iframe', src: '/ide-preview.html', w: 1280, h: 820 },
   ```
2. **Quick-launch widget** (around line 732) — add a `<button class="launch-tile" onclick="launch('ide')">` with `.ic`, `.name`, `.desc`
3. **Dock** (around line 789) — add a `<div class="dock-item" onclick="launch('ide')">` with icon + `.tip` tooltip

Forgetting any one of the three results in "the IDE shows up in the launcher tile but not in the dock" or similar half-wired surface. All three should ship together.

**Better:** ship `flux_launcher_register` (lane #80) so this 3-place edit becomes one MCP call. Until then, the manual edits are the only path.

### Hyprland theme adoption checklist (when building a new surface)

Every new surface should adopt `theme-hyprland.css` v0.1 (already deployed at `quillon.xyz/theme-hyprland.css`) by:

1. `<link rel="stylesheet" href="theme-hyprland.css" />` in `<head>`
2. `<body class="hypr-root">` for the radial-gradient background + Inter font default
3. Header: `<div class="hypr-brand-cube">F</div>` + `<h1 class="hypr-display--brand">Surface Name <span class="hypr-version-chip">v0.18</span></h1>`
4. Capability badges: `<div class="hypr-capability-strip"><span class="hypr-capability">⬡ feature</span>…</div>`
5. Panels: `.hypr-panel` (default mauve) or `.hypr-panel--tier-{indie,startup,enterprise,custom}` (cyan/green/purple/orange) for category-distinction
6. Buttons: `.hypr-btn.hypr-btn--primary` (cyan-gradient), `.hypr-btn--ghost`, `.hypr-btn--danger`
7. Inputs: `.hypr-input` (default mauve focus) or `.hypr-input--cyan` (cyan focus)
8. Section headers: `.hypr-section-header` (cyan, uppercase, tracked) + `--mauve|green|purple|orange|gold` modifiers
9. Status/result panels: `.hypr-status` + `--ok|--fail|--idle` modifiers (animated pulse/shake)

Design doc: `/home/storage/deepseek-codewhale/FLUX_THEME_HYPRLAND_v0.md`. Working examples in the production root: `ide-preview.html`, `verify-tip.html`.

### Local-dev preview (no deploy step)

When iterating on a UI before deploying to production, run `fluxc serve` with `FLUX_STATIC_DIR` pointing at your working directory:

```bash
FLUX_STATIC_DIR=/path/to/your/dist FLUX_SERVE_PORT=8087 fluxc serve
```

Then `http://127.0.0.1:8087/<file>.html` serves your in-progress copy with hot-reload. NOT `python3 -m http.server` — that pattern is forbidden ([FLUXFOOD.md lever 0](FLUXFOOD.md)). When ready: `flux_ui_deploy` ships it to production.

### Gotcha: `flux_ui_deploy` writes ATOMICALLY and OVERWRITES

`flux_ui_deploy` takes the full file `content`, not a patch. If you want to edit an existing 74KB desktop.html, you must first `flux_ui_read` it, edit the string in memory, then `flux_ui_deploy` the whole thing. The tool deliberately does not support partial updates — the cache-busting URL it returns is the proof that exactly THIS content is now live.

### Pragmatic exception for files already on disk + when running on Epsilon

When the working file is ALREADY on the filesystem at `/home/storage/.../sigil/gui/dist/foo.html` (or similar) AND you're running on Epsilon (the production host), you can `cp` to the dist root then call `flux_ui_preview` to get the cache-busted URL. The cache-bust still works — `flux_ui_preview` mints `?v=<epoch>` against the file's current mtime regardless of how it got there. This avoids reading a 26KB file through Read → reconstructing the content in a flux_ui_deploy call.

```bash
cp /home/storage/deepseek-codewhale/sigil/gui/dist/theme-hyprland.css \
   /home/orobit/q-narwhalknight/dist-final/theme-hyprland.css
```
followed by `flux_ui_preview {file: 'theme-hyprland.css'}` → returns `https://fluxapp.xyz/theme-hyprland.css?v=<epoch>`.

When this exception is acceptable:
- File is already on disk in a working dir (not programmatically generated this turn)
- You're on Epsilon (`hostname -I` shows `89.149.241.126`)
- File is >5KB (small files don't justify the bash detour)

When `flux_ui_deploy` is still the right tool:
- Programmatic content you're generating in-conversation
- Small files (<5KB) where read/edit/deploy round-trips cleanly
- Any non-Epsilon host (the `cp` path requires production-fs write access)

For Rust-side UIs being iterated in the workspace (e.g. `crates/fluxc-core/dashboard_sse.html` which is `include_str!`-bundled), `flux_ui_*` does NOT help — you must rebuild fluxc and redeploy the binary. For browser-facing static surfaces (HTML/CSS/JS in dist-final), `flux_ui_*` is the path.

### MCP tools that surfaced as deferred in this session

- `flux_ui_deploy`, `flux_ui_list`, `flux_ui_preview`, `flux_ui_read` — covered above
- `flux_chronos_run` — MCP wrapper around the `flux-chronos` crate's deterministic network simulator. One producer floods N-1 sinks under controlled latency/drop/redundancy in virtual time (instant). Use for reproducible gossip experiments. Don't confuse with `sigil-chronos` (the SIGIL chain).

### Operating rules added this session (binding)

- **NEVER `cp` into `/home/orobit/q-narwhalknight/dist-final/` by hand.** Use `flux_ui_deploy`. Raw `cp` skips cache-bust → human reloads, sees stale page → blames the deploy.
- **`flux_ui_list` before any UI edit** — saves you from editing the wrong copy at the wrong path.
- **When editing `desktop.html`, wire all 3 places** (APPS + launch-tile + dock). The launcher is the navigation primitive; a half-wired surface is worse than no surface.
- **Theme adoption is not optional for production surfaces.** A new surface that isn't `hypr-*`-themed breaks brand continuity. See checklist above.

### Lane opened by this update

- **#80 — `flux_launcher_register` MCP tool** — automate the 3-place desktop.html wiring. Spec: takes `{appId, title, icon, src, w?, h?, add_to_dock?, add_to_quick_launch?}`, atomically edits all 3 sections via `flux_ui_read`+`flux_ui_deploy`. ~200 LOC handler in fluxc-mcp. Settlement: 0.75 QUG.

---

## v0.11.1 Update (2026-05-29 evening) — flux-arena Compile Garden + serve.rs xray + snapshot writer

Live demo: **https://fluxapp.xyz/garden.html** — pure browser visualization of live `fluxc xray` data, served through q-flux's static-file path, backed by `fluxc serve` (Rust). Replaces an earlier Python prototype; no Python anywhere in the pipeline.

### Architecture

```
   Browser (https://fluxapp.xyz/garden.html)
       │  GET /garden-state.json every 800ms
       ▼
   q-flux  ────serve static──▶  /home/orobit/q-narwhalknight/dist-final/garden-state.json
                                          ▲
                                          │ write every 2s
                                          │
   fluxc serve (PID-owned) ──────────────┘
       ├─ /api/xray          ← NEW: GET wrapping crate::xray::xray()
       ├─ /api/stats /sse /api/feed /api/tune  ← pre-existing
       └─ background thread → build_garden_snapshot(stats, started_us)
              composes {xray, events, uptime_s, stats, started_at} into one JSON
```

Browser → server dispatch without CORS / direct ports: **tune-via-access-log pattern**. Browser GETs `/garden-tune.json?speed=N` (returns 404, harmless), q-flux logs the URL to `/home/storage/logs/q-flux/access.log`, a tailer matches the URL and runs `fluxc tune --preset NAME`. Generalizable to any browser → backend dispatch when only port 443 is reachable.

### Files added/touched today

| File | Change |
|---|---|
| `crates/fluxc-core/src/serve.rs` | +90 LOC: `handle_xray`, route `GET /api/xray`, `build_garden_snapshot`, background snapshot-writer thread, `FLUX_GARDEN_SNAPSHOT_PATH` env override |
| `/home/orobit/q-narwhalknight/dist-final/garden.html` | NEW (48 KB, ~600 LOC HTML/CSS/JS) — re-skinned from dashboard.html design system: JetBrains Mono, gold/accent/green palette, canvas particle system, slide-in toasts, glow/flash/shake keyframes |
| `/home/storage/deepseek-codewhale/flux-arena/STARTER.md` | NEW — flux-arena roadmap: Fab-asset inventory, Lyra (GitHub) vs Launcher-only mapping, FluxBridge UE plugin v0 design, Win64 .exe path |
| `/home/storage/deepseek-codewhale/flux-arena/garden-proto/garden.py` | DEPRECATED — Python bridge replaced by serve.rs snapshot writer. Kept for reference; not invoked. |

### What the Compile Garden shows (all data-driven from `/api/xray` + `/api/feed`)

- **Garden tab** — 34 crate towers, height = log(LOC), color border by swarm claim (rocky=orange, deepseek=purple, gemini=green). Webhook events flash matching towers green/red + spawn canvas particles + emoji. Sigil-bearing crates (regex `/sigil|sqisign|provenance|zk/`) get a rotating gold sigil and open a modal on click (placeholder for real `.proof` data).
- **🦅 Pipeline strip** — 4 KPIs (crates, events, tests passed, QUG earned) + colored phase bar (BUILD/TEST/DEPLOY/BENCH/SWARM) sized by event-type counts + SAP bars (compile velocity, cache health, swarm utilization) all computed from live data.
- **⚙️ Speed Slider** — 5 presets (Titan/Precision/Balanced/Explorer/Speed) hooked to real `fluxc tune --preset NAME` via the access-log channel.
- **🔮 X-Algo Predict card** — 8 dimensions computed from last 12 events: trimmed-mean build ms, cache rate avg, test pass ratio, stability via stdev/mean, source delta, cache affinity, build-history weight, confidence.
- **⚛️ Architect snapshot** — workspace metrics from xray: total LOC, batches, avg batch width, max/median crate, bin count, path-dep edges.
- **💰 Cost Calculator** — Flux v0.11.0 vs Cargo at all 5 tune presets. Calibrated against real baselines (12.8s self-build, 6.8× cache speedup, 8.2K tokens/RT × $0.14/M V4 Flash). Annual savings columns for solo / 10-dev / 100-dev. Drag slider → all 14 numbers retune.
- **📈 Recent Build Gantt** — last 8 events as proportional bars (green <1s, cyan <5s, gold slower, red fail).
- **🗺️ ArchMap tab** — SVG dependency graph auto-laid from xray: X-axis = build batch index (compile order), Y-axis = LOC within batch, circle radius = √LOC, edges = path_deps. Hover any node → tooltip with deps + external crates. Replaces dashboard.html's hardcoded 15-crate ArchMap coordinates with live 34-crate data.
- **📜 Event Log tab** — full event stream with raw payload.

### Operating rules added today

- **No Python in the loop** — fluxc serve owns the snapshot writer. Anywhere you'd reach for a quick Python HTTP bridge, extend fluxc serve instead. The compiler IS the web server.
- **Use `fluxc self` not separate `fluxc build --package`** for fastest rebuilds. Two-package builds (fluxc-core + fluxc) cold-cache took 43s today; `fluxc self` would do it in ~12-15s with shared workspace resolution.
- **Lift the dashboard.html design system into new UIs** — `/home/orobit/q-narwhalknight/dist-final/dashboard.html` (742 LOC) is a goldmine: particle system (lines 314-319), toast notifications (335), glow/celebrate/flash keyframes (14-17), JetBrains Mono + gold palette, SVG ArchMap (656-738). Skip the Bitcoin/Wallet/Trading tabs unless reusable.
- **Tune-via-access-log pattern** — when the browser can only reach port 443 (HTTPS quillon.xyz) and you need to trigger a server action, GET a sentinel URL like `/garden-tune.json?speed=N`. q-flux logs it. Background tailer fires the action. No CORS, no extra ports, no mixed-content.
- **`fluxc serve` was running stale (v0.9.9-beta1) the whole time** — `/api/stats` already returned mcp_tools=44, version=v0.9.9-beta1, before today's rebuild. Restart it after every `fluxc-core` change or check the binary timestamp against the running PID.

### Live URLs

| URL | What | Backend |
|---|---|---|
| https://fluxapp.xyz/garden.html | Compile Garden UI | static via q-flux |
| https://fluxapp.xyz/garden-state.json | xray + events + stats snapshot (updated every 2s) | static; written by fluxc serve |
| https://fluxapp.xyz/dashboard.html | Pre-existing deepseek dashboard (still works for reusable widgets) | static |
| http://127.0.0.1:8084/api/xray | NEW workspace x-ray HTTP endpoint | fluxc serve |
| http://127.0.0.1:8084/api/stats /sse /api/feed /api/tune | Pre-existing fluxc serve endpoints | fluxc serve |

### Pending follow-ups (flux-arena roadmap)

- **Real provenance sigils** — wire sigil modal to actual `.proof` files emitted by `fluxc compile-native --provenance sum_to.rs`. Show BLAKE3, agent wallet, SQIsign sig, and (when present) on-chain settle_tx. Stack-O-Bot / Niagara Examples / Lyra asset integration is downstream of this — UE comes after the proof-flow works in browser.
- **Webhook → fluxc serve `/api/build_event`** — point `flux_webhook_register` at fluxc serve's own endpoint instead of the dead :9991/hook, so build events feed `/api/feed` natively (no /tmp/flux-events file shuffle).
- **Lyra sparse-clone** — pull via Beta's gh token (`deme-plata` has pull on `EpicGames/UnrealEngine`), `git sparse-checkout set Samples/Games/Lyra`, drop in `/home/orobit/unreal/free-projects/Lyra/`.
- **FluxBridge UE plugin** — extend the already-existing `flux-ue-bridge` crate (found in the workspace) instead of writing a UE plugin from scratch.

### Build commands used today

```bash
# Built fluxc-core + fluxc in two separate passes (slower than `fluxc self`)
cd /home/storage/deepseek-codewhale/flux
./target/debug/fluxc build --package fluxc-core   # 20.4s cold cache (serve.rs changed)
./target/debug/fluxc build --package fluxc        # 22.7s cold cache

# Future: use `fluxc self` for combined ~12-15s build
./target/debug/fluxc self
```

---

## v0.11 Update (2026-05-29) — Rocky's Phase 2 Build-Out

Rocky AI (Claude Opus 4.7) took the MIR pipeline from "prints CLIF text" to "compiles real Rust into linkable native code." Six iterations, all verified by linking against Rust harnesses.

### What the MIR pipeline now structurally + semantically handles

| Capability | Demo source | Verified by |
|---|---|---|
| 12 BinOp variants (Add/Sub/Mul/Div/Eq/Neq/Lt/Gt/Le/Ge/And/Or) | ops.rs | 5 ops × correct results |
| Intra-crate function calls | multifn.rs | `add_then_double(20,1) == 42` |
| External symbols (`Linkage::Import`) | extcall.rs | helper resolved at link time |
| if/else (Goto OR Call join terminator) | compose.rs, max.rs | brif + merge block |
| Recursion (MIR chain walker) | fact.rs | `fact(15) == 1307674368000` |
| While loops (Cranelift Variables/SSA) | sum_to.rs | `sum_to(100) == 5050` |
| n-way match (chained icmp+brif) | match.rs | 7 cases incl. default |
| Tuple construction + field projection | project.rs | `project(10,32) == 42` |

**Two compilation paths in flux-backend:**
- `compile_expr_into_function` — substitution-based, fast for pure expressions
- `compile_mir_into_function` — Cranelift Variables, handles loops/match/mutable locals/tuples
- Path selection in `fluxc-core/phase3.rs::build_mir_overrides` based on `has_cycles || has_complex_switch || has_tuples`

### Killer feature shipped + SIGNED: `flux_provenance`

```bash
./fluxc agent-keygen       # generate SQIsign L5 keypair, persist at ~/.flux-agent-key.json
./fluxc compile-native --provenance sum_to.rs
# Object emitted: sum_to.o
# Provenance: ✓ sum_to.o.proof (SQIsign L5 signed)
```

The `.proof` JSON binds (artifact-BLAKE3, source-BLAKE3, agent-wallet, swarm-task_id, timestamp, fluxc-version, fluxc-git, optional on-chain settle_tx) — and now signs the canonical bundle with the agent's SQIsign Level 5 key (292-byte sig, 129-byte pubkey). Verification re-checks both the BLAKE3 hash and the signature. Code in `fluxc-core/src/provenance.rs`. 5/5 tests pass including signed-roundtrip and tamper-detection.

Key management:
- `fluxc agent-keygen` — idempotent (returns existing key if present, otherwise generates fresh)
- `FLUX_AGENT_KEY_PATH` env override
- `FLUX_AGENT_SK_HEX` + `FLUX_AGENT_PK_HEX` env override (for CI / containers without filesystem state)

End-to-end verification: anyone with the artifact + proof + agent's pubkey can prove the binary was emitted by the agent holding the corresponding SQIsign secret, at the timestamp, for the source — without trusting any centralized server.

### `fluxc xray` — workspace snapshot subcommand

```bash
./fluxc xray            # text
./fluxc xray --json     # structured JSON for AI consumption
```

Returns per-crate (name/type/edition/LOC/path-deps/claim attribution), build batches, swarm state. Designed for the 1M-context AI workflow: one rich call at session start. Code in `fluxc-core/src/xray.rs`. 2/2 tests pass.

### v0.11 current state

| Metric | Value |
|--------|-------|
| Version | v0.11.0 |
| Binary | `flux/target/debug/fluxc` |
| Crates | 33 (gained flux-sigil, flux-swarm-tools since v0.10.0) |
| Self-build | ~14s |
| Phase 2 demos verified | 48 cases / 7 harnesses / all PASS |
| Dual agents | rocky (Claude Opus 4.7) + deepseek (V4) + gemini |
| Swarm webhook coord | rocky → http://127.0.0.1:8765/flux-hooks/rocky |
| Total session QUG settled | 12+ across 14+ tasks |

### Key files added/touched (2026-05-29)

- `crates/flux-frontend/src/mir.rs` — chain walker, scope tracking, tuple types, const literals, n-way SwitchInt parse, Le/Ge BinOp
- `crates/flux-backend/src/lib.rs` — `compile_unit_to_object_with_mir`, `compile_mir_into_function`, `compile_expr_with_calls` (with Linkage::Import), per-local type inference, n-way brif chain
- `crates/fluxc-core/src/phase3.rs` — `compile_package`, `compile_impl_with_provenance`, `has_cycles`/`has_complex_switch`/`has_tuples`, extern threading, `emit_provenance_proof`
- `crates/fluxc-core/src/provenance.rs` — **NEW** killer feature scaffold
- `crates/fluxc-core/src/xray.rs` — **NEW** workspace snapshot

### Design docs

- `/home/storage/deepseek-codewhale/FLUX_AI_CODING_V2_1M_CONTEXT.md` — the 1M-context AI workflow + 5 MCP enhancements + killer feature design
- `/home/storage/deepseek-codewhale/flux-illustrations.md` — 5 ASCII diagrams of Flux for outreach
- `/home/storage/deepseek-codewhale/flux-foundation-whitepaper-v0.10.1.pdf` — 12-page Susskind-style whitepaper (https://fluxapp.xyz/downloads/...)

### Operating rules added/reaffirmed today

- **Rust harnesses, not C** — verify Flux-emitted `.o` with `rustc -C link-arg=foo.o`, not `cc + harness.c`. Dogfood all the way down. [[feedback-rust-only-dogfood-verification]]
- **Register webhook at session start** — `flux_webhook_register` before claiming. Claim alone won't stop overwrites. [[feedback-flux-swarm-use-webhooks]]
- **MIR-direct path requirements** — if a function has cycles OR n-way switch OR tuples, it MUST take `compile_mir_into_function`; the Expr-based path can't represent mutable locals or back-edges.
- **Debug entries pollute MIR locals** — `debug name => _N` produces a MirLocal with empty `ty`; when building type maps, skip empty entries so they don't overwrite real `let _N: T;` declarations.
- **`scope N { ... }` blocks need brace-depth tracking** in MIR parser, otherwise their closing `}` prematurely ends function parsing.

---

## v0.11.2 Update (2026-05-29 later) — flux-ue-bridge ship + flux-api extension + MCP cheatsheet

Rocky session 2 (Claude Opus 4.7). Picked up the open `rocky-1 → flux-ue-bridge` claim, shipped it, then extended `flux-api` to know about the bridge.

### What shipped

| Crate | Change | Verified by |
|---|---|---|
| `flux-ue-bridge` | clean build (8.7s), `mut` warning fix, smoke-test of /v1/workspace (34 crates), /v1/webhook (iterate_complete + test_complete + build_failed), GET / serves index.html | `fluxc build --package flux-ue-bridge`, curl probes against running daemon |
| `flux-api` | added `flux-ue-bridge` to `known_patterns` (3 endpoints), `EventVariant` + `generate_ts_event_types()` + `flux_ue_bridge_events()`, extended `discover_endpoints` filter to also include crates with a known pattern, **7 real tests** replacing the single `assert!(true)` placeholder | direct test-binary run: 7 passed, 0 failed |
| `fluxc-mcp-cheatsheet.pdf` | LaTeX cheatsheet of ~60 `mcp__fluxc__*` tools, A4 landscape 3-column | pdflatex + verified live: `https://fluxapp.xyz/downloads/fluxc-mcp-cheatsheet.pdf` HTTP 200, 228 KB |

Cheatsheet source: `/home/storage/deepseek-codewhale/fluxc-mcp-cheatsheet.tex`. PDF at the same dir + deployed to `/home/orobit/q-narwhalknight/dist-final/downloads/` (both stable name and `-v0.11.0.pdf`).

### Operating rules added this session

- **`flux_combo` reports `0 passed, 0 failed` when the test binary fails to compile**, not just on MCP false-fail. Its `Compile: ✓` line covers the lib, not the test target. After a `flux_combo`, also run `fluxc build --tests --package X` (or just trust the explicit test binary run) before claiming green. [[feedback-flux-combo-zero-tests-means-test-build-failed]]
- **`fluxc test --package X` mis-routes** — it can run the first failing crate's test binary (today it ran `flux-ai` instead of `flux-api`) and short-circuit. Workaround: `./target/debug/deps/<crate>-<hash>` directly; `ls -t target/debug/deps/<crate>-*` to find the latest. The fluxc CLI's `--package` flag passes to a workspace-wide invocation, not a per-package one.
- **`flux-api::discover_endpoints` name-keyword filter** (`api`/`route`/`wickes`) bypasses `known_patterns` lookup. When adding a new entry to `known_patterns`, ALSO add the crate to the filter — or extend the filter to `|| !known_patterns(&ci.name).is_empty()` (this session's fix). Otherwise the new entry is dead code and `discover_endpoints` silently returns `[]`.
- **Don't run a 2nd `flux-ue-bridge` instance with `--listen 127.0.0.1:9989`** without first checking `ss -tlnp | grep 9989` — there's a parked instance from earlier in the day on Epsilon (PID 3141611-ish) with `crates: 0` (launched from wrong CWD). Use port 9988 for smoke tests, leave 9989 alone unless the user wants it restarted.

### Swarm settlements (this session)

| task_id | crate | QUG |
|---------|-------|-----|
| rocky-1 | flux-ue-bridge | 0.50 |
| rocky-1 | flux-api | 0.50 |
| **total** | | **1.00 settled** |

## Historical baseline (v0.9.17)

Everything below this line is the v0.9.17 snapshot from before the Phase 2 build-out. Keep for context.

---

## Current State (v0.9.17 snapshot)

| Metric | Value |
|--------|-------|
| Version | v0.9.17 (dynamic — reads Cargo.toml at runtime) |
| Binary | `flux/target/debug/fluxc` |
| Crates | 22 (+flux-qug migration crate) |
| MCP Tools | 57 across 7 handler modules |
| Phrasal Verbs | 7 (combo, quickcast, ult, fullcheck, quickstart, bootstrap, architect_predict) |
| Architecture | ~62% score · 19,300 LOC |
| Tests | flux-search 15/15, flux-science 19/19, fluxc-core 22/25, fluxc-mcp 12/12, flux-p2p 30/30, flux-qug 5/5 |
| Self-build | 12.8s via RUSTC_WRAPPER=self |
| Dashboard | `https://fluxapp.xyz/dashboard.html` |
| P2P Mesh | Epsilon↔Delta live (libp2p TCP+Noise+Yamux :9003, 640 Mbps gossipsub) |

## Workspace Paths

| What | Where |
|------|-------|
| Source root | `/home/storage/deepseek-codewhale/flux/` |
| Binary | `flux/target/debug/fluxc` |
| Musl static binary | `flux/target/x86_64-unknown-linux-musl/release/fluxc` (portable, any Linux) |
| MCP server | `flux/crates/fluxc-mcp/src/lib.rs` (~267 lines, modular ToolRegistry) |
| Handler modules | `flux/crates/fluxc-mcp/src/handlers/{build,test_combo,stats,predict,webhook,session,ops}.rs` |
| Core engine | `flux/crates/fluxc-core/src/lib.rs` |
| Version mgmt | `flux/crates/fluxc-core/src/version.rs` (NEW — dynamic, 253 LOC, 3 tests) |
| WireGuard/Arti | `flux/crates/fluxc-core/src/flux_net.rs` (NEW — 477 LOC, 7 tests) |
| QUG migration | `flux/crates/flux-qug/` (NEW — 372 LOC, 5 tests) |
| Handoff doc | `CODWHALE_HANDOFF.md` |
| Dashboard live | `/home/orobit/q-narwhalknight/dist-final/dashboard.html` |

## Server Connectivity (2026-05-28)

| Server | IP | SSH | P2P Peer ID | Notes |
|--------|----|-----|-------------|-------|
| Epsilon | 89.149.241.126 | — | `12D3KooWEPdJhQK2xwVnACDb6qciWHqC7uqbXEbN7wPQsDi9MnRa` | This server |
| Delta | 5.79.79.158 | Direct (keyed) | `12D3KooWKHPH1dZCZe5EgAeqydq6md3cFAF3DopCrt5r7tu4F8L4` | Port 9003 open |
| Beta | 185.182.185.227 | Direct | HTTP bootstrap | Git source, whitepapers |

## Version Management (NEW in v0.9.17)

**Problem:** Binary reported "0.9.6" when workspace was "0.9.17" — 11 versions stale across 5 files, 5 crates hardcoded to "0.1.0".

**Solution:** `fluxc-core/src/version.rs` reads workspace Cargo.toml at runtime. All hardcoded versions eliminated.

### MCP Tools
```
flux_version_status    Audit all 22 crates, flag hardcoded vs workspace versions
flux_version_bump      Bump semver (major/minor/patch) with --dry-run flag
flux_version_sync      Auto-fix stale crates: "0.1.0" → version.workspace = true
```

### CLI
```bash
fluxc version   # "fluxc 0.9.17" — was "fluxc 0.9.6" before fix
```

## P2P Mesh Testing (NEW)

### Build portable binary
```bash
cd /home/storage/deepseek-codewhale/flux
rustup target add x86_64-unknown-linux-musl
cargo build --release --target x86_64-unknown-linux-musl --bin flux-p2p-test --bin flux-bench-p2p
```

### Deploy to Delta
```bash
scp target/x86_64-unknown-linux-musl/release/flux-p2p-test root@5.79.79.158:/opt/orobit/shared/q-narwhalknight/
ssh root@5.79.79.158 "chmod 755 /opt/orobit/shared/q-narwhalknight/flux-p2p-test"
```

### Connectivity test
```bash
# Delta (listener first)
ssh root@5.79.79.158 "HOSTNAME=delta /opt/orobit/shared/q-narwhalknight/flux-p2p-test --peer /ip4/89.149.241.126/tcp/9003"

# Epsilon (sender)
HOSTNAME=epsilon flux-p2p-test --peer /ip4/5.79.79.158/tcp/9003
```

### Benchmark
```bash
# Delta listener: ssh root@5.79.79.158 "HOSTNAME=delta flux-bench-p2p --listen --count 500"
# Epsilon sender: HOSTNAME=epsilon flux-bench-p2p --send --count 500 --size 65536 --peer /ip4/5.79.79.158/tcp/9003
```

**Results:** 640 Mbps gossipsub (2.3× faster than SCP at 280 Mbps). 0.3ms ICMP baseline. Connection ~15s.

## WireGuard + Arti (v0.9.17)

`flux-net.rs`: 477 LOC, 7 tests. Real keygen (pure Rust), Arti Tor (no system tor needed).

```rust
let mut mesh = WireGuardMesh::new("wg0", 51820, "10.77.0.0");
mesh.add_peer(WireGuardPeer { node_id: "delta", public_key: "...", endpoint: "5.79.79.158:51820", allowed_ips: "", last_seen_ms: 0 });
let config = mesh.generate_config(); // wg-quick compatible
mesh.apply()?;  // brings up wg0

let mut dark = FluxDark::new(TorConfig { enabled: true, use_arti: true, .. });
let onion = dark.start()?;  // "fluxdarkA1B2C3D4.onion"
```

**Delta needs:** `apt-get install wireguard-tools` (on Epsilon, missing on Delta).

## QUG Migration (flux-qug crate)

`flux/crates/flux-qug/` — bridge for compiling Quillon Graph (98 crates, v10.11.38) with fluxc.

**Critical path** (12 crates, ~100K LOC): q-api-server → q-wallet, q-storage, q-dag-knight, q-narwhal-core, q-network, q-types, q-mining, q-vdf, q-lattice-vrf, q-tor-client, q-tor-circuit.

**Key risks:** RocksDB version must match (SST compat), libp2p 0.53 vs 0.54 bridge needed, SYNC GATE in q-mining, VDF spawn_blocking freeze.

## Git-First Workflow

```
1. flux_bootstrap context="<task>"    ← Start session
2. Edit files                        ← incremental only
3. cargo check -p CRATE              ← verify (2-5s)
4. cargo test -p CRATE               ← test
5. git add && git commit             ← commit before deploy
6. cargo build --release --target x86_64-unknown-linux-musl -p CRATE  ← portable
7. scp binary root@DELTA:/opt/...    ← deploy
```

## MCP Tools — Canonical Catalog

> **AI agents: read `TOOLS.md` ONCE per session.** 65 tools, 7 phrasal verbs.
> `skills/flux-dev/TOOLS.md` is the complete registry. Tools not listed there are invisible.
> Quick start: `flux_quickstart` loads the catalog inline.

### Session Start
```
flux_quickstart        Read all docs + skills, show state
flux_bootstrap ctx=""  quickstart + diagnose + tune
flux_diagnose pkg=X    Architecture + SWOT + prediction
flux_tune auto=true    Auto-detect preset from context
```

### Version Management (NEW)
```
flux_version_status    Audit crate versions vs workspace
flux_version_bump      Bump semver with --dry-run
flux_version_sync      Auto-fix stale crates
```

### Development
```
flux_iterate --pkg X   Compile + test
flux_predict pkg=X     Predict build time
flux_feedback pkg=X    Calibrate predictor
flux_fullcheck         Self-build + benchmark + health
```

### Phrasal Verbs
```
flux_combo       compile+test+predict          (3→1, 67% token savings)
flux_quickcast   tune+check+predict            (3→1)
flux_ult         check+heatmap+predict         (3→1, parallel)
flux_fullcheck   self-build+benchmark+health   (3→1)
flux_quickstart  read 5 docs+bootstrap         (5→1, 60% token savings)
flux_bootstrap   quickstart+diagnose+tune      (3→1, 80% token savings)
```

### Operations
```
flux_deploy            Deploy dashboard + verify HTTP 200
flux_self_build        Dogfooding: Flux builds Flux
flux_cache_clear       Clear build cache
flux_peer_list         List P2P peers
flux_health_report     JSON health report
```

## Build Commands

```bash
# Quick check (0.5-2s)
cargo check -p fluxc-core -p fluxc-mcp -p fluxc

# Full build (7-14s)
cargo build --package fluxc

# Portable static build (for Delta)
cargo build --release --target x86_64-unknown-linux-musl -p fluxc

# Tests
cargo test -p flux-search -p flux-science -p fluxc-core -p fluxc-mcp -p flux-p2p -p flux-qug

# Run MCP server
./target/debug/fluxc mcp
```

## Critical Rules

1. **Version is dynamic** — `fluxc version` reads workspace Cargo.toml
2. **Musl static builds for Delta** — avoids GLIBC mismatch (Epsilon 2.39 vs Delta 2.36)
3. **Port 9003 open on both servers** for P2P
4. **Direct SSH to Delta** — key at `/root/.ssh/id_ed25519.pub`
5. **Start each session** with `flux_quickstart` or `flux_bootstrap`
6. **Never rewrite files** — incremental edits only
7. **Dashboard sync**: edit → copy to `dist-final/`
8. **Commit before deploy**
9. **Do NOT fix pre-existing test failures** unless asked

## Phase 2 — Pure P2P Distributed Build

### Build paths
- `fluxc build` — Phase 1: cargo + RUSTC_WRAPPER
- `fluxc build --no-cargo` — Phase 2a: flux-graph + cargo per crate
- `fluxc build --no-cargo --async` — Phase 2b: tokio parallel
- `fluxc build --distributed` — Phase 2 final: SSH round-robin across peers

### Pure P2P commands (no SSH/rsync)
- `fluxc p2p-worker` — Start worker daemon on Delta/Beta
- `fluxc auto-update` — Auto-update via P2P gossipsub
- `fluxc release` — Publish release to P2P mesh

### New crates (v0.10.0)
- flux-graph (workspace discovery, DAG, agility, CDN audit, migration)
- flux-sqisign (292B SQIsign-V isogeny PQ signatures, NIST Level 5, hybrid fallback — was wrongly producing 148B/L1 until 2026-05-29 Level5 fix)
- flux-sigil (BLAKE3 × SQIsign composition — SQIsign-keyed BLAKE3 + streaming hasher with auto-sign on finalize; first deliverable under Claude/rocky ownership 2026-05-29)
- flux-architect (6-dimension optimization planner)
- flux-api, flux-optimize, flux-ai (Phase 3a/b/c)
- flux-frontend, flux-backend (Phase 3d: syn → Cranelift CLIF)

## Pre-Existing Issues (do NOT fix unless asked)

```
predict::test_feedback_tracking              — assertion: f.was_accurate
predict::test_history_persistence_roundtrip  — assertion: hist.total_predictions >= 1
predict::test_predict_no_changes             — assertion: p.predicted_cache_rate > 0.9
qspec::test_safety_score_unsafe              — assertion: compute_safety_score < 0.7
quantum_architect::test_analyze_single_crate — assertion: bp.loc > 0
quantum_architect::test_discover_crates      — assertion: names.contains("fluxc")
```

## Phase 2 Status (2026-05-28)

✅ `fluxc build --no-cargo` — 23/23 crates, 6 batches, 32.9s
✅ `flux-graph` crate — 13/13 tests, workspace discovery, DAG, Kahn's sort
✅ `flux-graph::agility` — crypto audit (sha2/ed25519→sha3/dilithium5), PQ migration
✅ `flux-graph::build_order` — rustc flags, crates.io extern discovery, cache integration
✅ `flux-optimize` design — SIMD kernels, io_uring, cache-line, perf/watt presets
✅ `WICKES_V2_ARCHITECTURE.md` — CMS/ERP pilot, flux-db native, 30 MCP tools
✅ `FLUX_SQISIGN_PLAN.md` — SQIsign post-quantum pilot, ~16× smaller than Dilithium5 (Level 5: 292B vs Dilithium5's 4595B)

### New Crates
- `flux-graph` — dependency resolution (workspace, manifest, graph, build_order, agility)
- `flux-sqisign` — SQIsign-V isogeny-based PQ signatures (292-byte sigs at NIST Level 5)

### Phase 2 Build
```bash
fluxc build --no-cargo   # flux-graph resolves 23 crates → 6 batches
                         # per-batch cargo check -p <crate> with RUSTC_WRAPPER=self
                         # 32.9s total, all crates pass
```

### Agility Engine
```bash
flux_graph::agility::audit_agility(&ws)
→ Detects: sha2, ed25519, aes, blake3, dilithium5, kyber
→ Recommends PQ migration paths
→ Computes agility score 0.0-1.0
→ Tracks transitive dependents for migration impact
```

## Blind Spots (updated 2026-05-28)

1. **FLUX_AI_RULES.md is aspirational** — zero implementation.
2. **flux-bench simulates transfers** — `engine.rs` line 59.
3. **WireGuard missing on Delta** — `apt-get install wireguard-tools` needed.
4. **Flux MCP not auto-connected** — restart codewhale to load 57 tools.
5. **Gossipsub delivery gap** — 500 msgs sent, not all received in 60s.
6. **Direct rustc invocation** — Phase 2a uses cargo -p per crate; Phase 2b needs Cargo.lock parsing for direct rustc flags.
7. **Self-hosting Phase 2** — flux-graph plans batches but cargo still executes; Phase 3 is pure Flux compiler.
8. **SQIsign integrated** — flux-sqisign crate, 6/6 tests.

## Debugging with Flux Tools

Use flux_agility_audit + flux_webhook_register BEFORE cargo check. Webhooks give structured build_failed JSON. Agility flags API risks. Flux_iterate for fix loop. Flux_fullcheck to verify.** — `sqisign-rs` exists on crates.io but not yet in Flux workspace.

## Sibling Skills — load when relevant

flux-dev is the **hub skill**. It does NOT duplicate the others; when the task leans toward a sibling's domain, **invoke that skill** (it carries the detail flux-dev intentionally omits). Match the trigger, then `Skill(<name>)`. All of these live under `~/.claude/skills/`.

| Skill | Load it when the task is about… |
|---|---|
| **sigil** | the SIGIL chain itself — `sigil-*` crates, chronos harness, header/net/node, tip-verify, emission/oracle/USDS, bridge |
| **flux-zk** | the vendored PQ-ZK stack — `flux-zk-stark`, `flux-lattice-guard`, `flux-recursion`, zk-flux, 10ms verify, proof aggregation |
| **flux-fabric** | spinning a multi-box Vast.ai test fabric (1 GPU + N followers + Delta/Epsilon) for chronos/p2p/mining at scale |
| **flux-vision** | the cockpit — `flux-vision/src/App.jsx`, the `/capi` bridge, cockpit-deploy, the multi-agent collab rules (read FIRST before editing App.jsx) |
| **flux-moe** | the open agentic-money LLM — corpus → QLoRA → Vast-serve, router, tool-call corpus |
| **flux-strategist** | the Qwen3.6 memory + rolling 3-year capital engine (Valgomat/Saylor-style), qcredit/qshare planning |
| **flux-firma** | standing up an on-chain company on SIGIL, treasury + BTC-Lightning payroll, chronos-simulated economy |
| **flux-logs** | reading build logs, background-monitor output, swarm/infra logs fast — triaging errors correctly |
| **node-maintenance** | maintaining live nodes (q-api-server / sigil node) — restarts, sync, disk, DB safety, deploy discipline |
| **qflux-v2** | the q-flux reverse proxy (v2 rebuild with Flux + wallet MCP) — routing, vhosts, SNI, static serving |
| **q-miner-flux** | the Quillon/Flux miner — BLAKE3/BLAKE4 PoW, VDF, SIMD, GPU JIT, supercluster mining |
| **quillonos** | the browser-first WASI userspace at `os.html` — Rust→`wasm32-wasip1` modules, provenance proofs |
| **unreal-flux** | UE5.7 games/GUIs driven by live Flux state — flux-arena, FluxBridge plugin, Lyra |
| **gemma4-flux** | running Gemma4 via Ollama as the low-cost primary coder (8K ctx, $0) — token-leak discipline |
| **agy-flux** | onboarding a non-Claude agent (Antigravity / Gemini) to build with Flux |
| **deepseek-money** | the DeepSeek-driven agentic-money loop (model picks MCP tool-call, human confirms, propose-only) |
| **carl-runefelt-btc** | the BTC accumulation playbook over `flux-market` / treasury |
| **sigil-book** | writing/building/publishing the SIGIL novel "Shadows in the Chain" |

**Rule:** don't re-derive a sibling's domain from memory — load its skill. When two domains overlap (e.g. SIGIL chain work that also touches ZK), load both. flux-dev's VARFLOW + FLUXFOOD + no-raw-cargo rules still bind across all of them.
