File size: 13,773 Bytes
a526b57
 
 
 
 
 
 
 
7ba97b7
a526b57
f816c35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ba97b7
f816c35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ba97b7
 
 
 
 
 
f816c35
 
 
 
 
 
a526b57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b107c4a
 
 
 
 
 
 
a526b57
d1a28b0
 
 
 
b107c4a
 
 
a526b57
b107c4a
 
 
 
 
a526b57
b107c4a
 
 
a526b57
b107c4a
 
 
 
 
 
a526b57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""TemplateBuilder β€” input template generation and command registry.

Extracted from CoordinatorService as part of STRUCT-1 (V4.4).
STRUCT-4 CommandEntry / COMMAND_REGISTRY also live here (FR-S4.2).
"""

from __future__ import annotations

import json
from dataclasses import dataclass
from string import Formatter
from typing import Any, Callable, Generic, TypeVar

from pydantic import BaseModel

from polyhedra.core.quant_contracts import AgentName

InputModel = TypeVar("InputModel", bound=BaseModel)
OutputModel = TypeVar("OutputModel", bound=BaseModel)


@dataclass(frozen=True)
class AgentIOTemplate(Generic[InputModel, OutputModel]):
    """Bind one agent's schemas to its prompt and human-readable renderer.

    The caller supplies an ACL-filtered typed input. This binding neither reads
    files nor grants permissions. Concrete bindings are added during migration.
    """

    agent: AgentName
    input_schema: type[InputModel]
    output_schema: type[OutputModel]
    prompt_template: str
    markdown_renderer: Callable[[OutputModel], str]
    prompt_projector: Callable[[InputModel], BaseModel | dict[str, Any]] | None = None

    def __post_init__(self) -> None:
        from typing import get_args

        if self.agent not in get_args(AgentName):
            raise ValueError("unknown quant agent")
        fields = []
        for _, field, spec, conversion in Formatter().parse(self.prompt_template):
            if field is not None:
                if field != "input_json" or spec or conversion:
                    raise ValueError("prompt accepts only the input_json placeholder")
                fields.append(field)
        if fields != ["input_json"]:
            raise ValueError("prompt requires exactly one input_json placeholder")

    def build_prompt(self, inputs: InputModel) -> str:
        if type(inputs) is not self.input_schema:
            raise TypeError("input does not match this agent's concrete schema")
        snapshot = self.input_schema.model_validate_json(inputs.model_dump_json(), strict=True)
        prompt_input = self.prompt_projector(snapshot) if self.prompt_projector else snapshot
        if isinstance(prompt_input, BaseModel):
            input_json = prompt_input.model_dump_json(indent=2)
        else:
            input_json = json.dumps(prompt_input, indent=2, ensure_ascii=True, allow_nan=False)
        return self.prompt_template.format(input_json=input_json)

    def render_markdown(self, output: OutputModel) -> str:
        if type(output) is not self.output_schema:
            raise TypeError("output does not match this agent's concrete schema")
        validated = self.output_schema.model_validate_json(output.model_dump_json(), strict=True)
        return self.markdown_renderer(validated)


# --------------------------------------------------------------------------- #
# STRUCT-4 β€” Command registry (FR-S4.2 / FR-S4.3)
# --------------------------------------------------------------------------- #

@dataclass
class CommandEntry:
    """Single entry in the Polyhedra command registry."""

    group: str
    slash: str
    mention: str
    cli: str
    description: str


COMMAND_REGISTRY: list[CommandEntry] = [
    # Session
    CommandEntry("Session",   '/poly init "<goal>"',              '@coordinator init "<goal>"',              "poly init",              "Start a new session"),
    CommandEntry("Session",   '/poly init "<goal>" --force',      "β€”",                                       "β€”",                      "Force replace active session"),
    CommandEntry("Session",   '/poly goal "<text>"',              '@coordinator goal "<text>"',              'poly goal "<text>"',     "Update session goal"),
    CommandEntry("Session",   "/poly state",                      "@coordinator state",                      "poly state",             "Print current ResearchState"),
    CommandEntry("Session",   "/poly resume",                     "@coordinator resume",                     "poly resume",            "Resume after a checkpoint"),
    CommandEntry("Session",   "/poly stop",                       "@coordinator stop",                       "β€”",                      "End the current chain"),
    CommandEntry("Session",   "/poly export",                     "@coordinator export",                     "poly export",            "Export artifacts to zip"),
    # Quant
    CommandEntry("Quant",     "/poly quant",                      "@PolyTest quant",                         "β€”",                      "Run the governed quant workflow"),
    CommandEntry("Quant",     "/poly quant <ticker>",             "@PolyTest quant <ticker>",                "β€”",                      "Run the governed workflow for a ticker"),
    CommandEntry("Quant",     "/poly yolo <ticker>",              "@PolyTest yolo <ticker>",                 "β€”",                      "Run baseline or session-delta YOLO"),
    CommandEntry("Quant",     "/poly chart <type> [ticker]",      "@PolyTest chart <type> [ticker]",         "β€”",                      "Render a typed chart from a completed run"),
    CommandEntry("Quant",     "/poly watchlist",                  "@coordinator watchlist",                  "β€”",                      "Show current watchlist"),
    CommandEntry("Quant",     "/poly watchlist add <tickers>",    "@coordinator watchlist add <tickers>",    "β€”",                      "Add tickers to watchlist"),
    CommandEntry("Quant",     "/poly watchlist remove <tickers>", "@coordinator watchlist remove <tickers>", "β€”",                      "Remove tickers from watchlist"),
    # Portfolio
    CommandEntry("Portfolio", "/poly portfolio",                  "@coordinator portfolio",                  "β€”",                      "Show paper portfolio and P&L"),
    CommandEntry("Portfolio", "/poly trade approve <id>",         "@coordinator trade approve <id>",         "β€”",                      "Approve a trade proposal"),
    CommandEntry("Portfolio", "/poly trade reject <id>",          "@coordinator trade reject <id>",          "β€”",                      "Reject a trade proposal"),
    CommandEntry("Portfolio", "/poly trade revise <id>",          "@coordinator trade revise <id>",          "β€”",                      "Send proposal back for revision"),
    CommandEntry("Portfolio", "/poly trade close <id>",           "@coordinator trade close <id>",           "β€”",                      "Close a paper position"),
    # Monitor
    CommandEntry("Monitor",   "/poly monitor pause",              "@coordinator monitor pause",              "β€”",                      "Pause scheduled monitoring"),
    CommandEntry("Monitor",   "/poly monitor resume",             "@coordinator monitor resume",             "β€”",                      "Resume scheduled monitoring"),
    CommandEntry("Monitor",   "/poly monitor interval <min>",     "@coordinator monitor interval <min>",     "β€”",                      "Change monitor interval"),
    # System
    CommandEntry("System",    "/poly trace",                      "@coordinator trace",                      "poly trace",             "Show last 10 trace entries"),
    CommandEntry("System",    "/poly tokens",                     "@coordinator tokens",                     "poly tokens",            "Show token usage and cost"),
    CommandEntry("System",    "/poly cache clear",                "@coordinator cache clear",                "poly cache stats",       "Flush session cache"),
    CommandEntry("System",    "/poly cache status",               "@coordinator cache status",               "β€”",                      "Show cache hit/miss stats"),
    CommandEntry("System",    "/poly role <name> human|agent",    "@coordinator role <name> human|agent",    "poly role take|release", "Take over or reinstate a role"),
    CommandEntry("System",    "/poly help",                       "@coordinator help",                       "poly help",              "Show this menu"),
]


def render_help_slack() -> str:
    """Render ``COMMAND_REGISTRY`` as a Slack-formatted command menu (FR-S4.4)."""
    from itertools import groupby

    lines = ["πŸ“‹ *Polyhedra β€” Commands*\n"]
    groups = groupby(COMMAND_REGISTRY, key=lambda e: e.group)
    for group_name, entries in groups:
        lines.append(f"*{group_name.upper()}*")
        for entry in entries:
            lines.append(f"  `{entry.slash:<45}` `{entry.mention:<50}` _{entry.description}_")
        lines.append("")
    return "\n".join(lines)


def render_help_cli() -> str:
    """Render ``COMMAND_REGISTRY`` as a plain-text table for CLI output (FR-S4.5).

    Callers that import ``rich`` can pass the string through ``rich.Markdown``
    for coloured output.
    """
    from itertools import groupby

    lines = ["Polyhedra β€” Commands\n"]
    groups = groupby(COMMAND_REGISTRY, key=lambda e: e.group)
    for group_name, entries in groups:
        lines.append(group_name.upper())
        for entry in entries:
            lines.append(
                f"  {entry.slash:<45}  {entry.mention:<50}  {entry.cli:<25}  {entry.description}"
            )
        lines.append("")
    return "\n".join(lines)


# --------------------------------------------------------------------------- #
# STRUCT-1 β€” TemplateBuilder (FR-S1.2)
# --------------------------------------------------------------------------- #

_STOP = "/poly stop"
_QUANT_REPORT = "/poly quant report"

# Import at class level to avoid circular imports at module load
def _alt_agent_map() -> dict[str, str]:
    from polyhedra.core.agent_router import ALT_AGENT_MAP
    return ALT_AGENT_MAP


class TemplateBuilder:
    """Generates ranked, pre-filled input templates for human touchpoints.

    Rule-based β€” no LLM call (FR-1.4). Stateless.
    """

    def build(
        self,
        touchpoint: str,
        *,
        next_role: str | None = None,
        proposal_id: str | None = None,
        session_id: str | None = None,
    ) -> str:
        """Return a formatted Slack/CLI string of suggested next messages."""
        options = self._options(
            touchpoint,
            next_role=next_role,
            proposal_id=proposal_id,
            session_id=session_id,
        )
        if not options:
            return ""
        lines = ["\nπŸ’¬ *Suggested next messages:*\n"]
        for i, (msg, desc) in enumerate(options, 1):
            lines.append(f"{i}. > `{msg}`")
            lines.append(f"   _{desc}_")
            lines.append("")
        return "\n".join(lines)

    def _options(
        self,
        touchpoint: str,
        *,
        next_role: str | None,
        proposal_id: str | None,
        session_id: str | None,
    ) -> list[tuple[str, str]]:
        builders = {
            "checkpoint":      self._opts_checkpoint,
            "trade_proposals": self._opts_trade_proposals,
            "agent_blocked":   self._opts_agent_blocked,
            "uncertainty":     self._opts_uncertainty,
            "resume":          self._opts_resume,
        }
        builder = builders.get(touchpoint)
        if builder is None:
            return [(_STOP, "Stop the pipeline.")]
        return builder(next_role=next_role, proposal_id=proposal_id, session_id=session_id)

    def _opts_checkpoint(
        self, *, next_role: str | None, **_: Any
    ) -> list[tuple[str, str]]:
        alt = _alt_agent_map().get(next_role or "") if next_role else None
        opts: list[tuple[str, str]] = []
        if next_role:
            opts.append((f"@PolyTest @{next_role} continue", f"Recommended β€” continue to @{next_role}."))
        if alt and alt != next_role and alt != "human":
            opts.append((f"@PolyTest @{alt} continue", f"Skip to @{alt} if you've already reviewed."))
        opts.append((_STOP, "Stop and review artifacts before continuing."))
        return opts

    def _opts_trade_proposals(
        self, *, proposal_id: str | None, **_: Any
    ) -> list[tuple[str, str]]:
        pid = proposal_id or "<proposal_id>"
        return [
            (f"/poly trade approve {pid}", "Approve and add to the paper portfolio."),
            (f"/poly trade reject {pid} <reason>", "Reject the proposal with an optional reason."),
            (f"/poly trade revise {pid}", "Send back to QuantStrategist for revision."),
            (_STOP, "Stop and review before deciding."),
        ]

    def _opts_agent_blocked(
        self, *, next_role: str | None, **_: Any
    ) -> list[tuple[str, str]]:
        opts: list[tuple[str, str]] = []
        if next_role:
            opts.append((
                f"@PolyTest @{next_role} continue",
                f"Dispatch @{next_role} to produce missing data.",
            ))
        opts += [
            (_QUANT_REPORT, "Check which artifacts are available."),
            (_STOP, "Stop and investigate manually."),
        ]
        return opts

    def _opts_uncertainty(
        self, *, next_role: str | None, **_: Any
    ) -> list[tuple[str, str]]:
        opts: list[tuple[str, str]] = []
        if next_role:
            opts.append((
                f"@PolyTest @{next_role} continue",
                "Proceed β€” agent flagged uncertainty, not a hard block.",
            ))
        opts += [
            (_QUANT_REPORT, "Review current state before proceeding."),
            (_STOP, "Stop and reassess."),
        ]
        return opts

    def _opts_resume(
        self, *, session_id: str | None, **_: Any
    ) -> list[tuple[str, str]]:
        sid = session_id or "<session_id>"
        return [
            (f"/poly resume {sid}", "Resume the session from where it left off."),
            (_QUANT_REPORT, "See a summary of the last quant run before resuming."),
            (_STOP, "Do not resume β€” end the pipeline here."),
        ]