-
Notifications
You must be signed in to change notification settings - Fork 0
Add NeuroRift package scaffold, runtime & model checks, secure command runner, CLI and skill system #39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Add NeuroRift package scaffold, runtime & model checks, secure command runner, CLI and skill system #39
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,99 @@ | ||||||||||||
| """Ollama model capability verification for autonomous NeuroRift agent mode.""" | ||||||||||||
|
|
||||||||||||
| from __future__ import annotations | ||||||||||||
|
|
||||||||||||
| import json | ||||||||||||
| import subprocess | ||||||||||||
| from typing import Any | ||||||||||||
|
|
||||||||||||
| CAPABILITY_PROMPT = """Evaluate whether you can reliably perform the following tasks: | ||||||||||||
|
|
||||||||||||
| * structured tool invocation | ||||||||||||
| * Linux command generation | ||||||||||||
| * file creation and modification | ||||||||||||
| * interpreting tool outputs | ||||||||||||
| * multi-step reasoning for autonomous agents | ||||||||||||
|
|
||||||||||||
| Return a JSON response: | ||||||||||||
| { | ||||||||||||
| "tool_usage": true/false, | ||||||||||||
| "command_generation": true/false, | ||||||||||||
| "filesystem_operations": true/false, | ||||||||||||
| "multi_step_reasoning": true/false, | ||||||||||||
| "agent_ready": true/false | ||||||||||||
| }""" | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| def _extract_json(raw_text: str) -> dict[str, Any]: | ||||||||||||
| raw_text = (raw_text or "").strip() | ||||||||||||
| start = raw_text.find("{") | ||||||||||||
| end = raw_text.rfind("}") | ||||||||||||
| if start == -1 or end == -1 or end <= start: | ||||||||||||
| raise ValueError("No JSON object found in model response") | ||||||||||||
| return json.loads(raw_text[start : end + 1]) | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| def verify_model_capabilities(model_name: str) -> dict[str, Any]: | ||||||||||||
| try: | ||||||||||||
| proc = subprocess.run( | ||||||||||||
| ["ollama", "run", model_name, CAPABILITY_PROMPT], | ||||||||||||
| capture_output=True, | ||||||||||||
| text=True, | ||||||||||||
| timeout=120, | ||||||||||||
| check=False, | ||||||||||||
| ) | ||||||||||||
| except FileNotFoundError: | ||||||||||||
| return {"ok": False, "error": "ollama_missing", "agent_ready": False} | ||||||||||||
| except Exception as exc: # defensive for unstable environments | ||||||||||||
| return { | ||||||||||||
| "ok": False, | ||||||||||||
| "error": f"ollama_exec_error:{type(exc).__name__}", | ||||||||||||
| "agent_ready": False, | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| if proc.returncode != 0: | ||||||||||||
| return { | ||||||||||||
| "ok": False, | ||||||||||||
| "error": f"ollama_returned_{proc.returncode}", | ||||||||||||
| "stderr": proc.stderr, | ||||||||||||
| "agent_ready": False, | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| try: | ||||||||||||
| parsed = _extract_json(proc.stdout) | ||||||||||||
| except Exception as exc: | ||||||||||||
| return { | ||||||||||||
| "ok": False, | ||||||||||||
| "error": f"invalid_capability_json:{type(exc).__name__}", | ||||||||||||
| "raw": proc.stdout[:1000], | ||||||||||||
| "agent_ready": False, | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| required = { | ||||||||||||
| "tool_usage", | ||||||||||||
| "command_generation", | ||||||||||||
| "filesystem_operations", | ||||||||||||
| "multi_step_reasoning", | ||||||||||||
| "agent_ready", | ||||||||||||
| } | ||||||||||||
| if not required.issubset(parsed): | ||||||||||||
| return { | ||||||||||||
| "ok": False, | ||||||||||||
| "error": "capability_fields_missing", | ||||||||||||
| "parsed": parsed, | ||||||||||||
|
Comment on lines
+82
to
+83
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion: Severity Level: Critical 🚨- ❌ `run-agent` readiness gate bypassed by string booleans.
- ⚠️ Autonomous mode may run with unsupported models.
Suggested change
Steps of Reproduction ✅1. Start from the real gate path: `run-agent` in `_async_main`
(`neurorift_main.py:1007-1023`) calls `verify_model_capabilities()` at
`neurorift_main.py:1018`.
2. Return a capability JSON object where required keys exist but `agent_ready` is a
string, e.g. `"agent_ready": "false"` (parsed in `model_capability_check.py:58`, required
fields validated at `model_capability_check.py:67-80`).
3. Current code sets `parsed["ok"] = bool(parsed.get("agent_ready"))`
(`model_capability_check.py:82`), which converts non-empty `"false"` to `True`.
4. `run-agent` then checks `if not capability.get("agent_ready")`
(`neurorift_main.py:1019`); string `"false"` is truthy, so the failure branch is skipped
and agent runtime proceeds incorrectly.Prompt for AI Agent 🤖This is a comment left during a code review.
**Path:** model_capability_check.py
**Line:** 82:83
**Comment:**
*Logic Error: `agent_ready` is used as a truthy value without enforcing boolean type, so a model returning `"false"` (string) is treated as ready by callers because non-empty strings are truthy. Normalize `agent_ready` to a strict boolean before returning.
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. |
||||||||||||
| "agent_ready": False, | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| parsed["ok"] = bool(parsed.get("agent_ready")) | ||||||||||||
| return parsed | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| if __name__ == "__main__": | ||||||||||||
| import argparse | ||||||||||||
|
|
||||||||||||
| parser = argparse.ArgumentParser( | ||||||||||||
| description="Check Ollama model capability for NeuroRift agent mode" | ||||||||||||
| ) | ||||||||||||
| parser.add_argument("--model", required=True) | ||||||||||||
| args = parser.parse_args() | ||||||||||||
| print(json.dumps(verify_model_capabilities(args.model), indent=2)) | ||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class ChannelRouter: | ||
| def route(self, msg: dict): | ||
| return msg |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| class Channel: | ||
| def connect(self): | ||
| return True | ||
|
|
||
| def receive_message(self, payload=None): | ||
| return payload or {} | ||
|
|
||
| def send_message(self, message): | ||
| return message | ||
|
|
||
| def close(self): | ||
| return True |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| class Channel: | ||
| def connect(self): | ||
| return True | ||
|
|
||
| def receive_message(self, payload=None): | ||
| return payload or {} | ||
|
|
||
| def send_message(self, message): | ||
| return message | ||
|
|
||
| def close(self): | ||
| return True |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| class Channel: | ||
| def connect(self): | ||
| return True | ||
|
|
||
| def receive_message(self, payload=None): | ||
| return payload or {} | ||
|
|
||
| def send_message(self, message): | ||
| return message | ||
|
|
||
| def close(self): | ||
| return True |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| class Channel: | ||
| def connect(self): | ||
| return True | ||
|
|
||
| def receive_message(self, payload=None): | ||
| return payload or {} | ||
|
|
||
| def send_message(self, message): | ||
| return message | ||
|
|
||
| def close(self): | ||
| return True |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| class ClawHubAPI: | ||
| base_url = "https://clawhub.example/api" |
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,18 @@ | ||||||||||
| from pathlib import Path | ||||||||||
| import shutil | ||||||||||
|
|
||||||||||
|
|
||||||||||
| class ClawHubClient: | ||||||||||
| def __init__(self, cache_dir: Path): | ||||||||||
| self.cache_dir = cache_dir | ||||||||||
| cache_dir.mkdir(parents=True, exist_ok=True) | ||||||||||
|
|
||||||||||
| def fetch_skill(self, skill_name: str, source_dir: Path) -> Path: | ||||||||||
| src = source_dir / skill_name | ||||||||||
| if not src.exists(): | ||||||||||
| raise FileNotFoundError(skill_name) | ||||||||||
|
Comment on lines
+12
to
+13
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion: The existence check accepts regular files, but Severity Level: Major
|
||||||||||
| if not src.exists(): | |
| raise FileNotFoundError(skill_name) | |
| if not src.is_dir(): | |
| raise FileNotFoundError(skill_name) |
Steps of Reproduction ✅
1. Execute `python3 /workspace/NeuroRift/neurorift_main.py --clawhub __init__.py`;
`--clawhub` input is accepted by parser at `neurorift_main.py:914` and routed to
`install_clawhub()` at `neurorift_main.py:982-983`.
2. `SkillManager.install_clawhub()` forwards `__init__.py` directly to `fetch_skill()` at
`neurorift/skills/skill_manager.py:13-14`.
3. In `fetch_skill()`, existence-only check passes (`src.exists()`) at
`neurorift/clawhub/clawhub_client.py:7` because
`/workspace/NeuroRift/neurorift/skill_store/installed/__init__.py` is a real file
(verified in `neurorift/skill_store/installed` listing).
4. `shutil.copytree(src, dst)` at `neurorift/clawhub/clawhub_client.py:10` then raises
`NotADirectoryError`, aborting the install path.Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** neurorift/clawhub/clawhub_client.py
**Line:** 12:13
**Comment:**
*Possible Bug: The existence check accepts regular files, but `shutil.copytree` only works on directories; if a file exists with that name, this path raises `NotADirectoryError` at runtime. Validate that the source is a directory.
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.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reject traversal in skill_name before touching the filesystem.
skill_name is joined directly into both source_dir and cache_dir. Values like ../foo can make Line 16 delete outside the cache root and Line 17 copy arbitrary directories into it.
Suggested fix
def fetch_skill(self, skill_name: str, source_dir: Path) -> Path:
- src = source_dir / skill_name
- if not src.exists():
+ src_root = source_dir.resolve()
+ dst_root = self.cache_dir.resolve()
+ src = (src_root / skill_name).resolve()
+ dst = (dst_root / skill_name).resolve()
+ if src_root not in src.parents or dst_root not in dst.parents:
+ raise ValueError("invalid skill name")
+ if not src.is_dir():
raise FileNotFoundError(skill_name)
- dst = self.cache_dir / skill_name
if dst.exists():
shutil.rmtree(dst)
shutil.copytree(src, dst)
return dst🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@neurorift/clawhub/clawhub_client.py` around lines 10 - 17, Reject path
traversal in fetch_skill by validating skill_name before any filesystem
operations: ensure skill_name is a single path segment (no "..", no absolute
paths, no path separators) and normalize/resolve only after validation; use the
validated name to build src = source_dir / skill_name and dst = self.cache_dir /
skill_name, then proceed to check existence and perform
shutil.rmtree/shutil.copytree. Refer to symbols fetch_skill, skill_name,
source_dir, cache_dir, src, and dst when making the change.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class ClawHubResolver: | ||
| def resolve(self, skill_name: str) -> str: | ||
| return f"https://clawhub.example/skills/{skill_name}" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| """Package-level CLI helper that delegates to global entrypoint.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from neurorift_cli import build_parser, install_global_wrapper, main | ||
|
|
||
| __all__ = ["build_parser", "install_global_wrapper", "main"] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| CHANNELS = ["cli", "websocket", "discord", "telegram", "api"] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| MODEL_PROVIDERS = ["deepseek", "mistral", "llama", "openai"] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| @dataclass | ||
| class Settings: | ||
| data_dir: Path = Path.home() / ".neurorift" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class AgentLoop: | ||
| async def handle_message(self, session, message: str) -> dict: | ||
| return {"success": True, "response": f"Session {session.session_id}: {message}"} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| from dataclasses import dataclass | ||
| from neurorift.core.agent_loop import AgentLoop | ||
| from neurorift.sessions.session_manager import SessionManager | ||
|
|
||
|
|
||
| @dataclass | ||
| class AgentHandle: | ||
| session_id: str | ||
| user_id: str | ||
| channel: str | ||
|
|
||
|
|
||
| class AgentManager: | ||
| def __init__(self, session_manager: SessionManager, agent_loop: AgentLoop): | ||
| self.session_manager = session_manager | ||
| self.agent_loop = agent_loop | ||
| self.handles: dict[str, AgentHandle] = {} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass | ||
| class PlannedStep: | ||
| order: int | ||
| action: str | ||
|
|
||
|
|
||
| class Planner: | ||
| def create_plan(self, objective: str) -> list[PlannedStep]: | ||
| return ( | ||
| [PlannedStep(order=1, action=f"Investigate: {objective}")] | ||
| if objective | ||
| else [] | ||
| ) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class TaskRouter: | ||
| def route(self, task: str) -> dict: | ||
| return {"task": task, "route": "agent_loop"} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,12 @@ | ||||||||||||||||||||||
| import subprocess | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
|
|
||||||||||||||||||||||
| class CommandRunner: | ||||||||||||||||||||||
| def run(self, cmd: list[str]): | ||||||||||||||||||||||
| p = subprocess.run(cmd, capture_output=True, text=True, check=False) | ||||||||||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion: If the executable in the command does not exist, Severity Level: Major
|
||||||||||||||||||||||
| p = subprocess.run(cmd, capture_output=True, text=True, check=False) | |
| try: | |
| p = subprocess.run(cmd, capture_output=True, text=True, check=False) | |
| except FileNotFoundError as exc: | |
| return { | |
| "success": False, | |
| "stdout": "", | |
| "stderr": str(exc), | |
| "exit_code": 127, | |
| } |
Steps of Reproduction ✅
1. Confirm this runner is currently scaffolded but callable:
`neurorift/execution/command_runner.py:2-5`; no internal caller found except subclass
declaration `neurorift/execution/sandbox_runner.py:1-3`.
2. Execute `from neurorift.execution.command_runner import CommandRunner;
CommandRunner().run(["definitely_not_installed_bin"])`.
3. Call reaches `subprocess.run(...)` at `command_runner.py:4` with nonexistent
executable.
4. Observe uncaught `FileNotFoundError`, so no `{success, stderr, exit_code}` response is
returned.Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** neurorift/execution/command_runner.py
**Line:** 6:6
**Comment:**
*Possible Bug: If the executable in the command does not exist, `subprocess.run` raises `FileNotFoundError` and the method crashes. Catch this exception and return a normal error payload so callers can handle missing tools safely.
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.| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| from dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass | ||
| class ResourceLimits: | ||
| timeout_seconds: int = 30 | ||
| memory_limit_mb: int = 512 | ||
| cpu_seconds: int = 20 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import time | ||
|
|
||
|
|
||
| class RetryManager: | ||
| def __init__(self, retries=2): | ||
| self.retries = retries | ||
|
|
||
| def wait(self, attempt): | ||
| time.sleep(2**attempt) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from neurorift.execution.command_runner import CommandRunner | ||
|
|
||
|
|
||
| class SandboxRunner(CommandRunner): | ||
| pass |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class APIServer: | ||
| def start(self): | ||
| return True |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class AuthManager: | ||
| def validate(self, token: str): | ||
| return bool(token) | ||
|
Comment on lines
+2
to
+3
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Line [3] accepts arbitrary non-empty input as valid credentials. This is a critical auth flaw; validation must be cryptographic/authoritative and fail closed on errors. Safer pattern (inject verifier, fail closed) class AuthManager:
- def validate(self, token: str):
- return bool(token)
+ def __init__(self, token_verifier):
+ self._token_verifier = token_verifier
+
+ def validate(self, token: str) -> bool:
+ if not isinstance(token, str) or not token.strip():
+ return False
+ try:
+ return bool(self._token_verifier(token))
+ except Exception:
+ return False🤖 Prompt for AI Agents |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class WebSocketGateway: | ||
| def start(self): | ||
| return True |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| class LongTermMemory: | ||
| def __init__(self): | ||
| self.data = {} | ||
|
|
||
| def store(self, user_id: str, key: str, value): | ||
| self.data.setdefault(user_id, {})[key] = value |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class MemoryCompaction: | ||
| def compact(self, messages: list[str]): | ||
| return {"summary": " ".join(messages[:10]), "kept": messages[-10:]} |
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,9 @@ | ||||||||||||||||||||||||||||||||||||
| from collections import defaultdict, deque | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| class ShortTermMemory: | ||||||||||||||||||||||||||||||||||||
| def __init__(self, limit: int = 30): | ||||||||||||||||||||||||||||||||||||
| self.buffers = defaultdict(lambda: deque(maxlen=limit)) | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| def add(self, sid: str, msg: str): | ||||||||||||||||||||||||||||||||||||
| self.buffers[sid].append(msg) | ||||||||||||||||||||||||||||||||||||
|
Comment on lines
+5
to
+9
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion: Severity Level: Major
|
||||||||||||||||||||||||||||||||||||
| def __init__(self, limit: int = 30): | |
| self.buffers = defaultdict(lambda: deque(maxlen=limit)) | |
| def add(self, sid: str, msg: str): | |
| self.buffers[sid].append(msg) | |
| def __init__(self, limit: int = 30, max_sessions: int = 1000): | |
| self.buffers = defaultdict(lambda: deque(maxlen=limit)) | |
| self.max_sessions = max_sessions | |
| self._session_order = deque() | |
| def add(self, sid: str, msg: str): | |
| if sid not in self.buffers: | |
| if len(self._session_order) >= self.max_sessions: | |
| oldest_sid = self._session_order.popleft() | |
| self.buffers.pop(oldest_sid, None) | |
| self._session_order.append(sid) | |
| self.buffers[sid].append(msg) |
Steps of Reproduction ✅
1. Verify exposure: `setup.py:6` packages `neurorift.*`, so
`neurorift.memory.short_term_memory.ShortTermMemory` is importable API.
2. Verify current implementation: `neurorift/memory/short_term_memory.py:3-4` stores
messages in `self.buffers[sid]` with no session-count guard.
3. Use realistic session IDs from `neurorift/sessions/session_manager.py:10-12`
(`uuid4`-style `sid`) and repeatedly call `ShortTermMemory.add(sid, msg)` with new IDs.
4. Observe unbounded key growth (`len(memory.buffers)` keeps increasing) because each new
`sid` creates a new deque and no eviction path exists.Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** neurorift/memory/short_term_memory.py
**Line:** 5:9
**Comment:**
*Resource Leak: `buffers` is bounded per session but unbounded in number of sessions, so repeatedly adding messages for new `sid` values grows memory forever and can eventually exhaust process memory. Add a cap on tracked sessions and evict the oldest session buffer when that cap is reached.
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.| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| class VectorMemory: | ||
| def semantic_search(self, user_id: str, query: str, top_k: int = 5): | ||
| return [] | ||
|
|
||
| def time_based_retrieval(self, user_id: str, limit: int = 10): | ||
| return [] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class ContextBuilder: | ||
| def build(self, session, memories): | ||
| return {"session": session.session_id, "memories": memories} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class ModelFailover: | ||
| def pick(self, providers): | ||
| return providers[0] if providers else "fallback" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| class ModelRouter: | ||
| async def generate(self, prompt: str): | ||
| return { | ||
| "response": prompt, | ||
| "model": "openai", | ||
| "tokens": len(prompt.split()), | ||
| "cost": 0.0, | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| class PromptBuilder: | ||
| def build(self, message: str, context: dict): | ||
| return f"{context}\n{message}" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
|
|
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,29 @@ | ||||||||||||||
| from dataclasses import dataclass, field | ||||||||||||||
| from enum import Enum | ||||||||||||||
| from datetime import datetime, timezone | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| class SessionState(str, Enum): | ||||||||||||||
| CREATED = "CREATED" | ||||||||||||||
| ACTIVE = "ACTIVE" | ||||||||||||||
| IDLE = "IDLE" | ||||||||||||||
| PAUSED = "PAUSED" | ||||||||||||||
| CLOSED = "CLOSED" | ||||||||||||||
|
|
||||||||||||||
|
|
||||||||||||||
| @dataclass | ||||||||||||||
| class SessionContext: | ||||||||||||||
| session_id: str | ||||||||||||||
| user_id: str | ||||||||||||||
| channel: str | ||||||||||||||
| state: SessionState = SessionState.CREATED | ||||||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion: Severity Level: Major
|
||||||||||||||
| state: SessionState = SessionState.CREATED | |
| state: SessionState = SessionState.CREATED | |
| def __post_init__(self) -> None: | |
| if isinstance(self.state, str): | |
| self.state = SessionState(self.state) |
Steps of Reproduction ✅
1. Create and persist a session through `SessionManager.create_session()` at
`neurorift/sessions/session_manager.py:10-12`; this calls `SessionStore.save()` at
`neurorift/sessions/session_store.py:9`.
2. Simulate a new process (new `SessionManager` instance) and call
`SessionManager.get_session()` at `neurorift/sessions/session_manager.py:13`; this falls
through to `SessionStore.load()` at `neurorift/sessions/session_store.py:10-12`.
3. `SessionStore.load()` reconstructs via `SessionContext(**json.loads(...))`
(`neurorift/sessions/session_store.py:12`), while `SessionContext` has no `__post_init__`
normalization (`neurorift/sessions/session_context.py:8-19`), so `state` remains plain
`str`.
4. Access enum semantics on the loaded object (for example `loaded.state.name`) and
observe runtime failure: `AttributeError: 'str' object has no attribute 'name'` (verified
by executing this exact call chain with `PYTHONPATH=/workspace/NeuroRift`).Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** neurorift/sessions/session_context.py
**Line:** 19:19
**Comment:**
*Type Error: `SessionStore.load()` rebuilds this dataclass from JSON, where `state` comes back as a plain string. Without normalization, the object violates its own contract (`SessionState`) and will break when enum behavior is expected (for example accessing enum attributes). Coerce string input to `SessionState` in `__post_init__`.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Suggestion: The JSON parser currently slices from the first
{to the last}in the whole response, which breaks when the model outputs extra brace-containing text before or after the JSON object. This causes valid capability responses to be rejected as invalid JSON. Parse the first decodable JSON object instead of using greedy brace slicing. [logic error]Severity Level: Major⚠️
Steps of Reproduction ✅
Prompt for AI Agent 🤖