Commit Graph

386 Commits

Author SHA1 Message Date
ahmet guzererler 8efcf2a58e
Remove unused import `field` from `observability.py` (#120)
Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
2026-03-26 11:17:58 +01:00
ahmet guzererler 6b3dd4172a
feat: finalise storage layout, run history loading & phase-level re-run (#121)
* feat: introduce flow_id with timestamp-based report versioning

Replace run_id with flow_id as the primary grouping concept (one flow =
one user analysis intent spanning scan + pipeline + portfolio). Reports
are now written as {timestamp}_{name}.json so load methods always return
the latest version by lexicographic sort, eliminating the latest.json
pointer pattern for new flows.

Key changes:
- report_paths.py: add generate_flow_id(), ts_now() (ms precision),
  flow_id kwarg on all path helpers; keep run_id / pointer helpers for
  backward compatibility
- ReportStore: dual-mode save/load — flow_id uses timestamped layout,
  run_id uses legacy runs/{id}/ layout with latest.json
- MongoReportStore: add flow_id field and index; run_id stays for compat
- DualReportStore: expose flow_id property
- store_factory: accept flow_id as primary param, run_id as alias
- runs.py / langgraph_engine.py: generate and thread flow_id through all
  trigger endpoints and run methods
- Tests: add flow_id coverage for all layers; 905 tests pass

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: finalise storage layout, run history loading & phase-level re-run

Storage / persistence
- flow_id (8-char hex) replaces run_id as the disk storage key; all
  sub-phases of one auto run share the same flow_id directory
- Startup hydration: hydrate_runs_from_disk() rebuilds in-memory run
  store from run_meta.json on server restart (events lazy-loaded)

WebSocket / run history fixes
- Lazy-load events from run_events.jsonl on first WS connect; fixes
  blank terminal when clicking a historical run after restart
- Orphaned "running" runs (server restarted mid-run) auto-detected and
  marked "failed" with partial events replayed correctly

Phase re-run fixes
- Analysts checkpoint: use any() instead of all() — Social Analyst is
  optional; all() silently blocked checkpoint saves in typical runs
- Checkpoint lookup: pass original flow_id through rerun_params so
  _date_root() resolves to the correct flow_id subdirectory
- Selective event filtering on re-run: preserves scan nodes and other
  tickers; only removes stale events for the re-run phase+ticker
- Frontend graph now shows full auto-flow context during phase re-runs

Documentation
- ADR 018: canonical reference for storage layout, event schema,
  WebSocket streaming flows, checkpoint structure, MongoDB vs local
- ADR 013 updated: reflects background-task + lazy-loading evolution
- ADR 015 marked superseded by ADR 018
- CLAUDE.md: AgentOS storage section + 4 new critical patterns
- CURRENT_STATE.md updated

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 11:12:16 +01:00
ahmet guzererler 6b644c6058
Bolt: Optimize string building in yfinance_scanner.py (#114)
Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
2026-03-26 09:33:06 +01:00
ahmet guzererler 0efbbd9400
feat: load flow_id in FE to resume runs and fix max_tickers cap (#113)
* feat: introduce flow_id with timestamp-based report versioning

Replace run_id with flow_id as the primary grouping concept (one flow =
one user analysis intent spanning scan + pipeline + portfolio). Reports
are now written as {timestamp}_{name}.json so load methods always return
the latest version by lexicographic sort, eliminating the latest.json
pointer pattern for new flows.

Key changes:
- report_paths.py: add generate_flow_id(), ts_now() (ms precision),
  flow_id kwarg on all path helpers; keep run_id / pointer helpers for
  backward compatibility
- ReportStore: dual-mode save/load — flow_id uses timestamped layout,
  run_id uses legacy runs/{id}/ layout with latest.json
- MongoReportStore: add flow_id field and index; run_id stays for compat
- DualReportStore: expose flow_id property
- store_factory: accept flow_id as primary param, run_id as alias
- runs.py / langgraph_engine.py: generate and thread flow_id through all
  trigger endpoints and run methods
- Tests: add flow_id coverage for all layers; 905 tests pass

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: load flow_id in FE to resume runs and fix max_tickers cap on continuation

- Add flow_id to RunParams interface and initial state
- loadRun() now restores flow_id + max_auto_tickers from history so the next
  run continues in the same flow directory (Phase 1 scan skipped, already-done
  tickers skipped via skip-if-exists logic)
- startRun() spreads flow_id into the request body when set, letting the backend
  reuse the existing flow directory instead of generating a fresh flow_id
- After each run, params.flow_id is updated from the response so subsequent
  runs automatically continue from the same flow
- max_auto_tickers restored from run.params.max_tickers ensures the ticker cap
  matches the original run; scan_tickers[:max_t] on the backend then limits
  the Phase 2 queue to the user's setting even when the existing scan has more

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(mongo): fast-fail timeout + lazy ensure_indexes to avoid 30s block on fallback

MongoClient previously used pymongo's 30-second serverSelectionTimeoutMS default,
causing store_factory to hang for 30s before falling back to the filesystem when
Atlas is unreachable.  Also, ensure_indexes() was called eagerly in __init__,
making every store construction attempt block on a live network call.

- Set serverSelectionTimeoutMS=5_000 so fallback is triggered in ≤5s
- Move ensure_indexes() call out of __init__ — indexes are now created lazily
  on the first _save() call via a guarded self._indexes_ensured flag
- ensure_indexes() is still idempotent and safe to call explicitly in tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(store): wrap all DualReportStore mongo calls in _try_mongo() for graceful degradation

Any MongoDB exception (SSL error, ServerSelectionTimeout, auth failure) was
propagating uncaught through DualReportStore and crashing the run.  Reads
would return an error instead of falling back to local, and writes would
abort mid-run without saving anything.

Introduce a single _try_mongo(fn, default) helper that:
- Executes the Mongo callable
- Catches *any* exception, logs it as WARNING with type + message
- Returns the default value so the caller continues with local-only data

Pattern per method:
  writes  → try mongo (fire-and-forget); always return local result
  reads   → try mongo first; fall back to local on None or exception
  lists   → try mongo; fall back to local on empty/None

Runs now complete successfully even when Atlas is unreachable or returns SSL
errors.  MongoDB sync resumes automatically once connectivity is restored.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(observability): non-blocking MongoDB inserts + 5s timeout in RunLogger

Every LLM and tool callback called _append() which synchronously called
insert_one() against MongoDB.  When Atlas was unreachable this blocked the
entire LangGraph run for pymongo's 30-second default timeout per event,
effectively serializing all agent work behind MongoDB retries.

Two fixes:
1. serverSelectionTimeoutMS=5_000 on the RunLogger's MongoClient — consistent
   with the same fix applied to MongoReportStore.
2. MongoDB inserts are now fire-and-forget via daemon threads — _append() spawns
   a Thread(target=_insert, daemon=True) and returns immediately.  LLM callbacks
   and tool events are never delayed by MongoDB connectivity issues.
   Failures are still reported via WARNING log from the background thread.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* revert(observability): restore synchronous MongoDB inserts in RunLogger

Root cause was an IP whitelist issue on Atlas causing SSL failures, not
insert volume.  The background-thread approach added unnecessary complexity.
The 5s serverSelectionTimeoutMS is retained as a defensive safeguard.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 07:10:42 +01:00
Ahmet Guzererler c3762c0499 Reapply "feat: enhance data persistence with DualReportStore for local and MongoDB storage; update report store creation logic"
This reverts commit 9358b7edc8.
2026-03-25 19:54:34 +01:00
Ahmet Guzererler 9358b7edc8 Revert "feat: enhance data persistence with DualReportStore for local and MongoDB storage; update report store creation logic"
This reverts commit 5f0a52f8e6.
2026-03-25 19:44:01 +01:00
Ahmet Guzererler 5f0a52f8e6 feat: enhance data persistence with DualReportStore for local and MongoDB storage; update report store creation logic 2026-03-25 19:04:36 +01:00
ahmet guzererler 7c02e0c76c
feat: add launch configuration for Backend (FastAPI) and Frontend (Vite/React) (#112) 2026-03-25 16:19:19 +01:00
ahmet guzererler 1501c04dae
feat: add launch configuration for FastAPI and Vite; enhance Finviz filter validation tests (#111) 2026-03-25 16:18:54 +01:00
Ahmet Guzererler b87925d0b0 feat: add launch configuration for FastAPI and Vite in .claude/launch.json; include VSCode settings for pytest 2026-03-25 16:17:45 +01:00
ahmet guzererler d883731212
feat: add launch configuration for FastAPI and Vite; enhance Finviz filter validation tests (#110) 2026-03-25 15:50:49 +01:00
ahmet guzererler 97a0d0de53
feat: configurable max_auto_tickers + run persistence with phase-level node re-run (#109)
Feature 1 - Configurable max_auto_tickers:
- Add max_auto_tickers config key (default 10) with TRADINGAGENTS_MAX_AUTO_TICKERS env override
- Macro synthesis agent accepts max_scan_tickers param, injects exact count into LLM prompt
- ScannerGraph passes config value to create_macro_synthesis()
- Backend engine applies safety cap on scan candidates (portfolio holdings always included)
- Frontend adds Max Tickers number input in params panel, sends max_tickers in auto run body

Feature 2 - Run persistence + phase-level node re-run:
- 2A: ReportStore + MongoReportStore gain save/load_run_meta, save/load_run_events,
  list_run_metas methods; runs.py persists to disk in finally block; startup hydration
  restores historical runs; lazy event loading on GET /{run_id}
- 2B: Analysts + trader checkpoint save/load methods in both stores; engine saves
  checkpoints after pipeline completion alongside complete_report.json
- 2C: GraphSetup gains build_debate_subgraph() and build_risk_subgraph() for partial
  re-runs; TradingAgentsGraph exposes debate_graph/risk_graph as lazy properties;
  NODE_TO_PHASE mapping + run_pipeline_from_phase() engine method;
  POST /api/run/rerun-node endpoint with _append_and_store helper
- 2D: Frontend history popover (loads GET /api/run/, sorts by created_at, click to load);
  triggerNodeRerun() calls rerun-node endpoint; handleNodeRerun uses phase-level
  re-run when active run is loaded

All 890 existing tests pass (10 skipped).

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 15:27:28 +01:00
ahmet guzererler 2145b04318
fix: graceful LLM 404 handling + per-tier fallback model config (#108)
* fix: per-tier fallback LLM for provider 404/policy errors

- tool_runner: catch status_code==404 from chain.invoke(), re-raise as
  RuntimeError with actionable message (OpenRouter privacy URL + env var hint)
- langgraph_engine: wrap astream_events in try/except, detect policy errors
  and re-raise with model/provider context
- langgraph_engine: _run_one_ticker distinguishes policy 404s (logger.error,
  no traceback) from real bugs (logger.exception with traceback); if fallback
  is configured, rebuilds pipeline with fallback model tier and retries
- langgraph_engine: add _is_policy_error() and _build_fallback_config() helpers
- default_config: add quick/mid/deep_think_fallback_llm + _provider keys
  (TRADINGAGENTS_QUICK_THINK_FALLBACK_LLM etc.)
- .env.example: document new fallback env vars

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: ADR 017 LLM policy fallback, correct ADR 016 findings, update CLAUDE.md

- docs/agent/decisions/017: add ADR for per-tier LLM fallback design decision
- docs/agent/decisions/016: correct 3 inaccurate review findings — list_pm_decisions
  ObjectId projection, created_at datetime type, and base_dir pointer handling are
  all already correctly implemented in PR#106
- CLAUDE.md: add Per-Tier Fallback LLM section and _is_policy_error critical pattern
- CURRENT_STATE.md: update milestone and recent progress for PR#106/107/108 merges

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 11:19:08 +01:00
Copilot 9c9cc8c0b6
fix: address all PR#106 review findings (ADR 016) (#106)
* Initial plan

* feat: add observability logging - run event persistence and enriched tool events

- Integrate RunLogger into LangGraphEngine for JSONL event persistence
- Add _start_run_logger/_finish_run_logger lifecycle in all run methods
- Enrich tool events with service, status, and error fields
- Add _TOOL_SERVICE_MAP for tool-to-service name resolution
- Frontend: color error events in red, show service badges
- Frontend: display graceful_skip status with orange indicators
- Frontend: add error tab and service info to EventDetail/EventDetailModal
- Add 11 unit tests for new observability features

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/477a0676-af7b-48ff-8a3d-567e943323cf

* refactor: address code review - extract graceful keywords constant, fix imports

- Move get_daily_dir import to top-level (remove inline aliases)
- Extract _GRACEFUL_SKIP_KEYWORDS as module-level constant
- Update test patches to match top-level import location

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/477a0676-af7b-48ff-8a3d-567e943323cf

* feat: add run_id to report paths, MongoDB report store, store factory, and reflexion memory

- report_paths.py: All path helpers accept optional run_id for run-scoped dirs
- report_store.py: ReportStore supports run_id + latest.json pointer mechanism
- mongo_report_store.py: MongoDB-backed store with same interface (no overwrites)
- store_factory.py: Factory returns MongoDB or filesystem store based on config
- memory/reflexion.py: Reflexion memory for learning from past decisions
- langgraph_engine.py: Uses store factory + run_id for all run methods
- Fix save_holding_reviews bug (was save_holding_reviews, now save_holding_review)
- default_config.py: Add mongo_uri and mongo_db config keys
- pyproject.toml: Add pymongo>=4.12.1 dependency
- .env.example: Document TRADINGAGENTS_MONGO_URI and TRADINGAGENTS_MONGO_DB

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/16e673ea-40a1-40a0-8e77-f8cd08c1a716

* fix: clean up reflexion record_outcome (remove broken update_one with sort)

Also update runs.py reset endpoint to use store factory, fix tests,
add ADR 015, update CURRENT_STATE.md

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/16e673ea-40a1-40a0-8e77-f8cd08c1a716

* fix: address all PR#106 review findings (ADR 016)

- Fix save_holding_review: iterate per-ticker instead of passing
  portfolio_id as ticker (Finding 13)
- Fix RunLogger context: replace threading.local with contextvars
  for asyncio task isolation (Finding 3)
- Fix list_pm_decisions: add _id:0 projection to exclude ObjectId (Finding 6)
- Fix ReflexionMemory: native datetime for MongoDB, ISO string for
  local JSON fallback (Finding 7)
- Fix latest pointer: write/read_latest_pointer accept base_dir
  parameter, ReportStore passes _base_dir (Finding 12)
- Wire RunLogger callback into all astream_events calls (Finding 1)
- Call ensure_indexes in MongoReportStore.__init__ (Finding 11)
- Create ADR 016 documenting all 13 findings and resolutions
- Add 14 targeted tests covering all 7 fixes
- All 886 tests pass (872 existing + 14 new)

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/e52cdd2f-efae-4d2a-a56f-903d909b3342

* chore: remove unused imports in tests, remove redundant ensure_indexes call in factory

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/e52cdd2f-efae-4d2a-a56f-903d909b3342

* docs: update ADR 016 — mark Finding 2 resolved, update context docs for contextvars

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/ce9e2400-a60d-4a6b-896b-1b34ec786bed

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
2026-03-25 11:14:23 +01:00
ahmet guzererler b1a775882e
fix: Replace unsafe `ast.literal_eval` with `extract_json` in `parse_tool_call` (#105)
Remove the potential DoS and code-execution vulnerability by replacing `ast.literal_eval(tool_call)` with `json.loads` and `extract_json` in `cli/main.py`. Ensures strict JSON parsing without breaking tests or relying on unsafe structures.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
2026-03-25 10:17:28 +01:00
Ahmet Guzererler c39dcc6fe8 fix(supabase_client): enhance cursor method to reconnect on dropped connection 2026-03-25 01:03:10 +01:00
Copilot fdf54ae279
feat: include portfolio holdings in auto mode pipeline analysis (#104)
* Initial plan

* feat: include portfolio holdings in auto mode pipeline analysis

In run_auto (both AgentOS and CLI), Phase 2 now loads current portfolio
holdings and merges their tickers with scan candidates before running
the per-ticker pipeline. This ensures the portfolio manager has fresh
analysis for both new opportunities and existing positions.

Key changes:
- macro_bridge.py: add candidates_from_holdings() factory
- langgraph_engine.py run_auto: merge holding tickers with scan tickers
- cli/main.py auto: load holdings, create StockCandidates, pass to run_pipeline
- cli/main.py run_pipeline: accept optional holdings_candidates parameter
- 9 new unit tests covering holdings inclusion, dedup, and graceful fallback

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/53065a07-d9f8-47be-9956-0eb4ee8c87da

* fix: normalize ticker case in dedup and clarify count display

Address code review feedback:
- Use .upper() for case-insensitive ticker comparison in run_pipeline
- Display accurate filtered scan count instead of raw candidate count

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/53065a07-d9f8-47be-9956-0eb4ee8c87da

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
2026-03-24 18:35:53 +01:00
Copilot cd655cdae5
feat: concurrent per-ticker pipelines in auto mode, controlled by TRADINGAGENTS_MAX_CONCURRENT_PIPELINES (#103)
* Initial plan

* feat: concurrent per-ticker pipelines in auto mode, configurable via TRADINGAGENTS_MAX_CONCURRENT_PIPELINES

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/464f2038-3a60-4d86-9fe8-4e1cc6943174

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Co-authored-by: ahmet guzererler <guzererler@gmail.com>
2026-03-24 18:08:06 +01:00
Copilot 9c148b208a
Fix: websocket emits "Run completed." on failed runs, masking errors in frontend (#102)
* Initial plan

* Fix websocket sending "Run completed." on failed runs, masking errors from frontend

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/608ea02c-ca85-4f05-9ce1-611802493d7b

* Fix 5 failing unit tests (truthy MagicMock skips) + expose ticker_analyses in state + add Finviz live integration tests

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/7872ceae-cade-4563-aedb-34660d419a36

* docs: update testing.md with MagicMock explainer, current test counts, full catalogue, and detailed run commands

Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/13639e60-cb9b-4cb0-891c-df5d448c158d

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
2026-03-24 18:06:48 +01:00
ahmet guzererler 4c14080d73
feat(scanner): Finviz smart money scanner + Golden Overlap strategy
## Summary
- Adds `smart_money_scanner` as a new Phase 1b node that runs sequentially after `sector_scanner`, surfacing institutional footprints via Finviz screeners
- Introduces the **Golden Overlap** strategy in `macro_synthesis`: stocks confirmed by both top-down macro themes and bottom-up Finviz signals are labelled high-conviction
- Fixes model-name badge overflow in AgentGraph (long model IDs like OpenRouter paths were visually spilling into adjacent nodes)
- Completes all documentation: ADR-014, dataflow, architecture, components, glossary, current-state

## Key Decisions (see ADR-014)
- 3 zero-parameter tools (`get_insider_buying_stocks`, `get_unusual_volume_stocks`, `get_breakout_accumulation_stocks`) instead of 1 parameterised tool — prevents LLM hallucinations on string args
- Sequential after `sector_scanner` (not parallel fan-out) — gives access to `sector_performance_report` context and avoids `MAX_TOOL_ROUNDS=5` truncation in market_movers_scanner
- Graceful fallback: `_run_finviz_screen()` catches all exceptions and returns an error string — pipeline never hard-fails on web-scraper failure
- `breakout_accumulation` (52-wk high + 2x vol = O'Neil CAN SLIM institutional signal) replaces `oversold_bounces` (RSI<30 = retail contrarian, not smart money)

## Test Plan
- [x] 6 new mocked tests in `tests/unit/test_scanner_mocked.py` (happy path, empty DF, exception, sort order)
- [x] Fixed `tests/unit/test_scanner_graph.py` — added `smart_money_scanner` mock to compilation test
- [x] 2 pre-existing test failures excluded (verified baseline before changes)
- [x] AgentGraph badge: visually verified truncation with long OpenRouter model identifiers

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-03-24 16:03:17 +01:00
Ahmet Guzererler 6adf12eee6 packages 2026-03-24 10:14:11 +01:00
ahmet guzererler 5d5bd4a3cb
feat(ui): scoped graph nodes per ticker + MockEngine for LLM-free UI testing (#100)
* feat(ui): scoped graph nodes per ticker + MockEngine for LLM-free UI testing

## Summary
Adds a MockEngine that streams scripted agent events with zero real LLM calls,
enabling full UI testing (graph, terminal, drawer, metrics) without API keys or
network. Also fixes the ReactFlow graph so that each ticker/identifier gets its
own visual node — previously an auto run with 5 tickers collapsed all pipelines
into the same node IDs, overwriting each other.

## Changes
- **MockEngine** (`agent_os/backend/services/mock_engine.py`): new class that
  generates realistic scripted events for pipeline, scan, and auto run types.
  Supports configurable speed divisor (1× realistic → 10× instant). Auto mock
  accepts a `tickers` list for multi-ticker runs.
- **POST /api/run/mock** (`runs.py`): new endpoint wiring MockEngine into the
  BackgroundTasks + store pattern identical to real run endpoints.
- **WebSocket routing** (`websocket.py`): added `mock` run-type branch so the
  WS executor path also dispatches to MockEngine when the background task hasn't
  started yet.
- **LangGraphEngine** (`langgraph_engine.py`): added `_run_identifiers` dict to
  track ticker/MARKET/portfolio_id per run; all emitted events now carry an
  `identifier` field so the frontend can scope them.
- **AgentGraph.tsx**: ReactFlow nodes now keyed by `node_id:identifier` (e.g.
  `news_analyst:AAPL`, `news_analyst:NVDA`). Edges scoped to same identifier.
  `onNodeClick` passes raw `node_id` + `identifier` separately so the event
  drawer can filter without parsing the scoped key.
- **Dashboard.tsx**: Mock button + type/speed controls added. `openNodeDetail`
  accepts identifier; `NodeEventsDetail` filters by both `node_id` and
  `identifier`. Comma-separated ticker input for mock auto runs (e.g.
  `AAPL,NVDA,TSLA`).
- **useAgentStream.ts**: `AgentEvent` interface extended with `identifier?`
  field.

## Decision Context
- Scoped node ID format chosen as `node_id:identifier` (colon separator) rather
  than embedding identifier in the agent display name — keeps node labels clean
  and identifier visible as a coloured badge, not label text.
- Raw `node_id` and `identifier` stored separately in `node.data` so the drawer
  filtering (`events.filter(e => e.node_id === nodeId && e.identifier === id)`)
  does not need to parse/split the scoped key.
- Parent edges are scoped to the same identifier as the child, assuming intra-
  ticker chains. Cross-run topology edges (e.g. scan → pipeline) are implicit
  via log events, not ReactFlow edges.
- MockEngine uses `asyncio.sleep` with a speed divisor — higher speed values
  give faster replays for rapid iteration during UI development.

## Considerations for Future Agents
- Re-run button on graph nodes already uses `identifier` to dispatch
  `startRun('pipeline', { ticker: identifier })` or `startRun('scan')` — no
  further changes needed for per-node re-runs to be correctly scoped.
- The `_run_identifiers` dict in LangGraphEngine is keyed by `run_id`; it is
  cleaned up after each run. If parallel runs are ever supported per engine
  instance, this dict handles them correctly already.
- For run_auto, each sub-run (scan, per-ticker pipeline) calls its own
  `run_scan`/`run_pipeline` which sets `_run_identifiers[run_id]`. The outer
  `run_auto` does not set it — this is intentional.
- `uv.lock` changes reflect dependency tree after Chainlit removal in the
  previous commit; no new runtime dependencies were added by this PR.

---
🤖 Commit Agent | Session: mock-engine + scoped-graph-nodes

* feat(graph): two-phase column layout — scan top, ticker columns below

## Summary
Redesigns the ReactFlow graph layout engine so scan nodes form a centred funnel
at the top and each ticker gets its own vertical column below, matching the
agreed design. Ticker header cards (bold ticker symbol + pulse dot + progress
counter) act as column anchors; agent cards stack beneath each one. Fan-out
dashed edges connect macro_synthesis → each ticker header.

## Changes
- SCAN phase: geopolitical/market-movers/sector scanners placed on the same
  horizontal row at x = [0, COL_WIDTH, 2×COL_WIDTH] (aligns with first 3
  ticker columns); industry_deep_dive and macro_synthesis centered below.
- TICKER columns: new identifiers get a TickerHeaderNode at tickerStartY;
  agent nodes stack beneath using column-based parent tracking
  (header → agent0 → agent1 → …) independent of evt.parent_node_id.
- TickerHeaderNode: wide card, bold ticker symbol, animated pulse status dot,
  completedCount/agentCount counter updated live as results arrive.
- Tool nodes (node_id starts with "tool_") skipped from graph — visible in
  terminal/drawer, not cluttering the column layout.
- Portfolio nodes centred below all ticker columns.
- Layout state extracted into LayoutState ref + freshLayout() for clean resets.
- Node labels use toLabel() (snake_case → Title Case).
- Metrics row shows total tokens (in+out) instead of just latency.

## Decision Context
- Column-based parent edges chosen over evt.parent_node_id because mock engine
  emits parent_node_id="start" for all agents; column ordering is reliable.
- Scan phase X positions reuse COL_WIDTH so phase-1 scanners visually align
  above first three ticker columns — no arbitrary magic numbers.
- Tool nodes removed from graph (not hidden) — they add noise to column layout
  with no actionable meaning; the drawer already shows them per node.

## Considerations for Future Agents
- identifierLastNode tracks scoped ID of previous agent per ticker column —
  used for sequential edge chaining; do not remove without replacing edge logic.
- tickerStartY is set once on first ticker arrival; subsequent tickers share
  the same Y baseline — only colCount and identifierAgentRow differ per ticker.
- TickerHeaderNode clicks pass node_id='header' + identifier to onNodeClick;
  Dashboard NodeEventsDetail filters all events by identifier when node_id is
  'header' (shows the full ticker run timeline in the drawer).

---
🤖 Commit Agent | Session: two-phase column graph layout
2026-03-24 10:03:16 +01:00
ahmet guzererler 321cc80434
Merge pull request #99 from aguzererler/feature/portfolio-resumability-and-cleanup
feat: Add portfolio resumability, extend report saving, and gitignore uv.lock
2026-03-24 03:32:21 +01:00
ahmet guzererler 2a05e4b5a9
Merge branch 'main' into feature/portfolio-resumability-and-cleanup 2026-03-24 03:32:09 +01:00
Ahmet Guzererler c22b601f6c refactor: Remove Chainlit and several other unused dependencies, updating the lock file and related agent configurations. 2026-03-24 01:13:15 +01:00
ahmet guzererler 73cb317120
Merge pull request #98 from aguzererler/copilot/add-trades-with-stop-loss
Add stop_loss and take_profit to BUY trade records
2026-03-24 01:11:37 +01:00
ahmet guzererler 383b414698
Merge pull request #97 from aguzererler/copilot/optimize-llm-round-trips
Parallel pre-fetch for analyst agents to reduce LLM round-trips
2026-03-24 01:11:19 +01:00
Ahmet Guzererler 860968835c feat: add Reset Decision button to clear portfolio stage and re-run
- ReportStore.clear_portfolio_stage(date, portfolio_id): deletes pm_decision
  (.json + .md) and execution_result files for a given date/portfolio
- DELETE /api/run/portfolio-stage endpoint: calls clear_portfolio_stage
  and returns list of deleted files
- Dashboard: 'Reset Decision' button calls the endpoint, then user can
  run Auto to re-run Phase 3 from scratch while skipping Phase 1 & 2

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 00:34:53 +01:00
Ahmet Guzererler 2a17ea0cca feat: add Force re-run checkbox to dashboard params
Adds a 'Force re-run' checkbox that passes force=True to the backend,
bypassing all date-based skip checks (scan, pipeline, portfolio, execution).

Also fixes auto run: ticker is not required (scan discovers tickers),
portfolio_id is the correct required field instead.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 00:31:16 +01:00
Ahmet Guzererler 80a54b2411 fix: fetch live prices from yfinance when none available for trade execution
The scan summary never contained a 'prices' key, so trade execution always
ran with an empty prices dict. Now prices are fetched via yfinance:

- run_trade_execution: fetches prices for all tickers in the PM decision
  (sells/buys/holds) when prices arg is empty
- run_auto resume path: fetches prices for decision tickers instead of
  reading from scan data
- run_portfolio: fetches prices for current holdings + scan candidates
  before invoking the portfolio graph

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 00:25:51 +01:00
Ahmet Guzererler 56c5bea1ae feat: make reports root directory configurable via env var
TRADINGAGENTS_REPORTS_DIR now controls where all reports land (scans,
analysis, portfolio artifacts). Both report_paths.REPORTS_ROOT and
ReportStore.data_dir read from the same env var so the entire
reports/daily/{date}/... tree is rooted at one configurable location.

PORTFOLIO_DATA_DIR still works as a portfolio-specific override.
Falls back to "reports" (relative to CWD) when neither is set.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 00:15:04 +01:00
Ahmet Guzererler 0951ef17ec fix: resolve KeyError 'data_dir' when running trade execution
PortfolioRepository expects its own portfolio config (with data_dir),
not DEFAULT_CONFIG. Passing config=self.config caused a KeyError because
DEFAULT_CONFIG has no data_dir key. Removing the argument lets the
repository call get_portfolio_config() which provides the correct defaults.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 00:11:07 +01:00
ahmet guzererler 8461ed540e Fix all review issues 2026-03-23 23:58:51 +01:00
Ahmet Guzererler 57f1d561f9 feat: Add portfolio resumability, extend report saving, and gitignore uv.lock
- Extend run_portfolio to save Holding Reviews, Risk Metrics, PM Decision,
  and Execution Result from final state
- Add run_trade_execution method for resuming trade execution from a saved
  PM decision without re-running the full portfolio graph
- Update run_auto skip logic to check for execution result (not just decision)
  and resume from saved decision when available
- Gitignore uv.lock and untrack it from version control

Co-Authored-By: Oz <oz-agent@warp.dev>
2026-03-23 23:44:34 +01:00
Ahmet Guzererler c2b14dda35 refactor: Remove Chainlit and several other unused dependencies, updating the lock file and related agent configurations. 2026-03-23 23:07:45 +01:00
copilot-swe-agent[bot] 8e48bb4906 Add stop_loss and take_profit fields to Trade entries in database, API, and UI
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/3b6a6fcc-30ac-48fa-970f-995a3bed80ed
2026-03-23 21:12:01 +00:00
copilot-swe-agent[bot] 9c014a8038 Parallel pre-fetch for analyst agents to reduce LLM round-trips
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/a8c6b73e-9694-4e34-8767-36e475deb12f
2026-03-23 21:08:15 +00:00
copilot-swe-agent[bot] 8567f08b91 Initial plan 2026-03-23 21:02:05 +00:00
copilot-swe-agent[bot] 2c3efd0f87 Initial plan 2026-03-23 20:56:33 +00:00
ahmet guzererler e568cec68c
Merge pull request #96 from aguzererler/copilot/fix-report-saving-in-runs
Copilot/fix report saving in runs
2026-03-23 21:10:48 +01:00
ahmet guzererler aa4e9395bf
Merge pull request #95 from aguzererler/copilot/add-tests-for-langgraph-engine
Add unit tests for LangGraphEngine run modes (run_scan, run_pipeline, run_portfolio, run_auto)
2026-03-23 21:09:34 +01:00
ahmet guzererler 1c7de894ff
Merge pull request #94 from aguzererler/copilot/fix-langgraph-bug-reporting
Fix LangGraphEngine: final_state capture fallback, portfolio state shape, JSON serialization
2026-03-23 21:09:15 +01:00
ahmet guzererler b7d44f32b6
Merge pull request #93 from aguzererler/copilot/fix-json-serialization-error
Fix TypeError: LangChain message objects not JSON-serializable in ReportStore
2026-03-23 21:08:52 +01:00
copilot-swe-agent[bot] 69a2d72e60 Add tests for LangGraphEngine run modes (run_scan, run_pipeline, run_portfolio, run_auto)
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/ba209f7b-e985-42bb-bdce-95e73bc67bfc
2026-03-23 20:06:27 +00:00
copilot-swe-agent[bot] c0d13b9207 Fix langgraph engine: fallback ainvoke, portfolio state shape, JSON serialization
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/43d04354-154a-442c-8bfc-ede05860e7f9
2026-03-23 19:57:35 +00:00
copilot-swe-agent[bot] 73e5527afa Initial plan 2026-03-23 19:56:18 +00:00
copilot-swe-agent[bot] 90c49dc1f4 Initial plan 2026-03-23 19:50:13 +00:00
copilot-swe-agent[bot] 981cf7f1b1 Fix JSON serialization of LangChain message objects in ReportStore
Co-authored-by: aguzererler <6199053+aguzererler@users.noreply.github.com>
Agent-Logs-Url: https://github.com/aguzererler/TradingAgents/sessions/bed5160f-805a-417e-b563-461e8bfca683
2026-03-23 19:37:41 +00:00
copilot-swe-agent[bot] 9956420717 Initial plan 2026-03-23 19:32:42 +00:00
ahmet guzererler 36a6b17a22
Merge pull request #92 from aguzererler/copilot/fix-report-saving-in-runs
Fix report persistence, run status tracking, auto-mode stock sourcing, and portfolio context loading
2026-03-23 19:55:42 +01:00