Download src/polyhedra/core/artifacts.py from polyHedra/PolyHedra: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/spaces/polyHedra/PolyHedra/resolve/main/src/polyhedra/core/artifacts.py
- Command line
-
hf download hf://spaces/polyHedra/PolyHedra/src/polyhedra/core/artifacts.py
-
curl -L -o artifacts.py https://huggingface.co/spaces/polyHedra/PolyHedra/resolve/main/src/polyhedra/core/artifacts.py
10 kB
| """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 | |
| 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 | |
| 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 | |
| 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.", | |
| ) | |
| 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) | |
| 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 | |
| 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 | |