Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat: harness trading — persistent memory, session search, skill CRUD, 5-layer compression, tool batching

warren618e2a4654edb09
diff --git a/agent/cli.py b/agent/cli.py
index 37f717668..eff5556ce 100644
--- a/agent/cli.py
+++ b/agent/cli.py
@@ -172,17 +172,10 @@ def _format_tool_call_args(tool: str, args: Dict[str, str]) -> str:
if tool in ("bash", "background_run"):
cmd = args.get("command", "")[:80]
return f' [yellow]{cmd}[/yellow]'
- if tool == "subagent":
- desc = args.get("description", args.get("prompt", "")[:60])
- return f' [magenta]{desc}[/magenta]'
- if tool == "task_create":
- return f' "{args.get("subject", "")}"'
- if tool == "task_update":
- return f' #{args.get("task_id", "")} -> {args.get("status", "")}'
if tool == "check_background":
tid = args.get("task_id", "")
return f' {tid}' if tid else ""
- if tool in ("backtest", "compact", "task_list"):
+ if tool in ("backtest", "compact"):
return ""
for v in args.values():
if v and v != "None":
@@ -207,11 +200,6 @@ def _format_tool_result_preview(tool: str, status: str, preview: str) -> str:
if "OK" in preview[:50]:
return "OK"
return preview[:60].replace("\n", " ")
- if tool == "subagent":
- m = re.search(r'"summary":\s*"(.{0,80})', preview)
- return m.group(1).rstrip('"') if m else ""
- if tool in ("task_create", "task_update"):
- return preview[:60].replace("\n", " ")
if tool in ("read_file", "load_skill", "compact"):
return ""
return ""
@@ -283,11 +271,15 @@ def _run_agent(
tokens = data.get("tokens_before", "?")
console.print(f"\n [yellow]\u27f3 context compressed[/yellow] [dim]({tokens} tokens \u2192 summary)[/dim]\n")
+ from src.memory.persistent import PersistentMemory
+
+ pm = PersistentMemory()
agent = AgentLoop(
- registry=build_registry(),
+ registry=build_registry(persistent_memory=pm),
llm=ChatLLM(),
event_callback=on_event,
max_iterations=max_iter,
+ persistent_memory=pm,
)
if run_dir_override:
agent.memory.run_dir = run_dir_override
diff --git a/agent/src/agent/context.py b/agent/src/agent/context.py
index f1fd6bcce..03972e71c 100644
--- a/agent/src/agent/context.py
+++ b/agent/src/agent/context.py
@@ -3,14 +3,20 @@
from __future__ import annotations
import json
+import logging
from datetime import datetime
-from typing import Any, Dict, List, Optional
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
from src.agent.memory import WorkspaceMemory
from src.agent.skills import SkillsLoader
from src.agent.tools import ToolRegistry
-_SYSTEM_PROMPT = """You are a finance research agent with 68 specialist skills, 21 tools, 5 data sources (with auto-fallback), and 29 multi-agent swarm teams.
+if TYPE_CHECKING:
+ from src.memory.persistent import PersistentMemory
+
+logger = logging.getLogger(__name__)
+
+_SYSTEM_PROMPT = """You are a finance research agent with {skill_count} specialist skills, {tool_count} tools, 5 data sources (with auto-fallback), and 29 multi-agent swarm teams.
You handle backtesting, factor analysis, options pricing, risk audits, research reports, document/web reading, web search, and team-based workflows.
## Tools
@@ -36,10 +42,9 @@ Decide which workflow to use based on the request:
4. Syntax check → `backtest(run_dir=...)` → `read_file("artifacts/metrics.csv")`
5. Do NOT write run_backtest.py. The engine is built-in.
-**Swarm team** — user wants multi-agent analysis, risk audit, committee review, or any task with "team/committee/panel/desk":
+**Swarm team** — ONLY when the user explicitly requests team/committee/swarm analysis:
- Call `run_swarm(prompt="<user's full request>")` — it auto-selects the right preset.
-- Examples: risk audit, investment committee, equity research, technical panel, cross-market allocation.
-- Do NOT attempt multi-dimensional analysis solo. Use swarm.
+- Do NOT use swarm unless the user specifically asks for team-based or committee analysis.
**Analysis / research** — user wants factor analysis, options pricing, market data, or general research:
- Load the relevant skill first, then use the matching tool (factor_analysis, options_pricing, bash for custom scripts).
@@ -54,12 +59,21 @@ Decide which workflow to use based on the request:
- Output results as markdown tables. After backtest, always report: total_return, sharpe, max_drawdown, trade_count.
- All file paths are relative to run_dir (auto-injected).
- Respond in the same language the user used.
-
+- You have persistent cross-session memory (`remember` tool). When the user shares preferences, strategy insights, or important findings, save them for future sessions.
+- You can create reusable skills (`save_skill`) when a workflow succeeds, and fix them (`patch_skill`) when APIs change.
+{memory_section}
## Current Date & Time
Today is {current_datetime}.
"""
+_MEMORY_SECTION = """
+## Persistent Memory (cross-session)
+
+{snapshot}
+
+"""
+
class ContextBuilder:
"""Builds message context for AgentLoop.
@@ -71,22 +85,26 @@ class ContextBuilder:
"""
def __init__(self, registry: ToolRegistry, memory: WorkspaceMemory,
- skills_loader: Optional[SkillsLoader] = None) -> None:
+ skills_loader: Optional[SkillsLoader] = None,
+ persistent_memory: Optional[PersistentMemory] = None) -> None:
"""Initialize ContextBuilder.
Args:
registry: Tool registry.
memory: Workspace memory.
skills_loader: Skills loader (auto-created if not provided).
+ persistent_memory: PersistentMemory instance for cross-session recall.
"""
self.registry = registry
self.memory = memory
self.skills_loader = skills_loader or SkillsLoader()
+ self._persistent_memory = persistent_memory
def build_system_prompt(self, user_message: str = "") -> str:
"""Build system prompt.
Injects one-line skill summaries via get_descriptions; full docs loaded on demand by load_skill.
+ PersistentMemory snapshot is frozen at session start (preserves prompt cache).
Args:
user_message: User message (kept for API compatibility).
@@ -95,16 +113,31 @@ class ContextBuilder:
System prompt text.
"""
now = datetime.now()
+
+ # Build memory section only if there are saved memories
+ memory_section = ""
+ if self._persistent_memory and self._persistent_memory.snapshot:
+ memory_section = _MEMORY_SECTION.format(
+ snapshot=self._persistent_memory.snapshot,
+ )
+
return _SYSTEM_PROMPT.format(
+ tool_count=len(self.registry._tools),
+ skill_count=len(self.skills_loader.skills),
tool_descriptions=self._format_tool_descriptions(),
skill_descriptions=self.skills_loader.get_descriptions(),
memory_summary=self.memory.to_summary(),
+ memory_section=memory_section,
current_datetime=now.strftime("%A, %B %d, %Y %H:%M (local)"),
)
def build_messages(self, user_message: str, history: Optional[List[Dict[str, Any]]] = None) -> List[Dict[str, Any]]:
"""Build full message list.
+ Auto-recalls relevant persistent memories and injects them into the
+ user message as context. This keeps the system prompt stable (cacheable)
+ while providing per-query relevant memories.
+
Args:
user_message: User message.
history: Prior conversation messages.
@@ -117,7 +150,23 @@ class ContextBuilder:
]
if history:
messages.extend(history)
- messages.append({"role": "user", "content": user_message})
+
+ # Auto-recall: inject relevant memories into user message
+ enriched = user_message
+ if self._persistent_memory:
+ try:
+ recalls = self._persistent_memory.find_relevant(user_message, max_results=3)
+ if recalls:
+ lines = [f"- **{r.title}** ({r.memory_type}): {r.body[:500]}" for r in recalls]
+ recall_block = "\n".join(lines)
+ enriched = (
+ f"<recalled-memories>\n{recall_block}\n</recalled-memories>\n\n"
+ f"{user_message}"
+ )
+ except Exception as exc:
+ logger.debug("Auto-recall failed: %s", exc)
+
+ messages.append({"role": "user", "content": enriched})
return messages
def _format_tool_descriptions(self) -> str:
diff --git a/agent/src/agent/frontmatter.py b/agent/src/agent/frontmatter.py
new file mode 100644
index 000000000..6e670337f
--- /dev/null
+++ b/agent/src/agent/frontmatter.py
@@ -0,0 +1,40 @@
+"""Shared YAML-like frontmatter parser for skills and memory files."""
+
+from __future__ import annotations
+
+import re
+from typing import Any, Dict
+
+
+def parse_frontmatter(text: str) -> tuple[Dict[str, Any], str]:
+ """Parse YAML-like frontmatter and body from a markdown file.
+
+ Supports string, list (``[a, b]``), and boolean values.
+
+ Args:
+ text: Markdown text with optional ``---`` delimited frontmatter.
+
+ Returns:
+ Tuple of (metadata dict, body text).
+ """
+ match = re.match(r"^---\s*\n(.*?)\n---\s*\n(.*)", text, re.DOTALL)
+ if not match:
+ return {}, text.strip()
+
+ meta: Dict[str, Any] = {}
+ for line in match.group(1).strip().split("\n"):
+ line = line.strip()
+ if ":" not in line:
+ continue
+ key, value = line.split(":", 1)
+ key = key.strip()
+ value = value.strip()
+ if value.startswith("[") and value.endswith("]"):
+ items = [item.strip().strip("'\"") for item in value[1:-1].split(",")]
+ meta[key] = [i for i in items if i]
+ elif value.lower() in ("true", "false"):
+ meta[key] = value.lower() == "true"
+ else:
+ meta[key] = value
+
+ return meta, match.group(2).strip()
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 3701a3c4c..43651fb08 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -1,13 +1,19 @@
"""AgentLoop: ReAct core loop.
-Three-layer context management:
- Layer 1 (microcompact) — silently prunes old tool results each iteration, keeping the most recent 3
- Layer 2 (auto_compact) — LLM summarises and compresses when token count exceeds threshold, saves transcript
- Layer 3 (compact tool) — model explicitly calls the compact tool to trigger compression
+Five-layer context management:
+ Layer 1 (microcompact) — silently prunes old tool results each iteration
+ Layer 2 (context_collapse) — folds long text blocks without LLM call (zero cost)
+ Layer 3 (auto_compact) — LLM structured summary with token-budget tail protection
+ Layer 4 (compact tool) — model explicitly calls the compact tool to trigger L3
+ Layer 5 (iterative update) — Nth compression updates previous summary instead of starting fresh
+
+Tool execution:
+ - Read/write batching: consecutive readonly tools run in parallel via threads
"""
from __future__ import annotations
+import concurrent.futures
import json
import logging
import os
@@ -28,6 +34,16 @@ TOKEN_THRESHOLD = int(os.getenv("TOKEN_THRESHOLD", "40000"))
KEEP_RECENT = 3
TOOL_RESULT_LIMIT = 10_000
+# Layer 2: Context collapse thresholds
+COLLAPSE_THRESHOLD = int(TOKEN_THRESHOLD * 0.7)
+COLLAPSE_PRESERVE_RECENT = 6
+COLLAPSE_TEXT_MIN = 2400
+COLLAPSE_HEAD = 900
+COLLAPSE_TAIL = 500
+
+# Layer 3: Token-budget tail protection
+TAIL_TOKEN_BUDGET = 20_000
+
logger = logging.getLogger(__name__)
@@ -58,9 +74,167 @@ def _microcompact(messages: list) -> None:
msg["content"] = "[cleared]"
+def _context_collapse(messages: list) -> None:
+ """Layer 2: fold long text blocks in older messages without LLM call.
+
+ Preserves head + tail of large text, collapses the middle.
+ Zero API cost — pure string operation.
+
+ Args:
+ messages: Message list (mutated in place).
+ """
+ if len(messages) <= COLLAPSE_PRESERVE_RECENT + 1:
+ return
+ for msg in messages[1:-COLLAPSE_PRESERVE_RECENT]:
+ content = msg.get("content")
+ if not isinstance(content, str) or len(content) <= COLLAPSE_TEXT_MIN:
+ continue
+ if content == "[cleared]":
+ continue
+ head = content[:COLLAPSE_HEAD]
+ tail = content[-COLLAPSE_TAIL:]
+ trimmed = len(content) - COLLAPSE_HEAD - COLLAPSE_TAIL
+ msg["content"] = f"{head}\n\n...[{trimmed} chars collapsed]...\n\n{tail}"
+
+
+def _fix_tool_pairs(messages: list) -> None:
+ """Repair orphaned tool_call / tool_result pairs after compression.
+
+ Two fixes:
+ 1. Remove tool results whose matching tool_call was compressed away.
+ 2. Insert stub results for tool_calls whose results were compressed away.
+
+ Args:
+ messages: Message list (mutated in place).
+ """
+ # Collect all tool_call IDs from assistant messages
+ call_ids: set[str] = set()
+ for msg in messages:
+ if msg.get("role") == "assistant":
+ for tc in msg.get("tool_calls", []):
+ tc_id = tc.get("id", "")
+ if tc_id:
+ call_ids.add(tc_id)
+
+ # Remove orphaned tool results
+ i = 0
+ while i < len(messages):
+ msg = messages[i]
+ if msg.get("role") == "tool" and msg.get("tool_call_id") not in call_ids:
+ messages.pop(i)
+ else:
+ i += 1
+
+ # Collect existing result IDs
+ result_ids: set[str] = set()
+ for msg in messages:
+ if msg.get("role") == "tool":
+ tcid = msg.get("tool_call_id", "")
+ if tcid:
+ result_ids.add(tcid)
+
+ # Insert stub results for orphaned tool_calls
+ inserts: list[tuple[int, dict]] = []
+ for idx, msg in enumerate(messages):
+ if msg.get("role") != "assistant":
+ continue
+ for tc in msg.get("tool_calls", []):
+ tc_id = tc.get("id", "")
+ if tc_id and tc_id not in result_ids:
+ stub = {
+ "role": "tool",
+ "tool_call_id": tc_id,
+ "name": tc.get("function", {}).get("name", "unknown"),
+ "content": "[Result from earlier context — see summary above]",
+ }
+ inserts.append((idx + 1, stub))
+ result_ids.add(tc_id)
+
+ for pos, stub in reversed(inserts):
+ messages.insert(pos, stub)
+
+
+# -- Structured summary templates ------------------------------------------
+
+_STRUCTURED_SUMMARY_PROMPT = """\
+Summarize this conversation for handoff to a fresh context window.
+This summary is the ONLY context available — omitted information is lost.
+
+Use EXACTLY this structure:
+
+## Goal
+What the user is trying to accomplish.
+
+## Constraints & Preferences
+User-stated requirements: risk tolerance, strategy parameters, asset preferences.
+
+## Progress
+### Done
+- Completed steps with key results and specific numbers.
+### In Progress
+- Current work when compression triggered.
+
+## Key Decisions
+Choices made and rationale.
+
+## Resolved Questions
+Questions already answered — do NOT re-answer these.
+
+## Pending User Asks
+Unfinished requests still needing action.
+
+## Relevant Files
+File paths, run_dir, signal engines, artifact locations.
+
+## Remaining Work
+What still needs to be done (background reference, NOT active instructions).
+
+## Critical Context
+Specific numbers, parameters, error messages, configuration values.
+
+## Tools & Patterns
+Which tools worked, what failed, effective approaches.
+
+IMPORTANT: This is a handoff — background reference, NOT active instructions.
+Preserve ALL specific numbers, file paths, and parameter values.
+{focus_section}
+Conversation to summarize:
+"""
+
+_FOCUS_SECTION = """
+FOCUS TOPIC: {topic}
+Allocate 60-70% of the summary budget to content related to this topic.
+Aggressively compress unrelated content to make room.
+"""
+
+_ITERATIVE_UPDATE_PROMPT = """\
+Update the existing summary with new conversation turns.
+
+PREVIOUS SUMMARY:
+{previous_summary}
+
+NEW TURNS TO INCORPORATE:
+{new_turns}
+
+Rules:
+- PRESERVE all existing information from the previous summary.
+- ADD new progress, decisions, and findings.
+- Move "In Progress" items to "Done" when completed.
+- Move answered questions to "Resolved Questions".
+- Keep the same section structure.
+- Do NOT drop any critical context from the previous summary.
+{focus_section}"""
+
+
def _is_tool_success(result: str) -> bool:
- """Return True if the tool result does not contain an error."""
- return '"error"' not in result[:200]
+ """Return True if the tool result does not look like an error response."""
+ try:
+ data = json.loads(result)
+ if isinstance(data, dict) and data.get("status") == "error":
+ return False
+ except (json.JSONDecodeError, TypeError):
+ pass
+ return True
class AgentLoop:
@@ -80,6 +254,7 @@ class AgentLoop:
memory: Optional[WorkspaceMemory] = None,
event_callback: Optional[Callable[[str, Dict[str, Any]], None]] = None,
max_iterations: int = 50,
+ persistent_memory: Optional[Any] = None,
) -> None:
"""Initialize AgentLoop.
@@ -89,6 +264,7 @@ class AgentLoop:
memory: Workspace memory (created fresh if not provided).
event_callback: Event callback (event_type, data).
max_iterations: Maximum number of loop iterations.
+ persistent_memory: PersistentMemory for cross-session recall.
"""
self.registry = registry
self.llm = llm
@@ -97,6 +273,8 @@ class AgentLoop:
self.max_iterations = max_iterations
self._called_ok: set[str] = set()
self._cancelled: bool = False
+ self._previous_summary: str = ""
+ self._persistent_memory = persistent_memory
def cancel(self) -> None:
"""Cancel the current loop.
@@ -116,6 +294,11 @@ class AgentLoop:
Returns:
Execution result dict.
"""
+ # Reset per-run state (safe for reuse across multiple run() calls)
+ self._cancelled = False
+ self._called_ok = set()
+ self._previous_summary = ""
+
state_store = RunStateStore()
RUNS_DIR.mkdir(parents=True, exist_ok=True)
@@ -127,7 +310,8 @@ class AgentLoop:
state_store.save_request(run_dir, user_message, {"session_id": session_id})
- context = ContextBuilder(self.registry, self.memory)
+ context = ContextBuilder(self.registry, self.memory,
+ persistent_memory=self._persistent_memory)
messages = context.build_messages(user_message, history)
react_trace: List[Dict[str, Any]] = []
@@ -157,8 +341,13 @@ class AgentLoop:
# Layer 1: microcompact (every iteration)
_microcompact(messages)
- # Layer 2: auto_compact (token threshold exceeded)
+ # Layer 2: context collapse (fold long text, zero API cost)
tokens = estimate_tokens(messages)
+ if tokens > COLLAPSE_THRESHOLD:
+ _context_collapse(messages)
+ tokens = estimate_tokens(messages)
+
+ # Layer 3: auto_compact (token threshold exceeded)
if tokens > TOKEN_THRESHOLD:
logger.info(f"Auto compact triggered: {tokens} tokens > {TOKEN_THRESHOLD}")
self._auto_compact(messages, run_dir, trace)
@@ -191,56 +380,15 @@ class AgentLoop:
messages.append(context.format_assistant_tool_calls(response.tool_calls, content=response.content))
- compact_requested = False
-
- for tc in response.tool_calls:
- tool_def = self.registry.get(tc.name)
-
- # Layer 3: compact tool — mark then defer execution
- if tc.name == "compact":
- compact_requested = True
- messages.append(context.format_tool_result(tc.id, "compact", '{"status":"ok","message":"Compressing..."}'))
- trace.write({"type": "compact_requested", "iter": iteration})
- continue
-
- is_repeatable = tool_def.repeatable if tool_def else False
- if tc.name in self._called_ok and not is_repeatable:
- logger.warning(f"Blocked duplicate call: {tc.name} (already succeeded)")
- skip_msg = json.dumps({"skipped": True, "reason": f"{tc.name} already completed successfully. Use the previous result."})
- messages.append(context.format_tool_result(tc.id, tc.name, skip_msg))
- trace.write({"type": "tool_skipped", "iter": iteration, "tool": tc.name})
- react_trace.append({"type": "tool_skipped", "tool": tc.name})
- continue
-
- self._emit("tool_call", {"tool": tc.name, "arguments": {k: str(v)[:200] for k, v in tc.arguments.items()}, "iter": iteration})
- trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "args": {k: str(v)[:200] for k, v in tc.arguments.items()}})
- logger.info(f"Tool call: {tc.name}({list(tc.arguments.keys())})")
-
- if "run_dir" not in tc.arguments and self.memory.run_dir:
- tc.arguments["run_dir"] = self.memory.run_dir
-
- t0 = _time.perf_counter()
- result = self.registry.execute(tc.name, tc.arguments)
- elapsed_ms = int((_time.perf_counter() - t0) * 1000)
-
- self._update_memory(tc.name, result, state_store, run_dir)
-
- if _is_tool_success(result):
- self._called_ok.add(tc.name)
-
- status = "ok" if _is_tool_success(result) else "error"
- truncated = result[:TOOL_RESULT_LIMIT]
- messages.append(context.format_tool_result(tc.id, tc.name, truncated))
-
- trace.write({"type": "tool_result", "iter": iteration, "tool": tc.name, "status": status, "elapsed_ms": elapsed_ms, "preview": result[:200]})
- react_trace.append({"type": "tool_call", "tool": tc.name, "result_preview": result[:200]})
-
- self._emit("tool_result", {"tool": tc.name, "status": status, "elapsed_ms": elapsed_ms, "preview": result[:200]})
+ # Execute tools with read/write batching
+ compact_requested, focus_topic = self._process_tool_calls(
+ response.tool_calls, context, messages, trace, react_trace, iteration,
+ )
# Layer 3: compress after all tools have executed
if compact_requested:
logger.info("Manual compact triggered by model")
- self._auto_compact(messages, run_dir, trace)
+ self._auto_compact(messages, run_dir, trace, focus_topic=focus_topic)
except Exception as exc:
logger.exception(f"AgentLoop error: {exc}")
@@ -278,47 +426,327 @@ class AgentLoop:
"react_trace": react_trace,
}
- def _auto_compact(self, messages: list, run_dir: Path, trace: TraceWriter) -> None:
- """Layer 2/3: LLM summarise-and-compress; saves transcript before compressing.
+ # -- Tool execution with read/write batching --------------------------------
+
+ def _process_tool_calls(
+ self,
+ tool_calls: list,
+ context: ContextBuilder,
+ messages: list,
+ trace: TraceWriter,
+ react_trace: list,
+ iteration: int,
+ ) -> tuple[bool, str]:
+ """Pre-process tool calls: handle compact, filter duplicates, batch execute.
+
+ Args:
+ tool_calls: Raw tool calls from LLM response.
+ context: ContextBuilder for formatting messages.
+ messages: Conversation messages (appended in place).
+ trace: TraceWriter.
+ react_trace: React trace list.
+ iteration: Current iteration number.
+
+ Returns:
+ Tuple of (compact_requested, focus_topic).
+ """
+ compact_requested = False
+ focus_topic = ""
+ to_execute = []
+
+ for tc in tool_calls:
+ # Layer 4: compact tool — mark then defer execution
+ if tc.name == "compact":
+ compact_requested = True
+ focus_topic = tc.arguments.get("focus_topic", "")
+ messages.append(context.format_tool_result(tc.id, "compact", '{"status":"ok","message":"Compressing..."}'))
+ trace.write({"type": "compact_requested", "iter": iteration})
+ continue
+
+ tool_def = self.registry.get(tc.name)
+ is_repeatable = tool_def.repeatable if tool_def else False
+ if tc.name in self._called_ok and not is_repeatable:
+ logger.warning(f"Blocked duplicate call: {tc.name} (already succeeded)")
+ skip_msg = json.dumps({"skipped": True, "reason": f"{tc.name} already completed successfully. Use the previous result."})
+ messages.append(context.format_tool_result(tc.id, tc.name, skip_msg))
+ trace.write({"type": "tool_skipped", "iter": iteration, "tool": tc.name})
+ react_trace.append({"type": "tool_skipped", "tool": tc.name})
+ continue
+
+ to_execute.append(tc)
+
+ if not to_execute:
+ return compact_requested, focus_topic
+
+ # Batch execute: consecutive readonly → parallel, write → serial
+ if len(to_execute) == 1:
+ self._execute_single(to_execute[0], context, messages, trace, react_trace, iteration)
+ else:
+ self._batch_execute(to_execute, context, messages, trace, react_trace, iteration)
+
+ return compact_requested, focus_topic
+
+ def _batch_execute(
+ self,
+ tool_calls: list,
+ context: ContextBuilder,
+ messages: list,
+ trace: TraceWriter,
+ react_trace: list,
+ iteration: int,
+ ) -> None:
+ """Execute tools with read/write batching.
+
+ Consecutive readonly tools run in parallel via ThreadPoolExecutor.
+ Write tools run serially between readonly batches.
+
+ Args:
+ tool_calls: Tool calls to execute.
+ context: ContextBuilder.
+ messages: Conversation messages.
+ trace: TraceWriter.
+ react_trace: React trace list.
+ iteration: Current iteration.
+ """
+ # Split into batches: consecutive readonly → parallel, write → serial
+ batches: list[tuple[str, list]] = []
+ current_ro: list = []
+
+ for tc in tool_calls:
+ tool_def = self.registry.get(tc.name)
+ if tool_def and tool_def.is_readonly:
+ current_ro.append(tc)
+ else:
+ if current_ro:
+ batches.append(("parallel", current_ro))
+ current_ro = []
+ batches.append(("serial", [tc]))
+ if current_ro:
+ batches.append(("parallel", current_ro))
+
+ for mode, batch in batches:
+ if mode == "parallel" and len(batch) > 1:
+ self._execute_parallel(batch, context, messages, trace, react_trace, iteration)
+ else:
+ for tc in batch:
+ self._execute_single(tc, context, messages, trace, react_trace, iteration)
+
+ def _execute_parallel(
+ self,
+ tool_calls: list,
+ context: ContextBuilder,
+ messages: list,
+ trace: TraceWriter,
+ react_trace: list,
+ iteration: int,
+ ) -> None:
+ """Execute readonly tools in parallel using threads.
+
+ Args:
+ tool_calls: Readonly tool calls to execute in parallel.
+ context: ContextBuilder.
+ messages: Conversation messages.
+ trace: TraceWriter.
+ react_trace: React trace list.
+ iteration: Current iteration.
+ """
+ # Prepare args + emit events
+ runnable: list[tuple] = []
+ for tc in tool_calls:
+ args = dict(tc.arguments)
+ if "run_dir" not in args and self.memory.run_dir:
+ args["run_dir"] = self.memory.run_dir
+ self._emit("tool_call", {"tool": tc.name, "arguments": {k: str(v)[:200] for k, v in args.items()}, "iter": iteration})
+ trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "args": {k: str(v)[:200] for k, v in args.items()}})
+ runnable.append((tc, args))
+
+ # Execute in parallel
+ def _run(tc_args: tuple) -> tuple:
+ tc, args = tc_args
+ t0 = _time.perf_counter()
+ result = self.registry.execute(tc.name, args)
+ elapsed_ms = int((_time.perf_counter() - t0) * 1000)
+ return tc, result, elapsed_ms
+
+ with concurrent.futures.ThreadPoolExecutor(max_workers=min(len(runnable), 8)) as pool:
+ futures = [pool.submit(_run, item) for item in runnable]
+ results = []
+ for i, f in enumerate(futures):
+ try:
+ results.append(f.result())
+ except Exception as exc:
+ tc = runnable[i][0]
+ results.append((tc, json.dumps({"status": "error", "error": str(exc)}), 0))
+
+ # Process results in order
+ for tc, result, elapsed_ms in results:
+ self._finalize_tool_result(tc, result, elapsed_ms, context, messages, trace, react_trace, iteration)
+
+ def _execute_single(
+ self,
+ tc: Any,
+ context: ContextBuilder,
+ messages: list,
+ trace: TraceWriter,
+ react_trace: list,
+ iteration: int,
+ ) -> None:
+ """Execute a single tool call.
+
+ Args:
+ tc: Tool call object.
+ context: ContextBuilder.
+ messages: Conversation messages.
+ trace: TraceWriter.
+ react_trace: React trace list.
+ iteration: Current iteration.
+ """
+ args = dict(tc.arguments)
+ if "run_dir" not in args and self.memory.run_dir:
+ args["run_dir"] = self.memory.run_dir
+
+ self._emit("tool_call", {"tool": tc.name, "arguments": {k: str(v)[:200] for k, v in args.items()}, "iter": iteration})
+ trace.write({"type": "tool_call", "iter": iteration, "tool": tc.name, "args": {k: str(v)[:200] for k, v in args.items()}})
+ logger.info(f"Tool call: {tc.name}({list(args.keys())})")
+
+ t0 = _time.perf_counter()
+ result = self.registry.execute(tc.name, args)
+ elapsed_ms = int((_time.perf_counter() - t0) * 1000)
+
+ self._finalize_tool_result(tc, result, elapsed_ms, context, messages, trace, react_trace, iteration)
+
+ def _finalize_tool_result(
+ self,
+ tc: Any,
+ result: str,
+ elapsed_ms: int,
+ context: ContextBuilder,
+ messages: list,
+ trace: TraceWriter,
+ react_trace: list,
+ iteration: int,
+ ) -> None:
+ """Record a tool result: update memory, append message, write trace, emit event.
+
+ Args:
+ tc: Tool call object.
+ result: Raw tool result string.
+ elapsed_ms: Execution time in milliseconds.
+ context: ContextBuilder.
+ messages: Conversation messages.
+ trace: TraceWriter.
+ react_trace: React trace list.
+ iteration: Current iteration.
+ """
+ self._update_memory(tc.name)
+
+ success = _is_tool_success(result)
+ if success:
+ self._called_ok.add(tc.name)
+
+ status = "ok" if success else "error"
+ truncated = result[:TOOL_RESULT_LIMIT]
+ messages.append(context.format_tool_result(tc.id, tc.name, truncated))
+
+ trace.write({"type": "tool_result", "iter": iteration, "tool": tc.name, "status": status, "elapsed_ms": elapsed_ms, "preview": result[:200]})
+ react_trace.append({"type": "tool_call", "tool": tc.name, "result_preview": result[:200]})
+ self._emit("tool_result", {"tool": tc.name, "status": status, "elapsed_ms": elapsed_ms, "preview": result[:200]})
+
+ # -- Context compression ---------------------------------------------------
+
+ def _auto_compact(self, messages: list, run_dir: Path, trace: TraceWriter,
+ focus_topic: str = "") -> None:
+ """Layer 3/4/5: structured LLM summary with token-budget tail protection.
+
+ Upgrades over the original:
+ - Token-budget tail: keeps ~20K tokens of recent messages (not a fixed count).
+ - Structured summary template: preserves goal, progress, decisions, files, etc.
+ - Iterative update: Nth compression updates previous summary, zero info decay.
+ - Tool pair fix: repairs orphaned tool_call/tool_result after compression.
+ - Focus-topic: optionally prioritize specific topic in summary.
Args:
messages: Message list (replaced in place).
run_dir: Run directory.
trace: TraceWriter.
+ focus_topic: Optional topic to prioritize in the summary.
"""
- # Save full transcript (timestamped, one file per compression)
+ # Save full transcript before compressing
transcript_path = run_dir / f"transcript_{int(_time.time())}.jsonl"
with open(transcript_path, "w", encoding="utf-8") as f:
for msg in messages:
f.write(json.dumps(msg, default=str, ensure_ascii=False) + "\n")
- # LLM summary (no tools, plain text)
- conv_text = json.dumps(messages[1:], default=str, ensure_ascii=False)[:80000]
- summary_resp = self.llm.chat([
- {"role": "user", "content": (
- "Summarize this conversation for continuity. Include: "
- "1) What was accomplished, 2) Current state, 3) Key decisions made. "
- "Be concise but preserve critical details.\n\n" + conv_text
- )},
- ])
+ system_msg = messages[0]
+ body = messages[1:]
+
+ # Token-budget tail: walk backward to find how many recent messages to preserve
+ accumulated = 0
+ cut_idx = len(body)
+ for i in range(len(body) - 1, -1, -1):
+ content = body[i].get("content", "")
+ msg_tokens = (len(str(content)) // 4) + 10
+ if accumulated + msg_tokens > TAIL_TOKEN_BUDGET:
+ cut_idx = i + 1
+ break
+ accumulated += msg_tokens
+ cut_idx = i
+
+ # Don't split in the middle of a tool_call/tool_result pair
+ while 0 < cut_idx < len(body) and body[cut_idx].get("role") == "tool":
+ cut_idx += 1
+
+ head = body[:cut_idx]
+ tail = body[cut_idx:]
+
+ if not head:
+ # All body fits in tail budget — force a split to avoid infinite loop
+ if len(body) > 2:
+ cut_idx = max(1, len(body) // 2)
+ head = body[:cut_idx]
+ tail = body[cut_idx:]
+ else:
+ logger.warning("Auto compact: nothing to compress (body too small)")
+ return
+
+ # Build focus section
+ focus_section = _FOCUS_SECTION.format(topic=focus_topic) if focus_topic else ""
+
+ # Build summary prompt (structured template or iterative update)
+ conv_text = json.dumps(head, default=str, ensure_ascii=False)[:80000]
+
+ if self._previous_summary:
+ prompt = _ITERATIVE_UPDATE_PROMPT.format(
+ previous_summary=self._previous_summary,
+ new_turns=conv_text,
+ focus_section=focus_section,
+ )
+ else:
+ prompt = _STRUCTURED_SUMMARY_PROMPT.format(focus_section=focus_section) + conv_text
+
+ summary_resp = self.llm.chat([{"role": "user", "content": prompt}])
summary = summary_resp.content or ""
+ self._previous_summary = summary
tokens_before = estimate_tokens(messages)
- trace.write({"type": "compact", "tokens_before": tokens_before, "summary": summary[:500]})
+ trace.write({"type": "compact", "tokens_before": tokens_before, "summary": summary[:500],
+ "focus_topic": focus_topic or "(none)"})
self._emit("compact", {"tokens_before": tokens_before, "summary": summary[:200]})
- # Replace: keep system prompt + inject compressed summary + restore identity
- system_msg = messages[0]
+ # Reconstruct: system + summary + acknowledge + preserved tail
state_summary = self.memory.to_summary()
- compressed = f"[Conversation compressed. Transcript: {transcript_path}]\n\n{summary}"
+ compressed = f"[Conversation compressed — handoff summary. Transcript: {transcript_path}]\n\n{summary}"
if state_summary and state_summary != "(empty state)":
compressed += f"\n\nCurrent agent state:\n{state_summary}"
+
messages.clear()
- messages.extend([
- system_msg,
- {"role": "user", "content": compressed},
- {"role": "assistant", "content": "Understood. I have the context from the summary. Continuing."},
- ])
+ messages.append(system_msg)
+ messages.append({"role": "user", "content": compressed})
+ messages.append({"role": "assistant", "content": "Understood. Continuing from the summary."})
+ messages.extend(tail)
+
+ # Fix orphaned tool pairs in the reconstructed message list
+ _fix_tool_pairs(messages)
def _emit(self, event_type: str, data: Dict[str, Any]) -> None:
"""Fire an event via the callback."""
@@ -328,12 +756,6 @@ class AgentLoop:
except Exception:
pass
- def _update_memory(self, tool_name: str, result: str, state_store: RunStateStore, run_dir: Path) -> None:
- """Update memory and persist tool result."""
+ def _update_memory(self, tool_name: str) -> None:
+ """Update workspace memory counters after tool execution."""
self.memory.increment(tool_name)
- try:
- data = json.loads(result)
- if isinstance(data, dict):
- state_store.persist_tool_result(tool_name, data, run_dir)
- except (json.JSONDecodeError, TypeError):
- pass
diff --git a/agent/src/agent/memory.py b/agent/src/agent/memory.py
index 5a86b7e97..b205e7a47 100644
--- a/agent/src/agent/memory.py
+++ b/agent/src/agent/memory.py
@@ -1,7 +1,7 @@
-"""Workspace memory: shared state across tool calls.
+"""Workspace memory: shared state across tool calls within a single run.
-WorkspaceMemory passes intermediate results between tools during an agent run.
-Generic KV store + counters; no tool-specific fields.
+Lightweight runtime state — survives within one AgentLoop.run() invocation only.
+Cross-session persistence is handled by src.memory.persistent.PersistentMemory.
"""
from __future__ import annotations
@@ -12,53 +12,21 @@ from typing import Any, Dict, Optional
@dataclass
class WorkspaceMemory:
- """Shared workspace state between tools.
+ """Shared workspace state between tools during a single agent run.
Attributes:
- run_dir: Current run directory.
- store: Generic result store (tool memory_key -> JSON string).
+ run_dir: Current run directory path.
counters: Tool invocation counters.
- extra: Generic KV store for derived values passed between tools.
"""
run_dir: Optional[str] = None
- store: Dict[str, str] = field(default_factory=dict)
counters: Dict[str, int] = field(default_factory=dict)
- extra: Dict[str, Any] = field(default_factory=dict)
-
- def reset(self) -> None:
- """Reset all state."""
- self.run_dir = None
- self.store.clear()
- self.counters.clear()
- self.extra.clear()
-
- def set_result(self, key: str, value: str) -> None:
- """Store a tool result.
-
- Args:
- key: Memory key (e.g. "plan_output").
- value: JSON string.
- """
- self.store[key] = value
-
- def get_result(self, key: str, default: Optional[str] = None) -> Optional[str]:
- """Retrieve a tool result.
-
- Args:
- key: Memory key.
- default: Default value.
-
- Returns:
- JSON string or default.
- """
- return self.store.get(key, default)
def increment(self, key: str) -> int:
"""Increment a counter and return the new value.
Args:
- key: Counter key.
+ key: Counter key (typically tool name).
Returns:
Updated counter value.
@@ -66,60 +34,19 @@ class WorkspaceMemory:
self.counters[key] = self.counters.get(key, 0) + 1
return self.counters[key]
- def set_extra(self, key: str, value: Any) -> None:
- """Set an extra KV entry.
-
- Args:
- key: Key name.
- value: Value.
- """
- self.extra[key] = value
-
- def get_extra(self, key: str, default: Any = None) -> Any:
- """Get an extra KV entry.
-
- Args:
- key: Key name.
- default: Default value.
-
- Returns:
- Stored value or default.
- """
- return self.extra.get(key, default)
-
- def set(self, key: str, value: Any) -> None:
- """Set a KV entry (alias for set_extra).
-
- Args:
- key: Key name.
- value: Value.
- """
- self.extra[key] = value
-
- def get(self, key: str, default: Any = None) -> Any:
- """Get a KV entry (alias for get_extra).
-
- Args:
- key: Key name.
- default: Default value.
-
- Returns:
- Stored value or default.
- """
- return self.extra.get(key, default)
-
def to_summary(self) -> str:
- """Generate a state summary for the LLM indicating completed steps.
+ """Generate a state summary for the LLM.
+
+ Includes run_dir and tool counters.
+ This summary survives context compression and helps the LLM
+ remember what it was working on.
Returns:
State summary text.
"""
- lines = []
+ lines: list[str] = []
if self.run_dir:
lines.append(f"- run_dir: {self.run_dir}")
- if self.store:
- completed = list(self.store.keys())
- lines.append(f"- completed: {', '.join(completed)}")
if self.counters:
counter_parts = [f"{k}={v}" for k, v in self.counters.items()]
lines.append(f"- counters: {', '.join(counter_parts)}")
diff --git a/agent/src/agent/skills.py b/agent/src/agent/skills.py
index fa983f221..412d6f1ca 100644
--- a/agent/src/agent/skills.py
+++ b/agent/src/agent/skills.py
@@ -53,36 +53,7 @@ class Skill:
return None
-def _parse_frontmatter(text: str) -> tuple[Dict[str, Any], str]:
- """Parse YAML frontmatter and body.
-
- Args:
- text: Markdown text.
-
- Returns:
- Tuple of (metadata dict, body text).
- """
- match = re.match(r"^---\s*\n(.*?)\n---\s*\n(.*)", text, re.DOTALL)
- if not match:
- return {}, text.strip()
-
- meta: Dict[str, Any] = {}
- for line in match.group(1).strip().split("\n"):
- line = line.strip()
- if ":" not in line:
- continue
- key, value = line.split(":", 1)
- key = key.strip()
- value = value.strip()
- if value.startswith("[") and value.endswith("]"):
- items = [item.strip().strip("'\"") for item in value[1:-1].split(",")]
- meta[key] = [i for i in items if i]
- elif value.lower() in ("true", "false"):
- meta[key] = value.lower() == "true"
- else:
- meta[key] = value
-
- return meta, match.group(2).strip()
+from src.agent.frontmatter import parse_frontmatter as _parse_frontmatter # shared util
def _load_skill_dir(dir_path: Path) -> Optional[Skill]:
@@ -117,32 +88,45 @@ def _load_skill_dir(dir_path: Path) -> Optional[Skill]:
)
+USER_SKILLS_DIR = Path.home() / ".vibe-trading" / "skills" / "user"
+
+
class SkillsLoader:
- """Load skills from the skills/ directory.
+ """Load skills from bundled skills/ directory and user skills directory.
Attributes:
- skills: Loaded skill list.
+ skills: Loaded skill list (bundled + user-created).
"""
- def __init__(self, skills_dir: Optional[Path] = None) -> None:
+ def __init__(self, skills_dir: Optional[Path] = None,
+ user_skills_dir: Optional[Path] = None) -> None:
"""Initialize SkillsLoader.
Args:
- skills_dir: Skills directory path; defaults to agent/skills/.
+ skills_dir: Bundled skills directory path; defaults to agent/skills/.
+ user_skills_dir: User-created skills directory; defaults to ~/.vibe-trading/skills/user/.
"""
self.skills_dir = skills_dir or Path(__file__).resolve().parents[1] / "skills"
+ self._user_skills_dir = user_skills_dir or USER_SKILLS_DIR
self.skills: List[Skill] = []
self._load()
def _load(self) -> None:
- """Load all skill subdirectories from the skills directory."""
- if not self.skills_dir.exists():
- return
- for path in sorted(self.skills_dir.iterdir()):
- if path.is_dir() and (path / "SKILL.md").exists():
- skill = _load_skill_dir(path)
- if skill:
- self.skills.append(skill)
+ """Load all skill subdirectories from user and bundled directories.
+
+ User skills are loaded first so they override bundled skills with the same name
+ (e.g. after patch_skill copies and modifies a bundled skill).
+ """
+ seen_names: set[str] = set()
+ for directory in (self._user_skills_dir, self.skills_dir):
+ if not directory or not directory.exists():
+ continue
+ for path in sorted(directory.iterdir()):
+ if path.is_dir() and (path / "SKILL.md").exists():
+ skill = _load_skill_dir(path)
+ if skill and skill.name not in seen_names:
+ self.skills.append(skill)
+ seen_names.add(skill.name)
# Display order for categories (unlisted categories appear at the end).
_CATEGORY_ORDER = [
@@ -176,6 +160,8 @@ class SkillsLoader:
def get_content(self, name: str) -> str:
"""Return the full documentation for a skill (used by the load_skill tool).
+ Falls back to disk lookup for user skills created mid-session.
+
Args:
name: Skill name.
@@ -185,5 +171,13 @@ class SkillsLoader:
for skill in self.skills:
if skill.name == name:
return f'<skill name="{name}">\n{skill.body}\n</skill>'
+
+ # Fallback: check user skills directory on disk (mid-session created skills)
+ if self._user_skills_dir:
+ skill = _load_skill_dir(self._user_skills_dir / name)
+ if skill:
+ self.skills.append(skill)
+ return f'<skill name="{name}">\n{skill.body}\n</skill>'
+
available = ", ".join(s.name for s in self.skills)
return f"Error: Unknown skill '{name}'. Available: {available}"
diff --git a/agent/src/agent/tools.py b/agent/src/agent/tools.py
index 5611a5bba..bf3f59a43 100644
--- a/agent/src/agent/tools.py
+++ b/agent/src/agent/tools.py
@@ -3,8 +3,10 @@
from __future__ import annotations
import json
-import traceback
+import logging
from abc import ABC, abstractmethod
+
+logger = logging.getLogger(__name__)
from typing import Any, Dict, List, Optional
@@ -22,6 +24,16 @@ class BaseTool(ABC):
description: str = ""
parameters: Dict[str, Any] = {}
repeatable: bool = False
+ is_readonly: bool = True
+
+ @classmethod
+ def check_available(cls) -> bool:
+ """Check if this tool's dependencies are met.
+
+ Override in subclasses to check for API keys, packages, etc.
+ Tools that return False are excluded from the registry.
+ """
+ return True
@abstractmethod
def execute(self, **kwargs: Any) -> str:
@@ -65,9 +77,10 @@ class ToolRegistry:
try:
return tool.execute(**params)
except Exception as exc:
+ logger.exception("Tool %s failed", name)
return json.dumps({
"status": "error", "tool": name,
- "error": str(exc), "traceback": traceback.format_exc()[-500:],
+ "error": str(exc),
}, ensure_ascii=False)
@property
diff --git a/agent/src/core/runner.py b/agent/src/core/runner.py
index 2db0cc36f..b2b3ed23d 100644
--- a/agent/src/core/runner.py
+++ b/agent/src/core/runner.py
@@ -109,19 +109,6 @@ def _expand_artifacts_spec(spec: Dict[str, Any] | None) -> Dict[str, Dict[str, A
class Runner:
"""Execute entry scripts inside a run directory and collect outputs."""
- _PROXY_ENV_KEYS = (
- "HTTP_PROXY",
- "HTTPS_PROXY",
- "ALL_PROXY",
- "http_proxy",
- "https_proxy",
- "all_proxy",
- "GIT_HTTP_PROXY",
- "GIT_HTTPS_PROXY",
- "git_http_proxy",
- "git_https_proxy",
- )
-
def __init__(self, timeout: int = 300, artifacts_spec: Optional[Dict[str, Any]] = None) -> None:
"""Initialize runner.
diff --git a/agent/src/core/state.py b/agent/src/core/state.py
index 28c4d4335..112cab1f5 100644
--- a/agent/src/core/state.py
+++ b/agent/src/core/state.py
@@ -1,19 +1,16 @@
-"""Run state persistence: lightweight, no dependency on legacy agent types."""
+"""Run state persistence: creates run directories and records status."""
from __future__ import annotations
-import copy
import json
import uuid
from datetime import datetime
from pathlib import Path
-from typing import Any, Dict, List, Optional
-
-import yaml
+from typing import Any, Dict
class RunStateStore:
- """Run state store: records key files such as req/design/code/logs/review."""
+ """Run state store: manages run directories and their lifecycle status."""
def create_run_dir(self, workspace: Path) -> Path:
"""Create a unique run directory.
@@ -48,59 +45,6 @@ class RunStateStore:
self._write_json(run_dir / "req.json", payload)
return payload
- def save_planner_output(self, run_dir: Path, planner_output: Dict[str, Any]) -> Dict[str, Any]:
- """Save planner output.
-
- Args:
- run_dir: Run directory.
- planner_output: Planner output dict.
-
- Returns:
- Saved payload.
- """
- self._write_json(run_dir / "planner_output.json", planner_output)
- return planner_output
-
- def save_design(self, run_dir: Path, spec: Dict[str, Any], decision: Dict[str, Any]) -> None:
- """Save design spec and judge decision.
-
- Args:
- run_dir: Run directory.
- spec: Strategy design spec.
- decision: Judge decision result.
- """
- self._write_json(run_dir / "design_spec.json", spec)
- self._write_json(run_dir / "judge_decision.json", decision)
-
- def save_rag_spec(
- self,
- run_dir: Path,
- selection: Dict[str, Any],
- spec: Dict[str, Any],
- *,
- candidates: Optional[List[Dict[str, Any]]] = None,
- ) -> None:
- """Save RAG results.
-
- Args:
- run_dir: Run directory.
- selection: Selected API metadata.
- spec: Enriched data API spec.
- candidates: Candidate API list.
- """
- enriched_spec = copy.deepcopy(spec) if spec else {}
- enriched_spec["_rag_metadata"] = selection
- spec_yaml = yaml.safe_dump(enriched_spec, allow_unicode=True, sort_keys=False)
- (run_dir / "data_api_spec.yaml").write_text(spec_yaml, encoding="utf-8")
- self._write_json(run_dir / "rag_metadata.json", selection)
- if candidates:
- candidate_yaml = yaml.safe_dump(
- {"generated_at": datetime.now().isoformat(), "candidates": candidates},
- allow_unicode=True,
- sort_keys=False,
- )
- (run_dir / "rag_candidates.yaml").write_text(candidate_yaml, encoding="utf-8")
-
def mark_success(self, run_dir: Path) -> None:
"""Mark the run as successful.
@@ -118,54 +62,6 @@ class RunStateStore:
"""
self._write_json(run_dir / "state.json", {"status": "failed", "reason": reason})
- # -----------------------------------------------------------------------
- # Generic persistence: extract and save key artifacts by tool name
- # -----------------------------------------------------------------------
-
- _PERSIST_MAP: Dict[str, str] = {
- "plan": "_persist_plan",
- "search": "_persist_search",
- "resolve": "_persist_resolve",
- "design": "_persist_design",
- }
-
- def persist_tool_result(self, tool_name: str, result_data: Dict[str, Any], run_dir: Path) -> None:
- """Persist key artifacts by tool name.
-
- Args:
- tool_name: Tool name.
- result_data: Parsed tool result dict.
- run_dir: Run directory.
- """
- method_name = self._PERSIST_MAP.get(tool_name)
- if method_name:
- method = getattr(self, method_name, None)
- if method:
- try:
- method(result_data, run_dir)
- except Exception:
- pass
-
- def _persist_plan(self, data: Dict[str, Any], run_dir: Path) -> None:
- if data and "error" not in data:
- self.save_planner_output(run_dir, data)
-
- def _persist_search(self, data: Dict[str, Any], run_dir: Path) -> None:
- if data.get("selections"):
- sel = data["selections"][0] if data["selections"] else {}
- spec = data.get("data_api_spec") or {}
- self.save_rag_spec(run_dir, sel, spec, candidates=data.get("candidates"))
-
- def _persist_resolve(self, data: Dict[str, Any], run_dir: Path) -> None:
- if data and data.get("status") == "ok":
- self._write_json(run_dir / "data_config.json", data)
-
- def _persist_design(self, data: Dict[str, Any], run_dir: Path) -> None:
- spec = data.get("spec") or {}
- decision = data.get("judge_decision") or {}
- if spec:
- self.save_design(run_dir, spec, decision)
-
@staticmethod
def _write_json(path: Path, data: Any) -> None:
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
diff --git a/agent/src/memory/__init__.py b/agent/src/memory/__init__.py
new file mode 100644
index 000000000..7a816221b
--- /dev/null
+++ b/agent/src/memory/__init__.py
@@ -0,0 +1 @@
+"""Persistent cross-session memory system."""
diff --git a/agent/src/memory/persistent.py b/agent/src/memory/persistent.py
new file mode 100644
index 000000000..022d0a096
--- /dev/null
+++ b/agent/src/memory/persistent.py
@@ -0,0 +1,224 @@
+"""PersistentMemory: file-based cross-session memory, zero external dependencies.
+
+Storage layout:
+ ~/.vibe-trading/memory/
+ +-- MEMORY.md # Index (< 200 lines)
+ +-- user_prefs.md # Individual memory entries with YAML frontmatter
+ +-- project_btc.md
+ +-- ...
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from pathlib import Path
+
+from src.agent.frontmatter import parse_frontmatter as _parse_frontmatter
+from typing import List, Optional
+
+MEMORY_BASE = Path.home() / ".vibe-trading" / "memory"
+MAX_INDEX_LINES = 200
+MAX_ENTRY_CHARS = 8000
+MAX_RESULTS = 5
+METADATA_WEIGHT = 2.0
+
+
+@dataclass(frozen=True)
+class MemoryEntry:
+ """A single memory entry on disk.
+
+ Attributes:
+ path: File path.
+ title: Memory title.
+ description: One-line description (used for retrieval scoring).
+ memory_type: Category (user/feedback/project/reference).
+ body: Body text content.
+ modified_at: File modification timestamp.
+ """
+
+ path: Path
+ title: str
+ description: str
+ memory_type: str
+ body: str
+ modified_at: float
+
+
+def _tokenize(text: str) -> set[str]:
+ """Split text into searchable tokens.
+
+ ASCII words >= 3 chars + CJK individual characters.
+
+ Args:
+ text: Input text.
+
+ Returns:
+ Set of tokens.
+ """
+ ascii_tokens = set(re.findall(r"[a-zA-Z0-9_]{3,}", text.lower()))
+ cjk_tokens = set(re.findall(r"[\u4e00-\u9fff\u3400-\u4dbf]", text))
+ return ascii_tokens | cjk_tokens
+
+
+class PersistentMemory:
+ """File-based persistent memory that survives across sessions.
+
+ Design:
+ - Frozen snapshot injected into system prompt at session start (preserves prompt cache).
+ - Disk writes via add()/remove() update files immediately but do NOT change the snapshot.
+ - Next session picks up the updated state.
+
+ Attributes:
+ snapshot: Frozen memory index text for system prompt injection.
+ """
+
+ def __init__(self, memory_dir: Optional[Path] = None) -> None:
+ """Initialize PersistentMemory.
+
+ Args:
+ memory_dir: Override memory directory (default: ~/.vibe-trading/memory/).
+ """
+ self._dir = memory_dir or MEMORY_BASE
+ self._dir.mkdir(parents=True, exist_ok=True)
+ self._index_path = self._dir / "MEMORY.md"
+ self._snapshot: str = ""
+ self._load_snapshot()
+
+ def _load_snapshot(self) -> None:
+ """Load index as frozen snapshot. Called once at init."""
+ if self._index_path.exists():
+ try:
+ text = self._index_path.read_text(encoding="utf-8")
+ lines = text.split("\n")[:MAX_INDEX_LINES]
+ self._snapshot = "\n".join(lines)
+ except OSError:
+ self._snapshot = ""
+
+ @property
+ def snapshot(self) -> str:
+ """Frozen memory index for system prompt injection."""
+ return self._snapshot
+
+ def _scan_entries(self) -> List[MemoryEntry]:
+ """Scan all .md files (except MEMORY.md) and parse frontmatter.
+
+ Returns:
+ List of parsed memory entries.
+ """
+ entries: List[MemoryEntry] = []
+ for path in sorted(self._dir.glob("*.md")):
+ if path.name == "MEMORY.md":
+ continue
+ try:
+ text = path.read_text(encoding="utf-8")
+ except OSError:
+ continue
+ meta, body = _parse_frontmatter(text)
+ entries.append(MemoryEntry(
+ path=path,
+ title=meta.get("name", path.stem),
+ description=meta.get("description", ""),
+ memory_type=meta.get("type", "project"),
+ body=body[:MAX_ENTRY_CHARS],
+ modified_at=path.stat().st_mtime,
+ ))
+ return entries
+
+ def find_relevant(self, query: str, max_results: int = MAX_RESULTS) -> List[MemoryEntry]:
+ """Keyword search across all memory entries.
+
+ Scoring: metadata_hits * 2.0 + body_hits * 1.0.
+
+ Args:
+ query: Search query.
+ max_results: Maximum entries to return.
+
+ Returns:
+ Top-scoring memory entries.
+ """
+ query_tokens = _tokenize(query)
+ if not query_tokens:
+ return []
+
+ scored: list[tuple[float, MemoryEntry]] = []
+ for entry in self._scan_entries():
+ meta_tokens = _tokenize(f"{entry.title} {entry.description}")
+ body_tokens = _tokenize(entry.body)
+ score = len(query_tokens & meta_tokens) * METADATA_WEIGHT + len(query_tokens & body_tokens)
+ if score > 0:
+ scored.append((score, entry))
+
+ scored.sort(key=lambda x: (-x[0], -x[1].modified_at))
+ return [entry for _, entry in scored[:max_results]]
+
+ def add(self, name: str, content: str, memory_type: str = "project",
+ description: str = "") -> Path:
+ """Save a new memory entry and update the index.
+
+ Args:
+ name: Memory name (used as filename slug).
+ content: Memory body text.
+ memory_type: One of user/feedback/project/reference.
+ description: One-line description for retrieval scoring.
+
+ Returns:
+ Path to the created memory file.
+ """
+ slug = re.sub(r"[^a-z0-9_-]", "_", name.lower().strip())[:60]
+ filename = f"{memory_type}_{slug}.md"
+ path = self._dir / filename
+
+ safe_name = name.replace("\n", " ").replace("\r", " ")
+ safe_desc = (description or name).replace("\n", " ").replace("\r", " ")
+ frontmatter = (
+ f"---\nname: {safe_name}\n"
+ f"description: {safe_desc}\n"
+ f"type: {memory_type}\n---\n\n"
+ f"{content}"
+ )
+ path.write_text(frontmatter, encoding="utf-8")
+ self._update_index(name, filename, description or name)
+ return path
+
+ def remove(self, name: str) -> bool:
+ """Remove a memory entry by name.
+
+ Args:
+ name: Memory name to remove.
+
+ Returns:
+ True if found and removed.
+ """
+ for entry in self._scan_entries():
+ if entry.title == name:
+ entry.path.unlink(missing_ok=True)
+ self._rebuild_index()
+ return True
+ return False
+
+ def _update_index(self, title: str, filename: str, description: str) -> None:
+ """Append or update an entry in MEMORY.md."""
+ new_line = f"- [{title}]({filename}) — {description}"
+
+ if self._index_path.exists():
+ lines = self._index_path.read_text(encoding="utf-8").split("\n")
+ updated = False
+ for i, line in enumerate(lines):
+ if f"[{title}]" in line:
+ lines[i] = new_line
+ updated = True
+ break
+ if not updated:
+ lines.append(new_line)
+ text = "\n".join(lines[:MAX_INDEX_LINES])
+ else:
+ text = new_line
+
+ self._index_path.write_text(text, encoding="utf-8")
+
+ def _rebuild_index(self) -> None:
+ """Rebuild MEMORY.md from all existing entry files."""
+ entries = self._scan_entries()
+ lines = [f"- [{e.title}]({e.path.name}) — {e.description}" for e in entries]
+ self._index_path.write_text("\n".join(lines[:MAX_INDEX_LINES]), encoding="utf-8")
diff --git a/agent/src/session/search.py b/agent/src/session/search.py
new file mode 100644
index 000000000..701d0dacd
--- /dev/null
+++ b/agent/src/session/search.py
@@ -0,0 +1,343 @@
+"""SQLite FTS5 session search index for cross-session full-text search.
+
+Stores an inverted index of all conversation messages. The primary data
+remains in the file-based SessionStore; this module provides a fast search
+layer on top.
+
+Database location: ~/.vibe-trading/sessions.db (WAL mode for concurrent reads).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import sqlite3
+import time
+from dataclasses import dataclass
+from datetime import datetime
+from pathlib import Path
+from typing import List, Optional
+
+logger = logging.getLogger(__name__)
+
+_DB_PATH = Path.home() / ".vibe-trading" / "sessions.db"
+
+
+@dataclass(frozen=True)
+class SearchMatch:
+ """A single search result from the FTS5 index.
+
+ Attributes:
+ session_id: Session ID.
+ title: Session title.
+ started_at: Human-readable start time.
+ message_count: Total messages in the session.
+ snippet: FTS5 snippet with match highlights (>>> <<<).
+ rank: FTS5 relevance rank (lower is better).
+ """
+
+ session_id: str
+ title: str
+ started_at: str
+ message_count: int
+ snippet: str
+ rank: float
+
+ def to_dict(self) -> dict:
+ """Serialize to JSON-safe dict."""
+ return {
+ "session_id": self.session_id,
+ "title": self.title,
+ "started_at": self.started_at,
+ "message_count": self.message_count,
+ "snippet": self.snippet,
+ }
+
+
+class SessionSearchIndex:
+ """SQLite FTS5 index for cross-session search.
+
+ Supports:
+ - Indexing individual messages as they arrive
+ - Full-text search with relevance ranking
+ - Bulk reindex from the file-based SessionStore
+ """
+
+ def __init__(self, db_path: Path = _DB_PATH) -> None:
+ """Initialize the search index.
+
+ Args:
+ db_path: Path to SQLite database file.
+ """
+ self.db_path = db_path
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
+ self._conn: Optional[sqlite3.Connection] = None
+ self._init_db()
+
+ def _get_conn(self) -> sqlite3.Connection:
+ """Get or create the SQLite connection (WAL mode)."""
+ if self._conn is None:
+ self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False)
+ self._conn.execute("PRAGMA journal_mode=WAL")
+ self._conn.execute("PRAGMA synchronous=NORMAL")
+ return self._conn
+
+ def _init_db(self) -> None:
+ """Create tables and FTS5 virtual table if they don't exist."""
+ conn = self._get_conn()
+ conn.executescript("""
+ CREATE TABLE IF NOT EXISTS sessions (
+ id TEXT PRIMARY KEY,
+ title TEXT NOT NULL DEFAULT '',
+ started_at REAL NOT NULL,
+ message_count INTEGER NOT NULL DEFAULT 0
+ );
+
+ CREATE TABLE IF NOT EXISTS messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ session_id TEXT NOT NULL,
+ role TEXT NOT NULL,
+ content TEXT NOT NULL,
+ tool_name TEXT,
+ timestamp REAL NOT NULL
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_messages_session
+ ON messages(session_id);
+ """)
+ # FTS5 virtual table — create separately (not inside executescript with IF NOT EXISTS
+ # because FTS5 syntax varies across SQLite versions)
+ try:
+ conn.execute("""
+ CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts
+ USING fts5(content, content=messages, content_rowid=id)
+ """)
+ except sqlite3.OperationalError:
+ pass # already exists or FTS5 not available
+
+ # Auto-sync triggers
+ for trigger_sql in [
+ """CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN
+ INSERT INTO messages_fts(rowid, content) VALUES (new.id, new.content);
+ END""",
+ """CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN
+ INSERT INTO messages_fts(messages_fts, rowid, content)
+ VALUES ('delete', old.id, old.content);
+ END""",
+ ]:
+ try:
+ conn.execute(trigger_sql)
+ except sqlite3.OperationalError:
+ pass
+ conn.commit()
+
+ def index_session(self, session_id: str, title: str = "") -> None:
+ """Upsert a session record.
+
+ Args:
+ session_id: Session ID.
+ title: Session title.
+ """
+ conn = self._get_conn()
+ conn.execute(
+ "INSERT OR REPLACE INTO sessions (id, title, started_at, message_count) "
+ "VALUES (?, ?, ?, COALESCE((SELECT message_count FROM sessions WHERE id = ?), 0))",
+ (session_id, title, time.time(), session_id),
+ )
+ conn.commit()
+
+ def index_message(self, session_id: str, role: str, content: str,
+ tool_name: Optional[str] = None) -> None:
+ """Index a single message.
+
+ Args:
+ session_id: Session ID.
+ role: Message role (user/assistant/tool).
+ content: Message text.
+ tool_name: Tool name if this is a tool result.
+ """
+ if not content or not content.strip():
+ return
+ conn = self._get_conn()
+ conn.execute(
+ "INSERT INTO messages (session_id, role, content, tool_name, timestamp) "
+ "VALUES (?, ?, ?, ?, ?)",
+ (session_id, role, content[:50_000], tool_name, time.time()),
+ )
+ conn.execute(
+ "UPDATE sessions SET message_count = message_count + 1 WHERE id = ?",
+ (session_id,),
+ )
+ conn.commit()
+
+ @staticmethod
+ def _sanitize_fts_query(query: str) -> str:
+ """Sanitize a user query for FTS5 MATCH syntax.
+
+ - Splits on non-alphanumeric/CJK to extract tokens
+ - Joins with OR so any-word-matches (not all-words-required)
+ - Quotes each token to prevent FTS5 operator interpretation
+
+ Args:
+ query: Raw user query string.
+
+ Returns:
+ FTS5-safe MATCH expression.
+ """
+ import re as _re
+ # Extract alphanumeric tokens (3+ chars) and CJK characters
+ tokens = _re.findall(r"[a-zA-Z0-9_]{2,}|[\u4e00-\u9fff\u3400-\u4dbf]", query)
+ if not tokens:
+ return '""'
+ # Quote each token and join with OR for broader matching
+ return " OR ".join(f'"{t}"' for t in tokens)
+
+ def search(self, query: str, max_sessions: int = 3) -> List[SearchMatch]:
+ """Full-text search across all sessions.
+
+ Args:
+ query: Search query (keywords or phrase).
+ max_sessions: Maximum number of distinct sessions to return.
+
+ Returns:
+ List of SearchMatch results, grouped by session, ranked by relevance.
+ """
+ conn = self._get_conn()
+ fts_query = self._sanitize_fts_query(query)
+ try:
+ cursor = conn.execute(
+ """
+ SELECT
+ m.session_id,
+ s.title,
+ s.started_at,
+ s.message_count,
+ snippet(messages_fts, 0, '>>>', '<<<', '...', 64) AS snippet,
+ rank
+ FROM messages_fts
+ JOIN messages m ON m.id = messages_fts.rowid
+ JOIN sessions s ON s.id = m.session_id
+ WHERE messages_fts MATCH ?
+ ORDER BY rank
+ LIMIT ?
+ """,
+ (fts_query, max_sessions * 5),
+ )
+ except sqlite3.OperationalError as exc:
+ logger.warning("FTS5 search failed: %s", exc)
+ return []
+
+ seen: dict[str, SearchMatch] = {}
+ for row in cursor.fetchall():
+ sid = row[0]
+ if sid in seen:
+ continue
+ seen[sid] = SearchMatch(
+ session_id=row[0],
+ title=row[1] or "(untitled)",
+ started_at=self._format_time(row[2]),
+ message_count=row[3],
+ snippet=row[4],
+ rank=row[5],
+ )
+ if len(seen) >= max_sessions:
+ break
+
+ return list(seen.values())
+
+ def reindex_from_store(self, store_base_dir: Path) -> int:
+ """Rebuild the entire index from file-based session store.
+
+ Args:
+ store_base_dir: Root directory of the SessionStore (contains session subdirs).
+
+ Returns:
+ Number of messages indexed.
+ """
+ if not store_base_dir.exists():
+ return 0
+
+ conn = self._get_conn()
+ conn.execute("DELETE FROM messages")
+ conn.execute("DELETE FROM sessions")
+ try:
+ conn.execute("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')")
+ except sqlite3.OperationalError:
+ pass
+ conn.commit()
+
+ count = 0
+ for session_dir in store_base_dir.iterdir():
+ if not session_dir.is_dir():
+ continue
+
+ session_file = session_dir / "session.json"
+ messages_file = session_dir / "messages.jsonl"
+
+ if not session_file.exists():
+ continue
+
+ try:
+ session_data = json.loads(session_file.read_text(encoding="utf-8"))
+ sid = session_data.get("session_id", session_dir.name)
+ title = session_data.get("title", "")
+
+ try:
+ ts = datetime.fromisoformat(session_data.get("created_at", "")).timestamp()
+ except (ValueError, TypeError):
+ ts = time.time()
+
+ self.index_session(sid, title)
+
+ if messages_file.exists():
+ for line in messages_file.read_text(encoding="utf-8").strip().splitlines():
+ if not line.strip():
+ continue
+ try:
+ msg = json.loads(line)
+ role = msg.get("role", "")
+ content = msg.get("content", "")
+ if content and role in ("user", "assistant"):
+ self.index_message(sid, role, content)
+ count += 1
+ except json.JSONDecodeError:
+ continue
+ except Exception as exc:
+ logger.warning("Failed to index session %s: %s", session_dir.name, exc)
+
+ return count
+
+ @staticmethod
+ def _format_time(epoch: float) -> str:
+ """Format epoch timestamp to human-readable string."""
+ try:
+ return datetime.fromtimestamp(epoch).strftime("%Y-%m-%d %H:%M")
+ except (OSError, ValueError):
+ return "unknown"
+
+ def close(self) -> None:
+ """Close the database connection."""
+ if self._conn:
+ self._conn.close()
+ self._conn = None
+
+
+import threading as _threading
+
+_shared_index: Optional[SessionSearchIndex] = None
+_shared_lock = _threading.Lock()
+
+
+def get_shared_index() -> SessionSearchIndex:
+ """Return a process-wide singleton SessionSearchIndex.
+
+ Thread-safe via double-checked locking. Used by both
+ SessionService (indexing) and SessionSearchTool (searching)
+ so they share one SQLite connection.
+ """
+ global _shared_index
+ if _shared_index is None:
+ with _shared_lock:
+ if _shared_index is None:
+ _shared_index = SessionSearchIndex()
+ return _shared_index
diff --git a/agent/src/session/service.py b/agent/src/session/service.py
index eefdb97ee..df3a9c30e 100644
--- a/agent/src/session/service.py
+++ b/agent/src/session/service.py
@@ -21,6 +21,7 @@ from src.session.models import (
Message,
Session,
)
+from src.session.search import get_shared_index
from src.session.store import SessionStore
@@ -50,6 +51,7 @@ class SessionService:
self.event_bus = event_bus
self.runs_dir = runs_dir
self._active_loops: Dict[str, "AgentLoop"] = {}
+ self._search_index = get_shared_index()
def create_session(self, title: str = "", config: Optional[Dict[str, Any]] = None) -> Session:
"""Create a new session.
@@ -63,6 +65,7 @@ class SessionService:
"""
session = Session(title=title, config=config or {})
self.store.create_session(session)
+ self._search_index.index_session(session.session_id, title)
self.event_bus.emit(session.session_id, "session.created", {"session_id": session.session_id, "title": title})
return session
@@ -96,6 +99,7 @@ class SessionService:
message = Message(session_id=session_id, role=role, content=content)
self.store.append_message(message)
+ self._search_index.index_message(session_id, role, content)
self.event_bus.emit(session_id, "message.received", {"message_id": message.message_id, "role": role, "content": content})
if role != "user":
@@ -200,6 +204,7 @@ class SessionService:
metadata=reply_metadata,
)
self.store.append_message(reply)
+ self._search_index.index_message(session.session_id, "assistant", reply.content)
self.event_bus.emit(
session.session_id,
"attempt.completed" if attempt.status == AttemptStatus.COMPLETED else "attempt.failed",
@@ -225,9 +230,10 @@ class SessionService:
from src.tools import build_registry
from src.providers.chat import ChatLLM
from src.agent.loop import AgentLoop
+ from src.memory.persistent import PersistentMemory
- registry = build_registry()
llm = ChatLLM()
+ pm = PersistentMemory()
session_id = attempt.session_id
attempt_id = attempt.attempt_id
@@ -238,10 +244,11 @@ class SessionService:
self.event_bus.emit(session_id, event_type, data)
agent = AgentLoop(
- registry=registry,
+ registry=build_registry(persistent_memory=pm),
llm=llm,
event_callback=event_callback,
max_iterations=50,
+ persistent_memory=pm,
)
self._active_loops[session_id] = agent
@@ -249,7 +256,7 @@ class SessionService:
history = self._convert_messages_to_history(messages) if messages else None
try:
- loop = asyncio.get_event_loop()
+ loop = asyncio.get_running_loop()
result = await loop.run_in_executor(
_AGENT_EXECUTOR,
lambda: agent.run(
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index 8a034735c..3956eba1e 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -1,7 +1,7 @@
-"""Swarm Worker: standalone worker execution engine based on the SubagentTool ReAct pattern.
+"""Swarm Worker: standalone worker execution engine with a lightweight ReAct loop.
-Reuses the SubagentTool ReAct loop (ChatLLM.chat + manual for-loop) without
-instantiating AgentLoop, keeping the agent core unchanged.
+Uses ChatLLM.chat + manual for-loop directly (without instantiating AgentLoop),
+keeping the worker self-contained and the agent core unchanged.
"""
from __future__ import annotations
@@ -187,9 +187,9 @@ def run_worker(
run_dir: Path,
event_callback: Callable[[SwarmEvent], None] | None = None,
) -> WorkerResult:
- """Execute a single worker task using the SubagentTool ReAct pattern.
+ """Execute a single worker task using a lightweight ReAct loop.
- Follows the exact same ReAct loop as SubagentTool:
+ Steps:
1. Build filtered ToolRegistry from agent_spec.tools
2. Create ChatLLM with agent_spec.model_name
3. Build system prompt with role + upstream summaries + filtered skills
@@ -251,7 +251,7 @@ def run_worker(
{"role": "user", "content": user_prompt},
]
- # 6. ReAct loop (EXACTLY like SubagentTool)
+ # 6. ReAct loop
artifact_dir = run_dir / "artifacts" / agent_id
artifact_dir.mkdir(parents=True, exist_ok=True)
diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.py
index 8f3b64867..188bc8340 100644
--- a/agent/src/tools/__init__.py
+++ b/agent/src/tools/__init__.py
@@ -1,51 +1,92 @@
-"""Tool registry: v7 atomic tools + domain tools."""
+"""Tool registry: auto-discovery via BaseTool.__subclasses__().
-from src.agent.tools import ToolRegistry
+Adding a new tool:
+ 1. Create a file in src/tools/ with a class extending BaseTool
+ 2. Done. It's automatically discovered and registered.
+Tools with missing dependencies can override check_available() → False
+to be silently excluded from the registry.
+"""
-def build_registry() -> ToolRegistry:
- """Build the v7 tool registry (atomic tools + domain tools).
+import importlib
+import logging
+import pkgutil
+from collections import deque
+from pathlib import Path
+
+from src.agent.tools import BaseTool, ToolRegistry
+
+logger = logging.getLogger(__name__)
+
+_SUBCLASSES_CACHE: list[type[BaseTool]] | None = None
+
+
+def _discover_subclasses() -> list[type[BaseTool]]:
+ """Import all modules in this package, then collect BaseTool subclasses.
+
+ Results are cached after the first call.
+
+ Returns:
+ List of concrete BaseTool subclasses with a non-empty name.
+ """
+ global _SUBCLASSES_CACHE
+ if _SUBCLASSES_CACHE is not None:
+ return _SUBCLASSES_CACHE
+
+ pkg_dir = str(Path(__file__).parent)
+ for _, module_name, _ in pkgutil.iter_modules([pkg_dir]):
+ if module_name.startswith("_"):
+ continue
+ try:
+ importlib.import_module(f"src.tools.{module_name}")
+ except Exception as exc:
+ logger.warning("Skipped src.tools.%s: %s", module_name, exc)
+
+ classes: list[type[BaseTool]] = []
+ queue = deque(BaseTool.__subclasses__())
+ while queue:
+ cls = queue.popleft()
+ if cls.name:
+ classes.append(cls)
+ queue.extend(cls.__subclasses__())
+
+ _SUBCLASSES_CACHE = classes
+ return classes
+
+
+def build_registry(*, persistent_memory: "PersistentMemory | None" = None) -> ToolRegistry:
+ """Build the tool registry via auto-discovery.
+
+ Args:
+ persistent_memory: Shared PersistentMemory instance. Injected into
+ tools that need it (e.g. RememberTool) so all tools share one
+ instance instead of each creating their own.
Returns:
- ToolRegistry containing all v7 tools.
+ ToolRegistry containing all available tools.
"""
- from src.tools.bash_tool import BashTool
- from src.tools.read_file_tool import ReadFileTool
- from src.tools.write_file_tool import WriteFileTool
- from src.tools.edit_file_tool import EditFileTool
- from src.tools.load_skill_tool import LoadSkillTool
- from src.tools.backtest_tool import BacktestTool
- from src.tools.pattern_tool import PatternTool
- from src.tools.compact_tool import CompactTool
- from src.tools.subagent_tool import SubagentTool
- from src.tools.task_tools import TaskCreateTool, TaskUpdateTool, TaskListTool, TaskGetTool
- from src.tools.background_tools import BackgroundRunTool, CheckBackgroundTool
- from src.tools.web_reader_tool import WebReaderTool
- from src.tools.web_search_tool import WebSearchTool
- from src.tools.doc_reader_tool import DocReaderTool
- from src.tools.factor_analysis_tool import FactorAnalysisTool
- from src.tools.options_pricing_tool import OptionsPricingTool
- from src.tools.swarm_tool import SwarmTool
+ from src.tools.remember_tool import RememberTool
+
registry = ToolRegistry()
- for tool in [BashTool(), ReadFileTool(), WriteFileTool(),
- EditFileTool(), LoadSkillTool(), BacktestTool(),
- PatternTool(), CompactTool(), SubagentTool(),
- TaskCreateTool(), TaskUpdateTool(), TaskListTool(), TaskGetTool(),
- BackgroundRunTool(), CheckBackgroundTool(),
- WebReaderTool(), WebSearchTool(), DocReaderTool(),
- FactorAnalysisTool(), OptionsPricingTool(), SwarmTool()]:
- registry.register(tool)
+ for cls in _discover_subclasses():
+ try:
+ if not cls.check_available():
+ logger.info("Tool %s unavailable, skipping", cls.name)
+ continue
+ if cls is RememberTool and persistent_memory is not None:
+ registry.register(cls(memory=persistent_memory))
+ else:
+ registry.register(cls())
+ except Exception as exc:
+ logger.warning("Failed to register tool %s: %s", cls.name, exc)
return registry
def build_filtered_registry(tool_names: list[str]) -> ToolRegistry:
"""Build a ToolRegistry with only specified tools.
- Creates the full registry, then filters to include only tools
- whose names appear in the provided list. Unknown names are silently skipped.
-
Args:
- tool_names: Tool names to include in the filtered registry.
+ tool_names: Tool names to include.
Returns:
ToolRegistry containing only the requested tools.
diff --git a/agent/src/tools/background_tools.py b/agent/src/tools/background_tools.py
index bdd87c0e3..98eb83ccb 100644
--- a/agent/src/tools/background_tools.py
+++ b/agent/src/tools/background_tools.py
@@ -86,6 +86,7 @@ class BackgroundRunTool(BaseTool):
parameters = {"type": "object", "properties": {
"command": {"type": "string", "description": "Shell command to run in background"},
}, "required": ["command"]}
+ is_readonly = False
def execute(self, **kw: Any) -> str:
return _BG.run(kw["command"])
diff --git a/agent/src/tools/backtest_tool.py b/agent/src/tools/backtest_tool.py
index 5f6071a60..4bf0470a9 100644
--- a/agent/src/tools/backtest_tool.py
+++ b/agent/src/tools/backtest_tool.py
@@ -75,6 +75,7 @@ class BacktestTool(BaseTool):
"required": ["run_dir"],
}
repeatable = True
+ is_readonly = False
def execute(self, **kwargs) -> str:
"""Execute backtest."""
diff --git a/agent/src/tools/bash_tool.py b/agent/src/tools/bash_tool.py
index 09664d631..26e8288b4 100644
--- a/agent/src/tools/bash_tool.py
+++ b/agent/src/tools/bash_tool.py
@@ -26,6 +26,7 @@ class BashTool(BaseTool):
"required": ["command"],
}
repeatable = True
+ is_readonly = False
def execute(self, **kwargs: Any) -> str:
"""Execute a shell command.
diff --git a/agent/src/tools/compact_tool.py b/agent/src/tools/compact_tool.py
index 5a8f93441..59d8f22dd 100644
--- a/agent/src/tools/compact_tool.py
+++ b/agent/src/tools/compact_tool.py
@@ -12,8 +12,15 @@ class CompactTool(BaseTool):
"""Compress conversation history to free context space."""
name = "compact"
- description = "Compress conversation history to free context space. Call when the conversation feels long or you're losing track of earlier context."
- parameters = {"type": "object", "properties": {}, "required": []}
+ description = "Compress conversation history to free context space. Call when the conversation feels long or you're losing track of earlier context. Optionally specify focus_topic to preserve details about a specific subject."
+ parameters = {
+ "type": "object",
+ "properties": {
+ "focus_topic": {"type": "string", "description": "Topic to preserve in detail during compression (e.g. 'BTC-USDT backtest')"},
+ },
+ "required": [],
+ }
+ is_readonly = False
def execute(self, **kwargs: Any) -> str:
return json.dumps({"status": "ok", "message": "Compression triggered"})
diff --git a/agent/src/tools/edit_file_tool.py b/agent/src/tools/edit_file_tool.py
index 479f604d5..c5a775aaa 100644
--- a/agent/src/tools/edit_file_tool.py
+++ b/agent/src/tools/edit_file_tool.py
@@ -15,6 +15,7 @@ class EditFileTool(BaseTool):
name = "edit_file"
description = "Find and replace the first occurrence of old_text with new_text in a file."
+ is_readonly = False
parameters = {
"type": "object",
"properties": {
diff --git a/agent/src/tools/remember_tool.py b/agent/src/tools/remember_tool.py
new file mode 100644
index 000000000..0fe903772
--- /dev/null
+++ b/agent/src/tools/remember_tool.py
@@ -0,0 +1,109 @@
+"""Remember tool: LLM-initiated persistent memory operations (save / recall / forget)."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from src.agent.tools import BaseTool
+from src.memory.persistent import PersistentMemory
+
+
+class RememberTool(BaseTool):
+ """Save, recall, or forget cross-session memories.
+
+ Memories persist to ~/.vibe-trading/memory/ and survive across sessions.
+ """
+
+ name = "remember"
+ description = (
+ "Persistent cross-session memory. "
+ "save: store user preferences, strategy insights, or project context. "
+ "recall: search past memories by keyword. "
+ "forget: remove a memory by title."
+ )
+ is_readonly = False
+ parameters = {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["save", "recall", "forget"],
+ "description": "save | recall | forget",
+ },
+ "title": {
+ "type": "string",
+ "description": "Memory title (for save/forget)",
+ },
+ "content": {
+ "type": "string",
+ "description": "Memory content (for save)",
+ },
+ "memory_type": {
+ "type": "string",
+ "enum": ["user", "feedback", "project", "reference"],
+ "description": "Memory category (default: project)",
+ },
+ "query": {
+ "type": "string",
+ "description": "Search query (for recall)",
+ },
+ },
+ "required": ["action"],
+ }
+ repeatable = True
+
+ def __init__(self, memory: PersistentMemory | None = None) -> None:
+ """Initialize RememberTool.
+
+ Args:
+ memory: PersistentMemory instance (auto-created if omitted).
+ """
+ self._memory = memory or PersistentMemory()
+
+ def execute(self, **kwargs: Any) -> str:
+ """Execute a memory action.
+
+ Args:
+ **kwargs: Must include action; other params depend on action.
+
+ Returns:
+ JSON result string.
+ """
+ action = kwargs.get("action", "save")
+
+ if action == "save":
+ return self._save(kwargs)
+ if action == "recall":
+ return self._recall(kwargs)
+ if action == "forget":
+ return self._forget(kwargs)
+ return json.dumps({"status": "error", "error": f"Unknown action: {action}"})
+
+ def _save(self, kwargs: dict) -> str:
+ title = kwargs.get("title", "")
+ content = kwargs.get("content", "")
+ if not title or not content:
+ return json.dumps({"status": "error", "error": "title and content required"})
+ memory_type = kwargs.get("memory_type", "project")
+ path = self._memory.add(title, content, memory_type, description=title)
+ return json.dumps({"status": "ok", "message": f"Saved: {title}", "path": str(path)})
+
+ def _recall(self, kwargs: dict) -> str:
+ query = kwargs.get("query", "")
+ if not query:
+ return json.dumps({"status": "error", "error": "query required"})
+ entries = self._memory.find_relevant(query)
+ results = [
+ {"title": e.title, "type": e.memory_type, "content": e.body[:2000]}
+ for e in entries
+ ]
+ return json.dumps({"status": "ok", "count": len(results), "memories": results}, ensure_ascii=False)
+
+ def _forget(self, kwargs: dict) -> str:
+ title = kwargs.get("title", "")
+ if not title:
+ return json.dumps({"status": "error", "error": "title required"})
+ removed = self._memory.remove(title)
+ msg = f"Removed: {title}" if removed else f"Not found: {title}"
+ return json.dumps({"status": "ok" if removed else "not_found", "message": msg})
diff --git a/agent/src/tools/session_search_tool.py b/agent/src/tools/session_search_tool.py
new file mode 100644
index 000000000..61bf3b474
--- /dev/null
+++ b/agent/src/tools/session_search_tool.py
@@ -0,0 +1,67 @@
+"""Session search tool: FTS5 cross-session search for past conversations."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from src.agent.tools import BaseTool
+
+
+class SessionSearchTool(BaseTool):
+ """Search past conversation sessions by keyword using SQLite FTS5."""
+
+ name = "session_search"
+ description = (
+ "Search past conversation sessions by keyword. Returns matching sessions "
+ "with context snippets. Use when the user references past work, previous "
+ "strategies, or earlier conversations."
+ )
+ parameters = {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Search query (keywords or phrase)",
+ },
+ "max_results": {
+ "type": "integer",
+ "description": "Max sessions to return (default 3, max 10)",
+ "default": 3,
+ },
+ },
+ "required": ["query"],
+ }
+ repeatable = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Search past sessions.
+
+ Args:
+ **kwargs: Must include query; optionally max_results.
+
+ Returns:
+ JSON with search results or error.
+ """
+ query = kwargs.get("query", "")
+ if not query:
+ return json.dumps({"status": "error", "error": "query required"})
+
+ max_results = min(int(kwargs.get("max_results", 3)), 10)
+
+ try:
+ from src.session.search import get_shared_index
+ matches = get_shared_index().search(query, max_sessions=max_results)
+
+ if not matches:
+ return json.dumps(
+ {"status": "ok", "message": f"No past sessions matching '{query}'", "results": []},
+ ensure_ascii=False,
+ )
+
+ return json.dumps(
+ {"status": "ok", "query": query, "results": [m.to_dict() for m in matches]},
+ ensure_ascii=False,
+ )
+ except Exception as exc:
+ return json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False)
diff --git a/agent/src/tools/skill_writer_tool.py b/agent/src/tools/skill_writer_tool.py
new file mode 100644
index 000000000..7e4eb4e7f
--- /dev/null
+++ b/agent/src/tools/skill_writer_tool.py
@@ -0,0 +1,352 @@
+"""Skill management tools: full CRUD + auxiliary file support.
+
+User-created skills are stored separately from bundled skills:
+ ~/.vibe-trading/skills/user/<skill-name>/
+ SKILL.md # Main skill document
+ references/ # Reference materials
+ templates/ # Code/config templates
+ examples/ # Example usage
+ assets/ # Static files
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import shutil
+from pathlib import Path
+from typing import Any
+
+from src.agent.skills import USER_SKILLS_DIR
+from src.agent.tools import BaseTool
+
+_ALLOWED_SUBDIRS = {"references", "templates", "examples", "assets"}
+
+
+def _sanitize_skill_name(name: str) -> str:
+ """Sanitize skill name to a safe directory slug."""
+ return re.sub(r"[^a-z0-9-]", "-", name.lower().strip())[:60]
+
+
+class SaveSkillTool(BaseTool):
+ """Save a successful workflow as a reusable skill."""
+
+ name = "save_skill"
+ description = (
+ "Save a successful workflow or strategy template as a reusable skill. "
+ "The skill will be available in future sessions via load_skill."
+ )
+ is_readonly = False
+ parameters = {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Skill name (lowercase, a-z0-9 and hyphens, e.g. 'crypto-mean-reversion')",
+ },
+ "content": {
+ "type": "string",
+ "description": "Full SKILL.md content including frontmatter (---\\nname: ...\\n---) and body",
+ },
+ "category": {
+ "type": "string",
+ "description": "Skill category (e.g. strategy, analysis, flow). Default: user",
+ },
+ },
+ "required": ["name", "content"],
+ }
+ repeatable = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Create or overwrite a user skill.
+
+ Args:
+ **kwargs: Must include name and content.
+
+ Returns:
+ JSON result string.
+ """
+ name = kwargs.get("name", "")
+ content = kwargs.get("content", "")
+ category = kwargs.get("category", "user")
+
+ if not name or not content:
+ return json.dumps({"status": "error", "error": "name and content required"})
+
+ slug = _sanitize_skill_name(name)
+ skill_dir = USER_SKILLS_DIR / slug
+ skill_dir.mkdir(parents=True, exist_ok=True)
+ skill_path = skill_dir / "SKILL.md"
+
+ # Ensure frontmatter exists
+ if not content.strip().startswith("---"):
+ content = (
+ f"---\nname: {slug}\n"
+ f"description: User-created skill\n"
+ f"category: {category}\n---\n\n{content}"
+ )
+
+ skill_path.write_text(content, encoding="utf-8")
+ return json.dumps({
+ "status": "ok",
+ "message": f"Skill '{slug}' saved. Available via load_skill(\"{slug}\") in future sessions.",
+ "path": str(skill_path),
+ })
+
+
+class PatchSkillTool(BaseTool):
+ """Patch an existing skill with find-and-replace."""
+
+ name = "patch_skill"
+ description = (
+ "Fix or update an existing skill by replacing specific text. "
+ "Useful when a skill has outdated API parameters or incorrect examples."
+ )
+ is_readonly = False
+ parameters = {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Skill name to patch",
+ },
+ "find": {
+ "type": "string",
+ "description": "Text to find (exact match)",
+ },
+ "replace": {
+ "type": "string",
+ "description": "Replacement text",
+ },
+ },
+ "required": ["name", "find", "replace"],
+ }
+ repeatable = True
+
+ def execute(self, **kwargs: Any) -> str:
+ """Apply a find-and-replace patch to a skill.
+
+ Searches user skills first, then bundled skills (copies to user dir before patching).
+
+ Args:
+ **kwargs: Must include name, find, replace.
+
+ Returns:
+ JSON result string.
+ """
+ name = kwargs.get("name", "")
+ find_text = kwargs.get("find", "")
+ replace_text = kwargs.get("replace", "")
+
+ if not name or not find_text:
+ return json.dumps({"status": "error", "error": "name and find required"})
+
+ slug = _sanitize_skill_name(name)
+ user_path = USER_SKILLS_DIR / slug / "SKILL.md"
+ bundled_dir = Path(__file__).resolve().parents[1] / "skills"
+ bundled_path = bundled_dir / slug / "SKILL.md"
+
+ if user_path.exists():
+ skill_path = user_path
+ elif bundled_path.exists():
+ # Copy bundled skill to user dir before patching
+ user_path.parent.mkdir(parents=True, exist_ok=True)
+ user_path.write_text(bundled_path.read_text(encoding="utf-8"), encoding="utf-8")
+ skill_path = user_path
+ else:
+ return json.dumps({"status": "error", "error": f"Skill '{name}' not found"})
+
+ content = skill_path.read_text(encoding="utf-8")
+ if find_text not in content:
+ return json.dumps({"status": "error", "error": f"Text not found in skill '{name}'"})
+
+ patched = content.replace(find_text, replace_text, 1)
+ skill_path.write_text(patched, encoding="utf-8")
+ return json.dumps({
+ "status": "ok",
+ "message": f"Patched skill '{name}': replaced 1 occurrence.",
+ "path": str(skill_path),
+ })
+
+
+class DeleteSkillTool(BaseTool):
+ """Delete a user-created skill entirely."""
+
+ name = "delete_skill"
+ description = (
+ "Delete a user-created skill and all its files. "
+ "Only works on skills in ~/.vibe-trading/skills/user/. "
+ "Cannot delete bundled skills."
+ )
+ is_readonly = False
+ parameters = {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "Skill name to delete",
+ },
+ },
+ "required": ["name"],
+ }
+
+ def execute(self, **kwargs: Any) -> str:
+ """Delete a user skill directory.
+
+ Args:
+ **kwargs: Must include name.
+
+ Returns:
+ JSON result string.
+ """
+ name = kwargs.get("name", "").strip()
+ if not name:
+ return json.dumps({"status": "error", "error": "name required"})
+
+ slug = _sanitize_skill_name(name)
+ skill_dir = USER_SKILLS_DIR / slug
+ if not skill_dir.exists():
+ return json.dumps({"status": "error", "error": f"User skill '{slug}' not found"})
+
+ shutil.rmtree(skill_dir)
+ return json.dumps({
+ "status": "ok",
+ "message": f"Deleted skill '{name}' and all its files.",
+ })
+
+
+class SkillFileTool(BaseTool):
+ """Manage auxiliary files in a skill directory (references, templates, examples, assets)."""
+
+ name = "skill_file"
+ description = (
+ "Manage auxiliary files in a skill directory. "
+ "Actions: write (create/overwrite a file), remove (delete a file), list (show all files). "
+ "Supported subdirs: references, templates, examples, assets."
+ )
+ is_readonly = False
+ repeatable = True
+ parameters = {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["write", "remove", "list"],
+ "description": "Action to perform",
+ },
+ "skill_name": {
+ "type": "string",
+ "description": "Skill name (must exist in user skills)",
+ },
+ "path": {
+ "type": "string",
+ "description": "File path relative to skill dir (e.g. 'templates/sma_crossover.py'). Required for write/remove.",
+ },
+ "content": {
+ "type": "string",
+ "description": "File content. Required for write action.",
+ },
+ },
+ "required": ["action", "skill_name"],
+ }
+
+ def execute(self, **kwargs: Any) -> str:
+ """Manage skill auxiliary files.
+
+ Args:
+ **kwargs: action, skill_name, and optionally path/content.
+
+ Returns:
+ JSON result string.
+ """
+ action = kwargs.get("action", "")
+ skill_name = kwargs.get("skill_name", "").strip()
+
+ if not skill_name:
+ return json.dumps({"status": "error", "error": "skill_name required"})
+
+ skill_dir = USER_SKILLS_DIR / _sanitize_skill_name(skill_name)
+ if not skill_dir.exists():
+ return json.dumps({"status": "error", "error": f"User skill '{skill_name}' not found. Create it with save_skill first."})
+
+ if action == "list":
+ return self._list_files(skill_dir, skill_name)
+ elif action == "write":
+ return self._write_file(skill_dir, skill_name, kwargs)
+ elif action == "remove":
+ return self._remove_file(skill_dir, skill_name, kwargs)
+ else:
+ return json.dumps({"status": "error", "error": f"Unknown action '{action}'. Use write, remove, or list."})
+
+ @staticmethod
+ def _list_files(skill_dir: Path, skill_name: str) -> str:
+ """List all files in a skill directory."""
+ files = []
+ for path in sorted(skill_dir.rglob("*")):
+ if path.is_file():
+ rel = path.relative_to(skill_dir)
+ files.append({"path": str(rel), "size": path.stat().st_size})
+ return json.dumps({
+ "status": "ok",
+ "skill": skill_name,
+ "files": files,
+ }, ensure_ascii=False)
+
+ @staticmethod
+ def _write_file(skill_dir: Path, skill_name: str, kwargs: dict) -> str:
+ """Write a file to a skill subdirectory."""
+ rel_path = kwargs.get("path", "").strip()
+ content = kwargs.get("content", "")
+ if not rel_path:
+ return json.dumps({"status": "error", "error": "path required for write"})
+ if not content:
+ return json.dumps({"status": "error", "error": "content required for write"})
+
+ # Validate subdirectory
+ parts = Path(rel_path).parts
+ if len(parts) < 2 or parts[0] not in _ALLOWED_SUBDIRS:
+ return json.dumps({
+ "status": "error",
+ "error": f"Path must start with one of: {', '.join(sorted(_ALLOWED_SUBDIRS))}. Got: '{parts[0] if parts else ''}'",
+ })
+
+ target = skill_dir / rel_path
+ # Safety: prevent path traversal
+ try:
+ target.resolve().relative_to(skill_dir.resolve())
+ except ValueError:
+ return json.dumps({"status": "error", "error": "Path escapes skill directory"})
+
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+ return json.dumps({
+ "status": "ok",
+ "message": f"Written {rel_path} to skill '{skill_name}'.",
+ "path": str(target),
+ })
+
+ @staticmethod
+ def _remove_file(skill_dir: Path, skill_name: str, kwargs: dict) -> str:
+ """Remove a file from a skill directory."""
+ rel_path = kwargs.get("path", "").strip()
+ if not rel_path:
+ return json.dumps({"status": "error", "error": "path required for remove"})
+
+ # Prevent deleting SKILL.md (use delete_skill for that)
+ if Path(rel_path).name == "SKILL.md":
+ return json.dumps({"status": "error", "error": "Cannot remove SKILL.md. Use delete_skill to remove the entire skill."})
+
+ target = skill_dir / rel_path
+ try:
+ target.resolve().relative_to(skill_dir.resolve())
+ except ValueError:
+ return json.dumps({"status": "error", "error": "Path escapes skill directory"})
+
+ if not target.exists():
+ return json.dumps({"status": "error", "error": f"File not found: {rel_path}"})
+
+ target.unlink()
+ return json.dumps({
+ "status": "ok",
+ "message": f"Removed {rel_path} from skill '{skill_name}'.",
+ })
diff --git a/agent/src/tools/subagent_tool.py b/agent/src/tools/subagent_tool.py
deleted file mode 100644
index 4982ea008..000000000
--- a/agent/src/tools/subagent_tool.py
+++ /dev/null
@@ -1,101 +0,0 @@
-"""Subagent tool: isolated-context child agent that shares the filesystem and returns only a summary."""
-
-from __future__ import annotations
-
-import json
-import os
-import time
-from typing import Any
-
-from src.agent.tools import BaseTool, ToolRegistry
-from src.agent.context import ContextBuilder
-
-_MAX_SUBAGENT_ITERATIONS = int(os.getenv("SUBAGENT_MAX_ITER", "25"))
-_MAX_SUBAGENT_TIMEOUT_SEC = int(os.getenv("SUBAGENT_TIMEOUT", "300"))
-_MAX_SUBAGENT_TOKEN_ESTIMATE = 30000
-
-
-class SubagentTool(BaseTool):
- """Spawn a child agent to execute an independent task with isolated context."""
-
- name = "subagent"
- description = (
- "Spawn a subagent with fresh context. It shares the filesystem but not "
- "conversation history. Use for parallel research, isolated exploration, "
- "or tasks that would pollute the main context. Returns only a summary."
- )
- parameters = {
- "type": "object",
- "properties": {
- "prompt": {"type": "string", "description": "Task for the subagent"},
- "description": {"type": "string", "description": "Short label for display"},
- },
- "required": ["prompt"],
- }
-
- def execute(self, **kwargs: Any) -> str:
- """Start a child agent and return its summary.
-
- Three guards against infinite loops:
- - Iteration cap: _MAX_SUBAGENT_ITERATIONS rounds
- - Time cap: _MAX_SUBAGENT_TIMEOUT_SEC seconds
- - Token estimate cap: _MAX_SUBAGENT_TOKEN_ESTIMATE tokens
-
- Args:
- **kwargs: Must include prompt (str). Optional run_dir (str) and description (str).
-
- Returns:
- JSON string with status and summary fields.
- """
- prompt = kwargs["prompt"]
- run_dir = kwargs.get("run_dir")
-
- from src.providers.chat import ChatLLM
- from src.tools.bash_tool import BashTool
- from src.tools.read_file_tool import ReadFileTool
- from src.tools.write_file_tool import WriteFileTool
- from src.tools.edit_file_tool import EditFileTool
- from src.tools.load_skill_tool import LoadSkillTool
- from src.tools.backtest_tool import BacktestTool
-
- llm = ChatLLM()
- child = ToolRegistry()
- for t in [BashTool(), ReadFileTool(), WriteFileTool(),
- EditFileTool(), LoadSkillTool(), BacktestTool()]:
- child.register(t)
-
- messages = [
- {"role": "system", "content": "You are a quantitative research subagent. Complete the task using tools, then summarize findings."},
- {"role": "user", "content": prompt},
- ]
-
- t0 = time.monotonic()
- for iteration in range(_MAX_SUBAGENT_ITERATIONS):
- elapsed = time.monotonic() - t0
- if elapsed > _MAX_SUBAGENT_TIMEOUT_SEC:
- return json.dumps(
- {"status": "timeout", "summary": f"Subagent timed out after {elapsed:.0f}s ({iteration} iterations)"},
- ensure_ascii=False,
- )
-
- token_estimate = len(json.dumps(messages)) // 4
- if token_estimate > _MAX_SUBAGENT_TOKEN_ESTIMATE:
- return json.dumps(
- {"status": "token_limit", "summary": f"Subagent context too large (~{token_estimate} tokens, {iteration} iterations)"},
- ensure_ascii=False,
- )
-
- response = llm.chat(messages, tools=child.get_definitions())
- if not response.has_tool_calls:
- return json.dumps({"status": "ok", "summary": response.content or "(no summary)"}, ensure_ascii=False)
- messages.append(ContextBuilder.format_assistant_tool_calls(response.tool_calls, content=response.content))
- for tc in response.tool_calls:
- if run_dir and "run_dir" not in tc.arguments:
- tc.arguments["run_dir"] = run_dir
- result = child.execute(tc.name, tc.arguments)
- messages.append(ContextBuilder.format_tool_result(tc.id, tc.name, result[:10000]))
-
- return json.dumps(
- {"status": "iteration_limit", "summary": f"Subagent hit iteration limit ({_MAX_SUBAGENT_ITERATIONS} iterations)"},
- ensure_ascii=False,
- )
diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.py
index bba8f111a..1d42958b2 100644
--- a/agent/src/tools/swarm_tool.py
+++ b/agent/src/tools/swarm_tool.py
@@ -582,6 +582,7 @@ class SwarmTool(BaseTool):
},
"required": ["prompt"],
}
+ is_readonly = False
def execute(self, **kwargs: Any) -> str:
"""Start a swarm run: auto-match preset, extract variables, wait for completion.
diff --git a/agent/src/tools/task_tools.py b/agent/src/tools/task_tools.py
deleted file mode 100644
index dcfe29301..000000000
--- a/agent/src/tools/task_tools.py
+++ /dev/null
@@ -1,135 +0,0 @@
-"""Task system: persistent tasks + dependency graph stored as JSON files."""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-from typing import Any
-
-from src.agent.tools import BaseTool
-
-TASKS_DIR = Path(__file__).resolve().parents[2] / ".tasks"
-
-
-class TaskManager:
- """Task CRUD + dependency graph; one JSON file per task."""
-
- def __init__(self) -> None:
- self.dir = TASKS_DIR
- self.dir.mkdir(exist_ok=True)
- self._next_id = self._max_id() + 1
-
- def _max_id(self) -> int:
- ids = [int(f.stem.split("_")[1]) for f in self.dir.glob("task_*.json")]
- return max(ids) if ids else 0
-
- def _load(self, task_id: int) -> dict:
- path = self.dir / f"task_{task_id}.json"
- if not path.exists():
- raise ValueError(f"Task {task_id} not found")
- return json.loads(path.read_text(encoding="utf-8"))
-
- def _save(self, task: dict) -> None:
- path = self.dir / f"task_{task['id']}.json"
- path.write_text(json.dumps(task, indent=2, ensure_ascii=False), encoding="utf-8")
-
- def create(self, subject: str, description: str = "") -> str:
- task = {"id": self._next_id, "subject": subject, "description": description,
- "status": "pending", "blockedBy": [], "blocks": []}
- self._save(task)
- self._next_id += 1
- return json.dumps(task, indent=2, ensure_ascii=False)
-
- def get(self, task_id: int) -> str:
- return json.dumps(self._load(task_id), indent=2, ensure_ascii=False)
-
- def update(self, task_id: int, status: str = None,
- addBlockedBy: list = None, addBlocks: list = None) -> str:
- task = self._load(task_id)
- if status:
- task["status"] = status
- if status == "completed":
- self._clear_dep(task_id)
- if addBlockedBy:
- task["blockedBy"] = list(set(task["blockedBy"] + addBlockedBy))
- if addBlocks:
- task["blocks"] = list(set(task["blocks"] + addBlocks))
- for bid in addBlocks:
- try:
- blocked = self._load(bid)
- if task_id not in blocked["blockedBy"]:
- blocked["blockedBy"].append(task_id)
- self._save(blocked)
- except ValueError:
- pass
- self._save(task)
- return json.dumps(task, indent=2, ensure_ascii=False)
-
- def _clear_dep(self, completed_id: int) -> None:
- for f in self.dir.glob("task_*.json"):
- task = json.loads(f.read_text(encoding="utf-8"))
- if completed_id in task.get("blockedBy", []):
- task["blockedBy"].remove(completed_id)
- self._save(task)
-
- def list_all(self) -> str:
- tasks = [json.loads(f.read_text(encoding="utf-8")) for f in sorted(self.dir.glob("task_*.json"))]
- if not tasks:
- return "No tasks."
- lines = []
- for t in tasks:
- m = {"pending": "[ ]", "in_progress": "[>]", "completed": "[x]"}.get(t["status"], "[?]")
- b = f" (blocked by: {t['blockedBy']})" if t.get("blockedBy") else ""
- lines.append(f"{m} #{t['id']}: {t['subject']}{b}")
- return "\n".join(lines)
-
-
-TASKS = TaskManager()
-
-
-class TaskCreateTool(BaseTool):
- name = "task_create"
- description = "Create a new task."
- parameters = {"type": "object", "properties": {
- "subject": {"type": "string"}, "description": {"type": "string"}
- }, "required": ["subject"]}
-
- def execute(self, **kw: Any) -> str:
- return TASKS.create(kw["subject"], kw.get("description", ""))
-
-
-class TaskUpdateTool(BaseTool):
- name = "task_update"
- description = "Update a task's status or dependencies."
- parameters = {"type": "object", "properties": {
- "task_id": {"type": "integer"},
- "status": {"type": "string", "enum": ["pending", "in_progress", "completed"]},
- "addBlockedBy": {"type": "array", "items": {"type": "integer"}},
- "addBlocks": {"type": "array", "items": {"type": "integer"}},
- }, "required": ["task_id"]}
- repeatable = True
-
- def execute(self, **kw: Any) -> str:
- return TASKS.update(kw["task_id"], kw.get("status"), kw.get("addBlockedBy"), kw.get("addBlocks"))
-
-
-class TaskListTool(BaseTool):
- name = "task_list"
- description = "List all tasks with status summary."
- parameters = {"type": "object", "properties": {}, "required": []}
- repeatable = True
-
- def execute(self, **kw: Any) -> str:
- return TASKS.list_all()
-
-
-class TaskGetTool(BaseTool):
- name = "task_get"
- description = "Get full details of a task by ID."
- parameters = {"type": "object", "properties": {
- "task_id": {"type": "integer"},
- }, "required": ["task_id"]}
- repeatable = True
-
- def execute(self, **kw: Any) -> str:
- return TASKS.get(kw["task_id"])
diff --git a/agent/src/tools/web_search_tool.py b/agent/src/tools/web_search_tool.py
index 5d4f936b5..f94f8f38f 100644
--- a/agent/src/tools/web_search_tool.py
+++ b/agent/src/tools/web_search_tool.py
@@ -12,6 +12,18 @@ class WebSearchTool(BaseTool):
"""Search the web via DuckDuckGo and return top results."""
name = "web_search"
+
+ @classmethod
+ def check_available(cls) -> bool:
+ """Available only if ddgs or duckduckgo_search is installed."""
+ try:
+ try:
+ import ddgs # noqa: F401
+ except ImportError:
+ import duckduckgo_search # noqa: F401
+ return True
+ except ImportError:
+ return False
description = (
"Search the web via DuckDuckGo. Returns top results with title, URL, "
"and snippet. Use this to find information, news, or URLs before "
diff --git a/agent/src/tools/write_file_tool.py b/agent/src/tools/write_file_tool.py
index fccb91093..445591908 100644
--- a/agent/src/tools/write_file_tool.py
+++ b/agent/src/tools/write_file_tool.py
@@ -15,6 +15,7 @@ class WriteFileTool(BaseTool):
name = "write_file"
description = "Write content to a file in the workspace. Creates parent directories automatically."
+ is_readonly = False
parameters = {
"type": "object",
"properties": {
diff --git a/agent/tests/test_loop_helpers.py b/agent/tests/test_loop_helpers.py
new file mode 100644
index 000000000..c2756b61c
--- /dev/null
+++ b/agent/tests/test_loop_helpers.py
@@ -0,0 +1,250 @@
+"""Tests for AgentLoop pure helper functions (zero LLM dependency)."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from src.agent.loop import (
+ KEEP_RECENT,
+ COLLAPSE_PRESERVE_RECENT,
+ COLLAPSE_TEXT_MIN,
+ estimate_tokens,
+ _microcompact,
+ _context_collapse,
+ _fix_tool_pairs,
+ _is_tool_success,
+)
+
+
+# ---------------------------------------------------------------------------
+# estimate_tokens
+# ---------------------------------------------------------------------------
+
+
+class TestEstimateTokens:
+ def test_empty(self) -> None:
+ assert estimate_tokens([]) == len("[]") // 4
+
+ def test_proportional(self) -> None:
+ short = [{"role": "user", "content": "hi"}]
+ long = [{"role": "user", "content": "x" * 4000}]
+ assert estimate_tokens(long) > estimate_tokens(short)
+
+ def test_rough_accuracy(self) -> None:
+ # ~4 chars per token
+ msg = [{"role": "user", "content": "a" * 400}]
+ tokens = estimate_tokens(msg)
+ # Should be roughly 100 tokens for 400 chars of content (plus overhead)
+ assert 80 < tokens < 200
+
+
+# ---------------------------------------------------------------------------
+# _microcompact
+# ---------------------------------------------------------------------------
+
+
+class TestMicrocompact:
+ def test_clears_old_tool_messages(self) -> None:
+ messages = [
+ {"role": "system", "content": "system"},
+ ]
+ # Add KEEP_RECENT + 5 tool messages with long content
+ for i in range(KEEP_RECENT + 5):
+ messages.append({"role": "tool", "content": f"{'x' * 200} result_{i}", "tool_call_id": f"tc_{i}"})
+
+ _microcompact(messages)
+
+ tool_msgs = [m for m in messages if m.get("role") == "tool"]
+ # Old ones should be [cleared]
+ cleared = [m for m in tool_msgs if m["content"] == "[cleared]"]
+ preserved = [m for m in tool_msgs if m["content"] != "[cleared]"]
+ assert len(cleared) == 5
+ assert len(preserved) == KEEP_RECENT
+
+ def test_preserves_short_content(self) -> None:
+ messages = [
+ {"role": "tool", "content": "short", "tool_call_id": "tc_0"},
+ {"role": "tool", "content": "also short", "tool_call_id": "tc_1"},
+ {"role": "tool", "content": "short too", "tool_call_id": "tc_2"},
+ {"role": "tool", "content": "x" * 200, "tool_call_id": "tc_3"},
+ {"role": "tool", "content": "x" * 200, "tool_call_id": "tc_4"},
+ {"role": "tool", "content": "x" * 200, "tool_call_id": "tc_5"},
+ {"role": "tool", "content": "x" * 200, "tool_call_id": "tc_6"},
+ ]
+ _microcompact(messages)
+ # First tool msg is old and long enough → cleared
+ # But "short" is ≤100 chars → not cleared even if old
+ short_msgs = [m for m in messages if m["content"] in ("short", "also short")]
+ assert len(short_msgs) == 2
+
+ def test_no_op_when_few_messages(self) -> None:
+ messages = [
+ {"role": "tool", "content": "x" * 200, "tool_call_id": "tc_0"},
+ ]
+ _microcompact(messages)
+ assert messages[0]["content"] != "[cleared]"
+
+ def test_does_not_touch_non_tool(self) -> None:
+ messages = [
+ {"role": "user", "content": "x" * 500},
+ {"role": "assistant", "content": "x" * 500},
+ {"role": "tool", "content": "x" * 200, "tool_call_id": "tc_0"},
+ {"role": "tool", "content": "x" * 200, "tool_call_id": "tc_1"},
+ {"role": "tool", "content": "x" * 200, "tool_call_id": "tc_2"},
+ {"role": "tool", "content": "x" * 200, "tool_call_id": "tc_3"},
+ ]
+ _microcompact(messages)
+ assert messages[0]["content"] == "x" * 500
+ assert messages[1]["content"] == "x" * 500
+
+
+# ---------------------------------------------------------------------------
+# _context_collapse
+# ---------------------------------------------------------------------------
+
+
+class TestContextCollapse:
+ def test_collapses_long_content(self) -> None:
+ messages = [{"role": "system", "content": "sys"}]
+ # Add enough messages to exceed COLLAPSE_PRESERVE_RECENT
+ for i in range(COLLAPSE_PRESERVE_RECENT + 5):
+ messages.append({"role": "user", "content": f"{'z' * (COLLAPSE_TEXT_MIN + 500)} msg_{i}"})
+
+ _context_collapse(messages)
+
+ # Early messages should be collapsed
+ assert "collapsed" in messages[1]["content"]
+ # Recent messages should be intact
+ assert "collapsed" not in messages[-1]["content"]
+
+ def test_skips_short_content(self) -> None:
+ messages = [{"role": "system", "content": "sys"}]
+ for i in range(COLLAPSE_PRESERVE_RECENT + 3):
+ messages.append({"role": "user", "content": f"short msg {i}"})
+ originals = [m["content"] for m in messages]
+ _context_collapse(messages)
+ # Nothing should change because all content is short
+ for orig, msg in zip(originals, messages):
+ assert msg["content"] == orig
+
+ def test_skips_cleared_content(self) -> None:
+ messages = [{"role": "system", "content": "sys"}]
+ for _ in range(COLLAPSE_PRESERVE_RECENT + 3):
+ messages.append({"role": "tool", "content": "[cleared]"})
+ _context_collapse(messages)
+ # [cleared] should remain [cleared], not be collapsed
+ for m in messages[1:]:
+ assert m["content"] == "[cleared]"
+
+ def test_no_op_when_too_few_messages(self) -> None:
+ messages = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "x" * 5000},
+ ]
+ _context_collapse(messages)
+ assert "collapsed" not in messages[1]["content"]
+
+ def test_preserves_head_and_tail(self) -> None:
+ messages = [{"role": "system", "content": "sys"}]
+ for i in range(COLLAPSE_PRESERVE_RECENT + 3):
+ messages.append({"role": "user", "content": f"HEAD_MARKER{'x' * COLLAPSE_TEXT_MIN}TAIL_MARKER msg_{i}"})
+
+ _context_collapse(messages)
+
+ collapsed_msg = messages[1]["content"]
+ assert "HEAD_MARKER" in collapsed_msg
+ assert "TAIL_MARKER" in collapsed_msg
+ assert "collapsed" in collapsed_msg
+
+
+# ---------------------------------------------------------------------------
+# _fix_tool_pairs
+# ---------------------------------------------------------------------------
+
+
+class TestFixToolPairs:
+ def test_removes_orphan_result(self) -> None:
+ messages = [
+ {"role": "assistant", "content": "thinking", "tool_calls": [
+ {"id": "tc_1", "function": {"name": "bash"}},
+ ]},
+ {"role": "tool", "tool_call_id": "tc_1", "name": "bash", "content": "ok"},
+ # Orphan: no matching tool_call
+ {"role": "tool", "tool_call_id": "tc_orphan", "name": "ghost", "content": "orphan"},
+ ]
+ _fix_tool_pairs(messages)
+ tool_msgs = [m for m in messages if m.get("role") == "tool"]
+ assert len(tool_msgs) == 1
+ assert tool_msgs[0]["tool_call_id"] == "tc_1"
+
+ def test_inserts_stub_for_orphan_call(self) -> None:
+ messages = [
+ {"role": "assistant", "content": "thinking", "tool_calls": [
+ {"id": "tc_1", "function": {"name": "bash"}},
+ {"id": "tc_2", "function": {"name": "read_file"}},
+ ]},
+ # Only result for tc_1, tc_2 is missing
+ {"role": "tool", "tool_call_id": "tc_1", "name": "bash", "content": "ok"},
+ ]
+ _fix_tool_pairs(messages)
+ tool_msgs = [m for m in messages if m.get("role") == "tool"]
+ assert len(tool_msgs) == 2
+ stub = [m for m in tool_msgs if m["tool_call_id"] == "tc_2"]
+ assert len(stub) == 1
+ assert "earlier context" in stub[0]["content"]
+
+ def test_no_op_when_balanced(self) -> None:
+ messages = [
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"id": "tc_1", "function": {"name": "bash"}},
+ ]},
+ {"role": "tool", "tool_call_id": "tc_1", "name": "bash", "content": "ok"},
+ ]
+ before = len(messages)
+ _fix_tool_pairs(messages)
+ assert len(messages) == before
+
+ def test_handles_empty_messages(self) -> None:
+ messages = []
+ _fix_tool_pairs(messages)
+ assert messages == []
+
+ def test_multiple_orphans(self) -> None:
+ messages = [
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"id": "tc_1", "function": {"name": "a"}},
+ {"id": "tc_2", "function": {"name": "b"}},
+ {"id": "tc_3", "function": {"name": "c"}},
+ ]},
+ # No results at all
+ ]
+ _fix_tool_pairs(messages)
+ tool_msgs = [m for m in messages if m.get("role") == "tool"]
+ assert len(tool_msgs) == 3
+
+
+# ---------------------------------------------------------------------------
+# _is_tool_success
+# ---------------------------------------------------------------------------
+
+
+class TestIsToolSuccess:
+ def test_success_plain_text(self) -> None:
+ assert _is_tool_success("some output text") is True
+
+ def test_success_json_ok(self) -> None:
+ assert _is_tool_success('{"status": "ok", "data": 42}') is True
+
+ def test_failure_json_error(self) -> None:
+ assert _is_tool_success('{"status": "error", "error": "boom"}') is False
+
+ def test_success_non_dict_json(self) -> None:
+ assert _is_tool_success("[1, 2, 3]") is True
+
+ def test_success_empty_string(self) -> None:
+ assert _is_tool_success("") is True
+
+ def test_success_invalid_json(self) -> None:
+ assert _is_tool_success("{not json}") is True
diff --git a/agent/tests/test_persistent_memory.py b/agent/tests/test_persistent_memory.py
new file mode 100644
index 000000000..d4052aeff
--- /dev/null
+++ b/agent/tests/test_persistent_memory.py
@@ -0,0 +1,203 @@
+"""Tests for PersistentMemory: file-based cross-session memory."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from src.memory.persistent import PersistentMemory, MemoryEntry, _tokenize
+
+
+# ---------------------------------------------------------------------------
+# _tokenize
+# ---------------------------------------------------------------------------
+
+
+class TestTokenize:
+ def test_ascii_words(self) -> None:
+ tokens = _tokenize("hello world testing")
+ assert "hello" in tokens
+ assert "world" in tokens
+ assert "testing" in tokens
+
+ def test_short_words_excluded(self) -> None:
+ tokens = _tokenize("I am ok no")
+ # All < 3 chars, should be excluded
+ assert len(tokens) == 0
+
+ def test_cjk_characters(self) -> None:
+ tokens = _tokenize("比特币价格分析")
+ assert "比" in tokens
+ assert "币" in tokens
+ assert "价" in tokens
+
+ def test_mixed(self) -> None:
+ tokens = _tokenize("AAPL 苹果 stock analysis")
+ assert "aapl" in tokens
+ assert "苹" in tokens
+ assert "stock" in tokens
+ assert "analysis" in tokens
+
+ def test_empty(self) -> None:
+ assert _tokenize("") == set()
+
+
+# ---------------------------------------------------------------------------
+# PersistentMemory.add
+# ---------------------------------------------------------------------------
+
+
+class TestAdd:
+ def test_creates_file_and_index(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ path = pm.add("test-mem", "Some content", "project", description="Test desc")
+ assert path.exists()
+ assert "test-mem" in path.read_text(encoding="utf-8")
+ index = (tmp_path / "MEMORY.md").read_text(encoding="utf-8")
+ assert "test-mem" in index
+
+ def test_slug_sanitization(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ path = pm.add("My Fancy Skill!", "body", "user")
+ assert "my_fancy_skill_" in path.name
+
+ def test_frontmatter_structure(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ path = pm.add("meta-test", "body here", "feedback", description="one line")
+ text = path.read_text(encoding="utf-8")
+ assert text.startswith("---\n")
+ assert "name: meta-test" in text
+ assert "type: feedback" in text
+ assert "description: one line" in text
+ assert "body here" in text
+
+ def test_multiple_adds(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("mem-a", "aaa", "project")
+ pm.add("mem-b", "bbb", "user")
+ pm.add("mem-c", "ccc", "reference")
+ md_files = list(tmp_path.glob("*.md"))
+ # 3 entries + MEMORY.md = 4
+ assert len(md_files) == 4
+
+ def test_overwrite_same_name(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("overwrite", "v1", "project")
+ pm.add("overwrite", "v2", "project")
+ # Should overwrite the same file
+ path = tmp_path / "project_overwrite.md"
+ assert "v2" in path.read_text(encoding="utf-8")
+
+ def test_index_update_not_duplicate(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("dup-check", "v1", "project")
+ pm.add("dup-check", "v2", "project")
+ index = (tmp_path / "MEMORY.md").read_text(encoding="utf-8")
+ assert index.count("[dup-check]") == 1
+
+
+# ---------------------------------------------------------------------------
+# PersistentMemory.find_relevant
+# ---------------------------------------------------------------------------
+
+
+class TestFindRelevant:
+ def test_basic_search(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("btc-strategy", "Bitcoin mean reversion", "project", description="BTC trading strategy")
+ pm.add("aapl-analysis", "Apple earnings report", "project", description="AAPL fundamental analysis")
+ results = pm.find_relevant("Bitcoin trading")
+ assert len(results) >= 1
+ assert results[0].title == "btc-strategy"
+
+ def test_cjk_search(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("a-share", "上证指数分析报告", "project", description="A股市场分析")
+ results = pm.find_relevant("上证指数")
+ assert len(results) >= 1
+
+ def test_no_match(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("something", "unrelated content", "project")
+ results = pm.find_relevant("xyznonexistent999")
+ assert len(results) == 0
+
+ def test_max_results(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ for i in range(10):
+ pm.add(f"stock-{i}", f"stock analysis number {i}", "project", description=f"stock {i}")
+ results = pm.find_relevant("stock analysis", max_results=3)
+ assert len(results) == 3
+
+ def test_metadata_weighted_higher(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ # "bitcoin" in description (metadata) → weighted 2x
+ pm.add("meta-match", "unrelated body text", "project", description="bitcoin trading strategy")
+ # "bitcoin" only in body → weighted 1x
+ pm.add("body-match", "bitcoin analysis deep dive", "project", description="some other topic")
+ results = pm.find_relevant("bitcoin")
+ assert len(results) == 2
+ assert results[0].title == "meta-match"
+
+ def test_empty_query(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("anything", "content", "project")
+ results = pm.find_relevant("")
+ assert results == []
+
+
+# ---------------------------------------------------------------------------
+# PersistentMemory.remove
+# ---------------------------------------------------------------------------
+
+
+class TestRemove:
+ def test_remove_existing(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("to-remove", "gone soon", "project")
+ assert pm.remove("to-remove") is True
+ # File gone
+ assert not list(tmp_path.glob("*to_remove*"))
+ # Index rebuilt without it
+ index = (tmp_path / "MEMORY.md").read_text(encoding="utf-8")
+ assert "to-remove" not in index
+
+ def test_remove_nonexistent(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ assert pm.remove("ghost") is False
+
+ def test_remove_then_find(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("ephemeral", "temporary data", "project", description="temp")
+ pm.remove("ephemeral")
+ results = pm.find_relevant("temporary")
+ assert len(results) == 0
+
+
+# ---------------------------------------------------------------------------
+# PersistentMemory.snapshot
+# ---------------------------------------------------------------------------
+
+
+class TestSnapshot:
+ def test_snapshot_loaded_at_init(self, tmp_path: Path) -> None:
+ pm1 = PersistentMemory(memory_dir=tmp_path)
+ pm1.add("snap-test", "content", "project", description="snapshot check")
+ # New instance should load snapshot from MEMORY.md
+ pm2 = PersistentMemory(memory_dir=tmp_path)
+ assert "snap-test" in pm2.snapshot
+
+ def test_snapshot_frozen(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ pm.add("after-init", "new content", "project")
+ # Snapshot was frozen at init time (before add), so it should NOT contain "after-init"
+ # unless the dir was empty at init (then snapshot is empty string)
+ # In either case, snapshot should not update after add
+ snap_before_check = pm.snapshot
+ pm.add("another", "more content", "project")
+ assert pm.snapshot == snap_before_check
+
+ def test_empty_dir_snapshot(self, tmp_path: Path) -> None:
+ pm = PersistentMemory(memory_dir=tmp_path)
+ assert pm.snapshot == ""
diff --git a/agent/tests/test_remember_tool.py b/agent/tests/test_remember_tool.py
new file mode 100644
index 000000000..a23a49e7e
--- /dev/null
+++ b/agent/tests/test_remember_tool.py
@@ -0,0 +1,142 @@
+"""Tests for RememberTool: save / recall / forget via PersistentMemory."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from src.memory.persistent import PersistentMemory
+from src.tools.remember_tool import RememberTool
+
+
+def tool(tmp_path: Path) -> RememberTool:
+ """Create a RememberTool backed by a tmp_path memory directory."""
+ pm = PersistentMemory(memory_dir=tmp_path)
+ return RememberTool(memory=pm)
+
+
+# ---------------------------------------------------------------------------
+# save
+# ---------------------------------------------------------------------------
+
+
+class TestSave:
+ def test_save_basic(self, tool: RememberTool) -> None:
+ result = json.loads(tool.execute(action="save", title="pref", content="risk=low"))
+ assert result["status"] == "ok"
+ assert "pref" in result["message"]
+
+ def test_save_with_type(self, tool: RememberTool) -> None:
+ result = json.loads(tool.execute(action="save", title="user-pref", content="likes TSLA", memory_type="user"))
+ assert result["status"] == "ok"
+ assert Path(result["path"]).name.startswith("user_")
+
+ def test_save_missing_title(self, tool: RememberTool) -> None:
+ result = json.loads(tool.execute(action="save", content="body"))
+ assert result["status"] == "error"
+
+ def test_save_missing_content(self, tool: RememberTool) -> None:
+ result = json.loads(tool.execute(action="save", title="empty"))
+ assert result["status"] == "error"
+
+ def test_save_missing_both(self, tool: RememberTool) -> None:
+ result = json.loads(tool.execute(action="save"))
+ assert result["status"] == "error"
+
+
+# ---------------------------------------------------------------------------
+# recall
+# ---------------------------------------------------------------------------
+
+
+class TestRecall:
+ def test_recall_finds_saved(self, tool: RememberTool) -> None:
+ tool.execute(action="save", title="btc-insight", content="Bitcoin will rally in Q3", memory_type="project")
+ result = json.loads(tool.execute(action="recall", query="Bitcoin rally"))
+ assert result["status"] == "ok"
+ assert result["count"] >= 1
+ assert any("btc-insight" in m["title"] for m in result["memories"])
+
+ def test_recall_no_match(self, tool: RememberTool) -> None:
+ tool.execute(action="save", title="something", content="unrelated")
+ result = json.loads(tool.execute(action="recall", query="xyznonexistent"))
+ assert result["status"] == "ok"
+ assert result["count"] == 0
+
+ def test_recall_missing_query(self, tool: RememberTool) -> None:
+ result = json.loads(tool.execute(action="recall"))
+ assert result["status"] == "error"
+
+ def test_recall_content_truncated(self, tool: RememberTool) -> None:
+ tool.execute(action="save", title="long", content="x" * 5000)
+ result = json.loads(tool.execute(action="recall", query="long"))
+ if result["count"] > 0:
+ assert len(result["memories"][0]["content"]) <= 2000
+
+ def test_recall_multiple(self, tool: RememberTool) -> None:
+ for i in range(5):
+ tool.execute(action="save", title=f"stock-{i}", content=f"analysis of stock {i}")
+ result = json.loads(tool.execute(action="recall", query="stock analysis"))
+ assert result["count"] >= 2
+
+
+# ---------------------------------------------------------------------------
+# forget
+# ---------------------------------------------------------------------------
+
+
+class TestForget:
+ def test_forget_existing(self, tool: RememberTool) -> None:
+ tool.execute(action="save", title="forget-me", content="temporary")
+ result = json.loads(tool.execute(action="forget", title="forget-me"))
+ assert result["status"] == "ok"
+ assert "Removed" in result["message"]
+ # Confirm gone
+ recall = json.loads(tool.execute(action="recall", query="temporary"))
+ assert recall["count"] == 0
+
+ def test_forget_nonexistent(self, tool: RememberTool) -> None:
+ result = json.loads(tool.execute(action="forget", title="ghost"))
+ assert result["status"] == "not_found"
+
+ def test_forget_missing_title(self, tool: RememberTool) -> None:
+ result = json.loads(tool.execute(action="forget"))
+ assert result["status"] == "error"
+
+
+# ---------------------------------------------------------------------------
+# unknown action
+# ---------------------------------------------------------------------------
+
+
+class TestUnknownAction:
+ def test_unknown_action(self, tool: RememberTool) -> None:
+ result = json.loads(tool.execute(action="destroy"))
+ assert result["status"] == "error"
+ assert "Unknown" in result["error"]
+
+
+# ---------------------------------------------------------------------------
+# Full lifecycle
+# ---------------------------------------------------------------------------
+
+
+class TestLifecycle:
+ def test_save_recall_forget_recall(self, tool: RememberTool) -> None:
+ tool.execute(action="save", title="lifecycle", content="full cycle test", memory_type="feedback")
+ r1 = json.loads(tool.execute(action="recall", query="lifecycle"))
+ assert r1["count"] >= 1
+
+ tool.execute(action="forget", title="lifecycle")
+ r2 = json.loads(tool.execute(action="recall", query="lifecycle"))
+ assert r2["count"] == 0
+
+ def test_overwrite_and_recall(self, tool: RememberTool) -> None:
+ tool.execute(action="save", title="evolving", content="version 1")
+ tool.execute(action="save", title="evolving", content="version 2 updated")
+ result = json.loads(tool.execute(action="recall", query="evolving"))
+ assert result["count"] >= 1
+ assert "version 2" in result["memories"][0]["content"]
diff --git a/agent/tests/test_session_search.py b/agent/tests/test_session_search.py
new file mode 100644
index 000000000..45b441908
--- /dev/null
+++ b/agent/tests/test_session_search.py
@@ -0,0 +1,196 @@
+"""Tests for SessionSearchIndex: SQLite FTS5 cross-session search."""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+
+import pytest
+
+from src.session.search import SessionSearchIndex, SearchMatch
+
+
+def index(tmp_path: Path) -> SessionSearchIndex:
+ """Create an ephemeral SessionSearchIndex backed by a tmp_path SQLite db."""
+ db_path = tmp_path / "test_sessions.db"
+ idx = SessionSearchIndex(db_path=db_path)
+ yield idx
+ idx.close()
+
+
+# ---------------------------------------------------------------------------
+# Indexing
+# ---------------------------------------------------------------------------
+
+
+class TestIndexing:
+ def test_index_session(self, index: SessionSearchIndex) -> None:
+ index.index_session("s1", "My first session")
+ # No crash, session stored
+ results = index.search("first session")
+ # May or may not match depending on FTS5 availability
+ # At minimum: no crash
+
+ def test_index_message(self, index: SessionSearchIndex) -> None:
+ index.index_session("s1", "Test session")
+ index.index_message("s1", "user", "I want to analyze Bitcoin")
+ results = index.search("Bitcoin")
+ assert len(results) >= 1
+ assert results[0].session_id == "s1"
+
+ def test_index_empty_content_skipped(self, index: SessionSearchIndex) -> None:
+ index.index_session("s1", "Test")
+ index.index_message("s1", "user", "")
+ index.index_message("s1", "user", " ")
+ # Should not crash, empty content ignored
+
+ def test_index_multiple_sessions(self, index: SessionSearchIndex) -> None:
+ index.index_session("s1", "Bitcoin analysis")
+ index.index_message("s1", "user", "BTC price prediction")
+ index.index_session("s2", "Ethereum research")
+ index.index_message("s2", "user", "ETH DeFi analysis")
+
+ btc = index.search("Bitcoin BTC")
+ eth = index.search("Ethereum ETH")
+ assert any(m.session_id == "s1" for m in btc)
+ assert any(m.session_id == "s2" for m in eth)
+
+ def test_message_count_increments(self, index: SessionSearchIndex) -> None:
+ index.index_session("s1", "Counter test")
+ index.index_message("s1", "user", "msg 1")
+ index.index_message("s1", "assistant", "msg 2")
+ index.index_message("s1", "user", "msg 3")
+ results = index.search("msg")
+ if results:
+ assert results[0].message_count == 3
+
+
+# ---------------------------------------------------------------------------
+# Search
+# ---------------------------------------------------------------------------
+
+
+class TestSearch:
+ def test_relevance_ranking(self, index: SessionSearchIndex) -> None:
+ index.index_session("s1", "Unrelated topic")
+ index.index_message("s1", "user", "weather forecast for tomorrow")
+ index.index_session("s2", "Bitcoin deep dive")
+ index.index_message("s2", "user", "Bitcoin price analysis and trading strategy for Bitcoin")
+
+ results = index.search("Bitcoin")
+ assert len(results) >= 1
+ # s2 should rank higher (more mentions)
+ assert results[0].session_id == "s2"
+
+ def test_max_sessions_limit(self, index: SessionSearchIndex) -> None:
+ for i in range(10):
+ sid = f"s{i}"
+ index.index_session(sid, f"Session {i}")
+ index.index_message(sid, "user", f"common keyword topic {i}")
+
+ results = index.search("common keyword", max_sessions=3)
+ assert len(results) <= 3
+
+ def test_no_results(self, index: SessionSearchIndex) -> None:
+ index.index_session("s1", "Test")
+ index.index_message("s1", "user", "hello world")
+ results = index.search("xyznonexistent999zyx")
+ assert len(results) == 0
+
+ def test_cjk_search(self, index: SessionSearchIndex) -> None:
+ index.index_session("s1", "A股分析")
+ index.index_message("s1", "user", "上证指数今日走势分析 shanghai composite index")
+ # FTS5 tokenizes by whitespace; CJK single chars may not match.
+ # Search with the ASCII fallback to verify the session is indexed.
+ results = index.search("shanghai composite index")
+ assert len(results) >= 1
+
+ def test_snippet_contains_match(self, index: SessionSearchIndex) -> None:
+ index.index_session("s1", "Snippet test")
+ index.index_message("s1", "user", "The quick brown fox jumps over the lazy dog")
+ results = index.search("fox")
+ if results:
+ # FTS5 snippet markers
+ assert "fox" in results[0].snippet.lower()
+
+ def test_search_match_to_dict(self, index: SessionSearchIndex) -> None:
+ match = SearchMatch(
+ session_id="s1", title="Test", started_at="2026-01-01 00:00",
+ message_count=5, snippet="hello", rank=-1.0,
+ )
+ d = match.to_dict()
+ assert d["session_id"] == "s1"
+ assert d["message_count"] == 5
+ assert "rank" not in d # rank not in to_dict
+
+
+# ---------------------------------------------------------------------------
+# _sanitize_fts_query
+# ---------------------------------------------------------------------------
+
+
+class TestSanitizeFtsQuery:
+ def test_basic_words(self) -> None:
+ result = SessionSearchIndex._sanitize_fts_query("hello world")
+ assert '"hello"' in result
+ assert '"world"' in result
+
+ def test_special_chars_stripped(self) -> None:
+ result = SessionSearchIndex._sanitize_fts_query("hello* OR (world)")
+ assert "hello" in result
+ assert "world" in result
+ # Should not contain raw FTS5 operators
+ assert "OR (" not in result or result.count("OR") == result.count('" OR "')
+
+ def test_empty_query(self) -> None:
+ result = SessionSearchIndex._sanitize_fts_query("")
+ assert result == '""'
+
+ def test_cjk(self) -> None:
+ result = SessionSearchIndex._sanitize_fts_query("比特币价格")
+ assert "比" in result
+ assert "币" in result
+
+
+# ---------------------------------------------------------------------------
+# reindex_from_store
+# ---------------------------------------------------------------------------
+
+
+class TestReindex:
+ def test_reindex_empty_dir(self, index: SessionSearchIndex, tmp_path: Path) -> None:
+ store_dir = tmp_path / "empty_store"
+ store_dir.mkdir()
+ count = index.reindex_from_store(store_dir)
+ assert count == 0
+
+ def test_reindex_nonexistent_dir(self, index: SessionSearchIndex, tmp_path: Path) -> None:
+ count = index.reindex_from_store(tmp_path / "nope")
+ assert count == 0
+
+ def test_reindex_from_file_store(self, index: SessionSearchIndex, tmp_path: Path) -> None:
+ import json
+ store_dir = tmp_path / "sessions"
+ store_dir.mkdir()
+
+ # Create a fake session directory
+ s_dir = store_dir / "session-001"
+ s_dir.mkdir()
+ (s_dir / "session.json").write_text(json.dumps({
+ "session_id": "session-001",
+ "title": "Reindex test",
+ "created_at": "2026-01-01T00:00:00",
+ }), encoding="utf-8")
+ (s_dir / "messages.jsonl").write_text(
+ json.dumps({"role": "user", "content": "reindex probe message"}) + "\n"
+ + json.dumps({"role": "assistant", "content": "reindex probe reply"}) + "\n",
+ encoding="utf-8",
+ )
+
+ count = index.reindex_from_store(store_dir)
+ assert count == 2
+
+ results = index.search("reindex probe")
+ assert len(results) >= 1
+ assert results[0].session_id == "session-001"
diff --git a/agent/tests/test_skill_writer_tools.py b/agent/tests/test_skill_writer_tools.py
new file mode 100644
index 000000000..f7fe84633
--- /dev/null
+++ b/agent/tests/test_skill_writer_tools.py
@@ -0,0 +1,291 @@
+"""Tests for skill writer tools: SaveSkillTool, PatchSkillTool, DeleteSkillTool, SkillFileTool."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from src.tools.skill_writer_tool import (
+ SaveSkillTool,
+ PatchSkillTool,
+ DeleteSkillTool,
+ SkillFileTool,
+ _sanitize_skill_name,
+ USER_SKILLS_DIR,
+)
+
+
+# ---------------------------------------------------------------------------
+# _sanitize_skill_name
+# ---------------------------------------------------------------------------
+
+
+class TestSanitizeSkillName:
+ def test_lowercase(self) -> None:
+ assert _sanitize_skill_name("My-Skill") == "my-skill"
+
+ def test_special_chars(self) -> None:
+ assert _sanitize_skill_name("a b!c@d") == "a-b-c-d"
+
+ def test_truncation(self) -> None:
+ long = "x" * 100
+ assert len(_sanitize_skill_name(long)) <= 60
+
+ def test_empty(self) -> None:
+ assert _sanitize_skill_name("") == ""
+
+
+# ---------------------------------------------------------------------------
+# SaveSkillTool
+# ---------------------------------------------------------------------------
+
+
+class TestSaveSkillTool:
+ @pytest.fixture()
+ def tool(self, tmp_path: Path) -> SaveSkillTool:
+ with patch("src.tools.skill_writer_tool.USER_SKILLS_DIR", tmp_path):
+ yield SaveSkillTool()
+
+ @pytest.fixture()
+ def user_dir(self, tmp_path: Path) -> Path:
+ return tmp_path
+
+ def test_save_basic(self, tool: SaveSkillTool, user_dir: Path) -> None:
+ result = json.loads(tool.execute(name="test-skill", content="# My Skill\nBody text"))
+ assert result["status"] == "ok"
+ skill_dir = user_dir / "test-skill"
+ assert skill_dir.exists()
+ assert (skill_dir / "SKILL.md").exists()
+
+ def test_save_adds_frontmatter(self, tool: SaveSkillTool, user_dir: Path) -> None:
+ result = json.loads(tool.execute(name="no-fm", content="Plain body without frontmatter"))
+ assert result["status"] == "ok"
+ text = (user_dir / "no-fm" / "SKILL.md").read_text(encoding="utf-8")
+ assert text.startswith("---\n")
+ assert "name: no-fm" in text
+
+ def test_save_preserves_existing_frontmatter(self, tool: SaveSkillTool, user_dir: Path) -> None:
+ content = "---\nname: custom\ndescription: Custom skill\ncategory: strategy\n---\nBody"
+ result = json.loads(tool.execute(name="custom", content=content))
+ assert result["status"] == "ok"
+ text = (user_dir / "custom" / "SKILL.md").read_text(encoding="utf-8")
+ assert "description: Custom skill" in text
+
+ def test_save_missing_name(self, tool: SaveSkillTool) -> None:
+ result = json.loads(tool.execute(content="body"))
+ assert result["status"] == "error"
+
+ def test_save_missing_content(self, tool: SaveSkillTool) -> None:
+ result = json.loads(tool.execute(name="empty"))
+ assert result["status"] == "error"
+
+ def test_save_overwrite(self, tool: SaveSkillTool, user_dir: Path) -> None:
+ tool.execute(name="overwrite", content="v1")
+ tool.execute(name="overwrite", content="---\nname: overwrite\n---\nv2")
+ text = (user_dir / "overwrite" / "SKILL.md").read_text(encoding="utf-8")
+ assert "v2" in text
+
+
+# ---------------------------------------------------------------------------
+# PatchSkillTool
+# ---------------------------------------------------------------------------
+
+
+class TestPatchSkillTool:
+ @pytest.fixture()
+ def setup(self, tmp_path: Path):
+ user_dir = tmp_path / "user"
+ bundled_dir = tmp_path / "bundled"
+ with patch("src.tools.skill_writer_tool.USER_SKILLS_DIR", user_dir):
+ tool = PatchSkillTool()
+ yield tool, user_dir, bundled_dir
+
+ def test_patch_user_skill(self, setup) -> None:
+ tool, user_dir, _ = setup
+ skill_dir = user_dir / "patchme"
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md").write_text("old_api_call()", encoding="utf-8")
+
+ result = json.loads(tool.execute(name="patchme", find="old_api_call()", replace="new_api_call()"))
+ assert result["status"] == "ok"
+ assert "new_api_call()" in (skill_dir / "SKILL.md").read_text(encoding="utf-8")
+
+ def test_patch_text_not_found(self, setup) -> None:
+ tool, user_dir, _ = setup
+ skill_dir = user_dir / "nofind"
+ skill_dir.mkdir(parents=True)
+ (skill_dir / "SKILL.md").write_text("some content", encoding="utf-8")
+
+ result = json.loads(tool.execute(name="nofind", find="MISSING", replace="X"))
+ assert result["status"] == "error"
+
+ def test_patch_nonexistent_skill(self, setup) -> None:
+ tool, _, _ = setup
+ result = json.loads(tool.execute(name="ghost", find="x", replace="y"))
+ assert result["status"] == "error"
+
+ def test_patch_missing_params(self, setup) -> None:
+ tool, _, _ = setup
+ result = json.loads(tool.execute(name="", find="x", replace="y"))
+ assert result["status"] == "error"
+
+
+# ---------------------------------------------------------------------------
+# DeleteSkillTool
+# ---------------------------------------------------------------------------
+
+
+class TestDeleteSkillTool:
+ @pytest.fixture()
+ def setup(self, tmp_path: Path):
+ with patch("src.tools.skill_writer_tool.USER_SKILLS_DIR", tmp_path):
+ tool = DeleteSkillTool()
+ yield tool, tmp_path
+
+ def test_delete_existing(self, setup) -> None:
+ tool, user_dir = setup
+ skill_dir = user_dir / "deleteme"
+ skill_dir.mkdir()
+ (skill_dir / "SKILL.md").write_text("body", encoding="utf-8")
+
+ result = json.loads(tool.execute(name="deleteme"))
+ assert result["status"] == "ok"
+ assert not skill_dir.exists()
+
+ def test_delete_nonexistent(self, setup) -> None:
+ tool, _ = setup
+ result = json.loads(tool.execute(name="ghost"))
+ assert result["status"] == "error"
+
+ def test_delete_empty_name(self, setup) -> None:
+ tool, _ = setup
+ result = json.loads(tool.execute(name=""))
+ assert result["status"] == "error"
+
+
+# ---------------------------------------------------------------------------
+# SkillFileTool
+# ---------------------------------------------------------------------------
+
+
+class TestSkillFileTool:
+ @pytest.fixture()
+ def setup(self, tmp_path: Path):
+ with patch("src.tools.skill_writer_tool.USER_SKILLS_DIR", tmp_path):
+ tool = SkillFileTool()
+ # Pre-create a skill directory
+ skill_dir = tmp_path / "file-test"
+ skill_dir.mkdir()
+ (skill_dir / "SKILL.md").write_text("body", encoding="utf-8")
+ yield tool, tmp_path, skill_dir
+
+ def test_list_files(self, setup) -> None:
+ tool, _, skill_dir = setup
+ (skill_dir / "templates").mkdir()
+ (skill_dir / "templates" / "sma.py").write_text("code", encoding="utf-8")
+ result = json.loads(tool.execute(action="list", skill_name="file-test"))
+ assert result["status"] == "ok"
+ paths = [f["path"] for f in result["files"]]
+ assert any("sma.py" in p for p in paths)
+
+ def test_write_file(self, setup) -> None:
+ tool, _, skill_dir = setup
+ result = json.loads(tool.execute(
+ action="write", skill_name="file-test",
+ path="templates/strategy.py", content="def run(): pass",
+ ))
+ assert result["status"] == "ok"
+ assert (skill_dir / "templates" / "strategy.py").exists()
+
+ def test_write_invalid_subdir(self, setup) -> None:
+ tool, _, _ = setup
+ result = json.loads(tool.execute(
+ action="write", skill_name="file-test",
+ path="invalid_dir/file.py", content="code",
+ ))
+ assert result["status"] == "error"
+
+ def test_write_missing_path(self, setup) -> None:
+ tool, _, _ = setup
+ result = json.loads(tool.execute(
+ action="write", skill_name="file-test", content="code",
+ ))
+ assert result["status"] == "error"
+
+ def test_remove_file(self, setup) -> None:
+ tool, _, skill_dir = setup
+ (skill_dir / "assets").mkdir()
+ (skill_dir / "assets" / "data.csv").write_text("1,2,3", encoding="utf-8")
+ result = json.loads(tool.execute(
+ action="remove", skill_name="file-test", path="assets/data.csv",
+ ))
+ assert result["status"] == "ok"
+ assert not (skill_dir / "assets" / "data.csv").exists()
+
+ def test_remove_skill_md_blocked(self, setup) -> None:
+ tool, _, _ = setup
+ result = json.loads(tool.execute(
+ action="remove", skill_name="file-test", path="SKILL.md",
+ ))
+ assert result["status"] == "error"
+
+ def test_remove_nonexistent_file(self, setup) -> None:
+ tool, _, _ = setup
+ result = json.loads(tool.execute(
+ action="remove", skill_name="file-test", path="assets/ghost.txt",
+ ))
+ assert result["status"] == "error"
+
+ def test_nonexistent_skill(self, setup) -> None:
+ tool, _, _ = setup
+ result = json.loads(tool.execute(action="list", skill_name="nope"))
+ assert result["status"] == "error"
+
+ def test_unknown_action(self, setup) -> None:
+ tool, _, _ = setup
+ result = json.loads(tool.execute(action="explode", skill_name="file-test"))
+ assert result["status"] == "error"
+
+
+# ---------------------------------------------------------------------------
+# Full CRUD lifecycle
+# ---------------------------------------------------------------------------
+
+
+class TestSkillCRUDLifecycle:
+ def test_create_patch_file_delete(self, tmp_path: Path) -> None:
+ with patch("src.tools.skill_writer_tool.USER_SKILLS_DIR", tmp_path):
+ save = SaveSkillTool()
+ patch_tool = PatchSkillTool()
+ file_tool = SkillFileTool()
+ delete = DeleteSkillTool()
+
+ # 1. Create
+ r = json.loads(save.execute(name="lifecycle", content="---\nname: lifecycle\n---\nold_code()"))
+ assert r["status"] == "ok"
+
+ # 2. Patch
+ r = json.loads(patch_tool.execute(name="lifecycle", find="old_code()", replace="new_code()"))
+ assert r["status"] == "ok"
+ text = (tmp_path / "lifecycle" / "SKILL.md").read_text(encoding="utf-8")
+ assert "new_code()" in text
+
+ # 3. Add auxiliary file
+ r = json.loads(file_tool.execute(
+ action="write", skill_name="lifecycle",
+ path="templates/helper.py", content="def helper(): pass",
+ ))
+ assert r["status"] == "ok"
+
+ # 4. List files
+ r = json.loads(file_tool.execute(action="list", skill_name="lifecycle"))
+ assert r["status"] == "ok"
+ assert len(r["files"]) >= 2 # SKILL.md + helper.py
+
+ # 5. Delete
+ r = json.loads(delete.execute(name="lifecycle"))
+ assert r["status"] == "ok"
+ assert not (tmp_path / "lifecycle").exists()