yf176 commited on
Commit
032a712
Β·
1 Parent(s): dc39704

feat(v5.0): PublisherAgent (Finley) + Session Modes (Investigation/YOLO)

Browse files

- Add PublisherAgent ('Finley') as 10th quant agent
- Reads trade proposals, trend, sentiment, risk artifacts
- Produces <=500-word market post with mandatory disclaimer
- Supports @publisher write/rewrite with cache-bypass nonce
- Routes to @human after posting

- Add Session Modes
- investigation (default): full visibility, checkpoints enabled
- yolo: silent pipeline run, only Finley's post visible, no depth-3
checkpoints; live status via chat.update

- QuantState: add mode + yolo_status_ts fields
- AgentRouter: YOLO-aware can_dispatch(), publisher in QUANT_ROLES
- CoordinatorService: full YOLO support (post suppression, checkpoint
bypass, status updates, /poly mode handler)
- slack.py: --yolo flag in all 3 init paths, _cmd_mode,
_cmd_mode_from_mention, /poly mode router, help text v5.0
- Bump version to 5.0.0

docs/polyhedraV5.0.md ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Polyhedra V5.0 β€” PRD (Publisher Agent)
2
+
3
+ > Identity release. Adds a `PublisherAgent` as the final layer of the quant pipeline. Translates technical quant output into short, conversational, human-readable market posts. All upstream quant agents are unchanged.
4
+
5
+ ---
6
+
7
+ ## Vision
8
+
9
+ Polyhedra's quant team does rigorous analytical work β€” trend analysis, signal discovery, backtesting, risk assessment β€” but its output is dense, technical, and inaccessible to anyone outside the quant world. V5.0 adds a **publisher** who sits at the end of the pipeline, reads everything the team produced, and writes a short market post a normal person can read, enjoy, and share.
10
+
11
+ The quant team stays in the background. The publisher is the public face.
12
+
13
+ ---
14
+
15
+ ## The Publisher Persona
16
+
17
+ **Name:** Finley *(fixed, not customisable)*
18
+ **Voice:** Conversational and relatable. Finley writes like a sharp friend who follows markets β€” not a Bloomberg terminal, not a Reddit meme account. Plain language, a bit of personality, no jargon without explanation.
19
+ **Format:** Short-form post, Twitter/X style β€” 3–5 punchy paragraphs, under 500 words.
20
+ **Structure:** Narrative first, signal as a footnote.
21
+ **Disclaimer:** Always appended β€” one line, non-negotiable.
22
+
23
+ **Example output:**
24
+
25
+ ```
26
+ Gold had a rough week. πŸ“‰
27
+
28
+ GLD dropped 3.5% over the past five trading days, sliding from $476
29
+ to $459. The selloff wasn't panic β€” volume actually dried up toward
30
+ the end, which usually means the big sellers are done. But momentum
31
+ is still pointing down, and the news flow around gold has been
32
+ surprisingly quiet. No fear, no euphoria. Just a slow grind lower.
33
+
34
+ The interesting level to watch is around $456-457. That's where GLD
35
+ found support twice in the past week. If it holds, we might see a
36
+ bounce. If it breaks, the next meaningful floor is a fair bit lower.
37
+
38
+ Sentiment from the news is neutral β€” gold isn't getting much
39
+ attention right now, which can cut both ways. Sometimes the best
40
+ moves happen when nobody's watching.
41
+
42
+ ---
43
+ πŸ“Š Signal (paper trade): Short below $456.80 | Target $449 | Stop $459
44
+ ⚠️ This is a paper trading simulation. Not financial advice.
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Agent Definition
50
+
51
+ | Field | Value |
52
+ |---|---|
53
+ | Role key | `publisher` |
54
+ | Class | `PublisherAgent` |
55
+ | Display name | `Finley πŸ“` |
56
+ | LLM use | Yes β€” full post generation |
57
+ | Position in pipeline | Final β€” after `quantstrategist`, before `@human` |
58
+ | Triggered by | `QuantStrategistAgent` routing, or direct human `@publisher` mention |
59
+
60
+ ---
61
+
62
+ ## Pipeline Change
63
+
64
+ `QuantStrategistAgent` currently always routes to `@human`. In V5.0 it routes to `@publisher` first. Publisher routes to `@human` when the post is ready.
65
+
66
+ ```
67
+ Before V5.0:
68
+ QuantStrategist β†’ @human (trade proposals)
69
+
70
+ After V5.0:
71
+ QuantStrategist β†’ @publisher (content generation)
72
+ β”‚
73
+ β–Ό
74
+ @human (post + trade proposals together)
75
+ ```
76
+
77
+ The human sees both in the same Slack message: Finley's post above the fold, trade proposals below.
78
+
79
+ ---
80
+
81
+ ## Requirements
82
+
83
+ ### FR-1 β€” PublisherAgent
84
+
85
+ **FR-1.1** `PublisherAgent` is a new LLM-powered agent in `agents/quant/publisher.py`.
86
+
87
+ **FR-1.2** It reads the following artifacts via `FileWriter`:
88
+ - `quant/trade_proposals_<date>.md` β€” primary input
89
+ - `quant/trend_analysis_<date>.md` β€” price narrative
90
+ - `quant/sentiment_analysis_<date>.md` β€” sentiment colour
91
+ - `quant/risk_assessment_<date>.md` β€” risk context (for footnote signal rating)
92
+
93
+ **FR-1.3** It does NOT read:
94
+ - Raw data files (`quant/raw/`)
95
+ - Backtest results directly β€” risk rating from RiskAnalyst is sufficient
96
+ - Signal hypotheses β€” too technical for the output format
97
+
98
+ **FR-1.4** TokenBudget: same as other quant agents (`total=4000`).
99
+
100
+ **FR-1.5** Routing logic (LLM decides):
101
+ - Post complete β†’ `@human`
102
+ - Required input artifacts missing β†’ `@quantstrategist` with a note that proposals are needed first
103
+ - Cannot produce meaningful narrative (e.g. all signals rejected, no data) β†’ `@human` with a plain explanation instead of a post
104
+
105
+ ---
106
+
107
+ ### FR-2 β€” Post Structure
108
+
109
+ **FR-2.1** Every post must follow this structure:
110
+
111
+ ```
112
+ [HOOK β€” 1 sentence, names the ticker and what happened this week]
113
+
114
+ [BODY β€” 2-3 short paragraphs]
115
+ Para 1: What the price did and what it means in plain English
116
+ Para 2: What to watch β€” key levels, what would change the picture
117
+ Para 3: Sentiment / news colour β€” what people are saying (or not saying)
118
+
119
+ [FOOTNOTE]
120
+ πŸ“Š Signal (paper trade): [direction] [entry condition] | Target [TP] | Stop [SL]
121
+ ⚠️ This is a paper trading simulation. Not financial advice.
122
+ ```
123
+
124
+ **FR-2.2** Hard constraints on the post:
125
+ - Maximum 500 words
126
+ - No jargon without immediate plain-English explanation
127
+ - No invented data β€” every claim must be traceable to an artifact
128
+ - No first-person ("I think") β€” Finley observes, does not opine as an individual
129
+ - Signal footnote must exactly match the approved proposal οΏ½οΏ½ no paraphrasing of numbers
130
+
131
+ **FR-2.3** If multiple trade proposals exist, the footnote lists all of them, one per line.
132
+
133
+ **FR-2.4** The disclaimer is always the final line, verbatim:
134
+ ```
135
+ ⚠️ This is a paper trading simulation. Not financial advice.
136
+ ```
137
+
138
+ ---
139
+
140
+ ### FR-3 β€” Prompt Structure
141
+
142
+ Finley's system prompt (section [1] ROLE):
143
+
144
+ ```
145
+ You are Finley, a financial market commentator who writes short,
146
+ conversational posts about market trends for a general audience.
147
+
148
+ Your job is to take rigorous quant analysis and translate it into
149
+ something a curious, non-expert reader can understand and find
150
+ interesting. You write like a sharp, well-informed friend β€” not a
151
+ trading desk, not a meme account.
152
+
153
+ Rules:
154
+ - Plain language always. If you must use a technical term, explain it
155
+ immediately in the same sentence.
156
+ - Never invent data. Every claim must come from the analysis provided.
157
+ - Never give financial advice. The signal footnote is a paper trade
158
+ simulation only.
159
+ - No first-person opinions. Observe and report β€” don't say "I think".
160
+ - Keep it under 500 words. Punchy beats comprehensive.
161
+ - The disclaimer is always the last line, word for word.
162
+ ```
163
+
164
+ ---
165
+
166
+ ### FR-4 β€” Artifact
167
+
168
+ **FR-4.1** PublisherAgent writes its post to `quant/post_<date>.md`. Mode: overwrite (one post per day per session).
169
+
170
+ **FR-4.2** The artifact contains the full post including footnote and disclaimer β€” exactly as posted to Slack.
171
+
172
+ **FR-4.3** `/poly export` includes `quant/post_<date>.md` in the export archive.
173
+
174
+ ---
175
+
176
+ ### FR-5 β€” Slack Output
177
+
178
+ **FR-5.1** The post is posted to the Slack thread as a standalone message from `Finley πŸ“`, visually distinct from the technical agent messages above it.
179
+
180
+ **FR-5.2** Trade proposals are appended below the post in a collapsed section (Slack Block Kit) so the human can review and approve without the proposals cluttering the post itself.
181
+
182
+ **FR-5.3** Input templates follow the proposals β€” same approval flow as before:
183
+ ```
184
+ πŸ’¬ Suggested next messages:
185
+ 1. > /poly trade approve <id> ← recommended
186
+ 2. > /poly trade revise <id>
187
+ 3. > /poly trade reject <id>
188
+ ```
189
+
190
+ ---
191
+
192
+ ### FR-6 β€” Direct Human Invocation
193
+
194
+ **FR-6.1** Human can invoke Publisher directly at any time:
195
+ ```
196
+ @PolyTest @publisher write
197
+ @PolyTest @publisher rewrite ← regenerates the post with a fresh LLM call
198
+ ```
199
+
200
+ **FR-6.2** On direct invocation, Publisher reads whatever artifacts exist for today and generates the best post it can. If trade proposals don't exist yet, it writes a market commentary post without the signal footnote, and notes:
201
+ ```
202
+ [No trade proposals available yet β€” signal footnote omitted]
203
+ ```
204
+
205
+ **FR-6.3** `@publisher rewrite` regenerates without cache β€” bypasses the LLM cache for this call only.
206
+
207
+ ---
208
+
209
+ ### FR-7 β€” Multi-Ticker Handling
210
+
211
+ **FR-7.1** If the watchlist contains multiple tickers, Publisher writes one post that covers all of them, not one post per ticker.
212
+
213
+ **FR-7.2** The hook names the most significant ticker (highest confidence signal from Strategist). Other tickers are woven into the body where relevant.
214
+
215
+ **FR-7.3** If signals across tickers conflict (e.g. GLD short + AAPL long), Publisher acknowledges the contrast naturally in the narrative β€” "while gold looks shaky, tech is telling a different story."
216
+
217
+ ---
218
+
219
+ ### FR-8 β€” COMMAND_REGISTRY Update
220
+
221
+ Add to `TemplateBuilder.COMMAND_REGISTRY`:
222
+
223
+ | Slash | Mention | CLI | Description |
224
+ |---|---|---|---|
225
+ | β€” | `@publisher write` | β€” | Generate today's market post |
226
+ | β€” | `@publisher rewrite` | β€” | Regenerate post (bypasses cache) |
227
+
228
+ ---
229
+
230
+ ### FR-9 β€” Registration
231
+
232
+ **FR-9.1** `PublisherAgent` is registered as the 10th quant agent in `SlackIntegration._init_from_mention()` and `_cmd_init()`:
233
+
234
+ ```python
235
+ selected_roles = [
236
+ "datafetcher", "trendanalyst", "sentimentanalyst",
237
+ "quantresearcher", "backtester", "riskanalyst",
238
+ "quantstrategist", "vizagent", "portfoliomonitor",
239
+ "publisher" # new
240
+ ]
241
+ ```
242
+
243
+ **FR-9.2** Add to `_ROLE_DISPLAY`:
244
+ ```python
245
+ "publisher": "Finley πŸ“"
246
+ ```
247
+
248
+ ---
249
+
250
+ ## What Stays the Same
251
+
252
+ - All 9 existing quant agents β€” zero changes to logic, prompts, or artifacts
253
+ - Human approval flow for trade proposals β€” unchanged
254
+ - `QuantStrategistAgent` internal logic β€” only its routing JSON changes (`"next": "publisher"` instead of `"next": "human"`)
255
+ - All V4.x slash commands and mention commands
256
+ - Disclaimer language β€” fixed, never changes
257
+
258
+ ---
259
+
260
+ ## Example Full Slack Output
261
+
262
+ ```
263
+ Finley πŸ“
264
+
265
+ Gold had a rough week. πŸ“‰
266
+
267
+ GLD dropped 3.5% over the past five trading days, sliding from $476
268
+ to $459. The selloff wasn't panic β€” volume actually dried up toward
269
+ the end of the week, which usually means the big sellers are done.
270
+ But momentum is still pointing down and there's no obvious catalyst
271
+ to reverse it yet.
272
+
273
+ The level to watch is $456-$457. GLD found support there twice in the
274
+ past week. If it holds, a bounce back toward $465 is in play. If it
275
+ breaks, the next meaningful floor is a fair bit lower.
276
+
277
+ News sentiment around gold is quiet right now β€” most of the coverage
278
+ is macro background noise (oil, geopolitics) rather than anything gold
279
+ specific. That neutral backdrop means price action is driving the story,
280
+ not headlines.
281
+
282
+ ---
283
+ πŸ“Š Signal (paper trade): Short below $456.80 | Target $449.63 | Stop $459.00
284
+ ⚠️ This is a paper trading simulation. Not financial advice.
285
+
286
+ β–Ό Trade proposals for review
287
+ [GLD-001] Short GLD | Entry < $456.80 | TP $449.63 | SL $459.00 | Size 5%
288
+
289
+ πŸ’¬ Suggested next messages:
290
+ 1. > /poly trade approve GLD-001 ← recommended
291
+ 2. > /poly trade revise GLD-001
292
+ 3. > /poly trade reject GLD-001
293
+ ```
294
+
295
+ ---
296
+
297
+ ## Implementation Checklist
298
+
299
+ - [ ] `PublisherAgent` class β€” `agents/quant/publisher.py`
300
+ - [ ] `PublisherOutput` Pydantic model β€” `agents/quant/outputs.py`
301
+ - [ ] Finley system prompt β€” conversational voice, hard constraints
302
+ - [ ] Post structure enforced in TASK section
303
+ - [ ] Artifact write β€” `quant/post_<date>.md`, overwrite mode
304
+ - [ ] `QuantStrategistAgent` routing JSON updated β€” `"next": "publisher"`
305
+ - [ ] Slack Block Kit layout β€” post + collapsed proposals + input templates
306
+ - [ ] `@publisher write` and `@publisher rewrite` direct invocation
307
+ - [ ] Cache bypass on `rewrite` command
308
+ - [ ] Multi-ticker handling β€” single post, most significant ticker leads
309
+ - [ ] `PublisherAgent` registered as 10th quant agent
310
+ - [ ] `"publisher": "Finley πŸ“"` added to `_ROLE_DISPLAY`
311
+ - [ ] `COMMAND_REGISTRY` updated
312
+ - [ ] `/poly export` includes `quant/post_<date>.md`
313
+ - [ ] `version = "5.0.0"` in `__init__.py` and `pyproject.toml`
314
+
315
+ ---
316
+
317
+ ## Out of Scope for V5.0
318
+ - Multiple blogger personas or customisable voice β€” future
319
+ - Long-form article format β€” future
320
+ - Export to external platforms (Twitter API, Substack, etc.) β€” future
321
+ - LangSmith observability β€” future
322
+ - SSE streaming β€” future
323
+ - Research pipeline β€” permanently paused
pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
  [project]
2
  name = "polyhedra"
3
- version = "4.5.0"
4
  description = "Collaborative multi-agent research team with Slack/Teams/CLI, MCP server, and quant paper-trading simulation"
5
  readme = "README.md"
6
  requires-python = ">=3.11"
 
1
  [project]
2
  name = "polyhedra"
3
+ version = "5.0.0"
4
  description = "Collaborative multi-agent research team with Slack/Teams/CLI, MCP server, and quant paper-trading simulation"
5
  readme = "README.md"
6
  requires-python = ">=3.11"
src/polyhedra/__init__.py CHANGED
@@ -1,6 +1,6 @@
1
- ο»Ώ"""Polyhedra β€” Collaborative Multi-Agent Research Team (v4.5)."""
2
 
3
- __version__ = "4.5.0"
4
 
5
  # Lazy import to avoid MCP dependency during testing
6
  def main():
 
1
+ ο»Ώ"""Polyhedra β€” Collaborative Multi-Agent Research Team (v5.0)."""
2
 
3
+ __version__ = "5.0.0"
4
 
5
  # Lazy import to avoid MCP dependency during testing
6
  def main():
src/polyhedra/agents/coordinator.py CHANGED
@@ -47,6 +47,18 @@ logger = logging.getLogger(__name__)
47
  _MAX_MENTION_DEPTH = 3
48
  _COST_APPROVAL_THRESHOLD = 0.50
49
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  class _CostRejected(Exception):
52
  """Sentinel raised when the user declines a cost-gated operation."""
@@ -134,6 +146,7 @@ class CoordinatorAgent(Agent):
134
 
135
  PostFn = Callable[[str, str], Awaitable[None]] # (from_role, content) -> None
136
  CheckpointFn = Callable[[str], Awaitable[CheckpointResult]] # summary -> result
 
137
 
138
 
139
  class CoordinatorService:
@@ -157,11 +170,16 @@ class CoordinatorService:
157
  post_fn: PostFn,
158
  checkpoint_fn: CheckpointFn,
159
  llm_service: LLMService | None = None,
 
 
160
  ) -> None:
161
  self.session = session
162
  self._post = post_fn
163
  self._checkpoint = checkpoint_fn
164
  self._llm = llm_service
 
 
 
165
  self._parser = MentionParser(session.registry)
166
 
167
  # V4.4 STRUCT-1: delegate to focused sub-components
@@ -213,7 +231,7 @@ class CoordinatorService:
213
  return
214
 
215
  for mention in mentions:
216
- if not self._router.can_dispatch(origin_id, mention.mentioned_role):
217
  if self._router.is_quant_role(mention.mentioned_role):
218
  templates = _build_input_templates(
219
  "checkpoint", next_role=mention.mentioned_role
@@ -356,7 +374,10 @@ class CoordinatorService:
356
  return
357
 
358
  # Post agent response
359
- await self._post(entry.role, response.content)
 
 
 
360
  self.session.post(entry.role, response.content)
361
 
362
  # V4.3: determine current depth for the event
@@ -492,8 +513,16 @@ class CoordinatorService:
492
  if event.updates_state and event.state_patch:
493
  self._patcher.apply(self.session.session_dir, event.state_patch)
494
 
495
- # Checkpoint gate
496
- if event.checkpoint_required:
 
 
 
 
 
 
 
 
497
  result = await self._checkpoint(event.checkpoint_summary)
498
  if not result.approved:
499
  await self._post(
@@ -515,12 +544,48 @@ class CoordinatorService:
515
  )
516
  await self._route(follow_up, event.origin_id)
517
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  async def _on_agent_blocked(self, event: AgentBlockedEvent) -> None:
519
- """React to an agent blocked on missing data (FR-2.x)."""
 
 
 
 
 
 
 
 
 
520
  templates = _build_input_templates("agent_blocked", next_role=event.suggested_role)
521
  await self._post(
522
  "coordinator",
523
- f"⚠️ **Coordinator** β€” @{event.agent_role} is blocked: {event.reason}"
524
  f"{templates}",
525
  )
526
  if event.suggested_role:
@@ -587,6 +652,14 @@ class CoordinatorService:
587
  await self._post_trace_summary()
588
  return True
589
 
 
 
 
 
 
 
 
 
590
  if sub == "help":
591
  await self._post("coordinator", render_help_slack())
592
  return True
 
47
  _MAX_MENTION_DEPTH = 3
48
  _COST_APPROVAL_THRESHOLD = 0.50
49
 
50
+ # Short labels used in YOLO progress status message (V5.0)
51
+ _ROLE_LABELS: dict[str, str] = {
52
+ "datafetcher": "DataFetcher",
53
+ "trendanalyst": "TrendAnalyst",
54
+ "sentimentanalyst": "SentimentAnalyst",
55
+ "quantresearcher": "QuantResearcher",
56
+ "backtester": "Backtester",
57
+ "riskanalyst": "RiskAnalyst",
58
+ "quantstrategist": "QuantStrategist",
59
+ "publisher": "Finley",
60
+ }
61
+
62
 
63
  class _CostRejected(Exception):
64
  """Sentinel raised when the user declines a cost-gated operation."""
 
146
 
147
  PostFn = Callable[[str, str], Awaitable[None]] # (from_role, content) -> None
148
  CheckpointFn = Callable[[str], Awaitable[CheckpointResult]] # summary -> result
149
+ YoloUpdateFn = Callable[[str], Awaitable[None]] # new_content -> None
150
 
151
 
152
  class CoordinatorService:
 
170
  post_fn: PostFn,
171
  checkpoint_fn: CheckpointFn,
172
  llm_service: LLMService | None = None,
173
+ mode: str = "investigation",
174
+ yolo_update_fn: "YoloUpdateFn | None" = None,
175
  ) -> None:
176
  self.session = session
177
  self._post = post_fn
178
  self._checkpoint = checkpoint_fn
179
  self._llm = llm_service
180
+ self._mode = mode
181
+ self._yolo_update_fn = yolo_update_fn
182
+ self._yolo_completed: list[str] = [] # agents finished in this YOLO run
183
  self._parser = MentionParser(session.registry)
184
 
185
  # V4.4 STRUCT-1: delegate to focused sub-components
 
231
  return
232
 
233
  for mention in mentions:
234
+ if not self._router.can_dispatch(origin_id, mention.mentioned_role, self._mode):
235
  if self._router.is_quant_role(mention.mentioned_role):
236
  templates = _build_input_templates(
237
  "checkpoint", next_role=mention.mentioned_role
 
374
  return
375
 
376
  # Post agent response
377
+ # V5.0: in YOLO mode, suppress all agent posts β€” only errors and blocked
378
+ # states bypass suppression (FR-9.2 / FR-9.3).
379
+ if self._mode != "yolo" or entry.role not in _QUANT_ROLES:
380
+ await self._post(entry.role, response.content)
381
  self.session.post(entry.role, response.content)
382
 
383
  # V4.3: determine current depth for the event
 
513
  if event.updates_state and event.state_patch:
514
  self._patcher.apply(self.session.session_dir, event.state_patch)
515
 
516
+ # V5.0: in YOLO mode update the pipeline status message instead of posting
517
+ if self._mode == "yolo" and event.agent_role in _QUANT_ROLES:
518
+ self._yolo_completed.append(event.agent_role)
519
+ if self._yolo_update_fn is not None:
520
+ await self._yolo_update_fn(
521
+ self._build_yolo_status(event.agent_role, done=True)
522
+ )
523
+
524
+ # Checkpoint gate β€” skipped entirely in YOLO mode (FR-9.2)
525
+ if event.checkpoint_required and self._mode != "yolo":
526
  result = await self._checkpoint(event.checkpoint_summary)
527
  if not result.approved:
528
  await self._post(
 
544
  )
545
  await self._route(follow_up, event.origin_id)
546
 
547
+ def _build_yolo_status(self, latest_role: str, *, done: bool) -> str:
548
+ """Build the YOLO progress status message content (FR-9.2)."""
549
+ _PIPELINE = [
550
+ "datafetcher", "trendanalyst", "sentimentanalyst",
551
+ "quantresearcher", "backtester", "riskanalyst",
552
+ "quantstrategist", "publisher",
553
+ ]
554
+ parts: list[str] = []
555
+ for role in _PIPELINE:
556
+ if role in self._yolo_completed:
557
+ parts.append(f"βœ… {_ROLE_LABELS.get(role, role)}")
558
+ elif role == latest_role and not done:
559
+ parts.append(f"⏳ {_ROLE_LABELS.get(role, role)}…")
560
+ elif role not in self._yolo_completed:
561
+ parts.append(f"βšͺ {_ROLE_LABELS.get(role, role)}")
562
+ steps = " β†’ ".join(parts)
563
+ if all(r in self._yolo_completed for r in _PIPELINE):
564
+ return (
565
+ f"⚑ YOLO run complete β€” {self.session.goal}\n"
566
+ f" {steps}\n"
567
+ " Finley's post is ready below."
568
+ )
569
+ return (
570
+ f"⚑ YOLO run in progress β€” {self.session.goal}\n"
571
+ f" {steps}"
572
+ )
573
+
574
  async def _on_agent_blocked(self, event: AgentBlockedEvent) -> None:
575
+ """React to an agent blocked on missing data (FR-2.x / FR-9.3 V5.0).
576
+
577
+ Always posts regardless of YOLO mode β€” blocked events bypass suppression.
578
+ """
579
+ # V5.0: in YOLO mode, prepend an interrupted banner
580
+ yolo_header = ""
581
+ if self._mode == "yolo":
582
+ yolo_header = (
583
+ f"⚑ YOLO run interrupted β€” {self.session.goal}\n"
584
+ )
585
  templates = _build_input_templates("agent_blocked", next_role=event.suggested_role)
586
  await self._post(
587
  "coordinator",
588
+ f"{yolo_header}⚠️ **Coordinator** β€” @{event.agent_role} is blocked: {event.reason}"
589
  f"{templates}",
590
  )
591
  if event.suggested_role:
 
652
  await self._post_trace_summary()
653
  return True
654
 
655
+ if sub == "mode":
656
+ # V5.0 FR-10: /poly mode β€” show current session mode
657
+ if self._mode == "yolo":
658
+ await self._post("coordinator", "⚑ **YOLO mode** β€” silent pipeline run, Finley posts at end.")
659
+ else:
660
+ await self._post("coordinator", "πŸ” **Investigation mode** β€” full visibility, checkpoints enabled.")
661
+ return True
662
+
663
  if sub == "help":
664
  await self._post("coordinator", render_help_slack())
665
  return True
src/polyhedra/agents/quant/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- """Polyhedra V4.0/V4.2 quant agent package."""
2
 
3
  from polyhedra.agents.quant.datafetcher import DataFetcherAgent
4
  from polyhedra.agents.quant.trendanalyst import TrendAnalystAgent
@@ -9,6 +9,7 @@ from polyhedra.agents.quant.riskanalyst import RiskAnalystAgent
9
  from polyhedra.agents.quant.quantstrategist import QuantStrategistAgent
10
  from polyhedra.agents.quant.vizagent import VizAgent
11
  from polyhedra.agents.quant.portfoliomonitor import PortfolioMonitorAgent
 
12
 
13
  __all__ = [
14
  "DataFetcherAgent",
@@ -20,4 +21,5 @@ __all__ = [
20
  "QuantStrategistAgent",
21
  "VizAgent",
22
  "PortfolioMonitorAgent",
 
23
  ]
 
1
+ """Polyhedra V4.0/V4.2/V5.0 quant agent package."""
2
 
3
  from polyhedra.agents.quant.datafetcher import DataFetcherAgent
4
  from polyhedra.agents.quant.trendanalyst import TrendAnalystAgent
 
9
  from polyhedra.agents.quant.quantstrategist import QuantStrategistAgent
10
  from polyhedra.agents.quant.vizagent import VizAgent
11
  from polyhedra.agents.quant.portfoliomonitor import PortfolioMonitorAgent
12
+ from polyhedra.agents.quant.publisher import PublisherAgent
13
 
14
  __all__ = [
15
  "DataFetcherAgent",
 
21
  "QuantStrategistAgent",
22
  "VizAgent",
23
  "PortfolioMonitorAgent",
24
+ "PublisherAgent",
25
  ]
src/polyhedra/agents/quant/outputs.py CHANGED
@@ -148,8 +148,33 @@ class QuantStrategistOutput(BaseModel):
148
  description="Proposal rationale with the JSON block stripped out.",
149
  )
150
  next_role: str | None = Field(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  default="human",
152
- description="human (for trade approval) or None when no proposals were generated.",
153
  )
154
  reason: str = Field(
155
  default="",
 
148
  description="Proposal rationale with the JSON block stripped out.",
149
  )
150
  next_role: str | None = Field(
151
+ default="publisher",
152
+ description="publisher (V5.0 pipeline) or None when no proposals were generated.",
153
+ )
154
+ reason: str = Field(
155
+ default="",
156
+ description="Short explanation of the dispatch decision.",
157
+ )
158
+
159
+
160
+ # --------------------------------------------------------------------------- #
161
+ # PublisherAgent
162
+ # --------------------------------------------------------------------------- #
163
+
164
+ class PublisherOutput(BaseModel):
165
+ """Output produced by PublisherAgent (Finley πŸ“ β€” V5.0)."""
166
+
167
+ artifact_path: str = Field(
168
+ default="",
169
+ description="Session-relative path to the market post artifact written.",
170
+ )
171
+ post_word_count: int = Field(
172
+ default=0,
173
+ description="Approximate word count of the generated post (must be <= 500).",
174
+ )
175
+ next_role: str = Field(
176
  default="human",
177
+ description="human when post is ready; quantstrategist when proposals are needed first.",
178
  )
179
  reason: str = Field(
180
  default="",
src/polyhedra/agents/quant/publisher.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PublisherAgent β€” Finley πŸ“, market post writer for Polyhedra V5.0.
2
+
3
+ Sits at the end of the quant pipeline, after QuantStrategistAgent.
4
+ Reads quant artifacts and translates them into a short, conversational
5
+ market post that a non-expert reader can understand and enjoy.
6
+
7
+ Post format: hook β†’ body (2-3 paras) β†’ signal footnote β†’ disclaimer.
8
+ Hard limit: 500 words.
9
+
10
+ DISCLAIMER: Paper trading simulation only. No real capital. Not financial advice.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ from datetime import date, datetime, timezone
17
+ from typing import Any
18
+
19
+ from polyhedra.agents.base import Agent, AgentResponse, Mention
20
+ from polyhedra.agents.quant.routing import LLM_ROUTING_PROMPT, parse_llm_routing
21
+ from polyhedra.core.token_budget import TokenBudget
22
+ from polyhedra.services.llm_service import LLMService
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _DISCLAIMER = "⚠️ This is a paper trading simulation. Not financial advice."
27
+ _NOT_AVAILABLE = "_not available_"
28
+
29
+ _SYSTEM_PROMPT = """\
30
+ You are Finley, a financial market commentator who writes short, \
31
+ conversational posts about market trends for a general audience.
32
+
33
+ Your job is to take rigorous quant analysis and translate it into \
34
+ something a curious, non-expert reader can understand and find \
35
+ interesting. You write like a sharp, well-informed friend β€” not a \
36
+ trading desk, not a meme account.
37
+
38
+ Rules:
39
+ - Plain language always. If you must use a technical term, explain it \
40
+ immediately in the same sentence.
41
+ - Never invent data. Every claim must come from the analysis provided.
42
+ - Never give financial advice. The signal footnote is a paper trade \
43
+ simulation only.
44
+ - No first-person opinions. Observe and report β€” don't say "I think".
45
+ - Keep it under 500 words. Punchy beats comprehensive.
46
+ - The disclaimer is always the last line, word for word: \
47
+ "⚠️ This is a paper trading simulation. Not financial advice."
48
+ """
49
+
50
+
51
+ class PublisherAgent(Agent):
52
+ """Finley πŸ“ β€” translates quant output into a short market post."""
53
+
54
+ name = "Publisher"
55
+ role = "publisher"
56
+ role_title = "Finley πŸ“"
57
+ system_prompt = _SYSTEM_PROMPT
58
+ token_budget = TokenBudget(system=500, context=2000, task=500, thread=500, routing=200, total=4000)
59
+
60
+ def __init__(self, llm_service: LLMService | None = None) -> None:
61
+ super().__init__()
62
+ self._llm_service = llm_service
63
+ self.__llm: LLMService | None = None
64
+
65
+ @property
66
+ def _llm(self) -> LLMService:
67
+ if self.__llm is None:
68
+ self.__llm = self._llm_service or LLMService()
69
+ return self.__llm
70
+
71
+ async def can_handle(self, mention: Mention) -> bool:
72
+ return mention.mentioned_role == self.role
73
+
74
+ async def handle(
75
+ self,
76
+ mention: Mention,
77
+ thread_context: list[dict[str, Any]],
78
+ research_state: dict[str, Any],
79
+ ) -> AgentResponse:
80
+ today = date.today().isoformat()
81
+ content_lower = mention.content.lower()
82
+ is_rewrite = "rewrite" in content_lower
83
+
84
+ # ------------------------------------------------------------------ #
85
+ # Read artifacts
86
+ # ------------------------------------------------------------------ #
87
+ proposals_md = self.files.read(f"quant/trade_proposals_{today}.md")
88
+ trend_md = self.files.read(f"quant/trend_analysis_{today}.md")
89
+ sentiment_md = self.files.read(f"quant/sentiment_analysis_{today}.md") or _NOT_AVAILABLE
90
+ risk_md = self.files.read(f"quant/risk_assessment_{today}.md") or _NOT_AVAILABLE
91
+
92
+ # ------------------------------------------------------------------ #
93
+ # Guard: QuantStrategist must have run first when invoked from pipeline
94
+ # (not a direct @publisher write call)
95
+ # ------------------------------------------------------------------ #
96
+ invoked_directly = "write" in content_lower or "rewrite" in content_lower
97
+ if not proposals_md and not invoked_directly:
98
+ return AgentResponse(
99
+ agent_role=self.role,
100
+ content=(
101
+ "πŸ“ **Finley** β€” No trade proposals found for today. "
102
+ "Please run `@quantstrategist` first so there's something to publish."
103
+ ),
104
+ mentions=["quantstrategist"],
105
+ )
106
+
107
+ # ------------------------------------------------------------------ #
108
+ # Build prompt
109
+ # ------------------------------------------------------------------ #
110
+ prompt = self._build_prompt(
111
+ proposals_md=proposals_md,
112
+ trend_md=trend_md,
113
+ sentiment_md=sentiment_md,
114
+ risk_md=risk_md,
115
+ is_rewrite=is_rewrite,
116
+ )
117
+
118
+ # ------------------------------------------------------------------ #
119
+ # LLM call (nonce added on rewrite to bypass LLM cache β€” FR-6.3)
120
+ # ------------------------------------------------------------------ #
121
+ try:
122
+ result = await self._llm.complete(prompt)
123
+ if isinstance(result, tuple):
124
+ llm_text, prompt_tokens, completion_tokens = result
125
+ else:
126
+ llm_text, prompt_tokens, completion_tokens = (result or ""), 0, 0
127
+ self._log_token_usage(research_state, prompt_tokens, completion_tokens, cache_hit=False)
128
+ except Exception as exc:
129
+ logger.error("PublisherAgent LLM call failed: %s", exc)
130
+ llm_text = (
131
+ "Market post could not be generated (LLM unavailable).\n"
132
+ '{"next": "human", "reason": "LLM unavailable β€” fallback."}'
133
+ )
134
+ prompt_tokens, completion_tokens = 0, 0
135
+
136
+ next_role, reason, post_text = parse_llm_routing(llm_text)
137
+
138
+ # Guarantee routing β€” publisher always goes to human when done
139
+ if not next_role or next_role not in {"human", "quantstrategist"}:
140
+ next_role = "human"
141
+
142
+ # ------------------------------------------------------------------ #
143
+ # Ensure disclaimer is the final line (hard constraint FR-2.4)
144
+ # ------------------------------------------------------------------ #
145
+ post_text = self._enforce_disclaimer(post_text)
146
+
147
+ # ------------------------------------------------------------------ #
148
+ # Write artifact β€” quant/post_<date>.md (FR-4.1)
149
+ # ------------------------------------------------------------------ #
150
+ artifact_path = f"quant/post_{today}.md"
151
+ ts = datetime.now(tz=timezone.utc).strftime("%H%M")
152
+ self.files.write(
153
+ artifact_path,
154
+ f"# Market Post β€” {today} {ts} UTC\n\n{post_text}\n",
155
+ mode="overwrite",
156
+ )
157
+
158
+ # ------------------------------------------------------------------ #
159
+ # Format Slack output (FR-5.1/FR-5.2/FR-5.3)
160
+ # ------------------------------------------------------------------ #
161
+ slack_content = self._format_slack_output(
162
+ post_text=post_text,
163
+ proposals_md=proposals_md,
164
+ reason=reason,
165
+ )
166
+
167
+ return AgentResponse(
168
+ agent_role=self.role,
169
+ content=slack_content,
170
+ mentions=[next_role] if next_role else ["human"],
171
+ artifact_path=artifact_path,
172
+ artifact_mode="overwrite",
173
+ )
174
+
175
+ # ---------------------------------------------------------------------- #
176
+ # Prompt builder
177
+ # ---------------------------------------------------------------------- #
178
+
179
+ def _build_prompt(
180
+ self,
181
+ proposals_md: str | None,
182
+ trend_md: str | None,
183
+ sentiment_md: str,
184
+ risk_md: str,
185
+ is_rewrite: bool,
186
+ ) -> str:
187
+ proposals_section = (
188
+ proposals_md[:3000]
189
+ if proposals_md
190
+ else "[No trade proposals available yet β€” signal footnote omitted]"
191
+ )
192
+ trend_section = trend_md[:2000] if trend_md else _NOT_AVAILABLE
193
+
194
+ # Rewrite nonce β€” unique per call so LLM cache is never hit (FR-6.3)
195
+ nonce_line = ""
196
+ if is_rewrite:
197
+ nonce_ts = datetime.now(tz=timezone.utc).isoformat()
198
+ nonce_line = f"\n<!-- rewrite nonce: {nonce_ts} -->\n"
199
+
200
+ return f"""## [1] ROLE
201
+ {self.system_prompt}
202
+
203
+ ## [2] INPUTS
204
+ ### Trade proposals (from QuantStrategist):
205
+ {proposals_section}
206
+
207
+ ### Trend analysis (from TrendAnalyst):
208
+ {trend_section}
209
+
210
+ ### Sentiment analysis (from SentimentAnalyst):
211
+ {sentiment_md[:1000]}
212
+
213
+ ### Risk assessment (from RiskAnalyst):
214
+ {risk_md[:1000]}
215
+ {nonce_line}
216
+ ## [3] TASK
217
+ Write a short market post following this exact structure:
218
+
219
+ **HOOK** (1 sentence): Name the leading ticker and what happened this week.
220
+
221
+ **BODY** (2-3 short paragraphs):
222
+ - Para 1: What the price did and what it means in plain English.
223
+ - Para 2: What to watch β€” key levels, what would change the picture.
224
+ - Para 3: Sentiment / news colour β€” what people are saying (or not saying).
225
+ If no meaningful sentiment data is available, weave risk context here instead.
226
+
227
+ **SIGNAL FOOTNOTE**:
228
+ If trade proposals exist, list them all (one per line):
229
+ πŸ“Š Signal (paper trade): [direction] [entry condition] | Target [TP] | Stop [SL]
230
+ If no proposals exist, write:
231
+ [No trade proposals available yet β€” signal footnote omitted]
232
+
233
+ **DISCLAIMER** (always, verbatim, final line):
234
+ ⚠️ This is a paper trading simulation. Not financial advice.
235
+
236
+ Hard constraints:
237
+ - Maximum 500 words total.
238
+ - No jargon without immediate plain-English explanation.
239
+ - Every claim must come from the inputs above β€” never invent data.
240
+ - No first-person opinions ("I think", "I believe").
241
+ - Signal numbers must EXACTLY match the proposals β€” do not paraphrase figures.
242
+ - If multiple tickers, the hook names the highest-confidence one. Others are woven into the body.
243
+ - If signals across tickers conflict, acknowledge the contrast naturally in the narrative.
244
+
245
+ ## [4] ROUTING
246
+ After the post, decide who receives it.
247
+ - Post complete β†’ {{"next": "human", "reason": "Post ready for review."}}
248
+ - Required artifacts missing and cannot produce meaningful post β†’ {{"next": "quantstrategist", "reason": "Need proposals first."}}
249
+
250
+ {LLM_ROUTING_PROMPT}"""
251
+
252
+ # ---------------------------------------------------------------------- #
253
+ # Helpers
254
+ # ---------------------------------------------------------------------- #
255
+
256
+ @staticmethod
257
+ def _enforce_disclaimer(text: str) -> str:
258
+ """Ensure the disclaimer is the very last line of the post (FR-2.4)."""
259
+ stripped = text.rstrip()
260
+ if stripped.endswith(_DISCLAIMER):
261
+ return stripped
262
+ # Remove any stray disclaimer already embedded mid-text, then append
263
+ cleaned = stripped.replace(_DISCLAIMER, "").rstrip()
264
+ return f"{cleaned}\n{_DISCLAIMER}"
265
+
266
+ @staticmethod
267
+ def _format_slack_output(
268
+ post_text: str,
269
+ proposals_md: str | None,
270
+ reason: str,
271
+ ) -> str:
272
+ """Build the full Slack message: post + collapsed proposals + input templates (FR-5.2/5.3)."""
273
+ lines: list[str] = [
274
+ "πŸ“ **Finley** β€” Today's market post:\n",
275
+ "---",
276
+ post_text,
277
+ ]
278
+
279
+ if proposals_md:
280
+ lines += [
281
+ "\n---",
282
+ "β–Ό **Trade proposals for review**",
283
+ f"```\n{proposals_md[:2000]}\n```",
284
+ "\nπŸ’¬ Suggested next messages:",
285
+ "1. > `/poly trade approve <id>` ← recommended",
286
+ "2. > `/poly trade revise <id>`",
287
+ "3. > `/poly trade reject <id>`",
288
+ ]
289
+
290
+ if reason:
291
+ lines.append(f"\n_Routing: {reason}_")
292
+
293
+ return "\n".join(lines)
src/polyhedra/agents/quant/quantstrategist.py CHANGED
@@ -42,7 +42,7 @@ class QuantStrategistAgent(Agent):
42
  "Your job is to synthesise technical analysis, sentiment analysis, backtest results, "
43
  "and risk assessments into a maximum of 3 concrete paper trade proposals. "
44
  "Every proposal must include full rationale and a risk rating from RiskAnalyst. "
45
- "You must ALWAYS route to @human β€” the human approves all paper trades."
46
  )
47
  token_budget = TokenBudget(system=500, context=2000, task=500, thread=500, routing=200, total=4000)
48
 
@@ -143,22 +143,18 @@ class QuantStrategistAgent(Agent):
143
  )
144
 
145
  content = (
146
- "πŸ“‹ **QuantStrategist** β€” Paper trade proposals ready for your review.\n\n"
147
  "**⚠️ DISCLAIMER: Paper trading simulation only. Not financial advice. "
148
  "No real capital involved.**\n\n"
149
  f"{narrative}\n\n"
150
  "---\n"
151
- "**To act on a proposal:**\n"
152
- "- βœ… `/poly trade approve <proposal_id>` β€” add to paper portfolio\n"
153
- "- ❌ `/poly trade reject <proposal_id>` β€” reject with optional reason\n"
154
- "- πŸ” `/poly trade revise <proposal_id>` β€” send back for revision\n\n"
155
- "To view paper portfolio: `/poly portfolio`"
156
  )
157
 
158
  return AgentResponse(
159
  agent_role=self.role,
160
  content=content,
161
- mentions=["human"],
162
  artifact_path=artifact_path,
163
  artifact_mode="overwrite",
164
  updates_state=bool(state_patch),
@@ -225,8 +221,8 @@ After proposals, summarise which signals were excluded and why.
225
  - NEVER propose a Reject-rated signal.
226
  - Elevated signals MUST include a mitigation note.
227
  - This is paper trading only β€” no real capital, no financial advice.
228
- - You must ALWAYS route to @human β€” override routing JSON:
229
- {{"next": "human", "reason": "Trade proposals ready for human review."}}
230
 
231
  ## [5] STRUCTURED OUTPUT (REQUIRED)
232
  After the routing JSON, you MUST append a structured proposals JSON block:
 
42
  "Your job is to synthesise technical analysis, sentiment analysis, backtest results, "
43
  "and risk assessments into a maximum of 3 concrete paper trade proposals. "
44
  "Every proposal must include full rationale and a risk rating from RiskAnalyst. "
45
+ "You must ALWAYS route to @publisher so Finley can write the market post next."
46
  )
47
  token_budget = TokenBudget(system=500, context=2000, task=500, thread=500, routing=200, total=4000)
48
 
 
143
  )
144
 
145
  content = (
146
+ "πŸ“‹ **QuantStrategist** β€” Paper trade proposals ready. Sending to Finley πŸ“ for market post.\n\n"
147
  "**⚠️ DISCLAIMER: Paper trading simulation only. Not financial advice. "
148
  "No real capital involved.**\n\n"
149
  f"{narrative}\n\n"
150
  "---\n"
151
+ "_Finley will write a market post. You'll be able to review and approve trades after._"
 
 
 
 
152
  )
153
 
154
  return AgentResponse(
155
  agent_role=self.role,
156
  content=content,
157
+ mentions=["publisher"],
158
  artifact_path=artifact_path,
159
  artifact_mode="overwrite",
160
  updates_state=bool(state_patch),
 
221
  - NEVER propose a Reject-rated signal.
222
  - Elevated signals MUST include a mitigation note.
223
  - This is paper trading only β€” no real capital, no financial advice.
224
+ - You must ALWAYS route to @publisher β€” override routing JSON:
225
+ {{"next": "publisher", "reason": "Trade proposals ready β€” sending to Finley for market post."}}
226
 
227
  ## [5] STRUCTURED OUTPUT (REQUIRED)
228
  After the routing JSON, you MUST append a structured proposals JSON block:
src/polyhedra/agents/quant/routing.py CHANGED
@@ -27,6 +27,7 @@ QUANT_ROLES: frozenset[str] = frozenset({
27
  "quantstrategist",
28
  "vizagent",
29
  "portfoliomonitor",
 
30
  "human",
31
  })
32
 
@@ -39,7 +40,8 @@ LLM_ROUTING_PROMPT = """
39
  After completing your analysis above, decide who should be involved next.
40
 
41
  Available quant roles: datafetcher, trendanalyst, sentimentanalyst,
42
- quantresearcher, backtester, riskanalyst, quantstrategist, human
 
43
 
44
  Rules:
45
  - Choose exactly ONE role (or null if work is complete).
 
27
  "quantstrategist",
28
  "vizagent",
29
  "portfoliomonitor",
30
+ "publisher",
31
  "human",
32
  })
33
 
 
40
  After completing your analysis above, decide who should be involved next.
41
 
42
  Available quant roles: datafetcher, trendanalyst, sentimentanalyst,
43
+ quantresearcher, backtester, riskanalyst, quantstrategist,
44
+ publisher, vizagent, portfoliomonitor, human
45
 
46
  Rules:
47
  - Choose exactly ONE role (or null if work is complete).
src/polyhedra/core/agent_router.py CHANGED
@@ -20,6 +20,7 @@ QUANT_ROLES: frozenset[str] = frozenset({
20
  "quantstrategist",
21
  "vizagent",
22
  "portfoliomonitor",
 
23
  })
24
 
25
  # V4.2 β€” sensible skip-forward alternative per pipeline stage (FR-1.5)
@@ -29,7 +30,8 @@ ALT_AGENT_MAP: dict[str, str] = {
29
  "quantresearcher": "backtester",
30
  "backtester": "riskanalyst",
31
  "riskanalyst": "quantstrategist",
32
- "quantstrategist": "human",
 
33
  }
34
 
35
 
@@ -53,8 +55,14 @@ class AgentRouter:
53
  self._mention_depth[origin_id] = 0
54
  self._quant_mention_depth[origin_id] = 0
55
 
56
- def can_dispatch(self, origin_id: str, role: str) -> bool:
57
- """Return ``True`` if chain has not yet reached the depth limit."""
 
 
 
 
 
 
58
  depth_dict = self._quant_mention_depth if role in QUANT_ROLES else self._mention_depth
59
  return depth_dict.get(origin_id, 0) < _MAX_MENTION_DEPTH
60
 
 
20
  "quantstrategist",
21
  "vizagent",
22
  "portfoliomonitor",
23
+ "publisher", # V5.0
24
  })
25
 
26
  # V4.2 β€” sensible skip-forward alternative per pipeline stage (FR-1.5)
 
30
  "quantresearcher": "backtester",
31
  "backtester": "riskanalyst",
32
  "riskanalyst": "quantstrategist",
33
+ "quantstrategist": "publisher", # V5.0: route to publisher before human
34
+ "portfoliomonitor": "human",
35
  }
36
 
37
 
 
55
  self._mention_depth[origin_id] = 0
56
  self._quant_mention_depth[origin_id] = 0
57
 
58
+ def can_dispatch(self, origin_id: str, role: str, mode: str = "investigation") -> bool:
59
+ """Return ``True`` if chain has not yet reached the depth limit.
60
+
61
+ In YOLO mode, quant-pipeline depth-3 checkpoints are always bypassed
62
+ (FR-9.5 V5.0).
63
+ """
64
+ if mode == "yolo" and role in QUANT_ROLES:
65
+ return True
66
  depth_dict = self._quant_mention_depth if role in QUANT_ROLES else self._mention_depth
67
  return depth_dict.get(origin_id, 0) < _MAX_MENTION_DEPTH
68
 
src/polyhedra/core/research_state.py CHANGED
@@ -187,6 +187,9 @@ class QuantState:
187
  last_monitor_run: str | None = None
188
  # V4.3 token usage log
189
  token_log: list["TokenUsageEntry"] = dc_field(default_factory=list)
 
 
 
190
 
191
  def to_dict(self) -> dict:
192
  from dataclasses import asdict as _asdict
@@ -202,6 +205,9 @@ class QuantState:
202
  qs.risk_ratings = data.get("risk_ratings", {})
203
  qs.monitor_paused = data.get("monitor_paused", False)
204
  qs.last_monitor_run = data.get("last_monitor_run")
 
 
 
205
 
206
  qs.signals = [
207
  Signal(**{k: v for k, v in s.items() if k in Signal.__dataclass_fields__})
 
187
  last_monitor_run: str | None = None
188
  # V4.3 token usage log
189
  token_log: list["TokenUsageEntry"] = dc_field(default_factory=list)
190
+ # V5.0 session mode
191
+ mode: str = "investigation" # "investigation" | "yolo"
192
+ yolo_status_ts: str | None = None # Slack message ts for chat.update in YOLO mode
193
 
194
  def to_dict(self) -> dict:
195
  from dataclasses import asdict as _asdict
 
205
  qs.risk_ratings = data.get("risk_ratings", {})
206
  qs.monitor_paused = data.get("monitor_paused", False)
207
  qs.last_monitor_run = data.get("last_monitor_run")
208
+ # V5.0
209
+ qs.mode = data.get("mode", "investigation")
210
+ qs.yolo_status_ts = data.get("yolo_status_ts")
211
 
212
  qs.signals = [
213
  Signal(**{k: v for k, v in s.items() if k in Signal.__dataclass_fields__})
src/polyhedra/messaging/slack.py CHANGED
@@ -1,4 +1,4 @@
1
- """Slack integration for Polyhedra v3.0 / v4.5.
2
 
3
  Receives Slack events (slash commands + @mentions via Events API),
4
  maps them to CoordinatorService.dispatch(), and posts responses back.
@@ -86,8 +86,13 @@ _ROLE_DISPLAY: dict[str, str] = {
86
  # V4.2 additions
87
  "vizagent": "VizAgent πŸ“Š",
88
  "portfoliomonitor": "PortfolioMonitor πŸ””",
 
 
89
  }
90
 
 
 
 
91
  # V4.4 FIX-3 (FR-3.3): _parse_proposal_block() has been removed.
92
  # All proposal parsing now goes through parse_proposals_block() in
93
  # agents/quant/routing.py.
@@ -192,13 +197,17 @@ class SlackIntegration:
192
  await self._cmd_monitor(client, channel_id, args)
193
  elif sub == "goal":
194
  await self._cmd_goal(client, channel_id, args)
 
 
195
  else:
196
  await client.chat_postMessage(
197
  channel=channel_id,
198
  text=(
199
- "*Polyhedra v4.5* β€” available commands:\n"
200
  "β€’ `/poly init <goal>` β€” start a new research session\n"
201
  "β€’ `/poly init <goal> --force` β€” replace existing session\n"
 
 
202
  "β€’ `/poly goal <text>` β€” update session goal\n"
203
  "β€’ `/poly state` β€” show the current Research State\n"
204
  "β€’ `/poly export` β€” export all artifacts as a zip\n"
@@ -243,7 +252,9 @@ class SlackIntegration:
243
  init_match = re.match(r"^init\s+(.*)", text, re.IGNORECASE)
244
  if init_match:
245
  goal = init_match.group(1).strip().strip('"')
246
- await self._init_from_mention(channel_id, goal, say)
 
 
247
  return
248
 
249
  # V4.5 FR-7.1: @coordinator goal "<text>" β€” update session goal
@@ -252,6 +263,11 @@ class SlackIntegration:
252
  await self._cmd_goal_from_mention(channel_id, goal_match.group(1).strip(), say)
253
  return
254
 
 
 
 
 
 
255
  # Mirror slash-command shortcuts so @Bot <cmd> <args> works too
256
  # Also handle bare action words: "approve P001", "reject P001", etc.
257
  _bare_action = re.match(
@@ -262,7 +278,7 @@ class SlackIntegration:
262
  text = f"trade {text}" # normalise β†’ "trade approve P001 ..."
263
 
264
  _mention_cmds = re.match(
265
- r"^(watchlist|quant|portfolio|trade|export|proposals|monitor|help|status|role|checkpoint)\b(.*)",
266
  text, re.IGNORECASE,
267
  )
268
  if _mention_cmds:
@@ -304,6 +320,8 @@ class SlackIntegration:
304
  await self._cmd_state(client, channel_id)
305
  elif cmd == "role":
306
  await self._cmd_role(client, channel_id, args)
 
 
307
  return
308
 
309
  service = self._sessions.get(channel_id)
@@ -341,13 +359,13 @@ class SlackIntegration:
341
  logger.exception("dispatch failed: %s", exc)
342
  await say(f"⚠️ Error during dispatch: {exc}")
343
 
344
- async def _init_from_mention(self, channel_id: str, goal: str, say: Any) -> None:
345
  """Start a new session when triggered via @mention init."""
346
  from polyhedra.agents.coordinator import CoordinatorService
347
  from polyhedra.agents.quant import (
348
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
349
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
350
- VizAgent, PortfolioMonitorAgent,
351
  )
352
  from polyhedra.core.role_registry import RoleEntry
353
  from polyhedra.core.session import SessionManager
@@ -366,6 +384,7 @@ class SlackIntegration:
366
  (QuantStrategistAgent, "quantstrategist"),
367
  (VizAgent, "vizagent"),
368
  (PortfolioMonitorAgent, "portfoliomonitor"),
 
369
  ]:
370
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
371
 
@@ -378,13 +397,34 @@ class SlackIntegration:
378
  await say(f"⏸ Checkpoint: {summary}")
379
  return CheckpointResult(approved=True)
380
 
381
- service = CoordinatorService(session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
  self._sessions[channel_id] = service
383
 
384
  selected_roles = [
385
  "datafetcher", "trendanalyst", "sentimentanalyst",
386
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
387
- "vizagent", "portfoliomonitor",
388
  ]
389
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
390
 
@@ -394,6 +434,9 @@ class SlackIntegration:
394
  goal: str,
395
  tickers: list[str],
396
  say: Any,
 
 
 
397
  ) -> None:
398
  """Auto-create a session from detected tickers (V4.5 FR-2).
399
 
@@ -404,7 +447,7 @@ class SlackIntegration:
404
  from polyhedra.agents.quant import (
405
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
406
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
407
- VizAgent, PortfolioMonitorAgent,
408
  )
409
  from polyhedra.core.research_state import ResearchStateManager, QuantState
410
  from polyhedra.core.role_registry import RoleEntry
@@ -443,6 +486,7 @@ class SlackIntegration:
443
  (QuantStrategistAgent, "quantstrategist"),
444
  (VizAgent, "vizagent"),
445
  (PortfolioMonitorAgent, "portfoliomonitor"),
 
446
  ]:
447
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
448
 
@@ -455,21 +499,43 @@ class SlackIntegration:
455
  await say(f"⏸ Checkpoint: {summary}")
456
  return CheckpointResult(approved=True)
457
 
458
- service = CoordinatorService(session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  self._sessions[channel_id] = service
460
 
461
  selected_roles = [
462
  "datafetcher", "trendanalyst", "sentimentanalyst",
463
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
464
- "vizagent", "portfoliomonitor",
465
  ]
466
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
467
 
468
  # FR-2.3 β€” concise confirmation posted before dispatch proceeds
469
  wl_str = " | ".join(watchlist) if watchlist else "none"
 
470
  await say(
471
  f"πŸš€ Session started β€” {goal}\n"
472
- f" Watchlist: {wl_str} | Run `@PolyTest help` for commands."
473
  )
474
 
475
  async def _cmd_goal_from_mention(self, channel_id: str, new_goal: str, say: Any) -> None:
@@ -482,6 +548,36 @@ class SlackIntegration:
482
  service.session.save_meta()
483
  await say(f'βœ… Session goal updated: _{new_goal}_')
484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
485
  # ------------------------------------------------------------------ #
486
  # Command implementations
487
  # ------------------------------------------------------------------ #
@@ -491,14 +587,15 @@ class SlackIntegration:
491
  from polyhedra.agents.quant import (
492
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
493
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
494
- VizAgent, PortfolioMonitorAgent,
495
  )
496
  from polyhedra.core.role_registry import RoleEntry
497
  from polyhedra.core.session import SessionManager
498
 
499
- # V4.5 FR-5.2/FR-5.3 β€” parse optional "--force" flag
500
  force = "--force" in args
501
- goal = args.replace("--force", "").strip().strip('"') or "New research session"
 
502
 
503
  # Warn if a session already exists and --force not provided (FR-5.2)
504
  existing = self._sessions.get(channel_id)
@@ -533,6 +630,7 @@ class SlackIntegration:
533
  (QuantStrategistAgent, "quantstrategist"),
534
  (VizAgent, "vizagent"),
535
  (PortfolioMonitorAgent, "portfoliomonitor"),
 
536
  ]:
537
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
538
 
@@ -549,13 +647,34 @@ class SlackIntegration:
549
  )
550
  return CheckpointResult(approved=True)
551
 
552
- service = CoordinatorService(session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
553
  self._sessions[channel_id] = service
554
 
555
  selected_roles = [
556
  "datafetcher", "trendanalyst", "sentimentanalyst",
557
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
558
- "vizagent", "portfoliomonitor",
559
  ]
560
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
561
 
 
1
+ """Slack integration for Polyhedra v5.0.
2
 
3
  Receives Slack events (slash commands + @mentions via Events API),
4
  maps them to CoordinatorService.dispatch(), and posts responses back.
 
86
  # V4.2 additions
87
  "vizagent": "VizAgent πŸ“Š",
88
  "portfoliomonitor": "PortfolioMonitor πŸ””",
89
+ # V5.0 addition
90
+ "publisher": "Finley πŸ“",
91
  }
92
 
93
+ # V5.0 β€” shared constant for the YOLO session-start banner
94
+ _YOLO_START_MSG = "⚑ *YOLO run started* β€” pipeline running silently, Finley will post when done."
95
+
96
  # V4.4 FIX-3 (FR-3.3): _parse_proposal_block() has been removed.
97
  # All proposal parsing now goes through parse_proposals_block() in
98
  # agents/quant/routing.py.
 
197
  await self._cmd_monitor(client, channel_id, args)
198
  elif sub == "goal":
199
  await self._cmd_goal(client, channel_id, args)
200
+ elif sub == "mode":
201
+ await self._cmd_mode(client, channel_id)
202
  else:
203
  await client.chat_postMessage(
204
  channel=channel_id,
205
  text=(
206
+ "*Polyhedra v5.0* β€” available commands:\n"
207
  "β€’ `/poly init <goal>` β€” start a new research session\n"
208
  "β€’ `/poly init <goal> --force` β€” replace existing session\n"
209
+ "β€’ `/poly init <goal> --yolo` β€” silent YOLO run (Finley posts at end)\n"
210
+ "β€’ `/poly mode` β€” show current session mode\n"
211
  "β€’ `/poly goal <text>` β€” update session goal\n"
212
  "β€’ `/poly state` β€” show the current Research State\n"
213
  "β€’ `/poly export` β€” export all artifacts as a zip\n"
 
252
  init_match = re.match(r"^init\s+(.*)", text, re.IGNORECASE)
253
  if init_match:
254
  goal = init_match.group(1).strip().strip('"')
255
+ yolo = "--yolo" in goal
256
+ goal = goal.replace("--yolo", "").strip()
257
+ await self._init_from_mention(channel_id, goal, say, yolo=yolo, bolt_client=bolt_client)
258
  return
259
 
260
  # V4.5 FR-7.1: @coordinator goal "<text>" β€” update session goal
 
263
  await self._cmd_goal_from_mention(channel_id, goal_match.group(1).strip(), say)
264
  return
265
 
266
+ # V5.0: @coordinator mode β€” show current session mode
267
+ if re.match(r'^mode\s*$', text, re.IGNORECASE):
268
+ await self._cmd_mode_from_mention(channel_id, say)
269
+ return
270
+
271
  # Mirror slash-command shortcuts so @Bot <cmd> <args> works too
272
  # Also handle bare action words: "approve P001", "reject P001", etc.
273
  _bare_action = re.match(
 
278
  text = f"trade {text}" # normalise β†’ "trade approve P001 ..."
279
 
280
  _mention_cmds = re.match(
281
+ r"^(watchlist|quant|portfolio|trade|export|proposals|monitor|help|status|role|checkpoint|mode)\b(.*)",
282
  text, re.IGNORECASE,
283
  )
284
  if _mention_cmds:
 
320
  await self._cmd_state(client, channel_id)
321
  elif cmd == "role":
322
  await self._cmd_role(client, channel_id, args)
323
+ elif cmd == "mode":
324
+ await self._cmd_mode(client, channel_id)
325
  return
326
 
327
  service = self._sessions.get(channel_id)
 
359
  logger.exception("dispatch failed: %s", exc)
360
  await say(f"⚠️ Error during dispatch: {exc}")
361
 
362
+ async def _init_from_mention(self, channel_id: str, goal: str, say: Any, *, yolo: bool = False, bolt_client: Any = None) -> None:
363
  """Start a new session when triggered via @mention init."""
364
  from polyhedra.agents.coordinator import CoordinatorService
365
  from polyhedra.agents.quant import (
366
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
367
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
368
+ VizAgent, PortfolioMonitorAgent, PublisherAgent,
369
  )
370
  from polyhedra.core.role_registry import RoleEntry
371
  from polyhedra.core.session import SessionManager
 
384
  (QuantStrategistAgent, "quantstrategist"),
385
  (VizAgent, "vizagent"),
386
  (PortfolioMonitorAgent, "portfoliomonitor"),
387
+ (PublisherAgent, "publisher"),
388
  ]:
389
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
390
 
 
397
  await say(f"⏸ Checkpoint: {summary}")
398
  return CheckpointResult(approved=True)
399
 
400
+ # V5.0: YOLO mode wiring
401
+ mode = "yolo" if yolo else "investigation"
402
+ yolo_update_fn = None
403
+ if yolo and bolt_client is not None:
404
+ init_resp = await bolt_client.chat_postMessage(
405
+ channel=channel_id,
406
+ text=_YOLO_START_MSG,
407
+ )
408
+ yolo_ts: str | None = init_resp.get("ts")
409
+
410
+ async def _yolo_update(status_text: str) -> None:
411
+ if yolo_ts:
412
+ await bolt_client.chat_update(
413
+ channel=channel_id, ts=yolo_ts, text=status_text
414
+ )
415
+
416
+ yolo_update_fn = _yolo_update
417
+
418
+ service = CoordinatorService(
419
+ session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn,
420
+ mode=mode, yolo_update_fn=yolo_update_fn,
421
+ )
422
  self._sessions[channel_id] = service
423
 
424
  selected_roles = [
425
  "datafetcher", "trendanalyst", "sentimentanalyst",
426
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
427
+ "vizagent", "portfoliomonitor", "publisher",
428
  ]
429
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
430
 
 
434
  goal: str,
435
  tickers: list[str],
436
  say: Any,
437
+ *,
438
+ yolo: bool = False,
439
+ bolt_client: Any = None,
440
  ) -> None:
441
  """Auto-create a session from detected tickers (V4.5 FR-2).
442
 
 
447
  from polyhedra.agents.quant import (
448
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
449
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
450
+ VizAgent, PortfolioMonitorAgent, PublisherAgent,
451
  )
452
  from polyhedra.core.research_state import ResearchStateManager, QuantState
453
  from polyhedra.core.role_registry import RoleEntry
 
486
  (QuantStrategistAgent, "quantstrategist"),
487
  (VizAgent, "vizagent"),
488
  (PortfolioMonitorAgent, "portfoliomonitor"),
489
+ (PublisherAgent, "publisher"),
490
  ]:
491
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
492
 
 
499
  await say(f"⏸ Checkpoint: {summary}")
500
  return CheckpointResult(approved=True)
501
 
502
+ # V5.0: YOLO mode wiring
503
+ mode = "yolo" if yolo else "investigation"
504
+ yolo_update_fn = None
505
+ if yolo and bolt_client is not None:
506
+ init_resp = await bolt_client.chat_postMessage(
507
+ channel=channel_id,
508
+ text=_YOLO_START_MSG,
509
+ )
510
+ yolo_ts: str | None = init_resp.get("ts")
511
+
512
+ async def _yolo_update(status_text: str) -> None:
513
+ if yolo_ts:
514
+ await bolt_client.chat_update(
515
+ channel=channel_id, ts=yolo_ts, text=status_text
516
+ )
517
+
518
+ yolo_update_fn = _yolo_update
519
+
520
+ service = CoordinatorService(
521
+ session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn,
522
+ mode=mode, yolo_update_fn=yolo_update_fn,
523
+ )
524
  self._sessions[channel_id] = service
525
 
526
  selected_roles = [
527
  "datafetcher", "trendanalyst", "sentimentanalyst",
528
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
529
+ "vizagent", "portfoliomonitor", "publisher",
530
  ]
531
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
532
 
533
  # FR-2.3 β€” concise confirmation posted before dispatch proceeds
534
  wl_str = " | ".join(watchlist) if watchlist else "none"
535
+ mode_hint = " | ⚑ YOLO mode active" if yolo else ""
536
  await say(
537
  f"πŸš€ Session started β€” {goal}\n"
538
+ f" Watchlist: {wl_str}{mode_hint} | Run `@PolyTest help` for commands."
539
  )
540
 
541
  async def _cmd_goal_from_mention(self, channel_id: str, new_goal: str, say: Any) -> None:
 
548
  service.session.save_meta()
549
  await say(f'βœ… Session goal updated: _{new_goal}_')
550
 
551
+ async def _cmd_mode(self, client: Any, channel_id: str) -> None:
552
+ """Handle `/poly mode` slash command β€” report current session mode (V5.0)."""
553
+ service = self._sessions.get(channel_id)
554
+ if not service:
555
+ await client.chat_postMessage(channel=channel_id, text="No active session.")
556
+ return
557
+ mode = getattr(service, "_mode", "investigation")
558
+ if mode == "yolo":
559
+ await client.chat_postMessage(
560
+ channel=channel_id,
561
+ text="⚑ *YOLO mode* β€” pipeline runs silently, Finley posts at end.",
562
+ )
563
+ else:
564
+ await client.chat_postMessage(
565
+ channel=channel_id,
566
+ text="πŸ” *Investigation mode* β€” full visibility, checkpoints enabled.",
567
+ )
568
+
569
+ async def _cmd_mode_from_mention(self, channel_id: str, say: Any) -> None:
570
+ """Handle `@coordinator mode` mention β€” report current session mode (V5.0)."""
571
+ service = self._sessions.get(channel_id)
572
+ if not service:
573
+ await say("No active session.")
574
+ return
575
+ mode = getattr(service, "_mode", "investigation")
576
+ if mode == "yolo":
577
+ await say("⚑ *YOLO mode* β€” pipeline runs silently, Finley posts at end.")
578
+ else:
579
+ await say("πŸ” *Investigation mode* β€” full visibility, checkpoints enabled.")
580
+
581
  # ------------------------------------------------------------------ #
582
  # Command implementations
583
  # ------------------------------------------------------------------ #
 
587
  from polyhedra.agents.quant import (
588
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
589
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
590
+ VizAgent, PortfolioMonitorAgent, PublisherAgent,
591
  )
592
  from polyhedra.core.role_registry import RoleEntry
593
  from polyhedra.core.session import SessionManager
594
 
595
+ # V4.5 FR-5.2/FR-5.3 β€” parse optional "--force" flag; V5.0 β€” parse "--yolo" flag
596
  force = "--force" in args
597
+ yolo = "--yolo" in args
598
+ goal = args.replace("--force", "").replace("--yolo", "").strip().strip('"') or "New research session"
599
 
600
  # Warn if a session already exists and --force not provided (FR-5.2)
601
  existing = self._sessions.get(channel_id)
 
630
  (QuantStrategistAgent, "quantstrategist"),
631
  (VizAgent, "vizagent"),
632
  (PortfolioMonitorAgent, "portfoliomonitor"),
633
+ (PublisherAgent, "publisher"),
634
  ]:
635
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
636
 
 
647
  )
648
  return CheckpointResult(approved=True)
649
 
650
+ # V5.0: YOLO mode wiring for _cmd_init
651
+ mode_cmd = "yolo" if yolo else "investigation"
652
+ yolo_update_fn_cmd = None
653
+ if yolo:
654
+ init_resp = await client.chat_postMessage(
655
+ channel=channel_id,
656
+ text=_YOLO_START_MSG,
657
+ )
658
+ yolo_ts_cmd: str | None = init_resp.get("ts")
659
+
660
+ async def _yolo_update_cmd(status_text: str) -> None:
661
+ if yolo_ts_cmd:
662
+ await client.chat_update(
663
+ channel=channel_id, ts=yolo_ts_cmd, text=status_text
664
+ )
665
+
666
+ yolo_update_fn_cmd = _yolo_update_cmd
667
+
668
+ service = CoordinatorService(
669
+ session=session, post_fn=post_fn, checkpoint_fn=checkpoint_fn,
670
+ mode=mode_cmd, yolo_update_fn=yolo_update_fn_cmd,
671
+ )
672
  self._sessions[channel_id] = service
673
 
674
  selected_roles = [
675
  "datafetcher", "trendanalyst", "sentimentanalyst",
676
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
677
+ "vizagent", "portfoliomonitor", "publisher",
678
  ]
679
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
680