File size: 11,714 Bytes
4bebf98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce77b0b
 
4bebf98
 
 
 
 
 
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
"""Packaged quant routing and filename contracts, independent of agent imports.

These declarations describe permissions; the scoped file interface enforces them.
Loading this registry does not activate or migrate the existing runtime.
"""

from enum import StrEnum
from graphlib import CycleError, TopologicalSorter
from string import Formatter
from typing import Literal, Self, get_args

from pydantic import BaseModel, ConfigDict, field_validator, model_validator

AgentName = Literal[
    "DataFetcher", "OptionsFlowWatcher", "TrendAnalyst", "SentimentAnalyst",
    "MarketEventWatcher", "MacroContextWatcher", "UnusualEventDetector", "EventRouter",
    "BTCAnalyst", "SPYAnalyst", "QQQAnalyst", "GLDAnalyst", "QuantResearcher",
    "Backtester", "RiskAnalyst", "QuantStrategist", "Publisher", "VizAgent",
    "PortfolioMonitor",
]


class Scope(StrEnum):
    QUANT = "QUANT"
    GENERAL = "GENERAL"
    SPECIALIZED = "SPECIALIZED"
    OPTIONS = "OPTIONS"


class ExecutionContext(StrEnum):
    YOLO = "YOLO"
    VISUALIZATION = "VISUALIZATION"
    PORTFOLIO_MONITOR = "PORTFOLIO_MONITOR"


class ContractModel(BaseModel):
    model_config = ConfigDict(extra="forbid", frozen=True)


class FilePermissions(ContractModel):
    read: tuple[str, ...] = ()
    create: tuple[str, ...] = ()
    edit: tuple[str, ...] = ()
    list: tuple[str, ...] = ()
    baseline_read: tuple[str, ...] = ()
    baseline_list: tuple[str, ...] = ()

    @field_validator("read", "create", "edit", "list", "baseline_read", "baseline_list")
    @classmethod
    def valid_templates(cls, paths: tuple[str, ...], info) -> tuple[str, ...]:
        if len(paths) != len(set(paths)):
            raise ValueError("duplicate filename permission")
        run_field = "baseline_run_id" if info.field_name.startswith("baseline_") else "run_id"
        for path in paths:
            if path == "quant/strategist_performance.json" and run_field == "run_id":
                continue
            if not path.startswith(f"quant/runs/{{{run_field}}}/"):
                raise ValueError("permission must bind to its declared run")
            if any(part in {"", ".", ".."} for part in path.split("/")):
                raise ValueError("permission must be a normalized session-relative filename")
            if any(char in path for char in "\\:*?[]"):
                raise ValueError("wildcards and platform-specific paths are forbidden")
            for _, field, spec, conversion in Formatter().parse(path):
                if field is not None and (field not in {run_field, "ticker"} or spec or conversion):
                    raise ValueError("unknown filename placeholder")
            if not path.endswith((".json", ".md", ".png")):
                raise ValueError("permission must name an artifact file")
        return paths

    @model_validator(mode="after")
    def edits_are_owned(self) -> Self:
        if not set(self.edit).issubset(self.create):
            raise ValueError("edit permission requires output ownership")
        return self


class AgentContract(ContractModel):
    name: AgentName
    dependencies: tuple[AgentName, ...]
    scope: Scope
    context: ExecutionContext = ExecutionContext.YOLO
    symbol: Literal["BTC", "SPY", "QQQ", "GLD"] | None = None
    permissions: FilePermissions

    @model_validator(mode="after")
    def identity(self) -> Self:
        fixed = {"BTCAnalyst": "BTC", "SPYAnalyst": "SPY", "QQQAnalyst": "QQQ", "GLDAnalyst": "GLD"}
        if self.symbol != fixed.get(self.name):
            raise ValueError("fixed analyst symbol must match registered identity")
        if self.symbol and self.scope != Scope.SPECIALIZED:
            raise ValueError("fixed analyst requires SPECIALIZED scope")
        expected = {
            "VizAgent": ExecutionContext.VISUALIZATION,
            "PortfolioMonitor": ExecutionContext.PORTFOLIO_MONITOR,
        }.get(self.name, ExecutionContext.YOLO)
        if self.context != expected:
            raise ValueError("agent has the wrong execution context")
        if len(self.dependencies) != len(set(self.dependencies)):
            raise ValueError("duplicate dependency")
        return self


class QuantContracts(ContractModel):
    schema_version: Literal["8.0"] = "8.0"
    agents: tuple[AgentContract, ...]

    @model_validator(mode="after")
    def complete_registry(self) -> Self:
        names = [agent.name for agent in self.agents]
        if len(names) != len(set(names)) or set(names) != set(get_args(AgentName)):
            raise ValueError("registry must contain each of the 19 quant agents exactly once")
        try:
            tuple(TopologicalSorter({a.name: a.dependencies for a in self.agents}).static_order())
        except CycleError as exc:
            raise ValueError("quant dependency cycle") from exc
        owners: dict[str, str] = {}
        for agent in self.agents:
            for path in agent.permissions.create:
                if path in owners:
                    raise ValueError(f"duplicate output owner: {path}")
                if path == "quant/strategist_performance.json" and agent.name != "QuantStrategist":
                    raise ValueError("performance writes belong to the trusted strategist tool")
                owners[path] = agent.name
        return self

    def for_agent(self, name: AgentName) -> AgentContract:
        for agent in self.agents:
            if agent.name == name:
                return agent
        raise KeyError(name)


def _files(names: tuple[str, ...], *, baseline: bool = False) -> tuple[str, ...]:
    run = "{baseline_run_id}" if baseline else "{run_id}"
    return tuple(f"quant/runs/{run}/{name}" for name in names)


def _entry(
    name: AgentName, scope: Scope, dependencies: tuple[AgentName, ...], output: str,
    reads: tuple[str, ...] = (), baseline: tuple[str, ...] = (),
    *, listing: tuple[str, ...] = (), extra_outputs: tuple[str, ...] = (),
    baseline_listing: tuple[str, ...] = (), symbol=None,
    context: ExecutionContext = ExecutionContext.YOLO,
) -> AgentContract:
    outputs = _files((f"{output}.json", f"{output}.md", *extra_outputs))
    read = _files(reads)
    if name == "QuantStrategist":
        read += ("quant/strategist_performance.json",)
        outputs += ("quant/strategist_performance.json",)
    return AgentContract(
        name=name, scope=scope, dependencies=dependencies, symbol=symbol, context=context,
        permissions=FilePermissions(
            read=read, create=outputs, edit=outputs, list=_files(listing),
            baseline_read=_files(baseline, baseline=True),
            baseline_list=_files(baseline_listing, baseline=True),
        ),
    )


def load_quant_contracts() -> QuantContracts:
    """Load a fresh immutable contract from declarations shipped in the package."""
    raw = ("raw/{ticker}.json",)
    market = ("data_fetch.json", *raw, "trend_analysis.json")
    strategy = ("signals.json", "risk_assessment.json", "trade_proposals.json", "post.json")
    asset_reads = ("trend_analysis.json", "event_route.json", "market_events.json")
    asset_context = ("macro_context.json", "unusual_events.json", "sentiment_analysis.json")
    return QuantContracts(agents=(
        _entry("DataFetcher", Scope.QUANT, (), "data_fetch", ("data_fetch.json", *raw), raw,
               listing=raw, baseline_listing=raw,
               extra_outputs=("raw/{ticker}.json", "raw/{ticker}_summary.md")),
        _entry("OptionsFlowWatcher", Scope.OPTIONS, (), "options_flow", baseline=(
            "options_flow.json", "risk_assessment.json", "trade_proposals.json", "post.json")),
        _entry("TrendAnalyst", Scope.QUANT, ("DataFetcher",), "trend_analysis",
               ("data_fetch.json", *raw), ("trend_analysis.json", "post.json"), listing=raw),
        _entry("SentimentAnalyst", Scope.GENERAL, ("DataFetcher",), "sentiment_analysis", market,
               ("sentiment_analysis.json", "trend_analysis.json", "signals.json", "post.json"), listing=raw),
        _entry("MarketEventWatcher", Scope.SPECIALIZED, ("DataFetcher",), "market_events", market,
               ("market_events.json", "trend_analysis.json", *strategy), listing=raw),
        _entry("MacroContextWatcher", Scope.SPECIALIZED, ("MarketEventWatcher", "OptionsFlowWatcher"),
               "macro_context", ("market_events.json", "options_flow.json"),
               ("macro_context.json", "trend_analysis.json", *strategy)),
        _entry("UnusualEventDetector", Scope.SPECIALIZED,
               ("MarketEventWatcher", "MacroContextWatcher", "OptionsFlowWatcher"), "unusual_events",
               ("market_events.json", "options_flow.json", "macro_context.json"),
               ("unusual_events.json", *strategy)),
        _entry("EventRouter", Scope.SPECIALIZED, ("UnusualEventDetector",), "event_route",
               ("unusual_events.json", "market_events.json", "options_flow.json"),
               ("event_route.json", "risk_assessment.json", "trade_proposals.json", "post.json")),
        *(_entry(name, Scope.SPECIALIZED, ("TrendAnalyst", "EventRouter"), f"{symbol.lower()}_analysis",
                 (*asset_reads, *(("options_flow.json",) if symbol != "BTC" else ()), *asset_context),
                 (f"{symbol.lower()}_analysis.json", "trend_analysis.json", *strategy), symbol=symbol)
          for name, symbol in (("BTCAnalyst", "BTC"), ("SPYAnalyst", "SPY"),
                               ("QQQAnalyst", "QQQ"), ("GLDAnalyst", "GLD"))),
        _entry("QuantResearcher", Scope.QUANT,
               ("TrendAnalyst", "SentimentAnalyst", "BTCAnalyst", "SPYAnalyst", "QQQAnalyst", "GLDAnalyst"),
               "signals", ("trend_analysis.json", "sentiment_analysis.json", "asset_analysis.json",
                           "macro_context.json", "unusual_events.json"),
               ("signals.json", "backtest_results.json", "risk_assessment.json", "trade_proposals.json", "post.json")),
        _entry("Backtester", Scope.QUANT, ("QuantResearcher",), "backtest_results",
               ("signals.json", *raw),
               ("signals.json", "backtest_results.json", "risk_assessment.json", "trade_proposals.json"), listing=raw),
        _entry("RiskAnalyst", Scope.QUANT, ("Backtester",), "risk_assessment",
               ("backtest_results.json", "trend_analysis.json", "asset_analysis.json", "macro_context.json"),
               ("backtest_results.json", "risk_assessment.json", "trade_proposals.json", "post.json")),
        _entry("QuantStrategist", Scope.QUANT, ("RiskAnalyst",), "trade_proposals",
               ("risk_assessment.json", "backtest_results.json", "sentiment_analysis.json",
                "signals.json", "asset_analysis.json", "macro_context.json"),
               ("signals.json", "backtest_results.json", "risk_assessment.json", "trade_proposals.json", "post.json")),
        _entry("Publisher", Scope.QUANT, ("QuantStrategist",), "post",
               ("trade_proposals.json", "trend_analysis.json", "sentiment_analysis.json",
                "risk_assessment.json", "asset_analysis.json", "macro_context.json"),
               ("trade_proposals.json", "post.json", "risk_assessment.json")),
        _entry("VizAgent", Scope.QUANT, (), "visualizations",
               (*raw, "backtest_results.json", "risk_assessment.json", "portfolio_log.json"),
               listing=raw,
               extra_outputs=("viz/candlestick_{ticker}.png", "viz/rsi_macd_{ticker}.png",
                              "viz/backtest.png", "viz/risk_heatmap.png", "viz/portfolio_pnl.png"),
               context=ExecutionContext.VISUALIZATION),
        _entry("PortfolioMonitor", Scope.QUANT, (), "portfolio_log",
               context=ExecutionContext.PORTFOLIO_MONITOR),
    ))