π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(neural-trader): #2068 ADR-126 Phase 5 β SendMessage risk-gate pipeline
ruvf8485c7b77b0
diff --git a/.github/workflows/v3-ci.yml b/.github/workflows/v3-ci.ymlindex c2f4e3b85a..499548af56 100644--- a/.github/workflows/v3-ci.yml+++ b/.github/workflows/v3-ci.yml@@ -52,6 +52,15 @@ on:- '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'@@ -94,6 +103,13 @@ on:- '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'@@ -742,6 +758,60 @@ jobs:- name: Run backtest signing smokerun: 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 indiff --git a/plugins/ruflo-neural-trader/agents/backtest-engineer.md b/plugins/ruflo-neural-trader/agents/backtest-engineer.mdindex e9cbba3662..1d08e8a3f7 100644--- a/plugins/ruflo-neural-trader/agents/backtest-engineer.md+++ b/plugins/ruflo-neural-trader/agents/backtest-engineer.md@@ -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 executionmodel: 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```bashnpx @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`.diff --git a/plugins/ruflo-neural-trader/agents/market-analyst.md b/plugins/ruflo-neural-trader/agents/market-analyst.mdindex 1ca636bd29..5fe8765188 100644--- a/plugins/ruflo-neural-trader/agents/market-analyst.md+++ b/plugins/ruflo-neural-trader/agents/market-analyst.md@@ -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"```bashnpx @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`.diff --git a/plugins/ruflo-neural-trader/agents/risk-analyst.md b/plugins/ruflo-neural-trader/agents/risk-analyst.mdindex 7b49be0a20..018264e87b 100644--- a/plugins/ruflo-neural-trader/agents/risk-analyst.md+++ b/plugins/ruflo-neural-trader/agents/risk-analyst.md@@ -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:```bashnpx @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`.diff --git a/plugins/ruflo-neural-trader/agents/trading-strategist.md b/plugins/ruflo-neural-trader/agents/trading-strategist.mdindex 998dfbded8..c7997ab4ac 100644--- a/plugins/ruflo-neural-trader/agents/trading-strategist.md+++ b/plugins/ruflo-neural-trader/agents/trading-strategist.md@@ -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-traderAll 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 adaptivenpx 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:```bashnpx neural-trader --broker alpaca --strategy adaptive --swarm enablednpx 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:```bashnpx @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.diff --git a/plugins/ruflo-neural-trader/src/pipeline-messages.ts b/plugins/ruflo-neural-trader/src/pipeline-messages.tsnew file mode 100644index 0000000000..a1e95693f2--- /dev/null+++ b/plugins/ruflo-neural-trader/src/pipeline-messages.ts@@ -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;diff --git a/scripts/smoke-neural-trader-pipeline.mjs b/scripts/smoke-neural-trader-pipeline.mjsnew file mode 100644index 0000000000..4bd167565a--- /dev/null+++ b/scripts/smoke-neural-trader-pipeline.mjs@@ -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);+}