File size: 14,887 Bytes
1a72409
 
e2224c5
64f6c66
1a72409
fbd3600
 
e2224c5
 
1a72409
 
 
e2224c5
fbd3600
 
 
 
 
 
1a72409
 
 
 
 
64f6c66
 
1a72409
 
 
 
 
e2224c5
 
61f1bb5
1a72409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748cf22
 
1a72409
 
 
 
 
748cf22
 
 
1a72409
d859d38
 
 
 
 
30cc2cc
d859d38
 
 
 
 
 
 
30cc2cc
 
 
d859d38
1a72409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64f6c66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2224c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b051f02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a72409
 
 
 
 
 
 
61f1bb5
 
 
 
 
fbd3600
 
61f1bb5
fbd3600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2224c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64f6c66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b051f02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a72409
748cf22
1a72409
 
 
 
 
 
748cf22
 
 
1a72409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
748cf22
1a72409
 
 
 
 
 
748cf22
 
 
1a72409
 
d859d38
30cc2cc
d859d38
 
 
 
 
 
 
 
30cc2cc
 
 
 
d859d38
 
1a72409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
from __future__ import annotations

import asyncio
from datetime import date
from pathlib import Path
import sys
import types
from types import SimpleNamespace
from typing import Any

import pytest

from polyhedra.agents.base import Agent, AgentResponse, Mention

sentence_transformers_stub = types.ModuleType("sentence_transformers")
sentence_transformers_stub.SentenceTransformer = object
sys.modules.setdefault("sentence_transformers", sentence_transformers_stub)

from polyhedra.agents.coordinator import CoordinatorService
from polyhedra.agents.quant import (
    EventRouter,
    MacroContextWatcher,
    MarketEventWatcher,
    OptionsFlowWatcher,
    QuantStrategistAgent,
    RiskAnalystAgent,
    SPYAnalyst,
    TrendAnalystAgent,
    UnusualEventDetector,
)
from polyhedra.agents.quant.market_scope import split_v5_v6_markets
from polyhedra.core.role_registry import RoleEntry
from polyhedra.core.session import SessionManager
from polyhedra.messaging.slack import SlackIntegration, _extract_tickers_from_text
from polyhedra.services.file_writer import FileWriter


class _FakeClient:
    def __init__(self) -> None:
        self.messages: list[str] = []

    async def chat_postMessage(self, channel: str, text: str = "", **_: object) -> dict[str, str]:
        self.messages.append(text)
        return {"ts": str(len(self.messages))}


class _FakeService:
    def __init__(self, session_dir: Path) -> None:
        self.dispatched: list[str] = []
        self.runs: list[list[str]] = []
        self._mode = "investigation"
        self.session = SimpleNamespace(session_dir=session_dir)

    async def dispatch(self, from_role: str, text: str) -> None:
        self.dispatched.append(text)

    async def run_yolo(self, tickers: list[str]):
        self.runs.append(tickers)


class _FakeYoloService(_FakeService):
    def __init__(self, session_dir: Path) -> None:
        super().__init__(session_dir)
        self.session.goal = "YOLO & SPY Analysis Session"
        self.prepared: list[list[str]] = []
        self.runs: list[list[str]] = []
        self._mode = "investigation"
        self._yolo_update_fn = None

    def prepare_yolo_run(self, tickers: list[str]):
        self.prepared.append(tickers)
        return SimpleNamespace(label="Session-delta YOLO", run_mode="session_delta")

    async def run_yolo(self, tickers: list[str]):
        self.runs.append(tickers)


class _FakeLLM:
    async def complete(self, prompt: str, model: str | None = None):
        if "UnusualEventDetector" in prompt:
            return ("SPY PRICE_EVENT significance 0.55. Monitor confirmation.", 10, 10)
        if "MacroContextWatcher" in prompt:
            return ("Main line: equity risk appetite. SPY relevance weight 0.7.", 10, 10)
        return (
            "SPY specialized read: WATCH_FOR_CONFIRMATION. "
            "Confirmation: reclaim VWAP. Invalidation: lose prior low.\n"
            "Paper trading simulation only. Not financial advice.",
            10,
            10,
        )


class _RoutingLLM:
    async def complete(self, prompt: str, model: str | None = None):
        return (
            "## SPY\nTechnical analysis complete.\n"
            '{"next": "sentimentanalyst", "reason": "normal V5 next step"}',
            10,
            10,
        )


class _HumanRoutingRiskLLM:
    async def complete(self, prompt: str, model: str | None = None):
        return (
            "Risk report: all signals are Reject due to poor validation.\n"
            '{"next": "human", "reason": "All signals rejected; human review needed."}',
            10,
            10,
        )


class _NoTradeStrategyLLM:
    async def complete(self, prompt: str, model: str | None = None):
        return (
            "No paper trade proposal passed risk review.\n\n"
            "Outcome: NO_TRADE. Watch for a reclaim of SPY 768 with volume "
            "or a clean break below 762 before rerunning.\n"
            '{"next": "publisher", "reason": "Strategy review ready for Finley."}\n'
            '{"proposals": []}',
            10,
            10,
        )


class _UnavailableTrendAgent(Agent):
    name = "TrendAnalyst"
    role = "trendanalyst"
    role_title = "Technical Analyst"
    system_prompt = ""

    async def handle(
        self,
        mention: Mention,
        thread_context: list[dict[str, Any]],
        research_state: dict[str, Any],
    ) -> AgentResponse:
        return AgentResponse(
            agent_role=self.role,
            content="Technical analysis could not be completed (LLM unavailable).",
            mentions=["sentimentanalyst"],
        )

    async def can_handle(self, mention: Mention) -> bool:
        return mention.mentioned_role == self.role


class _HumanRoutingBacktesterAgent(Agent):
    name = "Backtester"
    role = "backtester"
    role_title = "Backtester"
    system_prompt = ""

    async def handle(
        self,
        mention: Mention,
        thread_context: list[dict[str, Any]],
        research_state: dict[str, Any],
    ) -> AgentResponse:
        return AgentResponse(
            agent_role=self.role,
            content="Backtest complete. Human review is needed.",
            mentions=["human"],
        )

    async def can_handle(self, mention: Mention) -> bool:
        return mention.mentioned_role == self.role


class _RecordingRiskAgent(Agent):
    name = "RiskAnalyst"
    role = "riskanalyst"
    role_title = "Risk Analyst"
    system_prompt = ""

    async def handle(
        self,
        mention: Mention,
        thread_context: list[dict[str, Any]],
        research_state: dict[str, Any],
    ) -> AgentResponse:
        return AgentResponse(agent_role=self.role, content="RiskAnalyst ran after backtest.")

    async def can_handle(self, mention: Mention) -> bool:
        return mention.mentioned_role == self.role


def test_split_v5_v6_markets() -> None:
    assert split_v5_v6_markets(["SPY", "AAPL", "BTC", "SPY"]) == (
        ["AAPL"],
        ["SPY", "BTC"],
    )


def test_yolo_is_not_extracted_as_ticker() -> None:
    assert _extract_tickers_from_text("YOLO SPY") == ["SPY"]
    assert _extract_tickers_from_text("run yolo QQQ") == ["QQQ"]


def test_yolo_status_shows_v6_planned_path_for_v6_goal() -> None:
    service = CoordinatorService.__new__(CoordinatorService)
    service.session = SimpleNamespace(goal="YOLO & SPY Analysis Session")
    service._yolo_completed = ["datafetcher"]

    status = service._build_yolo_status("datafetcher", done=True)

    assert "V6 specialized quant path" in status
    assert "DataFetcher" in status
    assert "TrendAnalyst" in status
    assert "MarketEventWatcher" in status
    assert "OptionsFlowWatcher" in status
    assert "MacroContextWatcher" in status
    assert "UnusualEventDetector" in status
    assert "EventRouter" in status
    assert "SPYAnalyst" in status
    assert "SentimentAnalyst" not in status


@pytest.mark.asyncio
async def test_yolo_blocks_llm_unavailable_agent_output(tmp_path: Path) -> None:
    manager = SessionManager(sessions_dir=tmp_path)
    session = manager.create(goal="YOLO & SPY Analysis Session", platform="web")
    session.registry.register(RoleEntry(role="trendanalyst", agent=_UnavailableTrendAgent()))
    posts: list[tuple[str, str]] = []

    async def post_fn(role: str, content: str) -> None:
        posts.append((role, content))

    async def checkpoint_fn(summary: str) -> None:
        raise AssertionError("YOLO LLM-unavailable guard must not request checkpoints")

    service = CoordinatorService(
        session=session,
        post_fn=post_fn,
        checkpoint_fn=checkpoint_fn,
        mode="yolo",
    )

    await service.dispatch("human", "@trendanalyst SPY")
    await asyncio.sleep(0)

    assert any("LLM service is unavailable" in content for _, content in posts)
    assert not any(message.from_role == "sentimentanalyst" for message in session.full_thread())


@pytest.mark.asyncio
async def test_risk_routes_rejected_v6_assessment_to_quantstrategist(tmp_path: Path) -> None:
    files = FileWriter(tmp_path)
    today = date.today().isoformat()
    quant_dir = tmp_path / "quant"
    quant_dir.mkdir()
    (quant_dir / f"backtest_results_{today}.md").write_text(
        "All candidate signals failed validation.",
        encoding="utf-8",
    )

    agent = RiskAnalystAgent(llm_service=_HumanRoutingRiskLLM())
    agent.files = files
    response = await agent.handle(
        Mention("riskanalyst", "backtester", "continue"),
        [],
        {"quant_state": {"watchlist": ["SPY"], "portfolio": []}},
    )

    assert response.mentions == ["quantstrategist"]
    assert "all signals are Reject" in response.content


@pytest.mark.asyncio
async def test_quantstrategist_allows_zero_trade_proposals(tmp_path: Path) -> None:
    files = FileWriter(tmp_path)
    today = date.today().isoformat()
    quant_dir = tmp_path / "quant"
    quant_dir.mkdir()
    (quant_dir / f"risk_assessment_{today}.md").write_text(
        "All signals are Reject.",
        encoding="utf-8",
    )
    (quant_dir / f"backtest_results_{today}.md").write_text(
        "No signal has enough valid evidence.",
        encoding="utf-8",
    )

    agent = QuantStrategistAgent(llm_service=_NoTradeStrategyLLM())
    agent.files = files
    response = await agent.handle(
        Mention("quantstrategist", "riskanalyst", "continue"),
        [],
        {"quant_state": {"watchlist": ["SPY"], "portfolio": []}},
    )

    assert response.mentions == ["publisher"]
    assert "Strategy review ready" in response.content
    assert "NO_TRADE" in response.content
    assert response.state_patch == {}


@pytest.mark.asyncio
async def test_yolo_converts_upstream_human_route_to_next_planned_agent(tmp_path: Path) -> None:
    manager = SessionManager(sessions_dir=tmp_path)
    session = manager.create(goal="YOLO & SPY Analysis Session", platform="web")
    session.registry.register(RoleEntry(role="backtester", agent=_HumanRoutingBacktesterAgent()))
    session.registry.register(RoleEntry(role="riskanalyst", agent=_RecordingRiskAgent()))

    async def post_fn(role: str, content: str) -> None:
        return None

    async def checkpoint_fn(summary: str) -> None:
        raise AssertionError("YOLO upstream human routing must not request checkpoints")

    service = CoordinatorService(
        session=session,
        post_fn=post_fn,
        checkpoint_fn=checkpoint_fn,
        mode="yolo",
    )

    await service.dispatch("human", "@backtester SPY")
    for _ in range(10):
        if any(message.from_role == "riskanalyst" for message in session.full_thread()):
            break
        await asyncio.sleep(0.05)

    messages = session.full_thread()
    assert any(message.from_role == "riskanalyst" for message in messages)


@pytest.mark.asyncio
async def test_quant_command_uses_shared_runtime_for_specialized_markets(tmp_path: Path) -> None:
    integration = SlackIntegration.__new__(SlackIntegration)
    service = _FakeService(tmp_path)
    integration._sessions = {"C123": service}

    await SlackIntegration._cmd_quant(integration, _FakeClient(), "C123", "SPY")

    assert service.runs == [["SPY"]]
    assert service.dispatched == []
    assert service._mode == "yolo"


@pytest.mark.asyncio
async def test_trend_analyst_hands_v6_scope_to_market_event_watcher(tmp_path: Path) -> None:
    files = FileWriter(tmp_path)
    raw_dir = tmp_path / "quant" / "raw"
    raw_dir.mkdir(parents=True)
    from datetime import date

    today = date.today().isoformat()
    (raw_dir / f"SPY_{today}_summary.md").write_text("SPY raw summary", encoding="utf-8")

    agent = TrendAnalystAgent(llm_service=_RoutingLLM())
    agent.files = files
    response = await agent.handle(
        Mention("trendanalyst", "datafetcher", "continue"),
        [],
        {"quant_state": {"watchlist": ["SPY"]}},
    )

    assert response.mentions == ["marketeventwatcher"]


@pytest.mark.asyncio
async def test_quant_command_uses_shared_runtime_for_general_markets(tmp_path: Path) -> None:
    integration = SlackIntegration.__new__(SlackIntegration)
    service = _FakeService(tmp_path)
    integration._sessions = {"C123": service}

    await SlackIntegration._cmd_quant(integration, _FakeClient(), "C123", "AAPL")

    assert service.runs == [["AAPL"]]
    assert service.dispatched == []
    assert service._mode == "yolo"


@pytest.mark.asyncio
async def test_yolo_command_reuses_active_session_and_invokes_shared_runtime(tmp_path: Path) -> None:
    integration = SlackIntegration.__new__(SlackIntegration)
    service = _FakeYoloService(tmp_path)
    integration._sessions = {"C123": service}
    client = _FakeClient()

    await SlackIntegration._cmd_yolo(integration, client, "C123", "SPY")

    assert service._mode == "yolo"
    assert service.runs == [["SPY"]]
    assert service.prepared == []
    assert service.dispatched == []
    assert any("YOLO starting" in message for message in client.messages)


@pytest.mark.asyncio
async def test_v6_agent_nodes_route_to_specialized_asset_analyst(tmp_path: Path) -> None:
    files = FileWriter(tmp_path)
    state = {"quant_state": {"watchlist": ["SPY"]}}
    mention = Mention(mentioned_role="marketeventwatcher", from_role="human", content="analyze SPY")

    market = MarketEventWatcher()
    market.files = files
    response = await market.handle(mention, [], state)
    assert response.mentions == ["optionsflowwatcher"]

    options = OptionsFlowWatcher()
    options.files = files
    response = await options.handle(
        Mention("optionsflowwatcher", "marketeventwatcher", response.content),
        [],
        state,
    )
    assert response.mentions == ["macrocontextwatcher"]

    macro = MacroContextWatcher(llm_service=_FakeLLM())
    macro.files = files
    response = await macro.handle(
        Mention("macrocontextwatcher", "optionsflowwatcher", response.content),
        [],
        state,
    )
    assert response.mentions == ["unusualeventdetector"]

    detector = UnusualEventDetector(llm_service=_FakeLLM())
    detector.files = files
    response = await detector.handle(
        Mention("unusualeventdetector", "macrocontextwatcher", response.content),
        [],
        state,
    )
    assert response.mentions == ["eventrouter"]

    router = EventRouter()
    router.files = files
    response = await router.handle(Mention("eventrouter", "unusualeventdetector", response.content), [], state)
    assert response.mentions == ["spyanalyst"]

    analyst = SPYAnalyst(llm_service=_FakeLLM())
    analyst.files = files
    response = await analyst.handle(Mention("spyanalyst", "eventrouter", response.content), [], state)
    assert response.mentions == ["quantresearcher"]
    assert (tmp_path / "quant" / "asset_analysis_").exists() is False
    assert any(path.name.startswith("asset_analysis_") for path in (tmp_path / "quant").iterdir())