clearfills-firewall 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
1
+ """ClearFills Universal Pre-Trade Risk Firewall & MCP Server (clearfills.com)."""
2
+
3
+ from .adapters import from_ai_hedge_fund_signal, from_tradingagents_decision
4
+ from .attestation import AttestationAuthority, canonical_order_hash
5
+ from .killswitch import KillSwitch, KillSwitchState
6
+ from .ledger import AuditLedger, GENESIS_HASH
7
+ from .mcp_server import handle_jsonrpc_request, run_stdio_server
8
+ from .models import (
9
+ AuditEntry,
10
+ DecisionStatus,
11
+ ExecutionReceipt,
12
+ OrderType,
13
+ PortfolioSnapshot,
14
+ Position,
15
+ RiskDecision,
16
+ Side,
17
+ SignedAttestation,
18
+ TradeProposal,
19
+ VenueType,
20
+ )
21
+ from .policy import RiskPolicy, evaluate_proposal
22
+ from .server import FirewallService, create_app
23
+
24
+ __all__ = [
25
+ "AttestationAuthority",
26
+ "AuditEntry",
27
+ "AuditLedger",
28
+ "DecisionStatus",
29
+ "ExecutionReceipt",
30
+ "FirewallService",
31
+ "GENESIS_HASH",
32
+ "KillSwitch",
33
+ "KillSwitchState",
34
+ "OrderType",
35
+ "PortfolioSnapshot",
36
+ "Position",
37
+ "RiskDecision",
38
+ "RiskPolicy",
39
+ "Side",
40
+ "SignedAttestation",
41
+ "TradeProposal",
42
+ "VenueType",
43
+ "canonical_order_hash",
44
+ "create_app",
45
+ "evaluate_proposal",
46
+ "from_ai_hedge_fund_signal",
47
+ "from_tradingagents_decision",
48
+ "handle_jsonrpc_request",
49
+ "run_stdio_server",
50
+ ]
@@ -0,0 +1,196 @@
1
+ """Pluggable upstream agent backend shims for open-source trading frameworks.
2
+
3
+ Allows frameworks such as `TauricResearch/TradingAgents` and `virattt/ai-hedge-fund`
4
+ to route proposals through the ClearFills Pre-Trade Risk Firewall without modifying
5
+ their core agent loops.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import Any, Optional
12
+
13
+ from .models import OrderType, Side, TradeProposal, VenueType
14
+
15
+
16
+ def _parse_side(raw_action: str) -> Side:
17
+ normalized = raw_action.strip().upper()
18
+ if normalized in {"BUY", "LONG", "BULLISH", "COVER"} or re.search(r"\bBUY\b", normalized):
19
+ return Side.BUY
20
+ if normalized in {"SELL", "SHORT", "BEARISH"} or re.search(r"\bSELL\b|\bSHORT\b", normalized):
21
+ return Side.SELL
22
+ raise ValueError(f"Unsupported or non-actionable trade decision: '{raw_action}'")
23
+
24
+
25
+ def _normalize_confidence(raw: Any, default: float = 0.55) -> float:
26
+ if raw is None:
27
+ return default
28
+ val = float(raw)
29
+ if val > 1.0:
30
+ # Frameworks like ai-hedge-fund often emit confidence on a 0..100 scale
31
+ val = val / 100.0
32
+ return max(0.0, min(1.0, val))
33
+
34
+
35
+ def _coerce_float(val: Any) -> Optional[float]:
36
+ if val is None or val == "":
37
+ return None
38
+ return float(val)
39
+
40
+
41
+ def from_tradingagents_decision(payload: dict[str, Any]) -> TradeProposal:
42
+ """Map a `TauricResearch/TradingAgents` state/decision dict into a `TradeProposal`.
43
+
44
+ Expected fields (supports standard TradingAgents graph output):
45
+ - `final_trade_decision`: str (e.g. `"BUY"`, `"FINAL TRANSACTION PROPOSAL: **BUY**"`) or dict
46
+ - `company_of_interest` or `ticker` or `symbol`
47
+ - `investment_debate_state`: optional dict with `bull_history`, `bear_history`, `judge_decision`
48
+ - `risk_debate_state`: optional dict with `judge_decision`
49
+ - `quantity`, `limit_price` (or `price`), `stop_price`, `target_price`, `venue`, `agent_id`
50
+ """
51
+ decision_raw = payload.get("final_trade_decision")
52
+ if decision_raw is None:
53
+ raise ValueError("TradingAgents payload missing 'final_trade_decision'")
54
+
55
+ if isinstance(decision_raw, dict):
56
+ action_str = str(decision_raw.get("action") or decision_raw.get("decision") or "")
57
+ decision_rationale = str(decision_raw.get("reasoning") or decision_raw.get("summary") or "")
58
+ else:
59
+ action_str = str(decision_raw)
60
+ decision_rationale = action_str
61
+
62
+ side = _parse_side(action_str)
63
+
64
+ symbol = str(
65
+ payload.get("company_of_interest")
66
+ or payload.get("ticker")
67
+ or payload.get("symbol")
68
+ or ""
69
+ ).strip()
70
+ if not symbol:
71
+ raise ValueError("TradingAgents payload missing 'company_of_interest' / 'ticker' / 'symbol'")
72
+
73
+ debate = payload.get("investment_debate_state") or {}
74
+ risk_debate = payload.get("risk_debate_state") or {}
75
+
76
+ trace_parts: list[str] = []
77
+ if decision_rationale:
78
+ trace_parts.append(f"Final Decision: {decision_rationale}")
79
+ if isinstance(debate, dict):
80
+ if debate.get("bull_history"):
81
+ trace_parts.append(f"Bull Case: {debate['bull_history']}")
82
+ if debate.get("bear_history"):
83
+ trace_parts.append(f"Bear Case: {debate['bear_history']}")
84
+ if debate.get("judge_decision"):
85
+ trace_parts.append(f"Research Judge: {debate['judge_decision']}")
86
+ if isinstance(risk_debate, dict) and risk_debate.get("judge_decision"):
87
+ trace_parts.append(f"Risk Judge: {risk_debate['judge_decision']}")
88
+
89
+ citations: list[str] = list(payload.get("source_citations") or [])
90
+ for report_key in ("market_report", "sentiment_report", "news_report", "fundamentals_report"):
91
+ if payload.get(report_key):
92
+ citations.append(f"tradingagents:{report_key}")
93
+
94
+ quantity = float(payload.get("quantity", 1.0))
95
+ limit_price = _coerce_float(payload.get("limit_price") or payload.get("price"))
96
+ stop_price = _coerce_float(payload.get("stop_price"))
97
+ target_price = _coerce_float(payload.get("target_price"))
98
+ confidence = _normalize_confidence(payload.get("confidence"), default=0.60)
99
+
100
+ venue = str(payload.get("venue", "ibkr"))
101
+ venue_type_raw = str(payload.get("venue_type", VenueType.EQUITY.value)).upper()
102
+ venue_type = VenueType(venue_type_raw)
103
+
104
+ order_type_raw = str(payload.get("order_type", OrderType.LIMIT.value)).upper()
105
+ order_type = OrderType(order_type_raw)
106
+
107
+ return TradeProposal(
108
+ agent_id=str(payload.get("agent_id", "tradingagents-orchestrator")),
109
+ venue=venue,
110
+ venue_type=venue_type,
111
+ symbol=symbol,
112
+ side=side,
113
+ order_type=order_type,
114
+ quantity=quantity,
115
+ limit_price=limit_price,
116
+ stop_price=stop_price,
117
+ target_price=target_price,
118
+ reasoning_trace="\n\n".join(trace_parts),
119
+ source_citations=citations,
120
+ confidence=confidence,
121
+ strategy_id=str(payload.get("strategy_id", "tradingagents_debate")),
122
+ )
123
+
124
+
125
+ def from_ai_hedge_fund_signal(payload: dict[str, Any]) -> TradeProposal:
126
+ """Map a `virattt/ai-hedge-fund` portfolio manager / analyst signal into a `TradeProposal`.
127
+
128
+ Expected fields:
129
+ - `ticker` or `symbol`
130
+ - `action` or `signal` (e.g. `"buy"`, `"sell"`, `"short"`, `"bullish"`, `"bearish"`)
131
+ - `quantity`
132
+ - `confidence` (0..100 or 0.0..1.0)
133
+ - `reasoning`: str or dict
134
+ - `analyst_signals`: optional dict of `{analyst_name: {signal, confidence, reasoning}}`
135
+ - `limit_price` (or `price`), `stop_price`, `target_price`, `venue`, `agent_id`
136
+ """
137
+ symbol = str(payload.get("ticker") or payload.get("symbol") or "").strip()
138
+ if not symbol:
139
+ raise ValueError("ai-hedge-fund payload missing 'ticker' / 'symbol'")
140
+
141
+ raw_action = payload.get("action") or payload.get("signal")
142
+ if not raw_action:
143
+ raise ValueError("ai-hedge-fund payload missing 'action' / 'signal'")
144
+ side = _parse_side(str(raw_action))
145
+
146
+ quantity = float(payload.get("quantity", 1.0))
147
+ confidence = _normalize_confidence(payload.get("confidence"), default=0.55)
148
+
149
+ reasoning_raw = payload.get("reasoning", "")
150
+ trace_parts: list[str] = []
151
+ if isinstance(reasoning_raw, dict):
152
+ for k, v in reasoning_raw.items():
153
+ trace_parts.append(f"{k}: {v}")
154
+ elif reasoning_raw:
155
+ trace_parts.append(str(reasoning_raw))
156
+
157
+ citations: list[str] = list(payload.get("source_citations") or [])
158
+ analyst_signals = payload.get("analyst_signals") or {}
159
+ if isinstance(analyst_signals, dict):
160
+ for analyst_name, sig_data in analyst_signals.items():
161
+ citations.append(f"ai-hedge-fund:{analyst_name}")
162
+ if isinstance(sig_data, dict):
163
+ sig_label = sig_data.get("signal", "neutral")
164
+ sig_conf = sig_data.get("confidence", "")
165
+ sig_reason = sig_data.get("reasoning", "")
166
+ trace_parts.append(
167
+ f"[{analyst_name}] signal={sig_label} conf={sig_conf}: {sig_reason}"
168
+ )
169
+
170
+ limit_price = _coerce_float(payload.get("limit_price") or payload.get("price"))
171
+ stop_price = _coerce_float(payload.get("stop_price"))
172
+ target_price = _coerce_float(payload.get("target_price"))
173
+
174
+ venue = str(payload.get("venue", "alpaca"))
175
+ venue_type_raw = str(payload.get("venue_type", VenueType.EQUITY.value)).upper()
176
+ venue_type = VenueType(venue_type_raw)
177
+
178
+ order_type_raw = str(payload.get("order_type", OrderType.LIMIT.value)).upper()
179
+ order_type = OrderType(order_type_raw)
180
+
181
+ return TradeProposal(
182
+ agent_id=str(payload.get("agent_id", "ai-hedge-fund-pm")),
183
+ venue=venue,
184
+ venue_type=venue_type,
185
+ symbol=symbol,
186
+ side=side,
187
+ order_type=order_type,
188
+ quantity=quantity,
189
+ limit_price=limit_price,
190
+ stop_price=stop_price,
191
+ target_price=target_price,
192
+ reasoning_trace="\n".join(trace_parts),
193
+ source_citations=citations,
194
+ confidence=confidence,
195
+ strategy_id=str(payload.get("strategy_id", "ai_hedge_fund_consensus")),
196
+ )
@@ -0,0 +1,260 @@
1
+ """Ed25519 single-use, exact-order-hash bound attestation authority."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import hashlib
7
+ import json
8
+ import secrets
9
+ import threading
10
+ from datetime import datetime, timedelta, timezone
11
+ from pathlib import Path
12
+ from typing import Any, Optional
13
+
14
+ from cryptography.exceptions import InvalidSignature
15
+ from cryptography.hazmat.primitives import serialization
16
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
17
+ Ed25519PrivateKey,
18
+ Ed25519PublicKey,
19
+ )
20
+
21
+ from .models import SignedAttestation, TradeProposal, utc_now
22
+
23
+
24
+ def _normalize_float(val: Optional[float]) -> Optional[str]:
25
+ if val is None:
26
+ return None
27
+ # Deterministic decimal representation without floating-point noise
28
+ return f"{val:.8f}"
29
+
30
+
31
+ def canonical_order_legs(proposal: TradeProposal) -> dict[str, Any]:
32
+ """Extract the exact immutable order legs bound by an attestation."""
33
+ return {
34
+ "proposal_id": proposal.proposal_id,
35
+ "agent_id": proposal.agent_id,
36
+ "venue": proposal.venue.strip().lower(),
37
+ "venue_type": proposal.venue_type.value,
38
+ "symbol": proposal.symbol.strip().upper(),
39
+ "side": proposal.side.value,
40
+ "order_type": proposal.order_type.value,
41
+ "quantity": _normalize_float(proposal.quantity),
42
+ "limit_price": _normalize_float(proposal.limit_price),
43
+ "stop_price": _normalize_float(proposal.stop_price),
44
+ "target_price": _normalize_float(proposal.target_price),
45
+ }
46
+
47
+
48
+ def canonical_order_hash(proposal: TradeProposal) -> str:
49
+ """Compute canonical SHA-256 hex digest over immutable order legs."""
50
+ payload = json.dumps(canonical_order_legs(proposal), sort_keys=True, separators=(",", ":"))
51
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
52
+
53
+
54
+ def _canonical_attestation_bytes(
55
+ *,
56
+ attestation_id: str,
57
+ nonce: str,
58
+ proposal_id: str,
59
+ agent_id: str,
60
+ order_hash: str,
61
+ issued_at: datetime,
62
+ expires_at: datetime,
63
+ key_id: str,
64
+ ) -> bytes:
65
+ message = {
66
+ "attestation_id": attestation_id,
67
+ "nonce": nonce,
68
+ "proposal_id": proposal_id,
69
+ "agent_id": agent_id,
70
+ "order_hash": order_hash,
71
+ "issued_at": issued_at.astimezone(timezone.utc).isoformat(),
72
+ "expires_at": expires_at.astimezone(timezone.utc).isoformat(),
73
+ "key_id": key_id,
74
+ }
75
+ return json.dumps(message, sort_keys=True, separators=(",", ":")).encode("utf-8")
76
+
77
+
78
+ class AttestationAuthority:
79
+ """Issues and verifies single-use, TTL-enforced Ed25519 trade attestations."""
80
+
81
+ def __init__(
82
+ self,
83
+ private_key: Optional[Ed25519PrivateKey] = None,
84
+ ttl_seconds: int = 120,
85
+ spent_nonces_path: Optional[str | Path] = None,
86
+ ) -> None:
87
+ if ttl_seconds <= 0:
88
+ raise ValueError("ttl_seconds must be positive")
89
+ self._private_key = private_key or Ed25519PrivateKey.generate()
90
+ self._public_key: Ed25519PublicKey = self._private_key.public_key()
91
+ self._ttl_seconds = ttl_seconds
92
+ self._lock = threading.Lock()
93
+ self._spent_nonces_path = Path(spent_nonces_path) if spent_nonces_path else None
94
+ self._spent_nonces: set[str] = self._load_spent_nonces()
95
+
96
+ pub_bytes = self._public_key.public_bytes(
97
+ encoding=serialization.Encoding.Raw,
98
+ format=serialization.PublicFormat.Raw,
99
+ )
100
+ self._key_id = f"ed25519_{hashlib.sha256(pub_bytes).hexdigest()[:16]}"
101
+
102
+ @classmethod
103
+ def from_pem_file(
104
+ cls,
105
+ pem_path: str | Path,
106
+ ttl_seconds: int = 120,
107
+ spent_nonces_path: Optional[str | Path] = None,
108
+ ) -> "AttestationAuthority":
109
+ """Load an Ed25519 private key from a local PEM file (or generate if absent)."""
110
+ path = Path(pem_path)
111
+ if path.exists():
112
+ key = serialization.load_pem_private_key(path.read_bytes(), password=None)
113
+ if not isinstance(key, Ed25519PrivateKey):
114
+ raise TypeError(f"Expected Ed25519 private key in {path}")
115
+ return cls(private_key=key, ttl_seconds=ttl_seconds, spent_nonces_path=spent_nonces_path)
116
+
117
+ key = Ed25519PrivateKey.generate()
118
+ path.parent.mkdir(parents=True, exist_ok=True)
119
+ pem_bytes = key.private_bytes(
120
+ encoding=serialization.Encoding.PEM,
121
+ format=serialization.PrivateFormat.PKCS8,
122
+ encryption_algorithm=serialization.NoEncryption(),
123
+ )
124
+ path.write_bytes(pem_bytes)
125
+ return cls(private_key=key, ttl_seconds=ttl_seconds, spent_nonces_path=spent_nonces_path)
126
+
127
+ @property
128
+ def key_id(self) -> str:
129
+ return self._key_id
130
+
131
+ @property
132
+ def ttl_seconds(self) -> int:
133
+ return self._ttl_seconds
134
+
135
+ def public_key_pem(self) -> str:
136
+ return self._public_key.public_bytes(
137
+ encoding=serialization.Encoding.PEM,
138
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
139
+ ).decode("utf-8")
140
+
141
+ def issue(
142
+ self,
143
+ proposal: TradeProposal,
144
+ now: Optional[datetime] = None,
145
+ ttl_seconds: Optional[int] = None,
146
+ ) -> SignedAttestation:
147
+ """Issue a fresh single-use Ed25519 attestation bound to exact order legs."""
148
+ issued_at = (now or utc_now()).astimezone(timezone.utc)
149
+ ttl = ttl_seconds if ttl_seconds is not None else self._ttl_seconds
150
+ expires_at = issued_at + timedelta(seconds=ttl)
151
+ order_hash = canonical_order_hash(proposal)
152
+ nonce = secrets.token_hex(16)
153
+ attestation_id = f"att_{secrets.token_hex(8)}"
154
+
155
+ msg = _canonical_attestation_bytes(
156
+ attestation_id=attestation_id,
157
+ nonce=nonce,
158
+ proposal_id=proposal.proposal_id,
159
+ agent_id=proposal.agent_id,
160
+ order_hash=order_hash,
161
+ issued_at=issued_at,
162
+ expires_at=expires_at,
163
+ key_id=self._key_id,
164
+ )
165
+ sig = self._private_key.sign(msg)
166
+ sig_b64 = base64.b64encode(sig).decode("ascii")
167
+
168
+ return SignedAttestation(
169
+ attestation_id=attestation_id,
170
+ nonce=nonce,
171
+ proposal_id=proposal.proposal_id,
172
+ agent_id=proposal.agent_id,
173
+ order_hash=order_hash,
174
+ issued_at=issued_at,
175
+ expires_at=expires_at,
176
+ key_id=self._key_id,
177
+ signature_b64=sig_b64,
178
+ )
179
+
180
+ def verify_and_consume(
181
+ self,
182
+ attestation: SignedAttestation,
183
+ proposal: TradeProposal,
184
+ now: Optional[datetime] = None,
185
+ ) -> tuple[bool, str]:
186
+ """Verify Ed25519 signature, exact order hash, TTL, and single-use nonce.
187
+
188
+ Consumes the nonce atomically on first valid dispatch so replays are impossible.
189
+ """
190
+ check_time = (now or utc_now()).astimezone(timezone.utc)
191
+
192
+ # 1. Key ID check
193
+ if attestation.key_id != self._key_id:
194
+ return False, "UNKNOWN_KEY_ID"
195
+
196
+ # 2. Verify Ed25519 signature over canonical attestation payload
197
+ msg = _canonical_attestation_bytes(
198
+ attestation_id=attestation.attestation_id,
199
+ nonce=attestation.nonce,
200
+ proposal_id=attestation.proposal_id,
201
+ agent_id=attestation.agent_id,
202
+ order_hash=attestation.order_hash,
203
+ issued_at=attestation.issued_at,
204
+ expires_at=attestation.expires_at,
205
+ key_id=attestation.key_id,
206
+ )
207
+ try:
208
+ raw_sig = base64.b64decode(attestation.signature_b64.encode("ascii"), validate=True)
209
+ self._public_key.verify(raw_sig, msg)
210
+ except (InvalidSignature, ValueError):
211
+ return False, "INVALID_SIGNATURE"
212
+
213
+ # 3. Verify exact order-leg hash binding (detects any post-attestation tampering)
214
+ expected_hash = canonical_order_hash(proposal)
215
+ if attestation.order_hash != expected_hash:
216
+ return False, "ORDER_HASH_MISMATCH"
217
+
218
+ # 4. Enforce TTL
219
+ if check_time > attestation.expires_at.astimezone(timezone.utc):
220
+ return False, "ATTESTATION_EXPIRED"
221
+ if check_time < attestation.issued_at.astimezone(timezone.utc) - timedelta(seconds=5):
222
+ return False, "ATTESTATION_NOT_YET_VALID"
223
+
224
+ # 5. Atomic single-use nonce check & consumption (prevents replay attacks)
225
+ with self._lock:
226
+ if attestation.nonce in self._spent_nonces:
227
+ return False, "ATTESTATION_REPLAY_DETECTED"
228
+ self._spent_nonces.add(attestation.nonce)
229
+ self._persist_spent_nonces()
230
+
231
+ return True, "OK"
232
+
233
+ def dispatch_check(
234
+ self,
235
+ attestation: SignedAttestation,
236
+ proposal: TradeProposal,
237
+ now: Optional[datetime] = None,
238
+ ) -> tuple[bool, str]:
239
+ """Alias for verify_and_consume() used at the execution gateway boundary."""
240
+ return self.verify_and_consume(attestation=attestation, proposal=proposal, now=now)
241
+
242
+ def _load_spent_nonces(self) -> set[str]:
243
+ if self._spent_nonces_path is None or not self._spent_nonces_path.exists():
244
+ return set()
245
+ try:
246
+ data = json.loads(self._spent_nonces_path.read_text(encoding="utf-8"))
247
+ if isinstance(data, list):
248
+ return {str(x) for x in data}
249
+ except (OSError, json.JSONDecodeError):
250
+ pass
251
+ return set()
252
+
253
+ def _persist_spent_nonces(self) -> None:
254
+ if self._spent_nonces_path is None:
255
+ return
256
+ self._spent_nonces_path.parent.mkdir(parents=True, exist_ok=True)
257
+ self._spent_nonces_path.write_text(
258
+ json.dumps(sorted(self._spent_nonces)),
259
+ encoding="utf-8",
260
+ )
@@ -0,0 +1,185 @@
1
+ """Fail-closed persistent KillSwitch for the ClearFills Pre-Trade Risk Firewall."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import tempfile
8
+ import threading
9
+ from datetime import datetime
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
14
+
15
+ from .models import utc_now
16
+
17
+
18
+ class KillSwitchState(BaseModel):
19
+ """Persisted JSON state for the fail-closed kill switch."""
20
+
21
+ model_config = ConfigDict(extra="forbid")
22
+
23
+ tripped: bool = True
24
+ reason: str = "Uninitialized kill-switch (fail-closed)"
25
+ actor: str = "system"
26
+ updated_at: datetime = Field(default_factory=utc_now)
27
+ corrupt_or_missing: bool = False
28
+ history: list[dict[str, Any]] = Field(default_factory=list)
29
+
30
+
31
+ class KillSwitch:
32
+ """Fail-closed persistent kill switch backed by a JSON state file.
33
+
34
+ Safety invariants:
35
+ - Missing, unreadable, or corrupt JSON state ALWAYS evaluates as tripped (fail-closed).
36
+ - `trip(reason, actor)` requires non-empty `reason` and `actor`.
37
+ - `reset(reason, approver)` requires explicit non-empty `reason` and `approver`.
38
+ - State writes are atomic (temp file in same directory + `os.replace`).
39
+ """
40
+
41
+ def __init__(self, state_path: str | Path) -> None:
42
+ self._path = Path(state_path)
43
+ self._lock = threading.Lock()
44
+
45
+ @property
46
+ def state_path(self) -> Path:
47
+ return self._path
48
+
49
+ def initialize_armed(self, actor: str = "system", reason: str = "Initial armed state") -> KillSwitchState:
50
+ """Explicitly initialize an armed (non-tripped) kill-switch state file."""
51
+ actor_clean = actor.strip()
52
+ reason_clean = reason.strip()
53
+ if not actor_clean or not reason_clean:
54
+ raise ValueError("actor and reason must be non-empty")
55
+
56
+ now = utc_now()
57
+ state = KillSwitchState(
58
+ tripped=False,
59
+ reason=reason_clean,
60
+ actor=actor_clean,
61
+ updated_at=now,
62
+ corrupt_or_missing=False,
63
+ history=[
64
+ {
65
+ "action": "INIT_ARMED",
66
+ "actor": actor_clean,
67
+ "reason": reason_clean,
68
+ "timestamp": now.isoformat(),
69
+ }
70
+ ],
71
+ )
72
+ with self._lock:
73
+ self._write_atomic(state)
74
+ return state
75
+
76
+ def status(self) -> KillSwitchState:
77
+ """Read current kill-switch state; fail-closed if missing or corrupt."""
78
+ with self._lock:
79
+ return self._read_fail_closed()
80
+
81
+ def is_tripped(self) -> bool:
82
+ """Return True if tripped OR if state file is missing/corrupt."""
83
+ return self.status().tripped
84
+
85
+ def trip(self, reason: str, actor: str) -> KillSwitchState:
86
+ """Trip the kill switch, blocking all new exposure."""
87
+ reason_clean = reason.strip()
88
+ actor_clean = actor.strip()
89
+ if not reason_clean:
90
+ raise ValueError("trip() requires a non-empty reason")
91
+ if not actor_clean:
92
+ raise ValueError("trip() requires a non-empty actor")
93
+
94
+ with self._lock:
95
+ current = self._read_fail_closed()
96
+ history = list(current.history)
97
+ now = utc_now()
98
+ history.append(
99
+ {
100
+ "action": "TRIP",
101
+ "actor": actor_clean,
102
+ "reason": reason_clean,
103
+ "timestamp": now.isoformat(),
104
+ }
105
+ )
106
+ new_state = KillSwitchState(
107
+ tripped=True,
108
+ reason=reason_clean,
109
+ actor=actor_clean,
110
+ updated_at=now,
111
+ corrupt_or_missing=False,
112
+ history=history[-100:],
113
+ )
114
+ self._write_atomic(new_state)
115
+ return new_state
116
+
117
+ def reset(self, reason: str, approver: str) -> KillSwitchState:
118
+ """Reset (arm) the kill switch. Requires explicit non-empty reason and approver."""
119
+ reason_clean = reason.strip()
120
+ approver_clean = approver.strip()
121
+ if not reason_clean:
122
+ raise ValueError("reset() requires an explicit non-empty reason")
123
+ if not approver_clean:
124
+ raise ValueError("reset() requires an explicit non-empty approver")
125
+
126
+ with self._lock:
127
+ current = self._read_fail_closed()
128
+ history = list(current.history)
129
+ now = utc_now()
130
+ history.append(
131
+ {
132
+ "action": "RESET",
133
+ "approver": approver_clean,
134
+ "reason": reason_clean,
135
+ "timestamp": now.isoformat(),
136
+ }
137
+ )
138
+ new_state = KillSwitchState(
139
+ tripped=False,
140
+ reason=reason_clean,
141
+ actor=approver_clean,
142
+ updated_at=now,
143
+ corrupt_or_missing=False,
144
+ history=history[-100:],
145
+ )
146
+ self._write_atomic(new_state)
147
+ return new_state
148
+
149
+ def _read_fail_closed(self) -> KillSwitchState:
150
+ if not self._path.exists():
151
+ return KillSwitchState(
152
+ tripped=True,
153
+ reason="FAIL_CLOSED: kill-switch state file is missing",
154
+ actor="system",
155
+ updated_at=utc_now(),
156
+ corrupt_or_missing=True,
157
+ )
158
+ try:
159
+ raw = self._path.read_text(encoding="utf-8")
160
+ data = json.loads(raw)
161
+ state = KillSwitchState.model_validate(data)
162
+ return state
163
+ except (OSError, json.JSONDecodeError, ValidationError, ValueError) as exc:
164
+ return KillSwitchState(
165
+ tripped=True,
166
+ reason=f"FAIL_CLOSED: kill-switch state file is corrupt or unreadable ({type(exc).__name__})",
167
+ actor="system",
168
+ updated_at=utc_now(),
169
+ corrupt_or_missing=True,
170
+ )
171
+
172
+ def _write_atomic(self, state: KillSwitchState) -> None:
173
+ self._path.parent.mkdir(parents=True, exist_ok=True)
174
+ payload = state.model_dump_json(indent=2)
175
+ fd, tmp_name = tempfile.mkstemp(prefix=".ks_", suffix=".tmp", dir=str(self._path.parent))
176
+ try:
177
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
178
+ fh.write(payload)
179
+ fh.flush()
180
+ os.fsync(fh.fileno())
181
+ os.replace(tmp_name, self._path)
182
+ except Exception:
183
+ if os.path.exists(tmp_name):
184
+ os.unlink(tmp_name)
185
+ raise