yf176 commited on
Commit
32e44f2
·
1 Parent(s): 448f145

feat: define common typed artifact contracts

Browse files
src/polyhedra/core/artifacts.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typed artifact identities and envelopes shared by quant agent contracts.
2
+
3
+ These schemas validate structure and provenance. Resolving references against
4
+ published files and applying effective-scope ACLs remain runtime duties.
5
+ """
6
+
7
+ from datetime import date
8
+ from enum import StrEnum
9
+ from typing import Annotated, Generic, Literal, Self, TypeVar
10
+
11
+ from pydantic import (
12
+ AfterValidator, AwareDatetime, BaseModel, ConfigDict, Field, model_validator,
13
+ )
14
+
15
+ from polyhedra.core.quant_contracts import AgentName, load_quant_contracts
16
+
17
+ Identifier = Annotated[str, Field(min_length=1, pattern=r"^[A-Za-z0-9_-]+$")]
18
+ NonEmptyText = Annotated[str, Field(min_length=1)]
19
+ SchemaVersion = Literal["8.0"]
20
+
21
+
22
+ def _ticker(value: str) -> str:
23
+ # Admission to the watchlist is a product concern. This validates only the
24
+ # normalized, undecorated ticker carried by an already-approved contract.
25
+ if value != value.upper() or not value or value in {".", ".."}:
26
+ raise ValueError("ticker must be normalized")
27
+ if any(not (char.isascii() and (char.isalnum() or char in ".-^=")) for char in value):
28
+ raise ValueError("ticker cannot contain status markers or path characters")
29
+ return value
30
+
31
+
32
+ Ticker = Annotated[str, AfterValidator(_ticker)]
33
+
34
+
35
+ def _scope(value: list[str]) -> list[str]:
36
+ if not value or len(value) != len(set(value)):
37
+ raise ValueError("ticker scope must be nonempty and unique")
38
+ return value
39
+
40
+
41
+ TickerScope = Annotated[list[Ticker], AfterValidator(_scope)]
42
+
43
+
44
+ class TypedModel(BaseModel):
45
+ model_config = ConfigDict(extra="forbid", frozen=True, allow_inf_nan=False)
46
+
47
+
48
+ class RunMode(StrEnum):
49
+ BASELINE = "BASELINE"
50
+ DELTA = "DELTA"
51
+
52
+
53
+ class Availability(StrEnum):
54
+ COMPLETE = "COMPLETE"
55
+ PARTIAL = "PARTIAL"
56
+ UNAVAILABLE = "UNAVAILABLE"
57
+
58
+
59
+ class ConfidenceLevel(StrEnum):
60
+ HIGH = "HIGH"
61
+ MEDIUM = "MEDIUM"
62
+ LOW = "LOW"
63
+ UNKNOWN = "UNKNOWN"
64
+
65
+
66
+ class Direction(StrEnum):
67
+ BULLISH = "BULLISH"
68
+ BEARISH = "BEARISH"
69
+ NEUTRAL = "NEUTRAL"
70
+ MIXED = "MIXED"
71
+ UNKNOWN = "UNKNOWN"
72
+
73
+
74
+ class TradeDirection(StrEnum):
75
+ LONG = "LONG"
76
+ SHORT = "SHORT"
77
+
78
+
79
+ class DeltaState(StrEnum):
80
+ NEW = "NEW"
81
+ CHANGED = "CHANGED"
82
+ UNCHANGED = "UNCHANGED"
83
+ RESOLVED = "RESOLVED"
84
+ INVALIDATED = "INVALIDATED"
85
+ NOT_COMPARED = "NOT_COMPARED"
86
+
87
+
88
+ class AnalysisOutcome(StrEnum):
89
+ NO_TRADE = "NO_TRADE"
90
+ WATCH_FOR_CONFIRMATION = "WATCH_FOR_CONFIRMATION"
91
+ PAPER_TRADE_SUGGESTION = "PAPER_TRADE_SUGGESTION"
92
+ ANALYSIS_UNAVAILABLE = "ANALYSIS_UNAVAILABLE"
93
+
94
+
95
+ class RiskVerdict(StrEnum):
96
+ ACCEPTABLE = "ACCEPTABLE"
97
+ ELEVATED = "ELEVATED"
98
+ REJECT = "REJECT"
99
+
100
+
101
+ class ReferenceIdentity(TypedModel):
102
+ session_id: Identifier
103
+ run_id: Identifier
104
+ artifact_id: NonEmptyText
105
+ producer: AgentName | Literal["Runtime"]
106
+ path: NonEmptyText
107
+
108
+ @model_validator(mode="after")
109
+ def validate_path(self) -> Self:
110
+ if any(part in {"", ".", ".."} for part in self.path.split("/")):
111
+ raise ValueError("artifact path must be normalized and session-relative")
112
+ if any(char in self.path for char in "\\:*?[]{}") or any(ord(c) < 32 for c in self.path):
113
+ raise ValueError("artifact path contains forbidden characters")
114
+ if self.path == "quant/strategist_performance.json":
115
+ if self.producer != "QuantStrategist":
116
+ raise ValueError("performance reference requires QuantStrategist ownership")
117
+ return self
118
+ prefix = f"quant/runs/{self.run_id}/"
119
+ if not self.path.startswith(prefix):
120
+ raise ValueError("artifact path does not match run identity")
121
+ if self.producer == "Runtime":
122
+ if self.path != prefix + "asset_analysis.json":
123
+ raise ValueError("unsupported runtime-owned dependency artifact")
124
+ return self
125
+ permissions = load_quant_contracts().for_agent(self.producer).permissions
126
+ for template in permissions.create:
127
+ candidate = template.replace("{run_id}", self.run_id)
128
+ if "{ticker}" in candidate:
129
+ before, after = candidate.split("{ticker}")
130
+ if self.path.startswith(before) and self.path.endswith(after):
131
+ ticker = self.path[len(before):len(self.path) - len(after)]
132
+ _ticker(ticker)
133
+ return self
134
+ elif candidate == self.path:
135
+ return self
136
+ raise ValueError("artifact filename does not belong to its producer")
137
+
138
+
139
+ class JsonArtifactRef(ReferenceIdentity):
140
+ format: Literal["JSON"] = "JSON"
141
+ schema_version: SchemaVersion
142
+
143
+ @model_validator(mode="after")
144
+ def json_filename(self) -> Self:
145
+ if not self.path.endswith(".json"):
146
+ raise ValueError("JSON reference requires a JSON filename")
147
+ return self
148
+
149
+
150
+ class RenderingRef(ReferenceIdentity):
151
+ format: Literal["MARKDOWN", "PNG"]
152
+ source: JsonArtifactRef
153
+
154
+ @model_validator(mode="after")
155
+ def source_identity(self) -> Self:
156
+ suffix = ".md" if self.format == "MARKDOWN" else ".png"
157
+ if not self.path.endswith(suffix):
158
+ raise ValueError("rendering filename does not match format")
159
+ if (self.session_id, self.run_id, self.producer) != (
160
+ self.source.session_id, self.source.run_id, self.source.producer
161
+ ):
162
+ raise ValueError("rendering and source must share session/run/producer")
163
+ if self.artifact_id == self.source.artifact_id:
164
+ raise ValueError("rendering and source must have distinct identities")
165
+ if self.format == "MARKDOWN":
166
+ expected = self.source.path.removesuffix(".json")
167
+ expected += "_summary.md" if "/raw/" in expected else ".md"
168
+ if self.path != expected:
169
+ raise ValueError("Markdown rendering does not match source JSON")
170
+ elif not self.source.path.endswith("/visualizations.json"):
171
+ raise ValueError("chart rendering requires the visualization manifest")
172
+ return self
173
+
174
+
175
+ ArtifactRef = Annotated[JsonArtifactRef | RenderingRef, Field(discriminator="format")]
176
+
177
+
178
+ class EvidenceRef(TypedModel):
179
+ artifact: JsonArtifactRef
180
+ record_id: NonEmptyText | None = None
181
+ field_path: str | None = Field(default=None, pattern=r"^(?:/(?:[^~/]|~[01])*)+$")
182
+
183
+ @model_validator(mode="after")
184
+ def locator(self) -> Self:
185
+ if self.record_id is None and self.field_path is None:
186
+ raise ValueError("evidence must identify a record or JSON Pointer field")
187
+ return self
188
+
189
+
190
+ class DataIssue(TypedModel):
191
+ component: NonEmptyText
192
+ code: Annotated[str, Field(pattern=r"^[A-Z][A-Z0-9_]*$")]
193
+ message: NonEmptyText
194
+ ticker: Ticker | None = None
195
+ record_refs: list[EvidenceRef] = Field(default_factory=list)
196
+ affected_dates: list[date] = Field(default_factory=list)
197
+
198
+
199
+ Dependencies = TypeVar("Dependencies", bound=BaseModel)
200
+ Context = TypeVar("Context", bound=BaseModel)
201
+ Payload = TypeVar("Payload", bound=BaseModel)
202
+
203
+
204
+ class AgentInput(TypedModel, Generic[Dependencies, Context]):
205
+ run_id: Identifier
206
+ session_id: Identifier
207
+ run_mode: RunMode
208
+ as_of: AwareDatetime
209
+ ticker_scope: TickerScope
210
+ dependencies: Dependencies
211
+ optional_context: Context
212
+ baseline_refs: list[JsonArtifactRef] = Field(default_factory=list)
213
+
214
+ @model_validator(mode="after")
215
+ def baseline_identity(self) -> Self:
216
+ if self.run_mode == RunMode.BASELINE and self.baseline_refs:
217
+ raise ValueError("baseline run cannot consume prior-run references")
218
+ _check_refs(self.baseline_refs, self.session_id, self.run_id, baseline=True)
219
+ return self
220
+
221
+
222
+ def _check_refs(refs: list[JsonArtifactRef], session_id: str, run_id: str, *, baseline: bool) -> None:
223
+ identities = set()
224
+ paths = set()
225
+ for ref in refs:
226
+ if ref.session_id != session_id:
227
+ raise ValueError("cross-session reference")
228
+ if (ref.run_id == run_id) == baseline:
229
+ raise ValueError("reference has the wrong current/baseline run identity")
230
+ if ref.artifact_id in identities or ref.path in paths:
231
+ raise ValueError("duplicate artifact identity or filename")
232
+ identities.add(ref.artifact_id)
233
+ paths.add(ref.path)
234
+
235
+
236
+ class AgentArtifact(TypedModel, Generic[Payload]):
237
+ schema_version: SchemaVersion
238
+ artifact_id: NonEmptyText
239
+ run_id: Identifier
240
+ session_id: Identifier
241
+ producer: AgentName
242
+ ticker_scope: TickerScope
243
+ created_at: AwareDatetime
244
+ status: Availability
245
+ input_refs: list[JsonArtifactRef]
246
+ baseline_refs: list[JsonArtifactRef]
247
+ data_gaps: list[DataIssue]
248
+ payload: Payload
249
+ render_ref: RenderingRef | None = None
250
+
251
+ @model_validator(mode="after")
252
+ def reference_identity(self) -> Self:
253
+ _check_refs(self.input_refs, self.session_id, self.run_id, baseline=False)
254
+ _check_refs(self.baseline_refs, self.session_id, self.run_id, baseline=True)
255
+ if self.render_ref:
256
+ source = self.render_ref.source
257
+ if (source.artifact_id, source.run_id, source.session_id, source.producer,
258
+ source.schema_version) != (
259
+ self.artifact_id, self.run_id, self.session_id, self.producer, self.schema_version
260
+ ):
261
+ raise ValueError("rendering does not reference this artifact")
262
+ for gap in self.data_gaps:
263
+ if gap.ticker is not None and gap.ticker not in self.ticker_scope:
264
+ raise ValueError("data issue ticker lies outside artifact scope")
265
+ return self
tests/test_artifacts.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Common quant contracts reject ambiguous identities before artifact access."""
2
+
3
+ import json
4
+
5
+ import pytest
6
+ from pydantic import TypeAdapter, ValidationError
7
+
8
+ from polyhedra.core.artifacts import (
9
+ AgentArtifact, AgentInput, ArtifactRef, DataIssue, Direction, EvidenceRef,
10
+ JsonArtifactRef, RenderingRef, TradeDirection, TypedModel,
11
+ )
12
+
13
+
14
+ def ref(**updates):
15
+ data = dict(
16
+ format="JSON", schema_version="8.0", artifact_id="current-data",
17
+ session_id="session1", run_id="run1", producer="DataFetcher",
18
+ path="quant/runs/run1/raw/SPY.json",
19
+ )
20
+ data.update(updates)
21
+ return JsonArtifactRef.model_validate(data)
22
+
23
+
24
+ class EmptyContext(TypedModel):
25
+ pass
26
+
27
+
28
+ class Dependencies(TypedModel):
29
+ market_data: JsonArtifactRef
30
+
31
+
32
+ class Payload(TypedModel):
33
+ interpretation: str
34
+
35
+
36
+ def input_data(**updates):
37
+ data = dict(
38
+ run_id="run1", session_id="session1", run_mode="BASELINE",
39
+ as_of="2026-09-09T12:00:00Z", ticker_scope=["SPY"],
40
+ dependencies={"market_data": ref().model_dump(mode="json")}, optional_context={},
41
+ )
42
+ data.update(updates)
43
+ return data
44
+
45
+
46
+ def artifact_data(**updates):
47
+ data = dict(
48
+ schema_version="8.0", artifact_id="trend", run_id="run1", session_id="session1",
49
+ producer="TrendAnalyst", ticker_scope=["SPY"], created_at="2026-09-09T12:01:00Z",
50
+ status="COMPLETE", input_refs=[ref().model_dump(mode="json")], baseline_refs=[],
51
+ data_gaps=[], payload={"interpretation": "Stable prices"},
52
+ )
53
+ data.update(updates)
54
+ return data
55
+
56
+
57
+ def test_typed_envelope_json_round_trip():
58
+ inputs = AgentInput[Dependencies, EmptyContext].model_validate_json(json.dumps(input_data()), strict=True)
59
+ assert inputs.dependencies.market_data.producer == "DataFetcher"
60
+ artifact = AgentArtifact[Payload].model_validate_json(json.dumps(artifact_data()), strict=True)
61
+ assert AgentArtifact[Payload].model_validate_json(artifact.model_dump_json(), strict=True) == artifact
62
+
63
+
64
+ @pytest.mark.parametrize("changes", [
65
+ {"schema_version": "7.1"}, {"path": "C:/secret.json"},
66
+ {"path": "quant/runs/run1/../secret.json"}, {"path": "quant/runs/run2/raw/SPY.json"},
67
+ {"path": "quant/runs/run1/raw/SPY*.json"}, {"path": "quant/runs/run1/raw/SPY.json:secret"},
68
+ {"path": "quant/runs/run1/raw/spy.json"}, {"producer": "TrendAnalyst"},
69
+ {"path": "quant/runs/run1/raw/SPY_summary.md"}, {"producer": "human"},
70
+ ])
71
+ def test_bad_json_reference(changes):
72
+ with pytest.raises(ValidationError):
73
+ ref(**changes)
74
+
75
+
76
+ def test_rendering_has_format_and_source_instead_of_schema_version():
77
+ rendering = RenderingRef(
78
+ format="MARKDOWN", artifact_id="summary", session_id="session1", run_id="run1",
79
+ producer="DataFetcher", path="quant/runs/run1/raw/SPY_summary.md", source=ref(),
80
+ )
81
+ adapter = TypeAdapter(ArtifactRef)
82
+ assert adapter.validate_json(rendering.model_dump_json(), strict=True) == rendering
83
+ with pytest.raises(ValidationError):
84
+ RenderingRef.model_validate({**rendering.model_dump(), "schema_version": "8.0"})
85
+ for changes in (
86
+ {"session_id": "other"}, {"artifact_id": "current-data"},
87
+ {"path": "quant/runs/run1/raw/QQQ_summary.md"}, {"format": "PNG"},
88
+ ):
89
+ with pytest.raises(ValidationError):
90
+ RenderingRef.model_validate({**rendering.model_dump(), **changes})
91
+
92
+
93
+ def test_evidence_requires_exact_locator():
94
+ assert EvidenceRef(artifact=ref(), field_path="/ohlcv/0/close").field_path
95
+ assert EvidenceRef(artifact=ref(), record_id="2026-09-08").record_id
96
+ with pytest.raises(ValidationError):
97
+ EvidenceRef(artifact=ref())
98
+ with pytest.raises(ValidationError):
99
+ EvidenceRef(artifact=ref(), field_path="/invalid~escape")
100
+
101
+
102
+ @pytest.mark.parametrize("changes", [
103
+ {"ticker_scope": []}, {"ticker_scope": ["SPY", "SPY"]}, {"ticker_scope": ["SPY*"]},
104
+ {"as_of": "2026-09-09T12:00:00"}, {"next_role": "human"},
105
+ {"optional_context": {"thread_history": "undeclared"}},
106
+ {"baseline_refs": [ref().model_dump(mode="json")]},
107
+ ])
108
+ def test_bad_input_envelope(changes):
109
+ with pytest.raises(ValidationError):
110
+ AgentInput[Dependencies, EmptyContext].model_validate(input_data(**changes))
111
+
112
+
113
+ def test_delta_reference_preserves_prior_run_and_session():
114
+ prior = ref(run_id="prior", path="quant/runs/prior/raw/SPY.json", artifact_id="prior-data")
115
+ model = AgentInput[Dependencies, EmptyContext]
116
+ assert model.model_validate(input_data(run_mode="DELTA", baseline_refs=[prior])).baseline_refs == [prior]
117
+ for references in ([ref()], [prior, prior], [prior.model_copy(update={"session_id": "other"})]):
118
+ with pytest.raises(ValidationError):
119
+ model.model_validate(input_data(run_mode="DELTA", baseline_refs=references))
120
+
121
+
122
+ @pytest.mark.parametrize("changes", [
123
+ {"status": "FAILED"}, {"input_refs": [ref(session_id="other")]},
124
+ {"input_refs": [ref(), ref()]}, {"baseline_refs": [ref()]},
125
+ {"data_gaps": [DataIssue(component="NEWS", code="UNAVAILABLE", message="Missing", ticker="QQQ")]},
126
+ {"payload": {"interpretation": "Stable", "next_role": "Publisher"}},
127
+ ])
128
+ def test_bad_output_envelope(changes):
129
+ with pytest.raises(ValidationError):
130
+ AgentArtifact[Payload].model_validate(artifact_data(**changes))
131
+
132
+
133
+ def test_render_reference_must_point_to_own_artifact():
134
+ source = ref(producer="TrendAnalyst", artifact_id="trend", path="quant/runs/run1/trend_analysis.json")
135
+ rendering = RenderingRef(
136
+ format="MARKDOWN", artifact_id="trend-render", session_id="session1", run_id="run1",
137
+ producer="TrendAnalyst", path="quant/runs/run1/trend_analysis.md", source=source,
138
+ )
139
+ model = AgentArtifact[Payload]
140
+ assert model.model_validate(artifact_data(render_ref=rendering)).render_ref == rendering
141
+ with pytest.raises(ValidationError):
142
+ model.model_validate(artifact_data(artifact_id="different", render_ref=rendering))
143
+
144
+
145
+ def test_trade_direction_is_not_market_direction():
146
+ with pytest.raises(ValidationError):
147
+ TypeAdapter(TradeDirection).validate_python("BULLISH")
148
+ with pytest.raises(ValidationError):
149
+ TypeAdapter(Direction).validate_python("LONG")
150
+
151
+
152
+ def test_runtime_aggregate_has_explicit_owner():
153
+ assert ref(producer="Runtime", path="quant/runs/run1/asset_analysis.json").producer == "Runtime"
154
+ with pytest.raises(ValidationError):
155
+ ref(producer="Runtime", path="quant/runs/run1/trend_analysis.json")