File size: 10,017 Bytes
32e44f2 589695d 32e44f2 589695d 32e44f2 0733d82 32e44f2 | 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 | """Typed artifact identities and envelopes shared by quant agent contracts.
These schemas validate structure and provenance. Resolving references against
published files and applying effective-scope ACLs remain runtime duties.
"""
from datetime import date
from enum import StrEnum
from typing import Annotated, Generic, Literal, Self, TypeVar
from pydantic import (
AfterValidator, AwareDatetime, BaseModel, ConfigDict, Field, model_validator,
)
from polyhedra.core.quant_contracts import AgentName, load_quant_contracts
Identifier = Annotated[str, Field(min_length=1, pattern=r"^[A-Za-z0-9_-]+$")]
NonEmptyText = Annotated[str, Field(min_length=1)]
SchemaVersion = Literal["8.0"]
def _ticker(value: str) -> str:
# Admission to the watchlist is a product concern. This validates only the
# normalized, undecorated ticker carried by an already-approved contract.
if value != value.upper() or not value or value in {".", ".."}:
raise ValueError("ticker must be normalized")
if any(not (char.isascii() and (char.isalnum() or char in ".-^=")) for char in value):
raise ValueError("ticker cannot contain status markers or path characters")
return value
Ticker = Annotated[str, AfterValidator(_ticker)]
def _scope(value: list[str]) -> list[str]:
if not value or len(value) != len(set(value)):
raise ValueError("ticker scope must be nonempty and unique")
return value
TickerScope = Annotated[list[Ticker], AfterValidator(_scope)]
class TypedModel(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True, allow_inf_nan=False)
class RunMode(StrEnum):
BASELINE = "BASELINE"
DELTA = "DELTA"
class Availability(StrEnum):
COMPLETE = "COMPLETE"
PARTIAL = "PARTIAL"
UNAVAILABLE = "UNAVAILABLE"
class ConfidenceLevel(StrEnum):
HIGH = "HIGH"
MEDIUM = "MEDIUM"
LOW = "LOW"
UNKNOWN = "UNKNOWN"
class Direction(StrEnum):
BULLISH = "BULLISH"
BEARISH = "BEARISH"
NEUTRAL = "NEUTRAL"
MIXED = "MIXED"
UNKNOWN = "UNKNOWN"
class TradeDirection(StrEnum):
LONG = "LONG"
SHORT = "SHORT"
class DeltaState(StrEnum):
NEW = "NEW"
CHANGED = "CHANGED"
UNCHANGED = "UNCHANGED"
RESOLVED = "RESOLVED"
INVALIDATED = "INVALIDATED"
NOT_COMPARED = "NOT_COMPARED"
class AnalysisOutcome(StrEnum):
NO_TRADE = "NO_TRADE"
WATCH_FOR_CONFIRMATION = "WATCH_FOR_CONFIRMATION"
PAPER_TRADE_SUGGESTION = "PAPER_TRADE_SUGGESTION"
ANALYSIS_UNAVAILABLE = "ANALYSIS_UNAVAILABLE"
class RiskVerdict(StrEnum):
ACCEPTABLE = "ACCEPTABLE"
ELEVATED = "ELEVATED"
REJECT = "REJECT"
class ReferenceIdentity(TypedModel):
session_id: Identifier
run_id: Identifier
artifact_id: NonEmptyText
producer: AgentName | Literal["Runtime"]
path: NonEmptyText
@model_validator(mode="after")
def validate_path(self) -> Self:
if any(part in {"", ".", ".."} for part in self.path.split("/")):
raise ValueError("artifact path must be normalized and session-relative")
if any(char in self.path for char in "\\:*?[]{}") or any(ord(c) < 32 for c in self.path):
raise ValueError("artifact path contains forbidden characters")
if self.path == "quant/strategist_performance.json":
if self.producer != "QuantStrategist":
raise ValueError("performance reference requires QuantStrategist ownership")
return self
prefix = f"quant/runs/{self.run_id}/"
if not self.path.startswith(prefix):
raise ValueError("artifact path does not match run identity")
if self.producer == "Runtime":
if self.path != prefix + "asset_analysis.json":
raise ValueError("unsupported runtime-owned dependency artifact")
return self
permissions = load_quant_contracts().for_agent(self.producer).permissions
for template in permissions.create:
candidate = template.replace("{run_id}", self.run_id)
if "{ticker}" in candidate:
before, after = candidate.split("{ticker}")
if self.path.startswith(before) and self.path.endswith(after):
ticker = self.path[len(before):len(self.path) - len(after)]
_ticker(ticker)
return self
elif candidate == self.path:
return self
raise ValueError("artifact filename does not belong to its producer")
class JsonArtifactRef(ReferenceIdentity):
format: Literal["JSON"] = "JSON"
schema_version: SchemaVersion
@model_validator(mode="after")
def json_filename(self) -> Self:
if not self.path.endswith(".json"):
raise ValueError("JSON reference requires a JSON filename")
return self
class RenderingRef(ReferenceIdentity):
format: Literal["MARKDOWN", "PNG"]
source: JsonArtifactRef
@model_validator(mode="after")
def source_identity(self) -> Self:
suffix = ".md" if self.format == "MARKDOWN" else ".png"
if not self.path.endswith(suffix):
raise ValueError("rendering filename does not match format")
if (self.session_id, self.run_id, self.producer) != (
self.source.session_id, self.source.run_id, self.source.producer
):
raise ValueError("rendering and source must share session/run/producer")
if self.artifact_id == self.source.artifact_id:
raise ValueError("rendering and source must have distinct identities")
if self.format == "MARKDOWN":
expected = self.source.path.removesuffix(".json")
expected += "_summary.md" if "/raw/" in expected else ".md"
if self.path != expected:
raise ValueError("Markdown rendering does not match source JSON")
elif not self.source.path.endswith("/visualizations.json"):
raise ValueError("chart rendering requires the visualization manifest")
return self
ArtifactRef = Annotated[JsonArtifactRef | RenderingRef, Field(discriminator="format")]
class EvidenceRef(TypedModel):
"""Exact published artifact plus a JSON Pointer or stable record ID."""
artifact: JsonArtifactRef
record_id: NonEmptyText | None = Field(
default=None,
description="Stable record ID copied exactly from the referenced artifact.",
)
field_path: str | None = Field(
default=None,
pattern=r"^(?:/(?:[^~/]|~[01])*)+$",
description="JSON Pointer beginning with / and copied from the referenced artifact.",
)
@model_validator(mode="after")
def locator(self) -> Self:
if self.record_id is None and self.field_path is None:
raise ValueError("evidence must identify a record or JSON Pointer field")
return self
class DataIssue(TypedModel):
component: NonEmptyText
code: Annotated[str, Field(pattern=r"^[A-Z][A-Z0-9_]*$")]
message: NonEmptyText
ticker: Ticker | None = None
record_refs: list[EvidenceRef] = Field(default_factory=list)
affected_dates: list[date] = Field(default_factory=list)
Dependencies = TypeVar("Dependencies", bound=BaseModel)
Context = TypeVar("Context", bound=BaseModel)
Payload = TypeVar("Payload", bound=BaseModel)
class AgentInput(TypedModel, Generic[Dependencies, Context]):
run_id: Identifier
session_id: Identifier
run_mode: RunMode
as_of: AwareDatetime
ticker_scope: TickerScope
dependencies: Dependencies
optional_context: Context
baseline_refs: list[JsonArtifactRef] = Field(default_factory=list)
@model_validator(mode="after")
def baseline_identity(self) -> Self:
if self.run_mode == RunMode.BASELINE and self.baseline_refs:
raise ValueError("baseline run cannot consume prior-run references")
_check_refs(self.baseline_refs, self.session_id, self.run_id, baseline=True)
return self
def _check_refs(refs: list[JsonArtifactRef], session_id: str, run_id: str, *, baseline: bool) -> None:
identities = set()
paths = set()
for ref in refs:
if ref.session_id != session_id:
raise ValueError("cross-session reference")
if (ref.run_id == run_id) == baseline:
raise ValueError("reference has the wrong current/baseline run identity")
if ref.artifact_id in identities or ref.path in paths:
raise ValueError("duplicate artifact identity or filename")
identities.add(ref.artifact_id)
paths.add(ref.path)
class AgentArtifact(TypedModel, Generic[Payload]):
schema_version: SchemaVersion
artifact_id: NonEmptyText
run_id: Identifier
session_id: Identifier
producer: AgentName
ticker_scope: TickerScope
created_at: AwareDatetime
status: Availability
input_refs: list[JsonArtifactRef]
baseline_refs: list[JsonArtifactRef]
data_gaps: list[DataIssue]
payload: Payload
render_ref: RenderingRef | None = None
@model_validator(mode="after")
def reference_identity(self) -> Self:
_check_refs(self.input_refs, self.session_id, self.run_id, baseline=False)
_check_refs(self.baseline_refs, self.session_id, self.run_id, baseline=True)
if self.render_ref:
source = self.render_ref.source
if (source.artifact_id, source.run_id, source.session_id, source.producer,
source.schema_version) != (
self.artifact_id, self.run_id, self.session_id, self.producer, self.schema_version
):
raise ValueError("rendering does not reference this artifact")
for gap in self.data_gaps:
if gap.ticker is not None and gap.ticker not in self.ticker_scope:
raise ValueError("data issue ticker lies outside artifact scope")
if self.status == Availability.UNAVAILABLE and not self.data_gaps:
raise ValueError("unavailable artifact requires explicit data gaps")
return self
|