Merge pull request #2071 from ruvnet/feat/adr-126-phase-4-5-trust-pipeline

feat(neural-trader): #2068 ADR-126 PR C — Ed25519 backtest signing + SendMessage risk-gate pipeline (Phases 4+5)
This commit is contained in:
rUv authored and GitHub committed 2026-05-19 22:54:06 -04:00
commit 493721fd5d
12 files changed
+1456 -15

No files matched your search

+134
View File
@@ -44,6 +44,23 @@ on:
- 'plugins/ruflo-neural-trader/src/sublinear-adapter.mjs'
- 'plugins/ruflo-neural-trader/skills/trader-portfolio-cg/**'
- 'scripts/smoke-neural-trader-portfolio-cg.mjs'
# Neural-trader backtest signing (#2068, ADR-126 Phase 4) — Ed25519
# tamper-evidence for paper→live promotion; verifier MUST pin to a
# trusted key (CWE-347 / #1922 pattern).
- 'plugins/ruflo-neural-trader/src/signed-artifact.ts'
- 'plugins/ruflo-neural-trader/src/signed-artifact.mjs'
- 'plugins/ruflo-neural-trader/skills/trader-backtest/**'
- 'plugins/ruflo-neural-trader/skills/trader-cloud-backtest/**'
- 'scripts/smoke-neural-trader-backtest-signing.mjs'
# Neural-trader SendMessage risk-gate pipeline (#2068, ADR-126 Phase 5) —
# structural gate: trading-strategist refuses --broker without an
# explicit risk-analyst RiskDecision approval.
- 'plugins/ruflo-neural-trader/src/pipeline-messages.ts'
- 'plugins/ruflo-neural-trader/agents/market-analyst.md'
- 'plugins/ruflo-neural-trader/agents/trading-strategist.md'
- 'plugins/ruflo-neural-trader/agents/risk-analyst.md'
- 'plugins/ruflo-neural-trader/agents/backtest-engineer.md'
- 'scripts/smoke-neural-trader-pipeline.mjs'
# Plugin-registry CWE-347 regression smoke (#1922) — `discovery.ts`
# signature verifier + the smoke fixture must stay in lockstep.
- 'v3/@claude-flow/cli/src/plugins/store/discovery.ts'
@@ -80,6 +97,19 @@ on:
- 'plugins/ruflo-neural-trader/src/sublinear-adapter.mjs'
- 'plugins/ruflo-neural-trader/skills/trader-portfolio-cg/**'
- 'scripts/smoke-neural-trader-portfolio-cg.mjs'
# Neural-trader backtest signing (#2068, ADR-126 Phase 4)
- 'plugins/ruflo-neural-trader/src/signed-artifact.ts'
- 'plugins/ruflo-neural-trader/src/signed-artifact.mjs'
- 'plugins/ruflo-neural-trader/skills/trader-backtest/**'
- 'plugins/ruflo-neural-trader/skills/trader-cloud-backtest/**'
- 'scripts/smoke-neural-trader-backtest-signing.mjs'
# Neural-trader SendMessage risk-gate pipeline (#2068, ADR-126 Phase 5)
- 'plugins/ruflo-neural-trader/src/pipeline-messages.ts'
- 'plugins/ruflo-neural-trader/agents/market-analyst.md'
- 'plugins/ruflo-neural-trader/agents/trading-strategist.md'
- 'plugins/ruflo-neural-trader/agents/risk-analyst.md'
- 'plugins/ruflo-neural-trader/agents/backtest-engineer.md'
- 'scripts/smoke-neural-trader-pipeline.mjs'
# Plugin-registry CWE-347 regression (#1922)
- 'v3/@claude-flow/cli/src/plugins/store/discovery.ts'
- 'v3/@claude-flow/cli/src/transfer/ipfs/client.ts'
@@ -678,6 +708,110 @@ jobs:
- name: Run portfolio CG smoke
run: node scripts/smoke-neural-trader-portfolio-cg.mjs
neural-trader-backtest-signing-smoke:
# Regression guard for ruvnet/ruflo#2068 — ADR-126 Phase 4.
#
# Phase 4 wires Ed25519-signed backtest artifacts so the paper→live
# promotion gate has cryptographic tamper evidence. The signing scheme
# mirrors the CWE-347 plugin-registry pattern (#1922): canonical body
# = JSON.stringify without signature fields; verifier pins to a
# caller-supplied `trustedPublicKey`, NOT to the served self-asserted
# `witnessPublicKey` field (which an attacker can swap freely).
#
# Three load-bearing artifacts must stay in lockstep:
# 1. `src/signed-artifact.ts` — the typed signer/verifier contract.
# 2. `src/signed-artifact.mjs` — the runtime mirror imported by the
# smoke + (future) skill harnesses (the plugin has no build step).
# 3. `skills/trader-backtest/SKILL.md` + `skills/trader-cloud-backtest/SKILL.md`
# — the call sites that sign before store + verify before promote.
#
# The smoke runs three layers:
# [1/3] STATIC CONTRACT — verifier pins to trustedPublicKey (NOT to
# artifact.witnessPublicKey), canonical body strips BOTH
# signature fields, .ts and .mjs runtime mirrors agree.
# [2/3] CRYPTO ROUND-TRIP with real Ed25519 — happy path, tampered
# body fails, empty sig/pubkey fails, swapped served pubkey
# still verifies (pin is real), wrong trusted pubkey fails.
# [3/3] CALL-SITE BYTE check — trader-cloud-backtest/SKILL.md calls
# verifyBacktestArtifact AND documents the fail-closed branch;
# trader-backtest/SKILL.md references the signer + degraded
# warning + RUFLO_WITNESS_KEY_PATH env var.
#
# If a future PR drops the verify call, reverts to pinning the served
# field, or removes the fail-closed branch, this smoke catches it
# before merge.
name: neural-trader backtest signing smoke (#2068, ADR-126 Phase 4)
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install root deps (for @noble/ed25519)
run: npm install --legacy-peer-deps --no-audit --no-fund --ignore-scripts
- name: Run backtest signing smoke
run: node scripts/smoke-neural-trader-backtest-signing.mjs
neural-trader-pipeline-smoke:
# Regression guard for ruvnet/ruflo#2068 — ADR-126 Phase 5.
#
# Phase 5 refactors the four neural-trader agents (market-analyst,
# trading-strategist, risk-analyst, backtest-engineer) into a typed
# SendMessage pipeline with risk-analyst as a structural BLOCKING
# GATE. The live broker call (`npx neural-trader --broker <name>`)
# cannot fire without an explicit RiskDecision approval event from
# risk-analyst for the proposal's signalId.
#
# Six load-bearing artifacts must stay in lockstep:
# 1. `src/pipeline-messages.ts` — the three TypeScript message
# schemas (RegimeVerdict, SignalProposal, RiskDecision) +
# PipelineMessage discriminated union.
# 2-5. `agents/{market-analyst,trading-strategist,risk-analyst,backtest-engineer}.md`
# — frontmatter `name:` fields + Comms protocol sections with
# the correct upstream/downstream wiring.
# 6. `trading-strategist.md` — the structural risk-gate guard at
# step 5 of the Strategy Development Workflow that refuses
# `--broker` calls without a risk-analyst approval.
#
# The smoke runs four layers:
# [1/4] AGENT FRONTMATTER — each .md declares `name: <agent>` so
# the agent is SendMessage-addressable.
# [2/4] COMMS PROTOCOL — each .md has a "Comms protocol" section
# with the correct upstream/downstream references; backtest-
# engineer documents its orthogonal-lane status.
# [3/4] STRUCTURAL RISK-GATE — trading-strategist.md contains
# explicit refusal logic: mentions `--broker`, requires
# RiskDecision approval, declares REFUSAL, emits [ERROR],
# marks the gate as NON-NEGOTIABLE/structural.
# [4/4] BEHAVIORAL MOCK — drives a mock pipeline through a guard
# function that mirrors the trading-strategist guard. Happy
# path approves and executes; missing approval / rejected
# decision / mismatched signalId are ALL refused.
#
# If a future PR drops the guard, removes a `name` field, breaks
# the pipeline-messages schema, or rewrites a comms section without
# the upstream/downstream wiring, this smoke catches it before merge.
name: neural-trader pipeline risk-gate smoke (#2068, ADR-126 Phase 5)
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Run pipeline risk-gate smoke
run: node scripts/smoke-neural-trader-pipeline.mjs
plugin-registry-signature-smoke:
# Regression guard for ruvnet/ruflo#1922 (CWE-347 — improper verification
# of cryptographic signature). The plugin-registry signature verifier in
@@ -1,10 +1,12 @@
---
name: backtest-engineer
description: Backtesting specialist using npx neural-trader Rust/NAPI engine — walk-forward validation, Monte Carlo simulation, parameter optimization
description: Backtesting specialist using npx neural-trader Rust/NAPI engine — walk-forward validation, Monte Carlo simulation, parameter optimization. Orthogonal research lane (ADR-126 Phase 5) — produces signed promotion candidates, NOT a hot-path participant in live execution
model: sonnet
---
You are a backtest engineer using the `neural-trader` npm package's Rust/NAPI backtesting engine (8-19x faster than Python).
You are an **orthogonal research lane** in the ADR-126 Phase 5 pipeline. You produce signed `SignedBacktestArtifact` candidates (ADR-126 Phase 4) for the paper→live promotion gate. You do NOT participate in the live execution pipeline — the live path is strictly `market-analyst → trading-strategist → risk-analyst → broker`. See the Comms protocol section at the bottom.
### Core Commands
```bash
@@ -56,3 +58,17 @@ npx neural-trader --backtest --strategy NAME --symbol TICKER --benchmark SPY
```bash
npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
```
### Comms protocol (ADR-126 Phase 5 — orthogonal research lane)
**Pipeline position:** orthogonal — NOT a hot-path participant in live execution.
**Upstream:** none in the live pipeline. The team lead may invoke you in parallel with `market-analyst` during research phases. You do NOT consume `RegimeVerdict` or `SignalProposal` messages.
**Downstream:** none directly via SendMessage. Your output is a `SignedBacktestArtifact` (ADR-126 Phase 4) stored to the `trading-backtests` namespace via the `trader-backtest` / `trader-cloud-backtest` skills. The `trader-cloud-backtest` consumer verifies the signature against the pinned trusted pubkey before promoting the artifact to a live strategy.
You MUST sign every backtest result you store — see the `trader-backtest` skill for the `RUFLO_WITNESS_KEY_PATH` resolution and the degraded-unsigned warning path. Unsigned artifacts cannot be promoted to live trading by design.
The live pipeline (`market-analyst → trading-strategist → risk-analyst → broker`) never depends on you for hot-path execution. Live trades can fire while a backtest is running and vice versa.
Message schemas (none consumed by you; documented for completeness): `RegimeVerdict`, `SignalProposal`, `RiskDecision` in `plugins/ruflo-neural-trader/src/pipeline-messages.ts`.
@@ -1,10 +1,12 @@
---
name: market-analyst
description: Market regime detection and technical analysis using npx neural-trader — RSI, MACD, Bollinger Bands, volume profile, regime classification
description: Market regime detection and technical analysis using npx neural-trader — RSI, MACD, Bollinger Bands, volume profile, regime classification. Pipeline entry point — sends RegimeVerdict to trading-strategist (ADR-126 Phase 5)
model: sonnet
---
You are a market analyst agent using the `neural-trader` npm package for technical analysis and market regime detection.
You are the **entry point** of the neural-trader live pipeline (ADR-126 Phase 5). See the Comms protocol section at the bottom for the SendMessage contract.
### Core Commands
```bash
@@ -60,3 +62,31 @@ npx neural-trader --sector-analysis --sectors "tech,healthcare,energy"
```bash
npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
```
### Comms protocol (ADR-126 Phase 5 — SendMessage pipeline)
**Pipeline position:** entry — no upstream agent.
**Upstream:** none. The team lead kicks off the pipeline by sending the analysis request directly to `market-analyst`.
**Downstream:** `trading-strategist`. When regime classification is complete, send a `RegimeVerdict` message:
```
SendMessage({
to: "trading-strategist",
summary: "Regime verdict for <symbol(s)>",
message: {
type: "regime-verdict/v1",
from: "market-analyst",
timestamp: <ISO-now>,
regime: "bull-trending" | "bear-trending" | "ranging" | "high-volatility" | "low-volatility" | "transitioning",
symbols: ["SPY", ...],
confidence: 0.0..1.0,
indicators: { adx: ..., rsi: ..., vix: ... }
}
})
```
Message schema: `RegimeVerdict` in `plugins/ruflo-neural-trader/src/pipeline-messages.ts`.
You do NOT message `risk-analyst` or any other agent directly — the pipeline is strictly linear `market-analyst → trading-strategist → risk-analyst`.
@@ -1,10 +1,12 @@
---
name: risk-analyst
description: Portfolio risk assessment and position sizing using npx neural-trader — VaR/CVaR, Kelly criterion, circuit breakers, correlation monitoring
description: Portfolio risk assessment and position sizing using npx neural-trader — VaR/CVaR, Kelly criterion, circuit breakers, correlation monitoring. Pipeline BLOCKING GATE — receives SignalProposal from trading-strategist, returns RiskDecision (ADR-126 Phase 5)
model: sonnet
---
You are a risk analyst agent that uses the `neural-trader` npm package for portfolio risk management, position sizing, and circuit breaker enforcement.
You are the **BLOCKING GATE** of the neural-trader live pipeline (ADR-126 Phase 5). Every live broker call is gated on your approval. See the Comms protocol section at the bottom — `trading-strategist` will refuse to fire `--broker` without a `RiskDecision` from you with `decision: 'approved'`.
### Core Tool: npx neural-trader
```bash
@@ -82,3 +84,44 @@ After completing tasks, store successful patterns:
```bash
npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
```
### Comms protocol (ADR-126 Phase 5 — SendMessage pipeline blocking gate)
**Pipeline position:** BLOCKING GATE. The live broker call cannot fire without your approval.
**Upstream — wait for `trading-strategist`:** Block until a `SignalProposal` arrives via SendMessage:
```
{ type: "signal-proposal/v1", from: "trading-strategist", signalId: "...", symbol: "...", side: "long|short|close", sizePct: ..., confidence: ..., regime: "..." }
```
**Risk evaluation (your job):** Run the proposal through the circuit-breaker checks documented above:
- VaR (95%) ≤ 2% per position
- CVaR ≤ 3% of portfolio
- Portfolio correlation ≤ 0.85
- Concentration ≤ 10% any single position
- Drawdown not exceeding daily/weekly limits
- VIX regime check (reduce size in high-vol)
You MAY adjust the size (set `adjustedSizePct` lower than the proposal's `sizePct`) and approve, OR reject outright.
**Downstream — send `RiskDecision` to `trading-strategist`:**
```
SendMessage({
to: "trading-strategist",
summary: "RiskDecision <signalId>: approved | rejected",
message: {
type: "risk-decision/v1",
from: "risk-analyst",
signalId: "<matches the proposal>",
timestamp: <ISO-now>,
decision: "approved" | "rejected",
adjustedSizePct: 0.015,
reasons: ["VaR within limits", "portfolio correlation 0.62 < 0.85"],
metrics: { var95: ..., cvar95: ..., portfolioCorrelation: ..., concentrationPct: ..., drawdownPct: ... }
}
})
```
**The `signalId` MUST match the upstream proposal** — `trading-strategist` correlates by signalId to enforce the gate.
Message schemas: `SignalProposal`, `RiskDecision` in `plugins/ruflo-neural-trader/src/pipeline-messages.ts`.
@@ -1,10 +1,12 @@
---
name: trading-strategist
description: Designs and optimizes neural trading strategies using npx neural-trader — LSTM/Transformer models, Rust/NAPI backtesting, Z-score anomaly detection
description: Designs and optimizes neural trading strategies using npx neural-trader — LSTM/Transformer models, Rust/NAPI backtesting, Z-score anomaly detection. Pipeline middle stage — receives RegimeVerdict from market-analyst, sends SignalProposal[] to risk-analyst, gated on RiskDecision approval (ADR-126 Phase 5)
model: opus
---
You are a trading strategist agent that orchestrates the `neural-trader` npm package (v2.7+) for strategy development, backtesting, and live execution.
You are the **middle stage** of the neural-trader live pipeline (ADR-126 Phase 5). You **MUST NOT** call the live broker (`--broker <name>`) without an explicit `RiskDecision` with `decision: 'approved'` from `risk-analyst` in the current SendMessage trace. See the Comms protocol section at the bottom.
### Core Tool: npx neural-trader
All trading operations go through the `neural-trader` CLI. Install once, then invoke via npx:
@@ -48,12 +50,22 @@ npx neural-trader --swarm enabled --broker <name> --strategy adaptive
npx neural-trader --signal scan --strategy <name> --symbols "AAPL,MSFT,GOOGL"
```
5. **Live execution** with swarm coordination:
5. **Live execution** with swarm coordination — **GATED on risk-analyst approval (ADR-126 Phase 5):**
**REFUSE to invoke `--broker <name>` unless a prior `risk-analyst` SendMessage event for the current `signalId` carries `decision: 'approved'`.** If no approval is present in the current session's SendMessage trace, halt and emit:
```
[ERROR] trading-strategist: refusing --broker call — no risk-analyst approval RiskDecision event found for signalId=<id>. ADR-126 Phase 5 risk-gate is structural; route the SignalProposal through risk-analyst first.
```
Only when the approval event is present do you invoke:
```bash
npx neural-trader --broker alpaca --strategy adaptive --swarm enabled
npx neural-trader --broker <name> --swarm enabled --risk-tolerance 0.02
```
If `RiskDecision.adjustedSizePct` is set, use that size (not the proposal's original `sizePct`).
### Strategy Types (neural-trader built-in)
| Strategy | CLI Flag | Entry Logic |
@@ -115,3 +127,44 @@ After completing tasks, store successful patterns:
```bash
npx @claude-flow/cli@latest hooks post-task --task-id "TASK_ID" --success true --train-neural true
```
### Comms protocol (ADR-126 Phase 5 — SendMessage pipeline with risk-gate)
**Pipeline position:** middle stage. Sits between `market-analyst` (upstream) and `risk-analyst` (downstream blocking gate).
**Upstream — wait for `market-analyst`:** Block until a `RegimeVerdict` message arrives via SendMessage:
```
{ type: "regime-verdict/v1", from: "market-analyst", regime: "...", symbols: [...], confidence: ... }
```
Use the regime to pick the appropriate strategy family (momentum for bull-trending, mean-reversion for ranging, etc. per the market-analyst regime table).
**Downstream — send `SignalProposal` to `risk-analyst` BEFORE any broker call:**
```
SendMessage({
to: "risk-analyst",
summary: "SignalProposal <signalId> for <symbol>",
message: {
type: "signal-proposal/v1",
from: "trading-strategist",
signalId: "<uuid>",
timestamp: <ISO-now>,
symbol: "SPY",
side: "long" | "short" | "close",
strategyId: "momentum-v2",
sizePct: 0.02,
confidence: 0.0..1.0,
regime: "<from RegimeVerdict>"
}
})
```
**Block on `RiskDecision` from `risk-analyst`:**
```
{ type: "risk-decision/v1", from: "risk-analyst", signalId: "<matches>", decision: "approved" | "rejected", reasons: [...], adjustedSizePct?: ... }
```
**Structural risk-gate (NON-NEGOTIABLE):** the live-trading branch above (step 5 of the Strategy Development Workflow) refuses to call `--broker` unless a `RiskDecision` with `decision: 'approved'` for the matching `signalId` is present in the SendMessage trace. The `scripts/smoke-neural-trader-pipeline.mjs` regression smoke fails the build if this guard is dropped or weakened.
Message schemas: `RegimeVerdict`, `SignalProposal`, `RiskDecision` in `plugins/ruflo-neural-trader/src/pipeline-messages.ts`.
**Note on `backtest-engineer`:** that agent runs in an orthogonal lane — it produces signed-artifact promotion candidates (ADR-126 Phase 4) and does NOT participate in the live pipeline. Do not consume or send messages to it from the live execution path.
@@ -1,10 +1,10 @@
---
name: trader-backtest
description: Run a historical backtest using npx neural-trader with Rust/NAPI engine (8-19x faster) and walk-forward validation
description: Run a historical backtest using npx neural-trader with Rust/NAPI engine (8-19x faster) and walk-forward validation; Ed25519-sign the result for paper→live tamper evidence (ADR-126 Phase 4)
allowed-tools: Bash Read mcp__claude-flow__memory_store mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_search mcp__claude-flow__memory_delete mcp__claude-flow__neural_train mcp__claude-flow__agentdb_pattern-store
argument-hint: "<strategy-name> --symbol <TICKER> [--period 2020-2024]"
---
Run a historical backtest using the `neural-trader` Rust/NAPI engine.
Run a historical backtest using the `neural-trader` Rust/NAPI engine, then Ed25519-sign the result so the paper→live promotion gate has cryptographic tamper evidence (ADR-126 Phase 4 + CWE-347 pattern).
Steps:
1. Ensure neural-trader is available:
@@ -20,14 +20,28 @@ Steps:
```bash
npx neural-trader --backtest --strategy multi-indicator --position-sizing kelly --symbol SPY --period 2020-2024
```
4. Capture performance metrics from output: total return, annualized return, Sharpe ratio, Sortino ratio, max drawdown, win rate, profit factor, number of trades
4. Capture performance metrics from output: total return, annualized return, Sharpe ratio, Sortino ratio, max drawdown, win rate, profit factor, number of trades.
5. Dedup prior backtests for the same `(strategyId, paramsHash)` before storing the fresh one (ADR-125 lifecycle / ADR-126 Phase 2 — `keep-newest` semantics):
- Search: `mcp__claude-flow__memory_search({ query: "backtest STRATEGY paramsHash:PARAMS_HASH", namespace: "trading-backtests", limit: 10 })`
- For each hit whose key matches `backtest-STRATEGY-*` AND whose stored `paramsHash` equals the current run's hash, delete it: `mcp__claude-flow__memory_delete({ key: "OLD_KEY", namespace: "trading-backtests" })`
- (Note: even without this proactive step, the `MemoryConsolidator.dedup('keep-newest')` background pass introduced in `@claude-flow/memory@3.0.0-alpha.18` runs every 6h and will eventually converge. Doing it inline keeps `memory_search` results deterministic immediately after a re-run.)
6. Store backtest results (long-lived; no TTL — backtest history is the audit trail that ADR-126 Phase 4 will Ed25519-sign):
`mcp__claude-flow__memory_store({ key: "backtest-STRATEGY-TIMESTAMP", value: "RESULTS_JSON", namespace: "trading-backtests" })`
7. If Sharpe > 1.5, store as successful pattern:
6. **Sign the artifact (ADR-126 Phase 4):**
- Build the `SignedBacktestArtifact` body — `{ strategyId, paramsHash, dataRange: {from,to}, metrics, runsHash, generatedAt }` — where `paramsHash = sha256(canonical params JSON)`, `runsHash = sha256(canonical runs array JSON)`, and `generatedAt = new Date().toISOString()`.
- Resolve the witness signing key. The skill reads the key path in this order; the FIRST that resolves wins:
1. `RUFLO_WITNESS_KEY_PATH` env var — points to a JSON file with `{ "privateKey": "<hex>" }`.
2. `verification/witness-key.json` (the ADR-103 default path, if present).
- If the key resolves: call `signBacktestArtifact(body, privateKeyHex)` from `plugins/ruflo-neural-trader/src/signed-artifact.mjs`. The returned value is a `SignedBacktestArtifact` with `schema`, `witnessPublicKey: "ed25519:<hex>"`, and `witnessSignature: "<hex>"` populated.
- If NEITHER path resolves: log a loud warning — `"[WARN] ruflo-neural-trader: no witness signing key found (RUFLO_WITNESS_KEY_PATH unset, verification/witness-key.json missing) — storing backtest artifact in UNSIGNED degraded mode. paper→live promotion will be refused by trader-cloud-backtest until a signed artifact replaces this one."` — and store the body unsigned. NEVER silently fall back.
7. **Store the (possibly signed) artifact** to the canonical `trading-backtests` namespace:
`mcp__claude-flow__memory_store({ key: "backtest-STRATEGY-TIMESTAMP", value: JSON.stringify(signedArtifact), namespace: "trading-backtests" })`
The stored value contains `witnessSignature` + `witnessPublicKey` when signed; downstream consumers (`trader-cloud-backtest`) MUST call `verifyBacktestArtifact(artifact, trustedPublicKey)` before promoting any artifact to live.
8. If Sharpe > 1.5, store as successful pattern:
`mcp__claude-flow__agentdb_pattern-store({ pattern: "profitable-STRATEGY_TYPE", data: "PARAMS_AND_RESULTS" })`
8. Train SONA on the outcome:
9. Train SONA on the outcome:
`mcp__claude-flow__neural_train({ patternType: "trading-strategy", epochs: 10 })`
### Key sourcing & key rotation (ADR-103)
- The witness key is a 32-byte Ed25519 private key, stored as `{ "privateKey": "<64-hex-chars>" }` in a JSON file referenced by `RUFLO_WITNESS_KEY_PATH`. Keep it OUT of the repo. For local development, generate one once with `node -e "import('@noble/ed25519').then(async ed=>{const sk=crypto.getRandomValues(new Uint8Array(32));console.log(Buffer.from(sk).toString('hex'))})"` and write it to `~/.ruflo/witness-key.json`.
- Production deployments pin the corresponding PUBLIC key in project config and supply it as `trustedPublicKey` to `verifyBacktestArtifact(...)` — never trust the `witnessPublicKey` field on the artifact itself (CWE-347 / #1922).
- Key rotation: re-sign existing backtest entries with the new key OR explicitly mark pre-rotation artifacts as non-promotable. Same pattern as ADR-103.
@@ -55,9 +55,11 @@ Prereq: `ANTHROPIC_API_KEY` (or `CLAUDE_API_KEY`) + Managed Agents beta access.
5. **Pull artifacts (if needed):** `managed_agent_prompt({ sessionId, message: "cat /tmp/equity.csv" })` or `managed_agent_events` and read the tool_result.
6. **Ingest locally:**
- `memory_store({ key: "backtest-<strategy>-<ts>", value: <metrics+params JSON>, namespace: "trading-backtests" })`
- If Sharpe > 1.5: `agentdb_pattern-store({ pattern: "profitable-<strategy-type>", data: "<params + results>" })`
6. **Ingest locally + Ed25519 verify (ADR-126 Phase 4 fail-closed gate):**
- Build the `SignedBacktestArtifact` body from the cloud-returned metrics + params hash + runs hash. Sign it locally with `signBacktestArtifact(body, privateKeyHex)` from `plugins/ruflo-neural-trader/src/signed-artifact.mjs` (key resolution same as `trader-backtest`: `RUFLO_WITNESS_KEY_PATH` → `verification/witness-key.json` → degraded-unsigned warning).
- **Before storing OR promoting the artifact to a live strategy**: call `await verifyBacktestArtifact(artifact, trustedPublicKey)` where `trustedPublicKey` is the pinned project-config Ed25519 public key (NOT the `artifact.witnessPublicKey` field — that's attacker-controllable; see CWE-347 / #1922). If verification returns `false`: **REFUSE to promote** — emit a loud error `"[ERROR] ruflo-neural-trader: SignedBacktestArtifact signature INVALID against trusted key — refusing to promote to live strategy"` and return early. This is the fail-closed gate per ADR-126.
- On verify success: `memory_store({ key: "backtest-<strategy>-<ts>", value: JSON.stringify(signedArtifact), namespace: "trading-backtests" })`. The stored value carries `witnessSignature` + `witnessPublicKey`.
- If Sharpe > 1.5: `agentdb_pattern-store({ pattern: "profitable-<strategy-type>", data: "<params + results>" })`.
- Record the run's container time + token cost to the `cost-tracking` namespace (per ADR-117 — cloud sessions bill until terminated).
7. **Terminate immediately** — results in hand:
@@ -0,0 +1,147 @@
/**
* Pipeline message schemas — ADR-126 Phase 5
*
* The four neural-trader agents (`market-analyst`, `trading-strategist`,
* `risk-analyst`, `backtest-engineer`) coordinate as a typed SendMessage
* pipeline, NOT as parallel role descriptions:
*
* market-analyst — (RegimeVerdict) ─→ trading-strategist
* trading-strategist — (SignalProposal[]) ─→ risk-analyst ◄── BLOCKING
* risk-analyst — (RiskDecision) ─→ trading-strategist
* └─→ execute-or-halt
*
* `trading-strategist` MUST NOT call the live broker (`--broker <name>`)
* without a `RiskDecision` with `decision: 'approved'` from `risk-analyst`
* in the current SendMessage trace. This is the structural risk-gate per
* ADR-126 — see `trading-strategist.md` for the in-agent enforcement.
*
* `backtest-engineer` is an orthogonal lane — it produces signed-artifact
* promotion candidates (ADR-126 Phase 4) and does NOT participate in the
* live execution pipeline. It runs in parallel during research, but the
* hot path of live trading never depends on it.
*
* These types are documentation + a future programmatic dispatcher
* contract. SendMessage payloads today are JSON literals; tomorrow a
* typed dispatcher can import + validate against this schema.
*
* Refs:
* - ADR-126 Phase 5 — SendMessage pipeline plan
* - CLAUDE.md — SendMessage protocol + named-agent rules
* - SKILL.md files for each agent — the actual call sites
*/
/* ---------------------------------------------------------------------- */
/* market-analyst → trading-strategist */
/* ---------------------------------------------------------------------- */
/**
* Regime verdict — produced by `market-analyst`, consumed by
* `trading-strategist`. Identifies the current market regime so the
* strategist can pick an appropriate strategy family before generating
* signals.
*/
export interface RegimeVerdict {
/** Message schema discriminator. */
type: 'regime-verdict/v1';
/** Originating agent name (must be `market-analyst` for valid messages). */
from: 'market-analyst';
/** ISO timestamp when the verdict was produced. */
timestamp: string;
/** The classified regime — one of the six market-analyst categories. */
regime:
| 'bull-trending'
| 'bear-trending'
| 'ranging'
| 'high-volatility'
| 'low-volatility'
| 'transitioning';
/** The ticker(s) the verdict applies to. */
symbols: string[];
/** Confidence score in [0,1]. */
confidence: number;
/** Optional supporting indicators (ADX, RSI, MACD, VIX, ...). */
indicators?: Record<string, number>;
}
/* ---------------------------------------------------------------------- */
/* trading-strategist → risk-analyst */
/* ---------------------------------------------------------------------- */
/**
* Signal proposal — produced by `trading-strategist`, consumed by
* `risk-analyst`. Represents a proposed live-trade action that requires
* risk approval before execution.
*/
export interface SignalProposal {
/** Message schema discriminator. */
type: 'signal-proposal/v1';
/** Originating agent name. */
from: 'trading-strategist';
/** Unique signal id — used to correlate the RiskDecision response. */
signalId: string;
/** ISO timestamp when the proposal was created. */
timestamp: string;
/** Symbol to trade. */
symbol: string;
/** Direction. */
side: 'long' | 'short' | 'close';
/** Strategy that produced the proposal. */
strategyId: string;
/** Position size as % of portfolio (e.g. 0.02 = 2%). */
sizePct: number;
/** Z-score / confidence score driving the entry. */
confidence: number;
/** Reference to the upstream regime that motivated the trade. */
regime?: RegimeVerdict['regime'];
/** Optional metadata — model attribution, indicator snapshot, etc. */
metadata?: Record<string, unknown>;
}
/* ---------------------------------------------------------------------- */
/* risk-analyst → trading-strategist */
/* ---------------------------------------------------------------------- */
/**
* Risk decision — produced by `risk-analyst`, consumed by
* `trading-strategist`. The BLOCKING GATE: `trading-strategist` MUST NOT
* execute a live broker call without a corresponding `RiskDecision` with
* `decision: 'approved'` for the proposal's `signalId`.
*
* Rejection reasons map to the risk-analyst's circuit-breaker / sizing
* checks (VaR, CVaR, concentration, correlation, drawdown).
*/
export interface RiskDecision {
/** Message schema discriminator. */
type: 'risk-decision/v1';
/** Originating agent name. */
from: 'risk-analyst';
/** The signal id this decision responds to (correlates with SignalProposal.signalId). */
signalId: string;
/** ISO timestamp when the decision was made. */
timestamp: string;
/** Decision — approved means the strategist may call the broker. */
decision: 'approved' | 'rejected';
/** Optional size adjustment — risk-analyst may shrink the proposal. */
adjustedSizePct?: number;
/** Human-readable reasons (empty array on approval). */
reasons: string[];
/** Risk metrics computed for the decision (VaR/CVaR snapshots, etc.). */
metrics?: {
var95?: number;
cvar95?: number;
portfolioCorrelation?: number;
concentrationPct?: number;
drawdownPct?: number;
};
}
/* ---------------------------------------------------------------------- */
/* Union for typed dispatchers */
/* ---------------------------------------------------------------------- */
/**
* Discriminated union of every valid SendMessage payload in the
* neural-trader pipeline. A future programmatic dispatcher can switch
* on `type` to validate + route incoming messages.
*/
export type PipelineMessage = RegimeVerdict | SignalProposal | RiskDecision;
@@ -0,0 +1,98 @@
// SignedBacktestArtifact — runtime ES module mirror of signed-artifact.ts.
//
// Why this file exists:
// The plugin (ruflo-neural-trader) has no package.json / tsconfig /
// build step — it ships skills + agents + scripts only. The `.ts`
// file is the documented type-shape + source of truth (ADR-126
// Phase 4 spec). This `.mjs` file is the runtime that the smoke
// (`scripts/smoke-neural-trader-backtest-signing.mjs`) imports
// directly, with zero compile step.
//
// Both files MUST stay in sync — any change to one is a change to the
// other. The smoke contract-checks the .ts file and runtime-tests the
// .mjs file; a divergence will fail one half of the smoke.
//
// Refs: ADR-126 Phase 4, CWE-347 pattern (#1922), ADR-103 witness.
/**
* Sign the body of a backtest artifact. Returns the fully-formed
* SignedBacktestArtifact envelope including witnessPublicKey + witnessSignature.
*/
export async function signBacktestArtifact(body, privateKeyHex) {
const ed = await import('@noble/ed25519');
const privateKey = hexToBytes(privateKeyHex);
if (privateKey.length !== 32) {
throw new Error(
`signBacktestArtifact: privateKey must be 32 bytes (got ${privateKey.length})`,
);
}
const canonical = canonicalBytes(body);
const signatureBytes = await ed.signAsync(canonical, privateKey);
const publicKeyBytes = await ed.getPublicKeyAsync(privateKey);
return {
schema: 'ruflo-neural-trader-backtest/v1',
...body,
witnessPublicKey: `ed25519:${bytesToHex(publicKeyBytes)}`,
witnessSignature: bytesToHex(signatureBytes),
};
}
/**
* Verify a signed backtest artifact against a caller-supplied trusted key.
*
* Pins to `trustedPublicKey`, NOT to artifact.witnessPublicKey. The latter
* is attacker-controllable; pinning to it defeats the entire verification.
* (CWE-347 / #1922 — same pattern the plugin-registry verifier uses.)
*/
export async function verifyBacktestArtifact(artifact, trustedPublicKey) {
if (!artifact || !artifact.witnessSignature || !trustedPublicKey) return false;
const ed = await import('@noble/ed25519');
const body = {
strategyId: artifact.strategyId,
paramsHash: artifact.paramsHash,
dataRange: artifact.dataRange,
metrics: artifact.metrics,
runsHash: artifact.runsHash,
generatedAt: artifact.generatedAt,
};
const canonical = canonicalBytes(body);
try {
const pubKeyHex = trustedPublicKey.replace(/^ed25519:/, '');
const pubKey = hexToBytes(pubKeyHex);
if (pubKey.length !== 32) return false;
const sig = hexToBytes(artifact.witnessSignature);
if (sig.length !== 64) return false;
return await ed.verifyAsync(sig, canonical, pubKey);
} catch {
return false;
}
}
// ---------------------------------------------------------------------------
// helpers (parity with .ts source)
// ---------------------------------------------------------------------------
function canonicalBytes(body) {
const message = JSON.stringify(body);
return new TextEncoder().encode(message);
}
function hexToBytes(hex) {
const clean = hex.replace(/^0x/, '');
if (clean.length % 2 !== 0) {
throw new Error('hexToBytes: odd-length hex string');
}
const out = new Uint8Array(clean.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
function bytesToHex(bytes) {
let s = '';
for (let i = 0; i < bytes.length; i++) {
s += bytes[i].toString(16).padStart(2, '0');
}
return s;
}
@@ -0,0 +1,186 @@
/**
* SignedBacktestArtifact — Phase 4 of ADR-126
*
* Ed25519-signed envelope for `trading-backtests` entries. The paper→live
* promotion gate stores backtest results as the artifact below; the cloud
* backtest pipeline (`trader-cloud-backtest`) verifies the signature with a
* pinned trusted key BEFORE promoting any artifact to a live strategy.
*
* Signing scheme — mirrors the CWE-347 plugin-registry pattern exactly
* (scripts/smoke-plugin-registry-signature.mjs:80-130, the verified-good
* reference for "sign with Ed25519, pin to a trusted key, fail closed"):
*
* 1. Build the artifact body WITHOUT signature fields
* (no `witnessSignature`, no `witnessPublicKey`).
* 2. `JSON.stringify(...)` plain — no whitespace, no sort.
* 3. Sign the resulting bytes with Ed25519.
* 4. Verify pins to a caller-supplied `trustedPublicKey`,
* NOT to the self-asserted `witnessPublicKey` field on the artifact
* (an attacker controls that field; pinning to it is a no-op).
*
* Key sourcing:
* - The signer accepts a 32-byte private key as a hex string. The
* `trader-backtest` skill resolves the key at runtime via the env var
* `RUFLO_WITNESS_KEY_PATH` (a JSON file with a `{ "privateKey": "<hex>" }`
* field). If unset, callers may fall back to the legacy ADR-103 witness
* key path; if neither is available, the skill stores the artifact in
* UNSIGNED degraded mode with a loud warning — never silently.
*
* - The verifier accepts a `trustedPublicKey` as `"ed25519:<hex>"` or
* plain `<hex>`. Production deployments pin this in project config.
*
* Refs:
* - ADR-126 Phase 4 — the integration plan
* - ADR-103 — witness temporal history
* - CWE-347 / #1922 — the pattern this signing scheme matches
* - scripts/smoke-plugin-registry-signature.mjs — the reference smoke
*/
/* ---------------------------------------------------------------------- */
/* Public types */
/* ---------------------------------------------------------------------- */
export interface SignedBacktestArtifact {
schema: 'ruflo-neural-trader-backtest/v1';
strategyId: string;
paramsHash: string; // sha256 of canonical params JSON
dataRange: { from: string; to: string };
metrics: Record<string, number>;
runsHash: string; // sha256 of the canonical runs array JSON
generatedAt: string; // ISO timestamp
witnessPublicKey: string; // 'ed25519:<hex>' — self-asserted (NOT pinned by verifier)
witnessSignature: string; // hex of the Ed25519 signature over the canonical body
}
/** The body that gets signed — everything except the two signature fields. */
export type SignedBacktestArtifactBody = Omit<
SignedBacktestArtifact,
'witnessPublicKey' | 'witnessSignature' | 'schema'
>;
/* ---------------------------------------------------------------------- */
/* Signing + verification */
/* ---------------------------------------------------------------------- */
/**
* Sign the body of a backtest artifact and return the fully-formed
* `SignedBacktestArtifact` envelope.
*
* The signature covers the artifact body WITHOUT `witnessSignature` and
* WITHOUT `witnessPublicKey` (CWE-347 pattern). This means an attacker who
* swaps the served `witnessPublicKey` field cannot bypass verification when
* the verifier pins to a trusted key (which is the only safe verifier).
*
* @param body — the artifact body (everything except signature fields + schema)
* @param privateKeyHex — 32-byte Ed25519 private key as hex string (no 'ed25519:' prefix)
* @returns — the signed artifact ready to be stored
*/
export async function signBacktestArtifact(
body: SignedBacktestArtifactBody,
privateKeyHex: string,
): Promise<SignedBacktestArtifact> {
const ed = await import('@noble/ed25519');
const privateKey = hexToBytes(privateKeyHex);
if (privateKey.length !== 32) {
throw new Error(
`signBacktestArtifact: privateKey must be 32 bytes (got ${privateKey.length})`,
);
}
// Canonical body = the artifact WITHOUT signature fields, plain JSON.stringify.
// Matches scripts/smoke-plugin-registry-signature.mjs:193-200.
const canonical = canonicalBytes(body);
const signatureBytes = await ed.signAsync(canonical, privateKey);
const publicKeyBytes = await ed.getPublicKeyAsync(privateKey);
return {
schema: 'ruflo-neural-trader-backtest/v1',
...body,
witnessPublicKey: `ed25519:${bytesToHex(publicKeyBytes)}`,
witnessSignature: bytesToHex(signatureBytes),
};
}
/**
* Verify a signed backtest artifact against a caller-supplied trusted
* public key. Returns `true` iff the signature is valid for the canonical
* body under the TRUSTED key.
*
* IMPORTANT — the verifier pins to `trustedPublicKey`, NOT to the artifact's
* `witnessPublicKey` field. The artifact's self-asserted public key is
* untrusted input: an attacker who tampers with the stored entry can swap
* that field freely. Pinning to a trusted key supplied by project config
* is the only safe pattern (CWE-347 / #1922).
*
* @param artifact — the artifact to verify (may have been tampered)
* @param trustedPublicKey — caller-supplied trusted pubkey, with or without 'ed25519:' prefix
* @returns — true iff signature verifies against the trusted key
*/
export async function verifyBacktestArtifact(
artifact: SignedBacktestArtifact,
trustedPublicKey: string,
): Promise<boolean> {
if (!artifact || !artifact.witnessSignature || !trustedPublicKey) return false;
const ed = await import('@noble/ed25519');
// Strip BOTH signature fields (and schema, which is constant) to get the
// canonical body that was signed.
const body: SignedBacktestArtifactBody = {
strategyId: artifact.strategyId,
paramsHash: artifact.paramsHash,
dataRange: artifact.dataRange,
metrics: artifact.metrics,
runsHash: artifact.runsHash,
generatedAt: artifact.generatedAt,
};
const canonical = canonicalBytes(body);
try {
const pubKeyHex = trustedPublicKey.replace(/^ed25519:/, '');
const pubKey = hexToBytes(pubKeyHex);
if (pubKey.length !== 32) return false;
const sig = hexToBytes(artifact.witnessSignature);
if (sig.length !== 64) return false;
return await ed.verifyAsync(sig, canonical, pubKey);
} catch {
return false;
}
}
/* ---------------------------------------------------------------------- */
/* Helpers */
/* ---------------------------------------------------------------------- */
/**
* Canonical bytes for signing = `JSON.stringify(body)` UTF-8 encoded.
*
* Matches the plugin-registry signer (publish-registry.ts:127-151) and the
* CWE-347 smoke (smoke-plugin-registry-signature.mjs:193-200): plain
* `JSON.stringify` with NO whitespace and NO key sort. The body shape is
* authored by us (the signer), so deterministic key order is guaranteed by
* construction — no canonicalizer needed.
*/
function canonicalBytes(body: SignedBacktestArtifactBody): Uint8Array {
const message = JSON.stringify(body);
return new TextEncoder().encode(message);
}
function hexToBytes(hex: string): Uint8Array {
const clean = hex.replace(/^0x/, '');
if (clean.length % 2 !== 0) {
throw new Error(`hexToBytes: odd-length hex string`);
}
const out = new Uint8Array(clean.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
function bytesToHex(bytes: Uint8Array): string {
let s = '';
for (let i = 0; i < bytes.length; i++) {
s += bytes[i].toString(16).padStart(2, '0');
}
return s;
}
@@ -0,0 +1,305 @@
#!/usr/bin/env node
/**
* Smoke test for ADR-126 Phase 4 (#2068) — Ed25519-signed backtest artifacts.
*
* Locks in three layers (modelled on scripts/smoke-plugin-registry-signature.mjs,
* the CWE-347 reference for "sign with Ed25519, pin to a trusted key, fail
* closed"):
*
* [1/3] STATIC CONTRACT on signed-artifact.{ts,mjs}:
* - both files exist and export `signBacktestArtifact` +
* `verifyBacktestArtifact`
* - the verifier pins to a caller-supplied `trustedPublicKey`, NOT
* to artifact.witnessPublicKey (CWE-347 / #1922)
* - canonical message construction strips BOTH `witnessSignature`
* AND `witnessPublicKey` before stringifying — otherwise an
* attacker who swaps the served pubkey can re-sign the body.
* - canonical message is JSON.stringify (no whitespace, no sort) —
* matches the plugin-registry signer scheme exactly.
*
* [2/3] CRYPTO ROUND-TRIP with real Ed25519 against the .mjs runtime:
* - signed fixture verifies with the trusted pubkey
* - tampered body fails
* - empty signature fails
* - empty pubkey fails
* - swapped served `witnessPublicKey` (attacker scenario) — still
* verifies because we pin to the TRUSTED pubkey, not the served field
* - wrong trusted pubkey fails (proves the pin is real, not a no-op)
*
* [3/3] CALL-SITE BYTE check on trader-cloud-backtest/SKILL.md:
* - skill contains an `verifyBacktestArtifact(...)` call
* - skill contains a fail-closed branch on the failure path (refuse
* to promote / return early / error message)
*
* If a future PR drops the verify call, reverts the canonical-message
* construction, or removes the fail-closed branch, this smoke catches it
* before merge.
*
* Usage: node scripts/smoke-neural-trader-backtest-signing.mjs
*/
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { TextEncoder } from 'node:util';
const __dirname = dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = join(__dirname, '..');
const PLUGIN_DIR = join(REPO_ROOT, 'plugins', 'ruflo-neural-trader');
const ARTIFACT_TS = join(PLUGIN_DIR, 'src', 'signed-artifact.ts');
const ARTIFACT_MJS = join(PLUGIN_DIR, 'src', 'signed-artifact.mjs');
const TRADER_BACKTEST_MD = join(PLUGIN_DIR, 'skills', 'trader-backtest', 'SKILL.md');
const CLOUD_BACKTEST_MD = join(PLUGIN_DIR, 'skills', 'trader-cloud-backtest', 'SKILL.md');
const failures = [];
function check(label, ok, detail = '') {
if (ok) console.log(` ✓ ${label}`);
else {
console.log(` ✗ ${label}${detail ? ' — ' + detail : ''}`);
failures.push(label);
}
}
// ---------------------------------------------------------------------------
// Part 1 — Static contract on signed-artifact.{ts,mjs}
// ---------------------------------------------------------------------------
console.log('[1/3] Static contract on signed-artifact.{ts,mjs}');
if (!existsSync(ARTIFACT_TS)) {
failures.push('signed-artifact.ts not found');
} else {
const src = readFileSync(ARTIFACT_TS, 'utf8');
check(
'TS exports `signBacktestArtifact` + `verifyBacktestArtifact`',
/export\s+async\s+function\s+signBacktestArtifact\s*\(/.test(src) &&
/export\s+async\s+function\s+verifyBacktestArtifact\s*\(/.test(src),
'expected both functions to be exported as async',
);
check(
'TS declares `SignedBacktestArtifact` interface with required fields',
/interface\s+SignedBacktestArtifact/.test(src) &&
/schema\s*:\s*'ruflo-neural-trader-backtest\/v1'/.test(src) &&
/witnessPublicKey\s*:\s*string/.test(src) &&
/witnessSignature\s*:\s*string/.test(src) &&
/paramsHash\s*:\s*string/.test(src) &&
/runsHash\s*:\s*string/.test(src),
'shape per ADR-126 Phase 4 spec',
);
// Verifier MUST pin to caller's trustedPublicKey, not the served field.
// We assert this by looking for the param `trustedPublicKey` in the
// verifier signature AND for `replace(/^ed25519:/, '')` on it (the pin
// path) AND for the absence of any `artifact.witnessPublicKey` usage
// INSIDE the verifier body's pubkey computation.
if (/export\s+async\s+function\s+verifyBacktestArtifact\s*\(\s*[^)]*trustedPublicKey/.test(src)) {
check('TS verifier accepts `trustedPublicKey` as a parameter', true);
} else {
check('TS verifier accepts `trustedPublicKey` as a parameter', false, 'verifier MUST take trustedPublicKey as second arg, not infer from artifact');
}
// The verifier must NOT use artifact.witnessPublicKey when computing the
// verification pubkey (the served field is attacker-controllable).
const verifierBody = (() => {
const m = /export\s+async\s+function\s+verifyBacktestArtifact[\s\S]*?\{([\s\S]*?)\n\}/.exec(src);
return m ? m[1] : '';
})();
check(
'TS verifier does NOT consume artifact.witnessPublicKey for verification',
verifierBody && !/artifact\.witnessPublicKey/.test(verifierBody),
'reading artifact.witnessPublicKey defeats the pin — pin to trustedPublicKey only',
);
// Canonical message construction must strip BOTH signature fields.
// The TS version does this implicitly by building a `body` object that
// omits `witnessPublicKey`, `witnessSignature`, and `schema`. We grep
// for that pattern.
check(
'TS verifier builds canonical body WITHOUT witnessSignature + witnessPublicKey',
/const\s+body[\s\S]{0,300}?strategyId:\s*artifact\.strategyId/.test(src) &&
!/body\.witnessSignature\s*=/.test(src) &&
!/body\.witnessPublicKey\s*=/.test(src),
'canonical body MUST exclude both signature fields before stringify',
);
check(
'TS canonical bytes use plain JSON.stringify (no whitespace, no sort)',
/JSON\.stringify\(\s*body\s*\)/.test(src),
'match the plugin-registry signer scheme: plain JSON.stringify',
);
}
if (!existsSync(ARTIFACT_MJS)) {
failures.push('signed-artifact.mjs (runtime mirror) not found');
} else {
const mjs = readFileSync(ARTIFACT_MJS, 'utf8');
check(
'MJS runtime exports `signBacktestArtifact` + `verifyBacktestArtifact`',
/export\s+async\s+function\s+signBacktestArtifact\b/.test(mjs) &&
/export\s+async\s+function\s+verifyBacktestArtifact\b/.test(mjs),
'.mjs mirror must keep parity with the .ts source',
);
check(
'MJS verifier pins to caller-supplied `trustedPublicKey`',
/verifyBacktestArtifact\s*\(\s*artifact\s*,\s*trustedPublicKey/.test(mjs) &&
/trustedPublicKey\.replace\(\s*\/\^ed25519:\/\s*,\s*''\)/.test(mjs),
'verifier param name must be trustedPublicKey AND it must be the one normalized',
);
}
// ---------------------------------------------------------------------------
// Part 2 — Crypto round-trip with real Ed25519
// ---------------------------------------------------------------------------
console.log('\n[2/3] Crypto round-trip via the .mjs runtime');
let ed;
try {
ed = await import('@noble/ed25519');
} catch (err) {
failures.push('@noble/ed25519 not installed — run `npm install` at repo root');
console.error(` ✗ @noble/ed25519 import failed: ${err.message}`);
}
let signBacktestArtifact, verifyBacktestArtifact;
try {
const mod = await import(pathToFileURL(ARTIFACT_MJS).href);
signBacktestArtifact = mod.signBacktestArtifact;
verifyBacktestArtifact = mod.verifyBacktestArtifact;
} catch (err) {
failures.push('signed-artifact.mjs runtime import failed');
console.error(` ✗ runtime import failed: ${err.message}`);
}
if (ed && signBacktestArtifact && verifyBacktestArtifact) {
// Deterministic test key (same scheme as the plugin-registry smoke).
const privateKey = new Uint8Array(32);
for (let i = 0; i < 32; i++) privateKey[i] = (i * 19 + 7) % 256;
const privateKeyHex = Buffer.from(privateKey).toString('hex');
const publicKeyBytes = await ed.getPublicKeyAsync(privateKey);
const trustedPubKeyHex = `ed25519:${Buffer.from(publicKeyBytes).toString('hex')}`;
const body = {
strategyId: 'momentum-spy-2024',
paramsHash: 'a'.repeat(64),
dataRange: { from: '2020-01-01', to: '2024-12-31' },
metrics: { sharpe: 1.8, maxDrawdown: 0.11, totalReturn: 0.42 },
runsHash: 'b'.repeat(64),
generatedAt: '2026-05-19T12:00:00.000Z',
};
const signed = await signBacktestArtifact(body, privateKeyHex);
// (a) happy path
check(
'signed fixture verifies with the trusted pubkey',
await verifyBacktestArtifact(signed, trustedPubKeyHex),
);
// sanity: artifact has the documented shape
check(
'signed artifact carries schema + witnessPublicKey + witnessSignature',
signed.schema === 'ruflo-neural-trader-backtest/v1' &&
typeof signed.witnessPublicKey === 'string' &&
signed.witnessPublicKey.startsWith('ed25519:') &&
typeof signed.witnessSignature === 'string' &&
signed.witnessSignature.length === 128,
`got: schema=${signed.schema} pk-len=${signed.witnessPublicKey?.length} sig-len=${signed.witnessSignature?.length}`,
);
// (b) tamper one byte of the body → verify fails
const tampered = JSON.parse(JSON.stringify(signed));
tampered.metrics.sharpe = 99.9; // attacker inflates Sharpe to clear promotion gate
check(
'tampered body (sharpe inflated) fails verification',
!(await verifyBacktestArtifact(tampered, trustedPubKeyHex)),
'inflating metrics MUST invalidate the signature',
);
// (c) empty signature fails
check(
'empty signature fails',
!(await verifyBacktestArtifact({ ...signed, witnessSignature: '' }, trustedPubKeyHex)),
);
// (d) empty pubkey fails
check(
'empty trusted pubkey fails',
!(await verifyBacktestArtifact(signed, '')),
);
// (e) swap served witnessPublicKey to a different value → verify still
// succeeds because we pin to the TRUSTED key (CWE-347 / #1922).
const swappedServed = {
...signed,
witnessPublicKey: 'ed25519:' + '0'.repeat(64),
};
check(
'verifier ignores swapped served witnessPublicKey (pinned to trusted key)',
await verifyBacktestArtifact(swappedServed, trustedPubKeyHex),
'pin to trustedPublicKey MUST override the served self-asserted pubkey',
);
// (f) different trusted pubkey fails — proves the pin is real
const wrongTrusted = 'ed25519:' + '0'.repeat(64);
check(
'wrong trusted pubkey fails (pin is real, not a no-op)',
!(await verifyBacktestArtifact(signed, wrongTrusted)),
);
}
// ---------------------------------------------------------------------------
// Part 3 — Call-site byte check on trader-cloud-backtest/SKILL.md
// ---------------------------------------------------------------------------
console.log('\n[3/3] Call-site byte check on trader-cloud-backtest/SKILL.md');
if (!existsSync(CLOUD_BACKTEST_MD)) {
failures.push('trader-cloud-backtest/SKILL.md not found');
} else {
const skill = readFileSync(CLOUD_BACKTEST_MD, 'utf8');
check(
'skill calls `verifyBacktestArtifact(artifact, trustedPublicKey)`',
/verifyBacktestArtifact\s*\([^)]*trustedPublicKey/.test(skill),
'skill must invoke the verifier with the pinned trusted pubkey before promotion',
);
check(
'skill documents the fail-closed branch (refuse to promote)',
/refuse to promote/i.test(skill) &&
(/return\s+early/i.test(skill) || /return\s*;/.test(skill) || /\[ERROR\]/.test(skill)),
'skill must show explicit refusal + early-return on verify failure',
);
check(
'skill references the pinned trusted pubkey path (NOT the served field)',
/trustedPublicKey/.test(skill) && /NOT\s+the\s+`?artifact\.witnessPublicKey`?\s+field|attacker-controllable/i.test(skill),
'docs must call out CWE-347: pin to trusted key, not served self-asserted field',
);
}
// Also verify the trader-backtest skill mentions signing in its flow.
if (!existsSync(TRADER_BACKTEST_MD)) {
failures.push('trader-backtest/SKILL.md not found');
} else {
const skill = readFileSync(TRADER_BACKTEST_MD, 'utf8');
check(
'trader-backtest skill references signBacktestArtifact',
/signBacktestArtifact/.test(skill),
'skill must invoke the signer when a key is present',
);
check(
'trader-backtest skill documents the degraded-unsigned warning path',
/UNSIGNED degraded mode/.test(skill) || /unsigned.*degraded/i.test(skill),
'no-key case must be logged loudly, never silent',
);
check(
'trader-backtest skill documents RUFLO_WITNESS_KEY_PATH env var',
/RUFLO_WITNESS_KEY_PATH/.test(skill),
'production key sourcing must be documented',
);
}
// ---------------------------------------------------------------------------
console.log('');
if (failures.length > 0) {
console.log(`FAIL: ${failures.length} issue(s) — see above`);
process.exit(1);
} else {
console.log('OK: ADR-126 Phase 4 backtest-signing — schema + signer + verifier + skill gates verified');
process.exit(0);
}
+413
View File
@@ -0,0 +1,413 @@
#!/usr/bin/env node
/**
* Smoke test for ADR-126 Phase 5 (#2068) — SendMessage risk-gate pipeline.
*
* The four neural-trader agents (`market-analyst`, `trading-strategist`,
* `risk-analyst`, `backtest-engineer`) coordinate as a typed SendMessage
* pipeline with `risk-analyst` as a structural BLOCKING GATE — the live
* broker call cannot fire without an explicit `RiskDecision` with
* `decision: 'approved'` for the proposal's signalId.
*
* Pipeline:
* market-analyst — (RegimeVerdict) ─→ trading-strategist
* trading-strategist — (SignalProposal[]) ─→ risk-analyst ◄── BLOCKING
* risk-analyst — (RiskDecision) ─→ trading-strategist
* └─→ execute-or-halt
* backtest-engineer — orthogonal (signed promotion candidates only)
*
* Locks in four layers:
*
* [1/4] AGENT FRONTMATTER — each of the four agent .md files declares
* `name:` in YAML frontmatter (so they're addressable via SendMessage).
*
* [2/4] COMMS PROTOCOL SECTION — each of the four agent .md files has a
* "Comms protocol" section that names the upstream + downstream
* agents correctly.
*
* [3/4] STRUCTURAL RISK-GATE — `trading-strategist.md` contains explicit
* refusal logic when `--broker` is invoked without a `risk-analyst`
* approval. The guard pattern must mention `risk-analyst`, the
* broker call, the refusal, AND link to the RiskDecision schema.
*
* [4/4] MESSAGE SCHEMAS + BEHAVIORAL MOCK — `src/pipeline-messages.ts`
* exports the three message types with the expected field shapes.
* A small mock pipeline (constructed in this smoke) drives the
* flow and asserts that:
* (a) market-analyst → strategist → risk-analyst (approved) →
* broker-execute SUCCEEDS
* (b) market-analyst → strategist → broker-execute (NO risk-analyst
* event) IS REFUSED with structural guard
*
* If a future PR drops the guard, removes a `name` field, or breaks the
* pipeline-messages schema, this smoke catches it before merge.
*
* Usage: node scripts/smoke-neural-trader-pipeline.mjs
*/
import { readFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = join(__dirname, '..');
const PLUGIN_DIR = join(REPO_ROOT, 'plugins', 'ruflo-neural-trader');
const AGENTS_DIR = join(PLUGIN_DIR, 'agents');
const MESSAGES_TS = join(PLUGIN_DIR, 'src', 'pipeline-messages.ts');
const AGENTS = [
{
name: 'market-analyst',
file: 'market-analyst.md',
upstream: null, // entry point
downstream: 'trading-strategist',
},
{
name: 'trading-strategist',
file: 'trading-strategist.md',
upstream: 'market-analyst',
downstream: 'risk-analyst',
},
{
name: 'risk-analyst',
file: 'risk-analyst.md',
upstream: 'trading-strategist',
downstream: 'trading-strategist', // returns RiskDecision
},
{
name: 'backtest-engineer',
file: 'backtest-engineer.md',
upstream: null, // orthogonal lane
downstream: null,
},
];
const failures = [];
function check(label, ok, detail = '') {
if (ok) console.log(` ✓ ${label}`);
else {
console.log(` ✗ ${label}${detail ? ' — ' + detail : ''}`);
failures.push(label);
}
}
// ---------------------------------------------------------------------------
// Part 1 — Agent frontmatter (each agent must be addressable by name)
// ---------------------------------------------------------------------------
console.log('[1/4] Agent frontmatter — `name:` declared for SendMessage addressing');
const agentBodies = new Map();
for (const a of AGENTS) {
const path = join(AGENTS_DIR, a.file);
if (!existsSync(path)) {
check(`${a.file} exists`, false);
continue;
}
const src = readFileSync(path, 'utf8');
agentBodies.set(a.name, src);
// Frontmatter: between leading `---` and the next `---`
const fmMatch = /^---\n([\s\S]+?)\n---/m.exec(src);
if (!fmMatch) {
check(`${a.file} has YAML frontmatter`, false);
continue;
}
const nameDecl = new RegExp(`^name:\\s*${a.name}\\b`, 'm');
check(
`${a.file} declares \`name: ${a.name}\``,
nameDecl.test(fmMatch[1]),
`frontmatter must declare \`name: ${a.name}\` so SendMessage can address the agent`,
);
}
// ---------------------------------------------------------------------------
// Part 2 — Comms protocol section + upstream/downstream references
// ---------------------------------------------------------------------------
console.log('\n[2/4] Comms protocol — section + upstream/downstream wiring');
for (const a of AGENTS) {
const src = agentBodies.get(a.name);
if (!src) continue;
check(
`${a.file} declares a "Comms protocol" section`,
/Comms protocol/i.test(src),
'each agent must document its SendMessage wiring under "Comms protocol"',
);
if (a.upstream) {
check(
`${a.file} references upstream agent \`${a.upstream}\``,
new RegExp(`\\b${a.upstream}\\b`).test(src),
`${a.name} must wait for SendMessage from ${a.upstream}`,
);
}
if (a.downstream) {
check(
`${a.file} references downstream agent \`${a.downstream}\``,
new RegExp(`\\b${a.downstream}\\b`).test(src),
`${a.name} must send to ${a.downstream}`,
);
}
}
// backtest-engineer is orthogonal — assert it documents that
const beSrc = agentBodies.get('backtest-engineer');
if (beSrc) {
check(
'backtest-engineer.md documents orthogonal-lane status (NOT in live pipeline)',
/orthogonal/i.test(beSrc) && /not.*participate|does NOT participate|NOT a hot-path/i.test(beSrc),
'backtest-engineer must be marked as orthogonal so it does not pollute the live pipeline',
);
}
// ---------------------------------------------------------------------------
// Part 3 — Structural risk-gate enforcement in trading-strategist.md
// ---------------------------------------------------------------------------
console.log('\n[3/4] Structural risk-gate — trading-strategist refuses --broker without approval');
const strategistSrc = agentBodies.get('trading-strategist');
if (strategistSrc) {
// Look for the guard pattern: must mention --broker, must mention
// risk-analyst approval, must mention refusal.
const hasBroker = /--broker/.test(strategistSrc);
const hasRiskAnalystApproval =
/risk-analyst.*approval|approval.*risk-analyst|RiskDecision.*approved/i.test(strategistSrc);
const hasRefusal = /REFUSE|[Rr]efus(e|ing)\s+to\s+(invoke|call|fire|execute)/.test(strategistSrc);
const hasErrorBranch = /\[ERROR\].*trading-strategist|halt and emit|refusing --broker/i.test(strategistSrc);
check(
'trading-strategist mentions --broker live execution',
hasBroker,
);
check(
'trading-strategist references risk-analyst RiskDecision approval',
hasRiskAnalystApproval,
'the guard must explicitly require a RiskDecision approval event',
);
check(
'trading-strategist declares structural REFUSAL of --broker without approval',
hasRefusal,
'the gate is structural — refusal logic must be explicit, not implied',
);
check(
'trading-strategist emits an [ERROR] line on guard violation',
hasErrorBranch,
'failure mode must be observable in logs, not silent',
);
// The non-negotiable hint should be present so a future refactor that
// softens the guard is at least noted in-file.
check(
'trading-strategist marks the risk-gate as NON-NEGOTIABLE or structural',
/NON-NEGOTIABLE|structural risk-gate/i.test(strategistSrc),
'language strength matters — anyone editing this file must see the gate is mandatory',
);
}
// ---------------------------------------------------------------------------
// Part 4 — Message schemas + behavioral mock
// ---------------------------------------------------------------------------
console.log('\n[4/4] Message schemas + behavioral mock pipeline');
if (!existsSync(MESSAGES_TS)) {
failures.push('pipeline-messages.ts not found');
} else {
const src = readFileSync(MESSAGES_TS, 'utf8');
check(
'pipeline-messages.ts exports `RegimeVerdict` with `type: "regime-verdict/v1"`',
/export\s+interface\s+RegimeVerdict/.test(src) &&
/type:\s*'regime-verdict\/v1'/.test(src),
);
check(
'pipeline-messages.ts exports `SignalProposal` with `signalId`',
/export\s+interface\s+SignalProposal/.test(src) &&
/signalId:\s*string/.test(src) &&
/type:\s*'signal-proposal\/v1'/.test(src),
);
check(
'pipeline-messages.ts exports `RiskDecision` with `decision: \'approved\' | \'rejected\'`',
/export\s+interface\s+RiskDecision/.test(src) &&
/decision:\s*'approved'\s*\|\s*'rejected'/.test(src) &&
/signalId:\s*string/.test(src) &&
/type:\s*'risk-decision\/v1'/.test(src),
'RiskDecision must carry signalId for correlation + the approved/rejected enum',
);
check(
'pipeline-messages.ts declares `PipelineMessage` union of the three types',
/export\s+type\s+PipelineMessage\s*=\s*RegimeVerdict\s*\|\s*SignalProposal\s*\|\s*RiskDecision/.test(src),
);
}
// Behavioral mock — drive a mini pipeline through a structural-gate function
// that mirrors the trading-strategist.md guard. The function MUST refuse to
// execute the broker call when no approval RiskDecision is present.
const mockEvents = [];
function record(event) {
mockEvents.push(event);
}
function mockExecuteBroker({ events, signalId }) {
// Mirror the trading-strategist.md guard exactly: REFUSE unless a
// RiskDecision with decision==='approved' for this signalId exists.
const approval = events.find(
(e) =>
e.type === 'risk-decision/v1' &&
e.signalId === signalId &&
e.decision === 'approved' &&
e.from === 'risk-analyst',
);
if (!approval) {
throw new Error(
`[ERROR] trading-strategist: refusing --broker call — no risk-analyst approval RiskDecision event found for signalId=${signalId}. ADR-126 Phase 5 risk-gate is structural; route the SignalProposal through risk-analyst first.`,
);
}
// Use adjustedSizePct if present
const size = approval.adjustedSizePct ?? 0;
record({ type: 'broker-executed', signalId, size });
return { ok: true, signalId, size };
}
// Scenario (a): full happy path
record({
type: 'regime-verdict/v1',
from: 'market-analyst',
timestamp: '2026-05-19T12:00:00.000Z',
regime: 'bull-trending',
symbols: ['SPY'],
confidence: 0.82,
});
record({
type: 'signal-proposal/v1',
from: 'trading-strategist',
signalId: 'sig-001',
timestamp: '2026-05-19T12:00:05.000Z',
symbol: 'SPY',
side: 'long',
strategyId: 'momentum-v2',
sizePct: 0.02,
confidence: 0.78,
regime: 'bull-trending',
});
record({
type: 'risk-decision/v1',
from: 'risk-analyst',
signalId: 'sig-001',
timestamp: '2026-05-19T12:00:08.000Z',
decision: 'approved',
adjustedSizePct: 0.015,
reasons: ['VaR within limits', 'portfolio correlation 0.62 < 0.85'],
});
let happyOk = false;
try {
const r = mockExecuteBroker({ events: mockEvents, signalId: 'sig-001' });
happyOk = r.ok === true && r.size === 0.015;
} catch (err) {
happyOk = false;
}
check(
'happy path: market-analyst → strategist → risk-analyst (approved) → broker SUCCEEDS',
happyOk,
'the full pipeline with an approval event must let the broker call through',
);
// Scenario (b): missing risk-analyst approval — must be refused
const noApprovalEvents = [
{
type: 'regime-verdict/v1',
from: 'market-analyst',
timestamp: '2026-05-19T12:01:00.000Z',
regime: 'bull-trending',
symbols: ['SPY'],
confidence: 0.82,
},
{
type: 'signal-proposal/v1',
from: 'trading-strategist',
signalId: 'sig-002',
timestamp: '2026-05-19T12:01:05.000Z',
symbol: 'SPY',
side: 'long',
strategyId: 'momentum-v2',
sizePct: 0.02,
confidence: 0.78,
},
// NB: no risk-decision/v1 event for sig-002
];
let refusedOk = false;
let refusalMessage = '';
try {
mockExecuteBroker({ events: noApprovalEvents, signalId: 'sig-002' });
refusedOk = false; // shouldn't reach here
} catch (err) {
refusedOk = /refusing --broker.*no risk-analyst approval/i.test(err.message);
refusalMessage = err.message;
}
check(
'refusal path: strategist → broker WITHOUT risk-analyst event IS REFUSED structurally',
refusedOk,
`expected structural refusal; got: ${refusalMessage}`,
);
// Scenario (c): rejected RiskDecision must NOT allow execution
const rejectedEvents = [
...noApprovalEvents,
{
type: 'risk-decision/v1',
from: 'risk-analyst',
signalId: 'sig-002',
timestamp: '2026-05-19T12:01:08.000Z',
decision: 'rejected',
reasons: ['concentration > 10%'],
},
];
let rejectedRefused = false;
try {
mockExecuteBroker({ events: rejectedEvents, signalId: 'sig-002' });
rejectedRefused = false;
} catch (err) {
rejectedRefused = /refusing --broker/i.test(err.message);
}
check(
'rejection path: RiskDecision.decision=="rejected" does NOT count as approval',
rejectedRefused,
'only decision==="approved" should let the broker call through',
);
// Scenario (d): signalId mismatch — approval for a different signal must
// NOT approve the current one
const mismatchedEvents = [
{
type: 'risk-decision/v1',
from: 'risk-analyst',
signalId: 'sig-OTHER',
timestamp: '2026-05-19T12:02:00.000Z',
decision: 'approved',
reasons: ['fine'],
},
];
let mismatchRefused = false;
try {
mockExecuteBroker({ events: mismatchedEvents, signalId: 'sig-002' });
mismatchRefused = false;
} catch (err) {
mismatchRefused = /refusing --broker/i.test(err.message);
}
check(
'signalId correlation: approval for sig-OTHER does NOT approve sig-002',
mismatchRefused,
'the gate correlates by signalId — replaying an old approval for a new signal must be refused',
);
// ---------------------------------------------------------------------------
console.log('');
if (failures.length > 0) {
console.log(`FAIL: ${failures.length} issue(s) — see above`);
process.exit(1);
} else {
console.log('OK: ADR-126 Phase 5 SendMessage risk-gate pipeline — agent wiring + structural gate verified');
process.exit(0);
}