Skip to content

Integrate NeuroRift with OpenClaw gateway (config, adapter, boot/heartbeat/persona)#24

Merged
Neuro-Rift merged 2 commits into
mainfrom
codex/integrate-neurorift-with-openclaw-gateway
Feb 27, 2026
Merged

Integrate NeuroRift with OpenClaw gateway (config, adapter, boot/heartbeat/persona)#24
Neuro-Rift merged 2 commits into
mainfrom
codex/integrate-neurorift-with-openclaw-gateway

Conversation

@Neuro-Rift
Copy link
Copy Markdown
Owner

@Neuro-Rift Neuro-Rift commented Feb 27, 2026

User description

Motivation

  • Provide a seamless bridge between NeuroRift's FastAPI-based tool/AI runtime and the OpenClaw gateway so NeuroRift can run its Planner→ToolSelector/Manus→Operator→Analyst pipeline as OpenClaw isolated sessions.
  • Enforce sandboxing, human-in-the-loop approval, channel routing, scheduling, session-memory, and environment normalization to secure and operationalize long-running reconnaissance workflows.

Description

  • Added a unified runtime configuration openclaw.json5 that registers NeuroRift as neurorift-primary, maps run_terminal_cmd/read_file/write_file/process_state to OpenClaw RPC methods (exec/read/write/process), enables Docker sandboxing for offensive tools, configures channel routing, and registers a CronService job weekly-attack-surface-recon with computeNextRunAtMs enabled.
  • Implemented an adapter bridge integrations/openclaw/openclaw_gateway_adapter.py that connects to the OpenClaw WebSocket (ws://127.0.0.1:18789/gateway), calls NeuroRift FastAPI at http://127.0.0.1:8766/execute, translates tool calls into RPC frames, enforces isolated session metadata, normalizes AI provider env keys, and forwards high-risk command approvals to Discord/Telegram (deny-on-timeout safe default).
  • Added operational runbooks and persona artifacts BOOT.md, HEARTBEAT.md, and SOUL.md to document startup, proactive monitoring checks, and persistent persona/memory anchors for session state and attack-surface context.
  • Approval forwarding implements pattern matching for high-risk commands (e.g. nmap -p-, --script, sqlmap, msfconsole, rm -rf, curl | sh) and sends notifications to configured OPENCLAW_DISCORD_WEBHOOK_URL and Telegram bot settings as a secure baseline placeholder for human callbacks.

Testing

  • Performed a syntax check with python3 -m py_compile integrations/openclaw/openclaw_gateway_adapter.py which completed successfully.
  • Verified presence and basic formatting of openclaw.json5, BOOT.md, HEARTBEAT.md, and SOUL.md as part of the integration artifacts.

Codex Task


CodeAnt-AI Description

Integrate NeuroRift with OpenClaw gateway; isolated sessions and approval forwarding

What Changed

  • NeuroRift can run as an OpenClaw agent: an adapter forwards NeuroRift tool calls to the OpenClaw gateway and opens sessions marked "isolated".
  • High-risk command patterns (e.g., nmap -p-, sqlmap, rm -rf, curl | sh) are intercepted and notifications are sent to configured Discord and Telegram channels; such commands default to deny if no approval is received.
  • Environment keys for AI providers are normalized so provider credentials (OpenAI, Anthropic/Claude, Z.AI) are consistently available.
  • Included runnable configuration and runbooks: unified OpenClaw config, adapter script, persona (SOUL.md), boot and heartbeat checklists to validate end-to-end behavior and scheduling.

Impact

✅ Isolated NeuroRift sessions
✅ High-risk commands require approval via Discord/Telegram
✅ Consistent AI provider env variables

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • New Features

    • Integrated OpenClaw gateway adapter with approval-based execution for high-risk commands.
    • Runtime configuration supporting agent orchestration, sandboxing, task pipelines, scheduling, and cross-channel routing.
  • Documentation

    • Added boot runbook, operational monitoring checklist, and agent operating principles guide.

@codeant-ai
Copy link
Copy Markdown

codeant-ai Bot commented Feb 27, 2026

CodeAnt AI is reviewing your PR.

Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

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

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

This commit fixes the style issues introduced in 8e69408 according to the output
from Black.

Details: #24
@codeant-ai codeant-ai Bot added the size:XL This PR changes 500-999 lines, ignoring generated files label Feb 27, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 27, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d8231f and a9e80b9.

📒 Files selected for processing (5)
  • BOOT.md
  • HEARTBEAT.md
  • SOUL.md
  • integrations/openclaw/openclaw_gateway_adapter.py
  • openclaw.json5

📝 Walkthrough

Walkthrough

This pull request introduces a NeuroRift + OpenClaw gateway integration, consisting of a new adapter module that bridges tool calls between services, enforces high-risk command approvals via Discord and Telegram notifications, manages environment secrets across providers, and implements isolated session handling. Supporting documentation outlines boot sequences, monitoring checklists, and agent operating principles.

Changes

Cohort / File(s) Summary
Documentation & Runbooks
BOOT.md, HEARTBEAT.md, SOUL.md
New documentation files defining boot sequence steps, proactive monitoring checklist covering runtime liveness and security controls, and NeuroRift persona operating principles with persistent memory anchors.
Gateway Adapter Implementation
integrations/openclaw/openclaw_gateway_adapter.py
New adapter module providing environment normalization, high-risk command detection via regex patterns, execution approval forwarding to Discord/Telegram with timeout handling, RPC frame construction, NeuroRift bridge communication, and WebSocket event orchestration.
Runtime Configuration
openclaw.json5
New comprehensive configuration file defining gateway settings, agent properties, execution bridge mappings, multi-stage task pipeline, Docker sandbox policies, approval forwarding rules, channel routing, scheduled cron jobs, memory persistence, environment normalization, and observability settings.

Sequence Diagram(s)

sequenceDiagram
    participant GW as OpenClaw Gateway
    participant Adapter as NeuroRiftOpenClawAdapter
    participant Approver as ExecutionApprovalForwarder
    participant Discord as Discord/Telegram
    participant Bridge as NeuroRift Bridge
    
    GW->>Adapter: neurorift.tool_call event
    Adapter->>Adapter: _build_rpc_frame()
    Adapter->>Approver: evaluate(command, session_id)
    Approver->>Approver: _is_high_risk(command)
    
    alt High-Risk Command
        Approver->>Discord: _notify_discord/telegram(content)
        Discord-->>Approver: approval response (or timeout)
        Approver-->>Adapter: ApprovalResult {approved, reason}
    else Low-Risk Command
        Approver-->>Adapter: ApprovalResult {approved: true}
    end
    
    alt Approved
        Adapter->>Bridge: _call_neurorift(payload) via HTTP POST
        Bridge-->>Adapter: execution result
        Adapter->>Adapter: build rpc.request frame
        Adapter->>GW: send rpc.request
    else Denied/Timeout
        Adapter->>Adapter: build rpc.reject frame
        Adapter->>GW: send rpc.reject (approval_required)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐰 A gateway blooms where bridges meet,
With safety checks and Discord's beat—
The NeuroRift and Claw align,
Approvals flow through threads divine,
One adapter hops from soul to soul! 🌟

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/integrate-neurorift-with-openclaw-gateway

Comment @coderabbitai help to get the list of available commands and usage tips.

@Neuro-Rift Neuro-Rift merged commit 5d354a3 into main Feb 27, 2026
3 of 5 checks passed
@deepsource-io
Copy link
Copy Markdown
Contributor

deepsource-io Bot commented Feb 27, 2026

DeepSource Code Review

We reviewed changes in 5d8231f...a9e80b9 on this pull request. Below is the summary for the review, and you can see the individual issues we found as inline review comments.

See full review on DeepSource ↗

PR Report Card

Overall Grade  

Focus Area: Complexity
Security  

Reliability  

Complexity  

Hygiene  

Code Review Summary

Analyzer Status Updated (UTC) Details
Python Feb 27, 2026 12:09p.m. Review ↗

@codeant-ai
Copy link
Copy Markdown

codeant-ai Bot commented Feb 27, 2026

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • Pattern Matching Bug
    High-risk pattern matching is performed against a JSON-dumped tool_call (escaped JSON) rather than the raw command string. This can cause false negatives because quotes/escaping and nested fields will break regex matches intended for literal shell commands.

  • Webhook Leakage
    The adapter posts the full command preview/payload to external webhooks (Discord/Telegram) including potentially sensitive content (file contents, credentials, tokens). The notification code also depends on env tokens; ensure content is sanitized/redacted before transmission and audit what is sent.

  • Approval Flow
    The async approval flow is a placeholder that immediately returns deny-on-timeout without any mechanism to wait for or receive a real approval callback. This means high-risk commands will always be rejected (or remain pending) in production unless a callback integration is added; it's also unclear how long callers should expect to wait and there is no backoff/retry or observable state update for approvals.

  • Approval Forwarder Failover
    The approval forwarder defaults to "deny" with a 300s timeout and forwards approvals to external channels (Discord/Telegram). If webhook/bot env variables are not set or unreachable, legitimate actions may be blocked for long periods. Validate fallback behavior and alerting when forward destinations are misconfigured.

  • High-risk Pattern Precision
    The configured highRiskPatterns are provided as simple strings and some are broad (e.g., "rm -rf", "nmap .* -p-") which can produce both false positives and false negatives. Patterns should be canonicalized as well-formed regular expressions with boundaries and explicit intent to avoid bypasses and unintended matches.

Comment on lines +134 to +169
async def _build_rpc_frame(self, tool_call: Dict[str, Any]) -> Dict[str, Any]:
rpc_method = self._map_method(tool_call)
command_preview = json.dumps(tool_call, ensure_ascii=False)

approval = await self.approval_forwarder.evaluate(command_preview, self.session_id)
if not approval.approved:
return {
"type": "rpc.reject",
"id": str(uuid.uuid4()),
"session": {"id": self.session_id, "mode": "isolated"},
"error": {
"code": "approval_required",
"message": approval.reason,
},
}

bridged = await self._call_neurorift(tool_call)

return {
"type": "rpc.request",
"id": str(uuid.uuid4()),
"session": {
"id": self.session_id,
"mode": "isolated",
"pipeline": ["planner", "tool-selector/manus", "operator", "analyst/cursor"],
},
"method": rpc_method,
"params": {
"source": "neurorift-fastapi",
"bridgePort": 8766,
"gatewayPort": 18789,
"yieldMs": YIELD_MS,
"payload": bridged,
},
"ts": int(time.time() * 1000),
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggestion: The HTTP call to the NeuroRift FastAPI bridge in _call_neurorift is used directly in _build_rpc_frame without any error handling, so if /execute is unavailable or returns a non-2xx status (triggering httpx HTTP errors), the exception will bubble up and crash the adapter instead of returning a structured RPC error to the OpenClaw gateway. [possible bug]

Severity Level: Major ⚠️
- ❌ Adapter process crashes when NeuroRift FastAPI /execute returns error.
- ⚠️ OpenClaw gateway loses active isolated NeuroRift session connection.
- ⚠️ High-risk command approvals fail when bridge temporarily unavailable.
Suggested change
async def _build_rpc_frame(self, tool_call: Dict[str, Any]) -> Dict[str, Any]:
rpc_method = self._map_method(tool_call)
command_preview = json.dumps(tool_call, ensure_ascii=False)
approval = await self.approval_forwarder.evaluate(command_preview, self.session_id)
if not approval.approved:
return {
"type": "rpc.reject",
"id": str(uuid.uuid4()),
"session": {"id": self.session_id, "mode": "isolated"},
"error": {
"code": "approval_required",
"message": approval.reason,
},
}
bridged = await self._call_neurorift(tool_call)
return {
"type": "rpc.request",
"id": str(uuid.uuid4()),
"session": {
"id": self.session_id,
"mode": "isolated",
"pipeline": ["planner", "tool-selector/manus", "operator", "analyst/cursor"],
},
"method": rpc_method,
"params": {
"source": "neurorift-fastapi",
"bridgePort": 8766,
"gatewayPort": 18789,
"yieldMs": YIELD_MS,
"payload": bridged,
},
"ts": int(time.time() * 1000),
}
async def _build_rpc_frame(self, tool_call: Dict[str, Any]) -> Dict[str, Any]:
rpc_method = self._map_method(tool_call)
command_preview = json.dumps(tool_call, ensure_ascii=False)
approval = await self.approval_forwarder.evaluate(command_preview, self.session_id)
if not approval.approved:
return {
"type": "rpc.reject",
"id": str(uuid.uuid4()),
"session": {"id": self.session_id, "mode": "isolated"},
"error": {
"code": "approval_required",
"message": approval.reason,
},
}
try:
bridged = await self._call_neurorift(tool_call)
except httpx.HTTPError as exc:
return {
"type": "rpc.reject",
"id": str(uuid.uuid4()),
"session": {"id": self.session_id, "mode": "isolated"},
"error": {
"code": "bridge_unavailable",
"message": f"neurorift-fastapi error: {exc}",
},
}
return {
"type": "rpc.request",
"id": str(uuid.uuid4()),
"session": {
"id": self.session_id,
"mode": "isolated",
"pipeline": ["planner", "tool-selector/manus", "operator", "analyst/cursor"],
},
"method": rpc_method,
"params": {
"source": "neurorift-fastapi",
"bridgePort": 8766,
"gatewayPort": 18789,
"yieldMs": YIELD_MS,
"payload": bridged,
},
"ts": int(time.time() * 1000),
}
Steps of Reproduction ✅
1. Configure and start the OpenClaw gateway using `openclaw.json5` at
`/workspace/NeuroRift/openclaw.json5`, which defines the `neurorift-primary` agent
entrypoint as `python3 integrations/openclaw/openclaw_gateway_adapter.py` (line 23).

2. Start the adapter process so `NeuroRiftOpenClawAdapter.run()` in
`integrations/openclaw/openclaw_gateway_adapter.py:171-201` connects to the WebSocket
gateway at `GATEWAY_WS_URL` and enters the `while True` loop receiving events.

3. Ensure the NeuroRift FastAPI bridge at `BRIDGE_URL` (default `http://127.0.0.1:8766`)
is unavailable or unhealthy, e.g. do not start the FastAPI service or configure it to
return HTTP 500 for `POST /execute`, which `NeuroRiftOpenClawAdapter._call_neurorift()` at
lines 128-132 calls via `httpx.AsyncClient.post(..., json=payload)` followed by
`response.raise_for_status()`.

4. From the OpenClaw side, trigger any workflow that causes a `neurorift.tool_call` event
to be sent over the gateway WebSocket; the adapter's `run()` method (lines 190-197)
receives the message, decodes it, and for events with `type == "neurorift.tool_call"`
calls `frame = await self._build_rpc_frame(event.get("payload", {}))` where
`_build_rpc_frame()` (lines 134-169) invokes `bridged = await
self._call_neurorift(tool_call)` (line 150), which raises `httpx.HTTPError` due to the
failing `/execute` call, propagating out of `_build_rpc_frame()` and `run()` without being
caught, causing `asyncio.run(NeuroRiftOpenClawAdapter().run())` at line 201 to terminate
and the adapter WebSocket session to drop instead of returning a structured `rpc.reject`
frame to the gateway.
Prompt for AI Agent 🤖
This is a comment left during a code review.

**Path:** integrations/openclaw/openclaw_gateway_adapter.py
**Line:** 134:169
**Comment:**
	*Possible Bug: The HTTP call to the NeuroRift FastAPI bridge in `_call_neurorift` is used directly in `_build_rpc_frame` without any error handling, so if `/execute` is unavailable or returns a non-2xx status (triggering `httpx` HTTP errors), the exception will bubble up and crash the adapter instead of returning a structured RPC error to the OpenClaw gateway.

Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
👍 | 👎

@codeant-ai
Copy link
Copy Markdown

codeant-ai Bot commented Feb 27, 2026

CodeAnt AI finished reviewing your PR.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8e69408c56

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

},
}

bridged = await self._call_neurorift(tool_call)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Send bridge-compatible command types

_build_rpc_frame posts the raw tool_call to /execute, but _map_method indicates those calls are run_terminal_cmd/read_file/write_file; the FastAPI bridge only handles ai_generate, tool_execute, robin_search, and browser_action (modules/web/bridge_server.py, lines 64-73), so these mapped calls are returned as "Unknown command type" and then forwarded as an RPC request payload. In practice this breaks the new adapter flow for the very command families it maps.

Useful? React with 👍 / 👎.

Comment on lines +89 to +93
# Placeholder for channel callback integration.
# Default-safe behavior is deny-on-timeout.
await asyncio.sleep(0)
return ApprovalResult(approved=False, reason="approval pending/timeout -> deny")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Honor approval responses before rejecting risky commands

For any command matching HIGH_RISK_PATTERNS, evaluate sends notifications and then immediately returns approved=False without waiting for any callback path, so high-risk operations are always denied even if an operator responds "APPROVE" in Discord/Telegram. This makes human-in-the-loop approval non-functional and blocks planned recon actions like full-port scans.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex size:XL This PR changes 500-999 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant