Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(goal): close research goal lifecycle

Haozhe Wuacab70c556ec
diff --git a/agent/api_server.py b/agent/api_server.py
index 652d69941..8bbb06a78 100644
--- a/agent/api_server.py
+++ b/agent/api_server.py
@@ -27,6 +27,7 @@ from pydantic import BaseModel, Field
from fastapi.middleware.cors import CORSMiddleware
from rich.console import Console
+from src.goal.context import default_goal_criteria
from src.ui_services import build_run_analysis, load_run_context
# UTF-8 on Windows
@@ -251,6 +252,15 @@ class CreateGoalRequest(BaseModel):
time_budget_seconds: Optional[int] = Field(None, ge=1)
+class UpdateGoalRequest(BaseModel):
+ """Edit mutable finance research goal fields."""
+
+ goal_id: str = Field(..., min_length=1)
+ expected_goal_id: str = Field(..., min_length=1)
+ objective: Optional[str] = Field(None, min_length=1, max_length=5000)
+ ui_summary: Optional[str] = Field(None, max_length=500)
+
+
class AddGoalEvidenceRequest(BaseModel):
"""Append evidence to a finance research goal."""
@@ -295,6 +305,39 @@ class AddGoalEvidenceResponse(BaseModel):
snapshot: GoalSnapshotResponse
+class GoalAuditRowRequest(BaseModel):
+ """One criterion row for goal status audits."""
+
+ criterion_id: str = Field(..., min_length=1)
+ result: str = Field(..., min_length=1)
+ evidence_ids: List[str] = Field(default_factory=list)
+ notes: str = ""
+
+
+class UpdateGoalStatusRequest(BaseModel):
+ """Update a finance research goal status."""
+
+ goal_id: str = Field(..., min_length=1)
+ expected_goal_id: str = Field(..., min_length=1)
+ status: str = Field(..., min_length=1)
+ audit: List[GoalAuditRowRequest] = Field(default_factory=list)
+ recap: Optional[str] = None
+
+
+class UpdateGoalStatusResponse(BaseModel):
+ """Response after changing a goal status."""
+
+ goal: Dict[str, Any]
+ snapshot: GoalSnapshotResponse
+
+
+class UpdateGoalResponse(BaseModel):
+ """Response after editing a goal."""
+
+ goal: Dict[str, Any]
+ snapshot: GoalSnapshotResponse
+
+
# ============================================================================
# FastAPI Application
@@ -1502,7 +1545,7 @@ async def create_session_goal(session_id: str, req: CreateGoalRequest):
criteria = [item.strip() for item in req.criteria if item.strip()]
if not criteria:
- criteria = ["Define research thesis", "Record at least one supporting or contradicting evidence row"]
+ criteria = default_goal_criteria()
try:
risk_tier = RiskTier(req.risk_tier)
except ValueError as exc:
@@ -1548,6 +1591,41 @@ async def get_session_goal(session_id: str):
return snapshot
+ "/sessions/{session_id}/goal",
+ response_model=UpdateGoalResponse,
+ dependencies=[Depends(require_auth)],
+)
+async def update_session_goal(session_id: str, req: UpdateGoalRequest):
+ """Edit the current finance research goal without replacing the session."""
+ _validate_path_param(session_id, "session_id")
+ svc, _session = _get_existing_session_or_404(session_id)
+ from src.goal import StaleGoalError
+
+ if req.objective is None and req.ui_summary is None:
+ raise HTTPException(status_code=400, detail="objective or ui_summary is required")
+
+ goal_store = _get_goal_store()
+ try:
+ goal = goal_store.update_goal(
+ session_id=session_id,
+ goal_id=req.goal_id,
+ expected_goal_id=req.expected_goal_id,
+ objective=req.objective,
+ ui_summary=req.ui_summary,
+ )
+ except StaleGoalError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ snapshot = goal_store.get_goal_snapshot(goal.goal_id)
+ if snapshot is None:
+ raise HTTPException(status_code=500, detail="Goal snapshot could not be reloaded")
+ svc.event_bus.emit(session_id, "goal.updated", {"goal": snapshot["goal"], "snapshot": snapshot})
+ return {"goal": snapshot["goal"], "snapshot": snapshot}
+
+
@app.post(
"/sessions/{session_id}/goal/evidence",
response_model=AddGoalEvidenceResponse,
@@ -1606,6 +1684,52 @@ async def add_session_goal_evidence(session_id: str, req: AddGoalEvidenceRequest
return {"evidence": asdict(evidence), "snapshot": snapshot}
+ "/sessions/{session_id}/goal/status",
+ response_model=UpdateGoalStatusResponse,
+ dependencies=[Depends(require_auth)],
+)
+async def update_session_goal_status(session_id: str, req: UpdateGoalStatusRequest):
+ """Update the current finance research goal status."""
+ _validate_path_param(session_id, "session_id")
+ svc, _session = _get_existing_session_or_404(session_id)
+ from src.goal import AuditRow, GoalStatus, StaleGoalError
+
+ try:
+ next_status = GoalStatus(req.status)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=f"invalid goal status: {req.status}") from exc
+
+ goal_store = _get_goal_store()
+ try:
+ goal = goal_store.update_status(
+ session_id=session_id,
+ goal_id=req.goal_id,
+ expected_goal_id=req.expected_goal_id,
+ status=next_status,
+ audit=[
+ AuditRow(
+ criterion_id=row.criterion_id,
+ result=row.result,
+ evidence_ids=row.evidence_ids,
+ notes=row.notes,
+ )
+ for row in req.audit
+ ],
+ recap=req.recap,
+ )
+ except StaleGoalError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+ snapshot = goal_store.get_goal_snapshot(goal.goal_id)
+ if snapshot is None:
+ raise HTTPException(status_code=500, detail="Goal snapshot could not be reloaded")
+ svc.event_bus.emit(session_id, "goal.updated", {"goal": snapshot["goal"], "snapshot": snapshot})
+ return {"goal": snapshot["goal"], "snapshot": snapshot}
+
+
@app.delete("/sessions/{session_id}", dependencies=[Depends(require_auth)])
async def delete_session(session_id: str):
"""Delete a session."""
diff --git a/agent/cli/commands/goal.py b/agent/cli/commands/goal.py
index 833ec794f..5f5d6c3ca 100644
--- a/agent/cli/commands/goal.py
+++ b/agent/cli/commands/goal.py
@@ -13,6 +13,7 @@ from rich.table import Table
from rich.text import Text
from cli.theme import get_console
+from src.goal.context import default_goal_criteria
_goal_store = None
@@ -34,11 +35,7 @@ def _get_goal_store():
def _default_criteria() -> list[str]:
"""Return the MVP finance protocol checklist."""
- return [
- "Define the research-only thesis and symbol universe",
- "Collect fresh market or benchmark evidence",
- "Record caveats, contradictions, and non-advice boundary",
- ]
+ return default_goal_criteria()
def _criterion_is_covered(criterion: dict, evidence: list[dict]) -> bool:
@@ -263,6 +260,98 @@ def cmd_evidence(ctx: Any = None, *args: str) -> int:
return 0
+def cmd_cancel(ctx: Any = None, *args: str) -> int:
+ """Cancel the current research goal."""
+ session_id = _session_id(ctx, create=False)
+ if session_id is None:
+ _resolve_console().print(Text("No current goal. Use /goal <objective> first.", style="dim"))
+ return 0
+ snapshot = _get_goal_store().get_current_snapshot(session_id)
+ if snapshot is None:
+ _resolve_console().print(Text("No current goal. Use /goal <objective> first.", style="dim"))
+ return 0
+
+ recap = " ".join(args).strip() or "Cancelled from CLI."
+ try:
+ from src.goal import GoalStatus
+
+ updated = _get_goal_store().update_status(
+ session_id=session_id,
+ goal_id=snapshot["goal"]["goal_id"],
+ expected_goal_id=snapshot["goal"]["goal_id"],
+ status=GoalStatus.CANCELLED,
+ recap=recap,
+ )
+ except Exception as exc: # noqa: BLE001
+ _resolve_console().print(Text(f"/goal cancel failed: {exc}", style="bold red"))
+ return 1
+
+ terminal_snapshot = _get_goal_store().get_goal_snapshot(updated.goal_id)
+ if terminal_snapshot is not None:
+ _render_snapshot(terminal_snapshot, title="/goal cancelled")
+ return 0
+
+
+def cmd_complete(ctx: Any = None, *args: str) -> int: # noqa: ARG001
+ """Complete the current research goal after auditing verified evidence."""
+ session_id = _session_id(ctx, create=False)
+ if session_id is None:
+ _resolve_console().print(Text("No current goal. Use /goal <objective> first.", style="dim"))
+ return 0
+ snapshot = _get_goal_store().get_current_snapshot(session_id)
+ if snapshot is None:
+ _resolve_console().print(Text("No current goal. Use /goal <objective> first.", style="dim"))
+ return 0
+
+ evidence = snapshot.get("evidence") or []
+ audit_rows = []
+ for criterion in snapshot.get("criteria") or []:
+ criterion_evidence = [
+ item
+ for item in evidence
+ if item.get("criterion_id") == criterion["criterion_id"]
+ and item.get("verification_status") == "verified"
+ ]
+ if not criterion_evidence:
+ _resolve_console().print(
+ Text(
+ "Cannot complete: every criterion needs verified run/artifact evidence.",
+ style="bold red",
+ )
+ )
+ return 1
+ from src.goal import AuditRow
+
+ audit_rows.append(
+ AuditRow(
+ criterion_id=criterion["criterion_id"],
+ result="satisfied",
+ evidence_ids=[item["evidence_id"] for item in criterion_evidence],
+ notes="Verified evidence attached from CLI audit.",
+ )
+ )
+
+ try:
+ from src.goal import GoalStatus
+
+ updated = _get_goal_store().update_status(
+ session_id=session_id,
+ goal_id=snapshot["goal"]["goal_id"],
+ expected_goal_id=snapshot["goal"]["goal_id"],
+ status=GoalStatus.COMPLETE,
+ audit=audit_rows,
+ recap=" ".join(args).strip() or "Completed from CLI audit.",
+ )
+ except Exception as exc: # noqa: BLE001
+ _resolve_console().print(Text(f"/goal complete failed: {exc}", style="bold red"))
+ return 1
+
+ terminal_snapshot = _get_goal_store().get_goal_snapshot(updated.goal_id)
+ if terminal_snapshot is not None:
+ _render_snapshot(terminal_snapshot, title="/goal completed")
+ return 0
+
+
def cmd_help() -> int:
"""Render /goal usage."""
body = Text()
@@ -272,6 +361,10 @@ def cmd_help() -> int:
body.append(" show the current goal snapshot\n", style="dim")
body.append("/goal evidence <criterion-index-or-id> <note>", style="bold")
body.append(" append manual evidence\n", style="dim")
+ body.append("/goal complete [recap]", style="bold")
+ body.append(" complete after verified evidence audit\n", style="dim")
+ body.append("/goal cancel [recap]", style="bold")
+ body.append(" cancel the current goal\n", style="dim")
_resolve_console().print(Panel(body, title="/goal", border_style="dim", padding=(1, 2)))
return 0
@@ -290,6 +383,10 @@ def run(ctx: Any = None, *args: str) -> int:
return cmd_start(ctx, *args[1:])
if command == "evidence":
return cmd_evidence(ctx, *args[1:])
+ if command == "complete":
+ return cmd_complete(ctx, *args[1:])
+ if command in {"cancel", "cancelled"}:
+ return cmd_cancel(ctx, *args[1:])
return cmd_start(ctx, *args)
@@ -298,4 +395,6 @@ __all__ = [
"cmd_start",
"cmd_status",
"cmd_evidence",
+ "cmd_complete",
+ "cmd_cancel",
]
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 17be5edfc..4718dde96 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -106,11 +106,9 @@ def _json_error(error: str, *, error_type: str = "error") -> str:
def _default_goal_criteria() -> list[str]:
"""Return the MVP finance protocol checklist."""
- return [
- "Define the research-only thesis and symbol universe",
- "Collect fresh market or benchmark evidence",
- "Record caveats, contradictions, and non-advice boundary",
- ]
+ from src.goal.context import default_goal_criteria
+
+ return default_goal_criteria()
def _clean_list(value: list[str] | None) -> list[str]:
@@ -126,6 +124,27 @@ def _blank_to_none(value: str | None) -> str | None:
return value or None
+def _audit_rows_from_payload(value: list[dict[str, Any]] | None):
+ """Parse MCP completion audit rows."""
+ from src.goal import AuditRow
+
+ rows = []
+ for item in value or []:
+ criterion_id = str(item.get("criterion_id") or "").strip()
+ result = str(item.get("result") or "").strip()
+ if not criterion_id or not result:
+ raise ValueError("audit rows require criterion_id and result")
+ rows.append(
+ AuditRow(
+ criterion_id=criterion_id,
+ result=result,
+ evidence_ids=_clean_list(item.get("evidence_ids") or []),
+ notes=str(item.get("notes") or ""),
+ )
+ )
+ return rows
+
+
def _risk_tier_from_text(value: str):
"""Parse and validate goal risk tier."""
from src.goal import RiskTier
@@ -277,8 +296,8 @@ def add_goal_evidence(
criterion_id: Optional criterion this evidence satisfies.
claim_id: Optional claim this evidence supports or contradicts.
evidence_type: Evidence category, default evidence.
- tool_call_id: Source tool call id. Presence marks evidence verified.
- run_id: Vibe-Trading run id. Presence marks evidence verified.
+ tool_call_id: Source tool call id for traceability; it does not verify evidence by itself.
+ run_id: Vibe-Trading run id. It verifies evidence only when the run directory exists.
source_provider: Data/provider name such as yfinance, OKX, tushare.
source_type: Source category such as market_data, document, backtest.
source_uri: Optional source URL/path.
@@ -287,8 +306,8 @@ def add_goal_evidence(
timeframe: Market timeframe.
method: Research method used.
assumptions: Structured assumptions.
- artifact_path: Artifact path. Presence marks evidence verified.
- artifact_hash: Optional artifact hash.
+ artifact_path: Artifact path. It verifies evidence only when allowed by path policy and paired with a matching sha256 hash.
+ artifact_hash: Required sha256 when artifact_path should verify evidence.
data_as_of: ISO timestamp/date for data freshness.
confidence: Optional confidence label.
caveat: Optional limitation note.
@@ -336,6 +355,50 @@ def add_goal_evidence(
return _json_error(str(exc), error_type="validation")
+def update_research_goal_status(
+ session_id: str,
+ goal_id: str,
+ expected_goal_id: str,
+ status: str,
+ audit: list[dict[str, Any]] | None = None,
+ recap: str | None = None,
+) -> str:
+ """Update a finance research goal status after an audit.
+
+ Use this to complete, cancel, block, pause, or otherwise move the current
+ goal through its lifecycle. ``complete`` requires one audit row per
+ required criterion and verified evidence for satisfied rows.
+
+ Args:
+ session_id: External conversation/session id.
+ goal_id: Goal being mutated.
+ expected_goal_id: Goal id captured before the tool/model turn started.
+ status: Goal lifecycle status, e.g. complete, cancelled, blocked.
+ audit: Optional list of criterion audit rows.
+ recap: Optional concise status recap.
+ """
+ try:
+ from src.goal import GoalStatus, StaleGoalError
+
+ updated = _get_goal_store().update_status(
+ session_id=session_id.strip(),
+ goal_id=goal_id.strip(),
+ expected_goal_id=expected_goal_id.strip(),
+ status=GoalStatus(status),
+ audit=_audit_rows_from_payload(audit),
+ recap=_blank_to_none(recap),
+ )
+ snapshot = _get_goal_store().get_goal_snapshot(updated.goal_id)
+ if snapshot is None:
+ return _json_error("Goal snapshot could not be reloaded")
+ return _json_ok(goal=snapshot["goal"], snapshot=snapshot)
+ except StaleGoalError as exc:
+ return _json_error(str(exc), error_type="stale_goal")
+ except ValueError as exc:
+ return _json_error(str(exc), error_type="validation")
+
+
# ---------------------------------------------------------------------------
# Backtest tool
# ---------------------------------------------------------------------------
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 932e43e92..b2ac6667d 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -27,6 +27,12 @@ from src.agent.progress import HeartbeatTimer, ProgressEvent, _set_emitter
from src.agent.tools import ToolRegistry
from src.agent.trace import TraceWriter
from src.core.state import RunStateStore
+from src.goal.context import (
+ format_goal_continuation_prompt,
+ get_current_goal_context,
+ goal_needs_continuation,
+ goal_progress_tuple,
+)
from src.providers.chat import ChatLLM
from src.tools.background_tools import get_background_manager
@@ -35,6 +41,7 @@ TOKEN_THRESHOLD = int(os.getenv("TOKEN_THRESHOLD", "40000"))
KEEP_RECENT = 3
TOOL_RESULT_LIMIT = 10_000
HEARTBEAT_INTERVAL_S = float(os.getenv("VT_HEARTBEAT_INTERVAL_S", "3.0"))
+GOAL_MAX_CONTINUATIONS = int(os.getenv("VIBE_TRADING_GOAL_MAX_CONTINUATIONS", "3"))
# Layer 2: Context collapse thresholds
COLLAPSE_THRESHOLD = int(TOKEN_THRESHOLD * 0.7)
@@ -339,7 +346,16 @@ class AgentLoop:
context = ContextBuilder(self.registry, self.memory,
persistent_memory=self._persistent_memory)
- messages = context.build_messages(user_message, history)
+ goal_context, active_goal_id = get_current_goal_context(session_id) if session_id else ("", None)
+ llm_user_message = user_message
+ if goal_context:
+ llm_user_message = (
+ f"{goal_context}\n\n"
+ f"<user-message>\n{user_message}\n</user-message>"
+ )
+ goal_store = None
+ goal_turn_accounted = False
+ messages = context.build_messages(llm_user_message, history)
react_trace: List[Dict[str, Any]] = []
trace = TraceWriter(run_dir)
@@ -347,6 +363,8 @@ class AgentLoop:
iteration = 0
final_content = ""
+ goal_continuations = 0
+ goal_last_progress: tuple[int, int] | None = None
try:
while iteration < self.max_iterations:
@@ -404,6 +422,31 @@ class AgentLoop:
"iter": iteration,
},
)
+ if active_goal_id and session_id:
+ token_delta = int(usage.get("total_tokens") or 0) if usage else 0
+ turn_delta = 0 if goal_turn_accounted else 1
+ if token_delta or turn_delta:
+ try:
+ if goal_store is None:
+ from src.goal import GoalStore
+
+ goal_store = GoalStore()
+ goal_store.account_usage(
+ session_id=session_id,
+ goal_id=active_goal_id,
+ expected_goal_id=active_goal_id,
+ token_delta=token_delta,
+ turn_delta=turn_delta,
+ )
+ goal_turn_accounted = True
+ snapshot = goal_store.get_goal_snapshot(active_goal_id)
+ if snapshot is not None:
+ self._emit(
+ "goal.updated",
+ {"goal": snapshot["goal"], "snapshot": snapshot},
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.debug("Goal usage accounting skipped: %s", exc)
thinking_text = "".join(thinking_chunks)
if thinking_text:
@@ -412,6 +455,67 @@ class AgentLoop:
if not response.has_tool_calls:
final_content = response.content or ""
+ should_continue_goal = False
+ continuation_snapshot = None
+ if active_goal_id and session_id and GOAL_MAX_CONTINUATIONS > 0:
+ try:
+ if goal_store is None:
+ from src.goal import GoalStore
+
+ goal_store = GoalStore()
+ continuation_snapshot = goal_store.get_goal_snapshot(active_goal_id)
+ should_continue_goal = bool(
+ continuation_snapshot
+ and goal_needs_continuation(continuation_snapshot)
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.debug("Goal continuation check skipped: %s", exc)
+
+ if should_continue_goal and continuation_snapshot is not None:
+ current_progress = goal_progress_tuple(continuation_snapshot)
+ no_new_progress = (
+ goal_last_progress is not None
+ and current_progress <= goal_last_progress
+ )
+ if goal_continuations >= GOAL_MAX_CONTINUATIONS or (
+ no_new_progress and goal_continuations > 0
+ ):
+ trace.write(
+ {
+ "type": "goal_continuation_suppressed",
+ "iter": iteration,
+ "goal_id": active_goal_id,
+ "progress": current_progress,
+ "continuations": goal_continuations,
+ }
+ )
+ else:
+ trace.write(
+ {
+ "type": "goal_intermediate_answer",
+ "iter": iteration,
+ "goal_id": active_goal_id,
+ "content": final_content[:2000],
+ "progress": current_progress,
+ }
+ )
+ react_trace.append(
+ {"type": "goal_intermediate_answer", "content": final_content[:500]}
+ )
+ messages.append({"role": "assistant", "content": final_content})
+ messages.append(
+ {
+ "role": "user",
+ "content": format_goal_continuation_prompt(
+ continuation_snapshot,
+ previous_answer=final_content,
+ ),
+ }
+ )
+ goal_last_progress = current_progress
+ goal_continuations += 1
+ continue
+
trace.write({"type": "answer", "iter": iteration, "content": final_content[:2000]})
react_trace.append({"type": "answer", "content": final_content[:500]})
break
diff --git a/agent/src/goal/context.py b/agent/src/goal/context.py
new file mode 100644
index 000000000..6e15ba790
--- /dev/null
+++ b/agent/src/goal/context.py
@@ -0,0 +1,178 @@
+"""Context helpers for session-scoped research goals."""
+
+from __future__ import annotations
+
+from typing import Any
+
+OPEN_CRITERION_STATUSES = {"", "pending", "open", "unsatisfied", "missing", "stale", "too_weak"}
+CONTINUABLE_GOAL_STATUSES = {"active", "needs_refresh", "insufficient_evidence"}
+
+
+DEFAULT_GOAL_CRITERIA = [
+ "Define the research-only thesis and symbol universe",
+ "Collect fresh market or benchmark evidence",
+ "Record caveats, contradictions, and non-advice boundary",
+]
+
+
+def default_goal_criteria() -> list[str]:
+ """Return the default research goal acceptance checklist."""
+ return list(DEFAULT_GOAL_CRITERIA)
+
+
+def format_goal_context(snapshot: dict[str, Any]) -> str:
+ """Format a compact active-goal block for the agent prompt.
+
+ Args:
+ snapshot: Goal snapshot returned by GoalStore.
+
+ Returns:
+ XML-ish context block injected into the next model turn.
+ """
+ goal = snapshot["goal"]
+ evidence = snapshot.get("evidence") or []
+ lines = [
+ "<current-research-goal>",
+ f"goal_id: {goal['goal_id']}",
+ f"expected_goal_id: {goal['goal_id']}",
+ f"status: {goal['status']}",
+ f"objective: {goal['objective']}",
+ f"risk_tier: {goal.get('risk_tier', 'research_general')}",
+ f"evidence_count: {snapshot.get('evidence_count', len(evidence))}",
+ "criteria:",
+ ]
+ for index, criterion in enumerate(snapshot.get("criteria") or [], start=1):
+ criterion_id = criterion["criterion_id"]
+ count = sum(1 for item in evidence if item.get("criterion_id") == criterion_id)
+ lines.append(
+ f"- {index}. [{criterion.get('status', 'pending')}] "
+ f"{criterion_id}: {criterion['text']} (evidence={count})"
+ )
+ lines.extend(
+ [
+ "instructions:",
+ "- Continue this goal unless the user explicitly replaces or cancels it.",
+ "- Use get_research_goal before mutating if you need the freshest snapshot.",
+ "- Add evidence with add_goal_evidence after tool-backed or concrete research steps.",
+ "- Do not treat a normal answer as finished while the goal status is still active.",
+ "- If all criteria are covered, audit the ledger and use update_research_goal_status.",
+ "- Complete or block the goal with update_research_goal_status only after an audit.",
+ "</current-research-goal>",
+ ]
+ )
+ return "\n".join(lines)
+
+
+def criterion_is_covered(snapshot: dict[str, Any], criterion: dict[str, Any]) -> bool:
+ """Return whether a criterion is already covered by status or evidence."""
+ status = str(criterion.get("status") or "").lower()
+ if status not in OPEN_CRITERION_STATUSES:
+ return True
+ criterion_id = criterion.get("criterion_id")
+ return any(item.get("criterion_id") == criterion_id for item in snapshot.get("evidence") or [])
+
+
+def goal_progress_tuple(snapshot: dict[str, Any]) -> tuple[int, int]:
+ """Return comparable progress as ``(covered_criteria, evidence_count)``."""
+ criteria = snapshot.get("criteria") or []
+ covered = sum(1 for item in criteria if criterion_is_covered(snapshot, item))
+ return covered, int(snapshot.get("evidence_count") or len(snapshot.get("evidence") or []))
+
+
+def goal_needs_continuation(snapshot: dict[str, Any]) -> bool:
+ """Return whether the runtime should keep working on this goal."""
+ goal = snapshot.get("goal") or {}
+ status = str(goal.get("status") or "").lower()
+ if status not in CONTINUABLE_GOAL_STATUSES:
+ return False
+ criteria = snapshot.get("criteria") or []
+ if not criteria:
+ return True
+ return True
+
+
+def format_goal_continuation_prompt(snapshot: dict[str, Any], previous_answer: str = "") -> str:
+ """Build the runtime-driven prompt for continuing an incomplete goal."""
+ goal = snapshot["goal"]
+ claims = snapshot.get("claims") or []
+ evidence = snapshot.get("evidence") or []
+ open_items = [
+ f"- {item['criterion_id']}: {item['text']}"
+ for item in snapshot.get("criteria") or []
+ if item.get("required", True) and not criterion_is_covered(snapshot, item)
+ ]
+ if not open_items:
+ open_items = ["- All criteria appear covered; audit evidence and update goal status if completion is justified."]
+
+ prior = previous_answer.strip()
+ prior_block = f"\nPrevious assistant text:\n{prior[:1200]}\n" if prior else ""
+ criteria_lines = []
+ for item in snapshot.get("criteria") or []:
+ count = sum(1 for ev in evidence if ev.get("criterion_id") == item.get("criterion_id"))
+ coverage = "covered" if criterion_is_covered(snapshot, item) else "open"
+ criteria_lines.append(
+ f"- {item['criterion_id']}: {item['text']} | status={item.get('status', 'pending')} "
+ f"| coverage={coverage} | evidence={count}"
+ )
+ claim_lines = [
+ f"- {item.get('claim_id')}: {item.get('claim_type')} | {item.get('status')} | {item.get('text')}"
+ for item in claims[:8]
+ ]
+ evidence_lines = []
+ for item in evidence[-6:]:
+ evidence_lines.append(
+ "- "
+ f"{item.get('evidence_id')}: criterion={item.get('criterion_id') or 'none'} "
+ f"| provider={item.get('source_provider') or item.get('source_type') or 'unknown'} "
+ f"| as_of={item.get('data_as_of') or 'unknown'} "
+ f"| verification={item.get('verification_status') or 'unknown'} "
+ f"| text={str(item.get('text') or '')[:240]}"
+ )
+ covered, total_evidence = goal_progress_tuple(snapshot)
+ return "\n".join(
+ [
+ "<goal-continuation>",
+ f"goal_id: {goal['goal_id']}",
+ f"expected_goal_id: {goal['goal_id']}",
+ f"status: {goal.get('status', 'active')}",
+ f"objective: {goal['objective']}",
+ f"snapshot_progress: covered_criteria={covered}/{len(snapshot.get('criteria') or [])}; evidence_count={total_evidence}",
+ "claims_snapshot:",
+ *(claim_lines or ["- none"]),
+ "criteria_snapshot:",
+ *(criteria_lines or ["- none"]),
+ "recent_evidence_snapshot:",
+ *(evidence_lines or ["- none"]),
+ "open_required_items:",
+ *open_items,
+ prior_block.rstrip(),
+ "Rules:",
+ "- Drive the next step from the snapshot above, not from the objective alone.",
+ "- Prefer the highest-priority open criterion with zero evidence.",
+ "- Use available tools when fresh or artifact-backed evidence is needed; reuse existing artifacts only when they answer the open criterion.",
+ "- After concrete research progress, call add_goal_evidence and link the exact criterion_id.",
+ "- If the ledger is sufficient, call update_research_goal_status with a completion audit.",
+ "- If progress is impossible, set a blocker/insufficient-evidence status instead of stopping silently.",
+ "</goal-continuation>",
+ ]
+ )
+
+
+def get_current_goal_context(session_id: str) -> tuple[str, str | None]:
+ """Return active-goal context and goal id for a session.
+
+ Args:
+ session_id: Current chat/session id.
+
+ Returns:
+ Tuple of formatted context block and active goal id. Both are empty
+ when no current goal exists.
+ """
+ if not session_id.strip():
+ return "", None
+ from src.goal.store import GoalStore
+
+ snapshot = GoalStore().get_current_snapshot(session_id)
+ if snapshot is None:
+ return "", None
+ return format_goal_context(snapshot), str(snapshot["goal"]["goal_id"])
diff --git a/agent/src/goal/store.py b/agent/src/goal/store.py
index 98ab42b30..ea0537a9e 100644
--- a/agent/src/goal/store.py
+++ b/agent/src/goal/store.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import json
+import os
import sqlite3
import threading
import uuid
@@ -30,6 +31,7 @@ from src.goal.policy import normalize_required_text, reject_live_execution_objec
from src.tools.path_utils import safe_document_path, safe_run_id
_DEFAULT_DB_PATH = Path.home() / ".vibe-trading" / "sessions.db"
+_DB_PATH_ENV = "VIBE_TRADING_GOAL_DB_PATH"
_CURRENT_STATUSES = {
GoalStatus.ACTIVE,
@@ -66,6 +68,14 @@ def _json_loads(value: str | None, default: object) -> object:
return json.loads(value)
+def _default_db_path() -> Path:
+ """Return the configured goal ledger database path."""
+ raw_path = os.getenv(_DB_PATH_ENV, "").strip()
+ if raw_path:
+ return Path(raw_path).expanduser()
+ return _DEFAULT_DB_PATH
+
+
def _to_json_dict(value: object) -> dict:
data = asdict(value)
for key, item in list(data.items()):
@@ -91,13 +101,14 @@ def _synchronized(method: F) -> F:
class GoalStore:
"""SQLite-backed store for finance research goals."""
- def __init__(self, db_path: Path = _DEFAULT_DB_PATH) -> None:
+ def __init__(self, db_path: Path | None = None) -> None:
"""Initialize the goal store.
Args:
- db_path: SQLite database path.
+ db_path: SQLite database path. When omitted,
+ ``VIBE_TRADING_GOAL_DB_PATH`` can override the default.
"""
- self.db_path = Path(db_path)
+ self.db_path = Path(db_path) if db_path is not None else _default_db_path()
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False)
self._conn.row_factory = sqlite3.Row
@@ -370,6 +381,71 @@ class GoalStore:
raise RuntimeError("created goal could not be reloaded")
return goal
+ @_synchronized
+ def update_goal(
+ self,
+ *,
+ session_id: str,
+ goal_id: str,
+ expected_goal_id: str,
+ objective: str | None = None,
+ ui_summary: str | None = None,
+ ) -> GoalRecord:
+ """Edit mutable goal metadata without superseding the active goal.
+
+ Args:
+ session_id: Owning session id.
+ goal_id: Goal being mutated.
+ expected_goal_id: Stale-write guard captured by the caller.
+ objective: Optional replacement research objective.
+ ui_summary: Optional compact display summary.
+
+ Returns:
+ Updated goal record.
+
+ Raises:
+ StaleGoalError: If the goal is stale or not current.
+ ValueError: If the new objective is empty or unsafe.
+ """
+ with self._write_transaction():
+ goal = self._require_mutable_goal(session_id, goal_id, expected_goal_id)
+ session_id = goal.session_id
+ goal_id = goal.goal_id
+ next_objective = goal.objective
+ if objective is not None:
+ next_objective = normalize_required_text(objective, "goal objective")
+ reject_live_execution_objective(next_objective)
+ next_summary = goal.ui_summary
+ if ui_summary is not None:
+ next_summary = ui_summary.strip() or next_objective[:80]
+ elif objective is not None and goal.ui_summary == goal.objective[:80]:
+ next_summary = next_objective[:80]
+ now = _now_iso()
+ self._conn.execute(
+ """
+ UPDATE goals
+ SET objective = ?, ui_summary = ?, updated_at = ?
+ WHERE goal_id = ? AND session_id = ?
+ """,
+ (next_objective, next_summary, now, goal_id, session_id),
+ )
+ if objective is not None:
+ self._conn.execute(
+ """
+ UPDATE goal_claims
+ SET text = ?, updated_at = ?
+ WHERE goal_id = ? AND session_id = ?
+ AND claim_type = 'thesis'
+ AND status = 'active'
+ """,
+ (next_objective, now, goal_id, session_id),
+ )
+
+ updated = self.get_goal(goal_id)
+ if updated is None:
+ raise RuntimeError("updated goal could not be reloaded")
+ return updated
+
@_synchronized
def get_goal(self, goal_id: str) -> GoalRecord | None:
"""Return a goal by id."""
@@ -600,6 +676,16 @@ class GoalStore:
now,
),
)
+ if evidence.criterion_id is not None:
+ self._conn.execute(
+ """
+ UPDATE goal_criteria
+ SET status = 'covered', updated_at = ?
+ WHERE goal_id = ? AND session_id = ? AND criterion_id = ?
+ AND status IN ('pending', 'open', 'unsatisfied')
+ """,
+ (now, goal_id, session_id, evidence.criterion_id),
+ )
record = self._get_evidence(evidence_id)
if record is None:
@@ -824,6 +910,7 @@ class GoalStore:
raise ValueError("complete goals require verified evidence")
if row.result == "not_applicable_user_accepted" and not row.notes.strip():
raise ValueError("not-applicable criteria require acceptance notes")
+ has_verified_evidence = False
for evidence_id in row.evidence_ids:
evidence = self._get_evidence(evidence_id)
if evidence is None or evidence.goal_id != goal.goal_id:
@@ -832,8 +919,10 @@ class GoalStore:
raise ValueError(
f"evidence {evidence_id} does not match criterion {criterion.criterion_id}"
)
- if evidence.verification_status != "verified":
- raise ValueError("complete goals require verified evidence")
+ if evidence.verification_status == "verified":
+ has_verified_evidence = True
+ if row.result in {"satisfied", "satisfied_with_caveat"} and not has_verified_evidence:
+ raise ValueError("complete goals require verified evidence")
def _get_evidence(self, evidence_id: str) -> EvidenceRecord | None:
row = self._conn.execute(
diff --git a/agent/src/skills/research-goal/SKILL.md b/agent/src/skills/research-goal/SKILL.md
index 704ee1af3..642c4bad6 100644
--- a/agent/src/skills/research-goal/SKILL.md
+++ b/agent/src/skills/research-goal/SKILL.md
@@ -26,6 +26,7 @@ Do not start a goal for a tiny one-shot answer unless the user explicitly asks.
3. Before continuing an existing task, call `get_research_goal`.
4. After a market-data lookup, backtest, document read, web source, or manual reasoning step, call `add_goal_evidence`.
5. Link evidence to a criterion using `criterion_id` or `criterion_index`.
+6. When all required criteria have been audited, call `update_research_goal_status`.
## Criteria Template
@@ -41,8 +42,16 @@ Use this shape when the user did not provide criteria:
- Keep evidence short and concrete.
- Prefer artifact-backed evidence when a tool produced a run or file.
- Include `run_id`, `artifact_path`, `source_provider`, `source_type`, `symbol_universe`, `benchmark`, and `data_as_of` when known.
+- `tool_call_id` is traceability only. Completion needs verified evidence from an existing `run_id` or an allowed `artifact_path` with a matching sha256 hash.
- Do not mark live trading instructions as evidence. Refuse or reframe them as research-only analysis.
+## Completion Rules
+
+- Use `update_research_goal_status(status="complete")` only after every required criterion has an audit row.
+- Satisfied audit rows must cite verified `evidence_ids`.
+- Use `status="blocked"` or `status="insufficient_evidence"` when evidence is missing, stale, contradictory, or not verifiable.
+- Use `status="cancelled"` only when the user explicitly asks to end or discard the goal.
+
## Response Style
Tell the user what the goal is tracking only when it helps. Do not flood the answer with ledger details. Lead with the research conclusion, then mention which criteria remain unresolved.
diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.py
index 465b2f063..0b3342723 100644
--- a/agent/src/tools/__init__.py
+++ b/agent/src/tools/__init__.py
@@ -104,11 +104,21 @@ def build_registry(
ToolRegistry containing all available local tools followed by any
successfully discovered MCP tools.
"""
- from src.tools.goal_tool import AddGoalEvidenceTool, GetResearchGoalTool, StartResearchGoalTool
+ from src.tools.goal_tool import (
+ AddGoalEvidenceTool,
+ GetResearchGoalTool,
+ StartResearchGoalTool,
+ UpdateResearchGoalStatusTool,
+ )
from src.tools.remember_tool import RememberTool
from src.tools.swarm_tool import SwarmTool
- goal_tool_classes = {StartResearchGoalTool, GetResearchGoalTool, AddGoalEvidenceTool}
+ goal_tool_classes = {
+ StartResearchGoalTool,
+ GetResearchGoalTool,
+ AddGoalEvidenceTool,
+ UpdateResearchGoalStatusTool,
+ }
registry = ToolRegistry()
for cls in _discover_subclasses():
try:
diff --git a/agent/src/tools/goal_tool.py b/agent/src/tools/goal_tool.py
index 12061fcca..90b56afd1 100644
--- a/agent/src/tools/goal_tool.py
+++ b/agent/src/tools/goal_tool.py
@@ -2,20 +2,15 @@
from __future__ import annotations
+import hashlib
import json
+from pathlib import Path
from typing import Any, Callable
from src.agent.tools import BaseTool
-from src.goal import EvidenceInput, GoalStore, RiskTier, StaleGoalError
-
-
-def _default_criteria() -> list[str]:
- """Return the minimal finance research goal checklist."""
- return [
- "Define the research-only thesis and symbol universe",
- "Collect fresh market or benchmark evidence",
- "Record caveats, contradictions, and non-advice boundary",
- ]
+from src.goal import AuditRow, EvidenceInput, GoalStatus, GoalStore, RiskTier, StaleGoalError
+from src.goal.context import default_goal_criteria
+from src.tools.path_utils import safe_run_dir
def _json_error(error: str, *, error_type: str = "validation") -> str:
@@ -37,6 +32,76 @@ def _coerce_string_list(value: Any) -> list[str]:
return []
+def _coerce_audit_rows(value: Any) -> list[AuditRow]:
+ """Coerce model/API-style audit rows into dataclasses."""
+ if value in (None, ""):
+ return []
+ if isinstance(value, str):
+ value = json.loads(value)
+ if not isinstance(value, list):
+ raise ValueError("audit must be a list")
+
+ rows: list[AuditRow] = []
+ for item in value:
+ if not isinstance(item, dict):
+ raise ValueError("audit rows must be objects")
+ criterion_id = str(item.get("criterion_id") or "").strip()
+ result = str(item.get("result") or "").strip()
+ if not criterion_id or not result:
+ raise ValueError("audit rows require criterion_id and result")
+ rows.append(
+ AuditRow(
+ criterion_id=criterion_id,
+ result=result,
+ evidence_ids=_coerce_string_list(item.get("evidence_ids")),
+ notes=str(item.get("notes") or ""),
+ )
+ )
+ return rows
+
+
+def _sha256_file(path: Path) -> str:
+ """Return the sha256 digest for a local artifact."""
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def _trace_fields_from_runtime(kwargs: dict[str, Any]) -> tuple[str | None, str | None, str | None]:
+ """Resolve host-injected run metadata into ledger-verifiable evidence fields."""
+ run_id = str(kwargs.get("run_id") or "").strip() or None
+ artifact_path = str(kwargs.get("artifact_path") or "").strip() or None
+ artifact_hash = str(kwargs.get("artifact_hash") or "").strip() or None
+
+ run_dir_raw = str(kwargs.get("run_dir") or "").strip()
+ run_dir: Path | None = None
+ if run_dir_raw:
+ run_dir = safe_run_dir(run_dir_raw)
+ if run_id is None:
+ run_id = run_dir.name
+
+ artifact_candidate: Path | None = None
+ if artifact_path:
+ raw_path = Path(artifact_path).expanduser()
+ if run_dir is not None and not raw_path.is_absolute():
+ resolved = (run_dir / raw_path).resolve()
+ try:
+ resolved.relative_to(run_dir)
+ except ValueError as exc:
+ raise ValueError("artifact_path escapes the current run_dir") from exc
+ artifact_candidate = resolved
+ artifact_path = str(resolved)
+ elif raw_path.is_absolute():
+ artifact_candidate = raw_path.resolve()
+
+ if artifact_candidate is not None and artifact_candidate.is_file() and not artifact_hash:
+ artifact_hash = _sha256_file(artifact_candidate)
+
+ return run_id, artifact_path, artifact_hash
+
+
class _GoalToolBase(BaseTool):
"""Shared helpers for local goal tools."""
@@ -130,7 +195,7 @@ class StartResearchGoalTool(_GoalToolBase):
return _json_error("session_id is required")
try:
- criteria = _coerce_string_list(kwargs.get("criteria")) or _default_criteria()
+ criteria = _coerce_string_list(kwargs.get("criteria")) or default_goal_criteria()
goal = self._store.replace_goal(
session_id=session_id,
objective=str(kwargs.get("objective", "")),
@@ -150,6 +215,99 @@ class StartResearchGoalTool(_GoalToolBase):
return _json_error(str(exc))
+class UpdateResearchGoalStatusTool(_GoalToolBase):
+ """Move the current research goal to another lifecycle status."""
+
+ name = "update_research_goal_status"
+ description = (
+ "Update the current finance research goal status. Use this to complete, "
+ "cancel, block, pause, or mark a goal as needing more evidence after an audit. "
+ "Completion requires an audit row for every required criterion with verified evidence."
+ )
+ is_readonly = False
+ parameters = {
+ "type": "object",
+ "properties": {
+ "session_id": {
+ "type": "string",
+ "description": "Optional session id. Omit when the host runtime injected the current session.",
+ },
+ "goal_id": {"type": "string", "description": "Optional goal id. Defaults to the current goal."},
+ "expected_goal_id": {
+ "type": "string",
+ "description": "Optional stale-write guard. Defaults to goal_id.",
+ },
+ "status": {
+ "type": "string",
+ "enum": [status.value for status in GoalStatus],
+ "description": "Next lifecycle status.",
+ },
+ "audit": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "criterion_id": {"type": "string"},
+ "result": {
+ "type": "string",
+ "enum": [
+ "satisfied",
+ "satisfied_with_caveat",
+ "not_applicable_user_accepted",
+ "unsatisfied",
+ ],
+ },
+ "evidence_ids": {"type": "array", "items": {"type": "string"}},
+ "notes": {"type": "string"},
+ },
+ "required": ["criterion_id", "result"],
+ },
+ "description": "Criterion audit rows, required when status is complete.",
+ },
+ "recap": {"type": "string", "description": "Optional concise status recap."},
+ },
+ "required": ["status"],
+ }
+
+ def execute(self, **kwargs: Any) -> str:
+ """Update the current research goal status.
+
+ Args:
+ **kwargs: Tool arguments from the model.
+
+ Returns:
+ JSON envelope with the updated goal snapshot or an error.
+ """
+ session_id = self._session_id(kwargs)
+ if not session_id:
+ return _json_error("session_id is required")
+ try:
+ snapshot = self._store.get_current_snapshot(session_id)
+ goal_id = str(kwargs.get("goal_id") or "").strip()
+ if not goal_id:
+ if snapshot is None:
+ return _json_error("no current goal for this session", error_type="not_found")
+ goal_id = str(snapshot["goal"]["goal_id"])
+ expected_goal_id = str(kwargs.get("expected_goal_id") or goal_id).strip()
+ status = GoalStatus(str(kwargs.get("status") or "").strip())
+ self._store.update_status(
+ session_id=session_id,
+ goal_id=goal_id,
+ expected_goal_id=expected_goal_id,
+ status=status,
+ audit=_coerce_audit_rows(kwargs.get("audit")),
+ recap=str(kwargs.get("recap") or "").strip() or None,
+ )
+ updated = self._store.get_goal_snapshot(goal_id)
+ if updated is not None:
+ self._emit("goal.updated", {"goal": updated["goal"], "snapshot": updated})
+ return json.dumps({"status": "ok", "snapshot": updated}, ensure_ascii=False)
+ except StaleGoalError as exc:
+ return _json_error(str(exc), error_type="stale_goal")
+ except (json.JSONDecodeError, TypeError, ValueError) as exc:
+ return _json_error(str(exc))
+
+
class GetResearchGoalTool(_GoalToolBase):
"""Read the current research goal snapshot."""
@@ -216,6 +374,10 @@ class AddGoalEvidenceTool(_GoalToolBase):
"claim_id": {"type": "string", "description": "Optional claim id."},
"text": {"type": "string", "description": "Evidence note or artifact summary."},
"run_id": {"type": "string", "description": "Optional local run id that produced this evidence."},
+ "run_dir": {
+ "type": "string",
+ "description": "Optional host-injected current run directory. Omit unless provided by the runtime.",
+ },
"tool_call_id": {"type": "string", "description": "Optional tool call id for traceability."},
"source_provider": {"type": "string", "description": "Data or tool provider."},
"source_type": {"type": "string", "description": "Source type, e.g. backtest, market_data, manual_note."},
@@ -267,6 +429,7 @@ class AddGoalEvidenceTool(_GoalToolBase):
if index < 1 or index > len(criteria):
return _json_error(f"criterion_index out of range: {index}")
criterion_id = str(criteria[index - 1]["criterion_id"])
+ run_id, artifact_path, artifact_hash = _trace_fields_from_runtime(kwargs)
record = self._store.append_evidence(
session_id=session_id,
@@ -276,7 +439,7 @@ class AddGoalEvidenceTool(_GoalToolBase):
criterion_id=criterion_id,
claim_id=str(kwargs.get("claim_id") or "").strip() or None,
text=str(kwargs.get("text", "")),
- run_id=str(kwargs.get("run_id") or "").strip() or None,
+ run_id=run_id,
tool_call_id=str(kwargs.get("tool_call_id") or "").strip() or None,
source_provider=str(kwargs.get("source_provider") or "agent_tool"),
source_type=str(kwargs.get("source_type") or "tool_note"),
@@ -285,8 +448,8 @@ class AddGoalEvidenceTool(_GoalToolBase):
benchmark=_coerce_string_list(kwargs.get("benchmark")),
timeframe=str(kwargs.get("timeframe") or "").strip() or None,
method=str(kwargs.get("method") or "").strip() or None,
- artifact_path=str(kwargs.get("artifact_path") or "").strip() or None,
- artifact_hash=str(kwargs.get("artifact_hash") or "").strip() or None,
+ artifact_path=artifact_path,
+ artifact_hash=artifact_hash,
data_as_of=str(kwargs.get("data_as_of") or "").strip() or None,
confidence=str(kwargs.get("confidence") or "").strip() or None,
caveat=str(kwargs.get("caveat") or "").strip() or None,
diff --git a/agent/tests/test_agent_goal_context.py b/agent/tests/test_agent_goal_context.py
new file mode 100644
index 000000000..10a0e8a29
--- /dev/null
+++ b/agent/tests/test_agent_goal_context.py
@@ -0,0 +1,167 @@
+"""AgentLoop regressions for active research goal context."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Callable
+
+from src.agent.loop import AgentLoop
+from src.goal import GoalStore
+
+
+class _AnswerResponse:
+ def __init__(self, content: str = "done", total_tokens: int = 0) -> None:
+ self.content = content
+ self.tool_calls: list[Any] = []
+ self.reasoning_content: str | None = None
+ self.has_tool_calls = False
+ self.usage_metadata = {"total_tokens": total_tokens} if total_tokens else {}
+
+
+class _CapturingLLM:
+ def __init__(self, total_tokens: int = 0) -> None:
+ self.total_tokens = total_tokens
+ self.messages: list[dict[str, Any]] = []
+ self.calls: list[list[dict[str, Any]]] = []
+
+ def stream_chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[Any] | None = None,
+ on_text_chunk: Callable[[str], None] | None = None,
+ ) -> _AnswerResponse:
+ del tools, on_text_chunk
+ self.messages = messages
+ self.calls.append([dict(item) for item in messages])
+ return _AnswerResponse(total_tokens=self.total_tokens)
+
+ def chat(self, messages: list[dict[str, Any]], **_: Any) -> _AnswerResponse:
+ self.messages = messages
+ return _AnswerResponse(total_tokens=self.total_tokens)
+
+
+def _agent(llm: _CapturingLLM, run_dir: Path) -> AgentLoop:
+ from src.memory.persistent import PersistentMemory
+ from src.tools import build_registry
+
+ pm = PersistentMemory()
+ agent = AgentLoop(
+ registry=build_registry(persistent_memory=pm, include_shell_tools=False),
+ llm=llm,
+ max_iterations=2,
+ persistent_memory=pm,
+ )
+ run_dir.mkdir(parents=True)
+ agent.memory.run_dir = str(run_dir)
+ return agent
+
+
+def test_agent_loop_injects_active_goal_context(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr("src.agent.loop.GOAL_MAX_CONTINUATIONS", 0)
+ monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
+ store = GoalStore()
+ goal = store.replace_goal(
+ session_id="session-1",
+ objective="Evaluate NVDA momentum.",
+ criteria=["Define thesis", "Check price action"],
+ )
+ llm = _CapturingLLM()
+
+ result = _agent(llm, tmp_path / "run").run(
+ user_message="Continue the analysis.",
+ session_id="session-1",
+ )
+
+ user_message = llm.messages[-1]["content"]
+ assert result["status"] == "success"
+ assert "<current-research-goal>" in user_message
+ assert goal.goal_id in user_message
+ assert "expected_goal_id" in user_message
+ assert "Evaluate NVDA momentum." in user_message
+ assert "Continue the analysis." in user_message
+
+
+def test_agent_loop_accounts_goal_token_and_turn_usage(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr("src.agent.loop.GOAL_MAX_CONTINUATIONS", 0)
+ monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
+ store = GoalStore()
+ goal = store.replace_goal(
+ session_id="session-1",
+ objective="Evaluate NVDA momentum.",
+ criteria=["Define thesis"],
+ token_budget=100,
+ turn_budget=5,
+ )
+ llm = _CapturingLLM(total_tokens=17)
+
+ _agent(llm, tmp_path / "run").run(
+ user_message="Continue the analysis.",
+ session_id="session-1",
+ )
+
+ updated = store.get_goal(goal.goal_id)
+ assert updated is not None
+ assert updated.tokens_used == 17
+ assert updated.turns_used == 1
+
+
+def test_agent_loop_continues_active_incomplete_goal(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr("src.agent.loop.GOAL_MAX_CONTINUATIONS", 1)
+ monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
+ store = GoalStore()
+ store.replace_goal(
+ session_id="session-1",
+ objective="Evaluate NVDA momentum.",
+ criteria=["Define thesis", "Check price action"],
+ )
+ llm = _CapturingLLM()
+
+ result = _agent(llm, tmp_path / "run").run(
+ user_message="Start the goal.",
+ session_id="session-1",
+ )
+
+ assert result["status"] == "success"
+ assert len(llm.calls) == 2
+ assert "<goal-continuation>" in llm.calls[1][-1]["content"]
+ assert "criteria_snapshot:" in llm.calls[1][-1]["content"]
+ assert "recent_evidence_snapshot:" in llm.calls[1][-1]["content"]
+ assert "Check price action" in llm.calls[1][-1]["content"]
+
+
+def test_agent_loop_continues_active_covered_goal_to_force_audit(tmp_path: Path, monkeypatch) -> None:
+ """Covered criteria still need a terminal status audit before the loop stops."""
+ from src.goal import EvidenceInput
+
+ monkeypatch.setattr("src.agent.loop.GOAL_MAX_CONTINUATIONS", 1)
+ monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
+ store = GoalStore()
+ goal = store.replace_goal(
+ session_id="session-1",
+ objective="Evaluate NVDA momentum.",
+ criteria=["Define thesis"],
+ )
+ criterion = store.list_criteria(goal.goal_id)[0]
+ store.append_evidence(
+ session_id="session-1",
+ goal_id=goal.goal_id,
+ expected_goal_id=goal.goal_id,
+ evidence=EvidenceInput(
+ criterion_id=criterion.criterion_id,
+ text="Thesis evidence exists, but the goal is not terminal yet.",
+ run_id="missing-run-is-ok-for-coverage",
+ ),
+ )
+ llm = _CapturingLLM()
+
+ result = _agent(llm, tmp_path / "run").run(
+ user_message="Finish the goal.",
+ session_id="session-1",
+ )
+
+ assert result["status"] == "success"
+ assert len(llm.calls) == 2
+ continuation = llm.calls[1][-1]["content"]
+ assert "<goal-continuation>" in continuation
+ assert "All criteria appear covered; audit evidence" in continuation
+ assert "status: active" in continuation
diff --git a/agent/tests/test_cli_goal.py b/agent/tests/test_cli_goal.py
index 107b5d9f6..4c7f8d53d 100644
--- a/agent/tests/test_cli_goal.py
+++ b/agent/tests/test_cli_goal.py
@@ -121,3 +121,26 @@ def test_goal_start_persists_session_id_on_plain_context(tmp_path: Path, monkeyp
assert goal_cmd.run(ctx, "Evaluate", "NVDA", "momentum.") == 0
assert ctx.session_id == "session-1"
assert goal_cmd.run(ctx, "status") == 0
+
+
+def test_goal_cancel_moves_goal_out_of_current_set(tmp_path: Path, monkeypatch) -> None:
+ """CLI users can end an active goal without replacing it."""
+ from cli.commands import goal as goal_cmd
+
+ store = GoalStore(tmp_path / "goals.db")
+ monkeypatch.setattr(goal_cmd, "_goal_store", store)
+ goal = store.replace_goal(
+ session_id="session-1",
+ objective="Evaluate NVDA momentum.",
+ criteria=["Define thesis"],
+ )
+ ctx = SimpleNamespace(session_id="session-1")
+
+ rc = goal_cmd.run(ctx, "cancel", "No", "longer", "needed.")
+
+ assert rc == 0
+ assert store.get_current_snapshot("session-1") is None
+ cancelled = store.get_goal(goal.goal_id)
+ assert cancelled is not None
+ assert cancelled.status.value == "cancelled"
+ assert cancelled.recap == "No longer needed."
diff --git a/agent/tests/test_goal_api.py b/agent/tests/test_goal_api.py
new file mode 100644
index 000000000..c4cc7edd2
--- /dev/null
+++ b/agent/tests/test_goal_api.py
@@ -0,0 +1,138 @@
+"""API regressions for research goal status and defaults."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from fastapi.testclient import TestClient
+
+import api_server
+
+
+def _client(tmp_path: Path, monkeypatch) -> TestClient:
+ monkeypatch.setenv("VIBE_TRADING_GOAL_DB_PATH", str(tmp_path / "goals.db"))
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(tmp_path / "runs"))
+ monkeypatch.setattr(api_server, "_goal_store", None)
+ monkeypatch.setattr(api_server, "_session_service", None)
+ monkeypatch.setattr(api_server, "SESSIONS_DIR", tmp_path / "sessions")
+ monkeypatch.setattr(api_server, "RUNS_DIR", tmp_path / "runs")
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
+def _session_id(client: TestClient) -> str:
+ response = client.post("/sessions", json={"title": "goal api"})
+ assert response.status_code == 201
+ return response.json()["session_id"]
+
+
+def test_api_goal_uses_full_default_research_checklist(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ sid = _session_id(client)
+
+ response = client.post(f"/sessions/{sid}/goal", json={"objective": "Evaluate NVDA momentum."})
+
+ assert response.status_code == 201
+ criteria = response.json()["criteria"]
+ assert [item["text"] for item in criteria] == [
+ "Define the research-only thesis and symbol universe",
+ "Collect fresh market or benchmark evidence",
+ "Record caveats, contradictions, and non-advice boundary",
+ ]
+
+
+def test_api_can_complete_goal_with_verified_evidence(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ sid = _session_id(client)
+ run_dir = tmp_path / "runs" / "goal-api-run"
+ run_dir.mkdir(parents=True)
+ goal_response = client.post(
+ f"/sessions/{sid}/goal",
+ json={"objective": "Evaluate NVDA momentum.", "criteria": ["Check price action"]},
+ )
+ goal_payload = goal_response.json()
+ goal_id = goal_payload["goal"]["goal_id"]
+ criterion_id = goal_payload["criteria"][0]["criterion_id"]
+ evidence_response = client.post(
+ f"/sessions/{sid}/goal/evidence",
+ json={
+ "goal_id": goal_id,
+ "expected_goal_id": goal_id,
+ "criterion_id": criterion_id,
+ "text": "Backtest artifact supports the criterion.",
+ "run_id": "goal-api-run",
+ },
+ )
+ evidence_id = evidence_response.json()["evidence"]["evidence_id"]
+
+ response = client.patch(
+ f"/sessions/{sid}/goal/status",
+ json={
+ "goal_id": goal_id,
+ "expected_goal_id": goal_id,
+ "status": "complete",
+ "audit": [
+ {
+ "criterion_id": criterion_id,
+ "result": "satisfied",
+ "evidence_ids": [evidence_id],
+ "notes": "Verified by generated run artifact.",
+ }
+ ],
+ "recap": "Research-only goal completed.",
+ },
+ )
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["goal"]["status"] == "complete"
+ assert payload["goal"]["recap"] == "Research-only goal completed."
+ assert payload["snapshot"]["criteria"][0]["status"] == "satisfied"
+
+
+def test_api_can_cancel_current_goal(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ sid = _session_id(client)
+ goal_payload = client.post(
+ f"/sessions/{sid}/goal",
+ json={"objective": "Evaluate NVDA momentum."},
+ ).json()
+ goal_id = goal_payload["goal"]["goal_id"]
+
+ response = client.patch(
+ f"/sessions/{sid}/goal/status",
+ json={
+ "goal_id": goal_id,
+ "expected_goal_id": goal_id,
+ "status": "cancelled",
+ "recap": "Cancelled from API.",
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["goal"]["status"] == "cancelled"
+ assert client.get(f"/sessions/{sid}/goal").status_code == 404
+
+
+def test_api_can_edit_current_goal_objective(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ sid = _session_id(client)
+ goal_payload = client.post(
+ f"/sessions/{sid}/goal",
+ json={"objective": "Evaluate NVDA momentum."},
+ ).json()
+ goal_id = goal_payload["goal"]["goal_id"]
+
+ response = client.patch(
+ f"/sessions/{sid}/goal",
+ json={
+ "goal_id": goal_id,
+ "expected_goal_id": goal_id,
+ "objective": "Evaluate NVDA versus QQQ momentum.",
+ },
+ )
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["goal"]["goal_id"] == goal_id
+ assert payload["goal"]["objective"] == "Evaluate NVDA versus QQQ momentum."
+ assert payload["snapshot"]["claims"][0]["text"] == "Evaluate NVDA versus QQQ momentum."
diff --git a/agent/tests/test_goal_store.py b/agent/tests/test_goal_store.py
index 5e0e98b9d..b2da41909 100644
--- a/agent/tests/test_goal_store.py
+++ b/agent/tests/test_goal_store.py
@@ -67,6 +67,29 @@ def test_replace_goal_creates_initial_thesis_claim(tmp_path: Path) -> None:
assert claims[0].status == "active"
+def test_update_goal_edits_current_objective_without_replacing_goal(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ goal = store.replace_goal(
+ session_id="session-1",
+ objective="Evaluate NVDA momentum.",
+ criteria=["Define thesis"],
+ )
+
+ updated = store.update_goal(
+ session_id="session-1",
+ goal_id=goal.goal_id,
+ expected_goal_id=goal.goal_id,
+ objective="Evaluate NVDA versus QQQ momentum.",
+ )
+
+ assert updated.goal_id == goal.goal_id
+ assert updated.objective == "Evaluate NVDA versus QQQ momentum."
+ current = store.get_current_goal("session-1")
+ assert current is not None
+ assert current.goal_id == goal.goal_id
+ assert store.list_claims(goal.goal_id)[0].text == "Evaluate NVDA versus QQQ momentum."
+
+
def test_replace_goal_rejects_live_execution_objective(tmp_path: Path) -> None:
store = _store(tmp_path)
@@ -332,6 +355,62 @@ def test_complete_goal_with_verified_evidence(tmp_path: Path, monkeypatch: pytes
assert store.list_criteria(goal.goal_id)[0].status == "satisfied"
+def test_completion_allows_mixed_verified_and_historical_evidence(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Audit rows may cite old evidence as long as each criterion has verified evidence."""
+ store = _store(tmp_path)
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(tmp_path))
+ goal = store.replace_goal(
+ session_id="session-1",
+ objective="Evaluate NVDA momentum.",
+ criteria=["Check price action"],
+ )
+ criterion = store.list_criteria(goal.goal_id)[0]
+ old_evidence = store.append_evidence(
+ session_id="session-1",
+ goal_id=goal.goal_id,
+ expected_goal_id=goal.goal_id,
+ evidence=EvidenceInput(
+ criterion_id=criterion.criterion_id,
+ text="Historical unverified note from an earlier model turn.",
+ ),
+ )
+ artifact = tmp_path / "nvda_momentum.txt"
+ artifact.write_text("Verified NVDA momentum artifact.", encoding="utf-8")
+ verified_evidence = store.append_evidence(
+ session_id="session-1",
+ goal_id=goal.goal_id,
+ expected_goal_id=goal.goal_id,
+ evidence=EvidenceInput(
+ criterion_id=criterion.criterion_id,
+ text="Verified artifact evidence for the same criterion.",
+ artifact_path=str(artifact),
+ artifact_hash=_sha256(artifact),
+ ),
+ )
+
+ completed = store.update_status(
+ session_id="session-1",
+ goal_id=goal.goal_id,
+ expected_goal_id=goal.goal_id,
+ status=GoalStatus.COMPLETE,
+ audit=[
+ AuditRow(
+ criterion_id=criterion.criterion_id,
+ result="satisfied",
+ evidence_ids=[old_evidence.evidence_id, verified_evidence.evidence_id],
+ notes="Historical note plus current verified evidence.",
+ )
+ ],
+ )
+
+ assert old_evidence.verification_status == "unverified"
+ assert verified_evidence.verification_status == "verified"
+ assert completed.status is GoalStatus.COMPLETE
+
+
def test_artifact_evidence_requires_allowed_path_and_hash(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
@@ -426,6 +505,28 @@ def test_goal_snapshot_includes_claims_criteria_and_evidence(tmp_path: Path) ->
assert snapshot["evidence_count"] == 1
+def test_append_evidence_marks_linked_pending_criterion_covered(tmp_path: Path) -> None:
+ store = _store(tmp_path)
+ goal = store.replace_goal(
+ session_id="session-1",
+ objective="Evaluate NVDA momentum.",
+ criteria=["Check price action"],
+ )
+ criterion = store.list_criteria(goal.goal_id)[0]
+
+ store.append_evidence(
+ session_id="session-1",
+ goal_id=goal.goal_id,
+ expected_goal_id=goal.goal_id,
+ evidence=EvidenceInput(
+ criterion_id=criterion.criterion_id,
+ text="NVDA outperformed QQQ over the last 5 sessions.",
+ ),
+ )
+
+ assert store.list_criteria(goal.goal_id)[0].status == "covered"
+
+
def test_goal_snapshot_caps_evidence_but_reports_total_count(tmp_path: Path) -> None:
store = _store(tmp_path)
goal = store.replace_goal(
diff --git a/agent/tests/test_goal_tools.py b/agent/tests/test_goal_tools.py
index 86220aace..37fac4fcb 100644
--- a/agent/tests/test_goal_tools.py
+++ b/agent/tests/test_goal_tools.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import hashlib
import json
from pathlib import Path
@@ -11,6 +12,7 @@ from src.tools.goal_tool import (
AddGoalEvidenceTool,
GetResearchGoalTool,
StartResearchGoalTool,
+ UpdateResearchGoalStatusTool,
)
@@ -117,6 +119,77 @@ def test_goal_tools_emit_mutation_events(tmp_path: Path) -> None:
assert events[1][1]["goal_id"] == created["snapshot"]["goal"]["goal_id"]
+def test_goal_evidence_tool_binds_runtime_artifact(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """Runtime run_dir artifacts become verified goal evidence automatically."""
+ run_root = tmp_path / "runs"
+ run_dir = run_root / "goal-tool-run"
+ artifact = run_dir / "artifacts" / "metrics.csv"
+ artifact.parent.mkdir(parents=True)
+ artifact.write_text("symbol,return\nNVDA,0.12\n", encoding="utf-8")
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_RUN_ROOTS", str(run_root))
+ monkeypatch.setenv("VIBE_TRADING_ALLOWED_FILE_ROOTS", str(run_root))
+
+ store = GoalStore(tmp_path / "goals.db")
+ start = StartResearchGoalTool(default_session_id="session-1", store=store)
+ add = AddGoalEvidenceTool(default_session_id="session-1", store=store)
+ created = json.loads(
+ start.execute(
+ objective="Evaluate NVDA momentum as a research-only thesis.",
+ criteria=["Check price action"],
+ )
+ )
+
+ result = json.loads(
+ add.execute(
+ goal_id=created["snapshot"]["goal"]["goal_id"],
+ criterion_index=1,
+ text="Generated metrics artifact for NVDA momentum.",
+ source_provider="pytest",
+ source_type="market_data",
+ artifact_path="artifacts/metrics.csv",
+ run_dir=str(run_dir),
+ )
+ )
+
+ expected_hash = hashlib.sha256(artifact.read_bytes()).hexdigest()
+ evidence = result["evidence"]
+ assert result["status"] == "ok"
+ assert evidence["run_id"] == "goal-tool-run"
+ assert evidence["artifact_path"] == str(artifact.resolve())
+ assert evidence["artifact_hash"] == expected_hash
+ assert evidence["verification_status"] == "verified"
+
+
+def test_goal_status_tool_can_cancel_current_goal(tmp_path: Path) -> None:
+ """Agent tools can move a current goal to a terminal status."""
+ store = GoalStore(tmp_path / "goals.db")
+ start = StartResearchGoalTool(default_session_id="session-1", store=store)
+ update = UpdateResearchGoalStatusTool(default_session_id="session-1", store=store)
+ created = json.loads(
+ start.execute(
+ objective="Evaluate NVDA momentum as a research-only thesis.",
+ criteria=["Define thesis"],
+ )
+ )
+ goal_id = created["snapshot"]["goal"]["goal_id"]
+
+ result = json.loads(
+ update.execute(
+ goal_id=goal_id,
+ expected_goal_id=goal_id,
+ status="cancelled",
+ recap="Cancelled during tool test.",
+ )
+ )
+
+ assert result["status"] == "ok"
+ assert result["snapshot"]["goal"]["status"] == "cancelled"
+ assert store.get_current_snapshot("session-1") is None
+
+
def test_registry_injects_goal_event_callback() -> None:
"""SessionService can build goal tools that emit through the event bus."""
from src.tools import build_registry
diff --git a/agent/tests/test_mcp_regression.py b/agent/tests/test_mcp_regression.py
index 00070838c..14a93c896 100644
--- a/agent/tests/test_mcp_regression.py
+++ b/agent/tests/test_mcp_regression.py
@@ -163,9 +163,10 @@ def test_mcp_server_exposes_well_known_tool_names() -> None:
"start_research_goal",
"get_research_goal",
"add_goal_evidence",
+ "update_research_goal_status",
}
missing = expected - registered
assert not missing, (
f"MCP server is missing well-known tools: {missing}. "
"A tool may have been accidentally renamed or removed."
- )
\ No newline at end of file
+ )
diff --git a/agent/tests/test_mcp_server_smoke.py b/agent/tests/test_mcp_server_smoke.py
index c2bb19fd3..ac8c0497d 100644
--- a/agent/tests/test_mcp_server_smoke.py
+++ b/agent/tests/test_mcp_server_smoke.py
@@ -51,6 +51,7 @@ REQUIRED_TOOL_NAMES = {
"start_research_goal",
"get_research_goal",
"add_goal_evidence",
+ "update_research_goal_status",
}
diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts
index 2e4247f4f..31929c6bc 100644
--- a/frontend/src/hooks/useSSE.ts
+++ b/frontend/src/hooks/useSSE.ts
@@ -82,7 +82,7 @@ export function useSSE(config?: SSEConfig) {
const knownTypes = [
"text_delta", "thinking_done", "tool_call", "tool_result", "compact",
"attempt.completed", "attempt.failed",
- "goal.created", "goal.evidence",
+ "goal.created", "goal.evidence", "goal.updated",
"heartbeat", "done",
];
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index f6252d01e..046111582 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -90,11 +90,21 @@ export const api = {
body: JSON.stringify(body),
}),
getGoal: (sid: string) => request<GoalSnapshot>(`/sessions/${sid}/goal`),
+ updateGoal: (sid: string, body: UpdateGoalRequest) =>
+ request<UpdateGoalResponse>(`/sessions/${sid}/goal`, {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ }),
addGoalEvidence: (sid: string, body: AddGoalEvidenceRequest) =>
request<AddGoalEvidenceResponse>(`/sessions/${sid}/goal/evidence`, {
method: "POST",
body: JSON.stringify(body),
}),
+ updateGoalStatus: (sid: string, body: UpdateGoalStatusRequest) =>
+ request<UpdateGoalStatusResponse>(`/sessions/${sid}/goal/status`, {
+ method: "PATCH",
+ body: JSON.stringify(body),
+ }),
sseUrl: (sid: string, options?: { replay?: "active" }) => {
let url = withAuthQuery(`${BASE}/sessions/${sid}/events`);
if (options?.replay) url = appendQueryParam(url, "replay", options.replay);
@@ -530,11 +540,43 @@ export interface AddGoalEvidenceRequest {
contradicts_claim_ids?: string[];
}
+export interface UpdateGoalRequest {
+ goal_id: string;
+ expected_goal_id: string;
+ objective?: string;
+ ui_summary?: string;
+}
+
+export interface UpdateGoalResponse {
+ goal: GoalRecord;
+ snapshot: GoalSnapshot;
+}
+
export interface AddGoalEvidenceResponse {
evidence: GoalEvidence;
snapshot: GoalSnapshot;
}
+export interface GoalAuditRowRequest {
+ criterion_id: string;
+ result: string;
+ evidence_ids?: string[];
+ notes?: string;
+}
+
+export interface UpdateGoalStatusRequest {
+ goal_id: string;
+ expected_goal_id: string;
+ status: GoalStatus;
+ audit?: GoalAuditRowRequest[];
+ recap?: string | null;
+}
+
+export interface UpdateGoalStatusResponse {
+ goal: GoalRecord;
+ snapshot: GoalSnapshot;
+}
+
// --- Alpha Zoo types ---
export interface AlphaListParams {
diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsx
index 4a6a35f88..f26654943 100644
--- a/frontend/src/pages/Agent.tsx
+++ b/frontend/src/pages/Agent.tsx
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState, useMemo, useCallback, type FormEvent } from "react";
import { useSearchParams } from "react-router-dom";
-import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users, Target, ChevronDown } from "lucide-react";
+import { Send, Loader2, ArrowDown, Square, Download, Plus, Paperclip, X, Users, Target, ChevronDown, Pencil, Check, Play } from "lucide-react";
import { toast } from "sonner";
import { useAgentStore } from "@/stores/agent";
import { useSSE } from "@/hooks/useSSE";
@@ -49,7 +49,7 @@ function getGoalProgress(snapshot: GoalSnapshot | null): {
evidenceTotal: number;
} {
const total = snapshot?.criteria.length ?? 0;
- const met = snapshot?.criteria.filter((item) => isCriterionStatusMet(item.status)).length ?? 0;
+ const met = snapshot?.criteria.filter((item) => criterionCovered(snapshot, item)).length ?? 0;
const evidenceTotal = snapshot?.evidence_count ?? 0;
return {
met,
@@ -64,6 +64,10 @@ function statusLabel(status: string): string {
return status.replace(/_/g, " ");
}
+function isTerminalGoalStatus(status: string): boolean {
+ return ["complete", "cancelled", "blocked", "superseded", "usage_limited"].includes(status);
+}
+
function criterionIndexLabel(index: number): string {
return String(index + 1);
}
@@ -72,12 +76,39 @@ function criterionEvidenceCount(snapshot: GoalSnapshot, criterionId: string): nu
return snapshot.evidence.filter((item) => item.criterion_id === criterionId).length;
}
+function criterionCovered(snapshot: GoalSnapshot, criterion: GoalSnapshot["criteria"][number]): boolean {
+ return isCriterionStatusMet(criterion.status) || criterionEvidenceCount(snapshot, criterion.criterion_id) > 0;
+}
+
function latestGoalEvidence(snapshot: GoalSnapshot) {
return [...snapshot.evidence]
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
.slice(0, 2);
}
+function goalKickoffPrompt(objective: string): string {
+ return [
+ "Start working on this research goal now.",
+ "Keep it research-only, use available tools when evidence is needed, add concrete evidence to the goal ledger, and keep going until the goal is complete, blocked, waiting for user input, or budget-limited.",
+ "",
+ `Goal: ${objective}`,
+ ].join("\n");
+}
+
+function goalContinuePrompt(snapshot: GoalSnapshot): string {
+ const openCriteria = snapshot.criteria
+ .filter((item) => item.required && !criterionCovered(snapshot, item))
+ .map((item) => `- ${item.text}`)
+ .join("\n");
+ return [
+ "Continue the active research goal.",
+ "Use real available tools as needed, add evidence to the goal ledger, and only stop when the goal is complete, blocked, waiting for user input, or budget-limited.",
+ "",
+ `Goal: ${snapshot.goal.objective}`,
+ openCriteria ? `Open criteria:\n${openCriteria}` : "All criteria appear covered; audit the ledger and update the goal status if completion is justified.",
+ ].join("\n");
+}
+
/* ---------- Component ---------- */
export function Agent() {
const [input, setInput] = useState("");
@@ -104,6 +135,8 @@ export function Agent() {
const [goalComposerActive, setGoalComposerActive] = useState(false);
const [goalDetailsOpen, setGoalDetailsOpen] = useState(false);
const [goalSnapshot, setGoalSnapshot] = useState<GoalSnapshot | null>(null);
+ const [goalEditActive, setGoalEditActive] = useState(false);
+ const [goalEditValue, setGoalEditValue] = useState("");
const messages = useAgentStore(s => s.messages);
const streamingText = useAgentStore(s => s.streamingText);
@@ -172,6 +205,7 @@ export function Agent() {
if (!targetSession) {
setGoalSnapshot(null);
setGoalDetailsOpen(false);
+ setGoalEditActive(false);
return;
}
try {
@@ -183,6 +217,7 @@ export function Agent() {
if (error instanceof ApiError && error.status === 404) {
setGoalSnapshot(null);
setGoalDetailsOpen(false);
+ setGoalEditActive(false);
} else {
toast.error(error instanceof Error ? error.message : "Failed to load goal.");
}
@@ -387,6 +422,23 @@ export function Agent() {
loadGoalSnapshot(sid);
},
+ "goal.updated": (d) => {
+ touch();
+ const snapshot = d.snapshot as GoalSnapshot | undefined;
+ const goal = (d.goal as GoalSnapshot["goal"] | undefined) ?? snapshot?.goal;
+ if (goal && isTerminalGoalStatus(goal.status)) {
+ setGoalSnapshot(null);
+ setGoalDetailsOpen(false);
+ setGoalEditActive(false);
+ return;
+ }
+ if (snapshot) {
+ setGoalSnapshot(snapshot);
+ return;
+ }
+ loadGoalSnapshot(sid);
+ },
+
heartbeat: () => {},
reconnect: (d) => { act().setSseStatus("reconnecting", Number(d.attempt ?? 0)); },
});
@@ -458,7 +510,14 @@ export function Agent() {
setGoalComposerActive(false);
setGoalDetailsOpen(true);
toast.success("Research goal attached");
+ const kickoff = goalKickoffPrompt(prompt);
+ act().addMessage({ id: "", type: "user", content: kickoff, timestamp: Date.now() });
+ act().setStatus("streaming");
+ forceScrollToBottom();
+ setupSSE(sid);
+ await api.sendMessage(sid, kickoff);
} catch (error) {
+ act().setStatus("idle");
toast.error(error instanceof Error ? error.message : "Failed to start goal.");
}
return;
@@ -529,6 +588,63 @@ export function Agent() {
}
};
+ const handleCancelGoal = useCallback(async () => {
+ if (!sessionId || !goalSnapshot) return;
+ try {
+ await api.updateGoalStatus(sessionId, {
+ goal_id: goalSnapshot.goal.goal_id,
+ expected_goal_id: goalSnapshot.goal.goal_id,
+ status: "cancelled",
+ recap: "Cancelled from Web UI.",
+ });
+ setGoalSnapshot(null);
+ setGoalDetailsOpen(false);
+ toast.success("Research goal cancelled");
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Failed to cancel goal.");
+ }
+ }, [goalSnapshot, sessionId]);
+
+ const handleStartGoalEdit = useCallback(() => {
+ if (!goalSnapshot) return;
+ setGoalEditValue(goalSnapshot.goal.objective);
+ setGoalEditActive(true);
+ }, [goalSnapshot]);
+
+ const handleSaveGoalEdit = useCallback(async () => {
+ const objective = goalEditValue.trim();
+ if (!sessionId || !goalSnapshot || !objective) return;
+ try {
+ const response = await api.updateGoal(sessionId, {
+ goal_id: goalSnapshot.goal.goal_id,
+ expected_goal_id: goalSnapshot.goal.goal_id,
+ objective,
+ });
+ setGoalSnapshot(response.snapshot);
+ setGoalEditActive(false);
+ toast.success("Research goal updated");
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Failed to update goal.");
+ }
+ }, [goalEditValue, goalSnapshot, sessionId]);
+
+ const handleContinueGoal = useCallback(async () => {
+ if (!sessionId || !goalSnapshot || status === "streaming") return;
+ const prompt = goalContinuePrompt(goalSnapshot);
+ act().addMessage({ id: "", type: "user", content: prompt, timestamp: Date.now() });
+ act().setStatus("streaming");
+ forceScrollToBottom();
+ inputRef.current?.focus();
+ try {
+ setupSSE(sessionId);
+ await api.sendMessage(sessionId, prompt);
+ } catch {
+ act().setStatus("error");
+ toast.error("Failed to continue goal, please retry.");
+ act().addMessage({ id: "", type: "error", content: "Failed to continue goal, please retry.", timestamp: Date.now() });
+ }
+ }, [forceScrollToBottom, goalSnapshot, sessionId, setupSSE, status]);
+
const handleRetry = useCallback((errorMsg: AgentMessage) => {
if (status === "streaming") return;
const msgs = act().messages;
@@ -758,6 +874,39 @@ export function Agent() {
</button>
{goalDetailsOpen && (
<div className="grid gap-3 rounded-xl border border-primary/20 bg-background/95 p-3 text-xs shadow-sm">
+ {goalEditActive ? (
+ <div className="grid gap-2">
+ <textarea
+ value={goalEditValue}
+ onChange={(event) => setGoalEditValue(event.target.value)}
+ rows={3}
+ className="w-full rounded-lg border bg-background px-3 py-2 text-xs leading-relaxed text-foreground outline-none focus:ring-2 focus:ring-primary/30"
+ />
+ <div className="flex justify-end gap-2">
+ <button
+ type="button"
+ onClick={() => setGoalEditActive(false)}
+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <X className="h-3 w-3" />
+ Cancel
+ </button>
+ <button
+ type="button"
+ onClick={handleSaveGoalEdit}
+ disabled={!goalEditValue.trim()}
+ className="inline-flex items-center gap-1 rounded-lg bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground transition-opacity disabled:opacity-40"
+ >
+ <Check className="h-3 w-3" />
+ Save
+ </button>
+ </div>
+ </div>
+ ) : (
+ <div className="rounded-lg border bg-muted/20 px-3 py-2 text-[11px] leading-relaxed text-muted-foreground">
+ {goalSnapshot.goal.objective}
+ </div>
+ )}
<div className="grid grid-cols-2 gap-2">
<div className="rounded-lg border bg-muted/20 p-2.5">
<div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
@@ -779,6 +928,9 @@ export function Agent() {
<div className="grid gap-1.5">
{goalSnapshot.criteria.map((criterion, index) => {
const evidenceCount = criterionEvidenceCount(goalSnapshot, criterion.criterion_id);
+ const displayStatus = criterionCovered(goalSnapshot, criterion) && !isCriterionStatusMet(criterion.status)
+ ? "covered"
+ : statusLabel(criterion.status);
return (
<div
key={criterion.criterion_id}
@@ -790,7 +942,7 @@ export function Agent() {
<span className="min-w-0">
<span className="block truncate font-medium text-foreground">{criterion.text}</span>
<span className="block text-[11px] text-muted-foreground">
- {statusLabel(criterion.status)}
+ {displayStatus}
</span>
</span>
<span className="rounded-full border px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
@@ -818,6 +970,34 @@ export function Agent() {
))}
</div>
)}
+ <div className="flex flex-wrap justify-end gap-2 border-t pt-2">
+ <button
+ type="button"
+ onClick={handleContinueGoal}
+ disabled={status === "streaming"}
+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"
+ >
+ <Play className="h-3 w-3" />
+ Continue
+ </button>
+ <button
+ type="button"
+ onClick={handleStartGoalEdit}
+ disabled={goalEditActive}
+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-40"
+ >
+ <Pencil className="h-3 w-3" />
+ Edit
+ </button>
+ <button
+ type="button"
+ onClick={handleCancelGoal}
+ className="inline-flex items-center gap-1 rounded-lg border px-2 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:border-destructive/40 hover:text-destructive"
+ >
+ <X className="h-3 w-3" />
+ Cancel Goal
+ </button>
+ </div>
</div>
)}
</div>