@aigis-ai/cli 1.0.3 → 2.0.2

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.
Files changed (47) hide show
  1. package/CONTRIBUTING.md +53 -0
  2. package/README.md +58 -188
  3. package/SKILL.md +20 -55
  4. package/aigis-ai-cli-2.0.1.tgz +0 -0
  5. package/bin/aigis.js +446 -59
  6. package/content/index/audit-scan.md +21 -207
  7. package/content/index/auto-verify-rules.json +439 -0
  8. package/content/index/context-rules.json +90 -0
  9. package/content/resolvers/triggers.json +229 -0
  10. package/content/{implement → skills/areas}/audit-logging.md +5 -0
  11. package/content/skills/areas/fallback-patterns.md +200 -0
  12. package/content/skills/areas/input-validation.md +380 -0
  13. package/content/skills/areas/pii-handling.md +189 -0
  14. package/content/skills/areas/rate-limiting.md +246 -0
  15. package/content/skills/core.md +62 -0
  16. package/content/skills/infrastructure/logging.md +202 -0
  17. package/content/skills/infrastructure/rate-limiting.md +169 -0
  18. package/content/skills/infrastructure/secrets.md +167 -0
  19. package/content/skills/workflows/fastapi-llm.md +86 -0
  20. package/docs/resolvers.md +114 -0
  21. package/lib/auto-verify.js +378 -0
  22. package/lib/build.js +629 -0
  23. package/lib/checksum.js +39 -0
  24. package/lib/fetch.js +164 -9
  25. package/lib/init.js +141 -93
  26. package/lib/keywords.js +92 -130
  27. package/lib/special-recognizers.js +370 -0
  28. package/package.json +1 -1
  29. package/scripts/baseline-cursorrules.snapshot.txt +30 -0
  30. package/scripts/bootstrap-step-6-bench.js +85 -0
  31. package/scripts/check-content-sync.js +91 -0
  32. package/scripts/triggers.schema.json +50 -0
  33. package/scripts/validate-triggers.js +176 -0
  34. package/content/implement/fallback-patterns.md +0 -190
  35. package/content/implement/input-validation.md +0 -212
  36. package/content/implement/pii-handling.md +0 -207
  37. package/content/implement/rate-limiting.md +0 -217
  38. /package/content/{implement → skills/areas}/bias-monitoring.md +0 -0
  39. /package/content/{implement → skills/areas}/confidence-scoring.md +0 -0
  40. /package/content/{implement → skills/areas}/data-integrity.md +0 -0
  41. /package/content/{implement → skills/areas}/explainability.md +0 -0
  42. /package/content/{implement → skills/areas}/human-oversight.md +0 -0
  43. /package/content/{implement → skills/areas}/monitoring.md +0 -0
  44. /package/content/{implement → skills/areas}/output-sanitization.md +0 -0
  45. /package/content/{implement → skills/areas}/prompt-security.md +0 -0
  46. /package/content/{implement → skills/areas}/rag-security.md +0 -0
  47. /package/content/{implement → skills/areas}/supply-chain.md +0 -0
@@ -0,0 +1,229 @@
1
+ {
2
+ "version": "1.0",
3
+ "tier_rule": "High-confidence: phrase implies the listed traits in essentially every realistic project where it appears (no plausible counterexample). Low-confidence: phrase implies the traits only some of the time (a realistic counter-project exists). Decision rule: if you can describe a project where the phrase appears but the trait does not apply, the entry is low-confidence. When in doubt, low-confidence.",
4
+
5
+ "high_confidence": {
6
+ "Anthropic": {
7
+ "traits": ["uses-llm", "uses-thirdparty-api"],
8
+ "confidence": "high",
9
+ "notes": "Mentioning the provider implies third-party + LLM."
10
+ },
11
+ "chatbot": {
12
+ "traits": ["uses-llm", "accepts-user-input"],
13
+ "confidence": "high",
14
+ "notes": "Any LLM-backed conversational interface."
15
+ },
16
+ "Claude": {
17
+ "traits": ["uses-llm", "uses-thirdparty-api"],
18
+ "confidence": "high",
19
+ "notes": "Specific model name implies the provider."
20
+ },
21
+ "code assistant": {
22
+ "traits": ["uses-llm", "generates-code"],
23
+ "confidence": "high",
24
+ "notes": "Code completion or code-explanation tooling."
25
+ },
26
+ "coding agent": {
27
+ "traits": ["uses-llm", "generates-code", "is-agentic"],
28
+ "confidence": "high",
29
+ "notes": "Agent that reads and writes code (Cursor-style)."
30
+ },
31
+ "fine-tune": {
32
+ "traits": ["uses-finetuned"],
33
+ "confidence": "high",
34
+ "notes": "Matches 'fine-tune', 'fine-tuned', 'fine-tuning'."
35
+ },
36
+ "function calling": {
37
+ "traits": ["is-agentic", "uses-llm"],
38
+ "confidence": "high",
39
+ "notes": "OpenAI/Anthropic function/tool calling — by definition agentic."
40
+ },
41
+ "GDPR": {
42
+ "traits": ["jurisdiction-eu"],
43
+ "confidence": "high",
44
+ "notes": "EU regulatory scope."
45
+ },
46
+ "GPT-4": {
47
+ "traits": ["uses-llm", "uses-thirdparty-api"],
48
+ "confidence": "high",
49
+ "notes": "Matches 'GPT-4', 'GPT-4o', 'GPT-4 Turbo' via substring."
50
+ },
51
+ "HIPAA": {
52
+ "traits": ["handles-health", "jurisdiction-us-regulated"],
53
+ "confidence": "high",
54
+ "notes": "Mentioning HIPAA implies health data + US regulated."
55
+ },
56
+ "OpenAI": {
57
+ "traits": ["uses-llm", "uses-thirdparty-api"],
58
+ "confidence": "high",
59
+ "notes": "Same pattern as Anthropic."
60
+ },
61
+ "RAG": {
62
+ "traits": ["uses-rag", "uses-llm"],
63
+ "confidence": "high",
64
+ "notes": "Retrieval-augmented generation. Spelled out in next entry."
65
+ },
66
+ "retrieval-augmented generation": {
67
+ "traits": ["uses-rag", "uses-llm"],
68
+ "confidence": "high",
69
+ "notes": "Spelled-out form of RAG."
70
+ },
71
+ "tool calling": {
72
+ "traits": ["is-agentic", "uses-llm"],
73
+ "confidence": "high",
74
+ "notes": "Same concept as function calling."
75
+ },
76
+ "vector database": {
77
+ "traits": ["uses-rag"],
78
+ "confidence": "high",
79
+ "notes": "Pinecone/Weaviate/Chroma/pgvector — any of these implies RAG."
80
+ }
81
+ },
82
+
83
+ "low_confidence": {
84
+ "AI agent": {
85
+ "traits": ["is-agentic"],
86
+ "confidence": "low",
87
+ "confirmation_prompt": "You mentioned an AI agent. Does an LLM choose the next action at each step (decides which tool to call, when to stop), or is the flow scripted by your code with the LLM only doing per-step generation? (yes / no / unsure)",
88
+ "notes": "'Agent' is overloaded marketing language. True agentic systems delegate the action loop to the LLM."
89
+ },
90
+ "analytics": {
91
+ "traits": ["processes-pii"],
92
+ "confidence": "low",
93
+ "confirmation_prompt": "You mentioned analytics. Are individual users identifiable in the data, or is it aggregated (counts, percentages, no per-user records)? (yes / no / unsure)",
94
+ "notes": "Aggregate analytics avoids PII."
95
+ },
96
+ "checkout": {
97
+ "traits": ["handles-financial"],
98
+ "confidence": "low",
99
+ "confirmation_prompt": "You mentioned checkout. Does this code touch payment processing, transaction records, or money flow? (yes / no / unsure)",
100
+ "notes": "Checkout UI vs payment backend are different things."
101
+ },
102
+ "content moderation": {
103
+ "traits": ["influences-decisions", "accepts-user-input"],
104
+ "confidence": "low",
105
+ "confirmation_prompt": "You mentioned content moderation. Does the AI's classification act on content directly (delete/hide), or does a human reviewer make the final call? (yes / no / unsure)",
106
+ "notes": "Same as 'moderation' but explicit two-trait suggestion."
107
+ },
108
+ "customer support": {
109
+ "traits": ["accepts-user-input", "is-external"],
110
+ "confidence": "low",
111
+ "confirmation_prompt": "You mentioned customer support. Is this exposed directly to customers (external) or only used by your support team (internal)? (yes / no / unsure)",
112
+ "notes": "Some support tools are agent-only."
113
+ },
114
+ "dashboard": {
115
+ "traits": ["processes-pii"],
116
+ "confidence": "low",
117
+ "confirmation_prompt": "You mentioned a dashboard. Does it display per-user data, or aggregate metrics only? (yes / no / unsure)",
118
+ "notes": "Aggregate dashboards skip PII."
119
+ },
120
+ "education": {
121
+ "traits": ["handles-minors"],
122
+ "confidence": "low",
123
+ "confirmation_prompt": "You mentioned education. Is this product used by anyone under 13 (or under 16 in the EU)? (yes / no / unsure)",
124
+ "notes": "Adult education products don't trigger COPPA/minors."
125
+ },
126
+ "email automation": {
127
+ "traits": ["generates-content", "processes-pii"],
128
+ "confidence": "low",
129
+ "confirmation_prompt": "You mentioned email automation. Are the emails generated per-recipient (uses customer data) or templated/broadcast (no per-user PII in the generation)? (yes / no / unsure)",
130
+ "notes": "Drip campaigns differ from per-recipient generation."
131
+ },
132
+ "extract from documents": {
133
+ "traits": ["uses-rag"],
134
+ "confidence": "low",
135
+ "confirmation_prompt": "You mentioned document extraction. Does the system index and search documents semantically (RAG), or is this single-document OCR/extraction without retrieval? (yes / no / unsure)",
136
+ "notes": "OCR pipelines aren't RAG."
137
+ },
138
+ "form processing": {
139
+ "traits": ["accepts-user-input", "processes-pii"],
140
+ "confidence": "low",
141
+ "confirmation_prompt": "You mentioned form processing. Do the forms collect personally identifiable information (name, email, phone, etc.)? (yes / no / unsure)",
142
+ "notes": "Anonymous feedback forms don't have PII."
143
+ },
144
+ "high traffic": {
145
+ "traits": ["is-high-volume"],
146
+ "confidence": "low",
147
+ "confirmation_prompt": "You mentioned high traffic. Are you actually expecting >1000 LLM requests/day, or describing aspirational scale? (yes / no / unsure)",
148
+ "notes": "Aspirational scale != current reality."
149
+ },
150
+ "image upload": {
151
+ "traits": ["is-multimodal"],
152
+ "confidence": "low",
153
+ "confirmation_prompt": "You mentioned image upload. Are the images analyzed by a vision model (multimodal LLM), or just stored/displayed without AI processing? (yes / no / unsure)",
154
+ "notes": "Image hosting != multimodal AI."
155
+ },
156
+ "internal tool": {
157
+ "traits": ["is-internal"],
158
+ "confidence": "low",
159
+ "confirmation_prompt": "You mentioned an internal tool. Is access restricted to employees only (no external users), or is 'internal' a marketing term? (yes / no / unsure)",
160
+ "notes": "Some 'internal' tools have customer-facing surfaces."
161
+ },
162
+ "marketplace": {
163
+ "traits": ["handles-financial", "is-external"],
164
+ "confidence": "low",
165
+ "confirmation_prompt": "You mentioned a marketplace. Does it process payments directly, or just facilitate connections (no money flow through your service)? (yes / no / unsure)",
166
+ "notes": "Lead-gen marketplaces don't always touch money."
167
+ },
168
+ "moderation": {
169
+ "traits": ["influences-decisions"],
170
+ "confidence": "low",
171
+ "confirmation_prompt": "You mentioned moderation. Does the AI act directly on user content (delete, hide, suspend) without a human reviewer in the loop? (yes / no / unsure)",
172
+ "notes": "Human-in-the-loop moderation is advisory, not deciding."
173
+ },
174
+ "notifications": {
175
+ "traits": ["processes-pii"],
176
+ "confidence": "low",
177
+ "confirmation_prompt": "You mentioned notifications. Are notifications addressed to individual users (their email/phone/device token)? (yes / no / unsure)",
178
+ "notes": "Broadcast notifications without targeting don't need PII."
179
+ },
180
+ "personalization": {
181
+ "traits": ["processes-pii"],
182
+ "confidence": "low",
183
+ "confirmation_prompt": "You mentioned personalization. Does this system use information that identifies an individual user (account, profile, history) to personalize output? Anonymous session-only personalization does not count. (yes / no / unsure)",
184
+ "notes": "Anonymous session-based personalization doesn't trigger PII."
185
+ },
186
+ "recommendations": {
187
+ "traits": ["influences-decisions"],
188
+ "confidence": "low",
189
+ "confirmation_prompt": "You mentioned recommendations. Do they directly affect a user's outcomes (price, eligibility, hiring) or are they advisory only? (yes / no / unsure)",
190
+ "notes": "Product recommendations are usually advisory; loan recommendations are not."
191
+ },
192
+ "search through documents": {
193
+ "traits": ["uses-rag"],
194
+ "confidence": "low",
195
+ "confirmation_prompt": "You mentioned searching through documents. Are the documents embedded into a vector store, or is this keyword search (Postgres FTS, Elasticsearch BM25, grep)? (yes / no / unsure)",
196
+ "notes": "Keyword search != RAG."
197
+ },
198
+ "summarize": {
199
+ "traits": ["uses-llm", "generates-content"],
200
+ "confidence": "low",
201
+ "confirmation_prompt": "You mentioned summarization. Is this an LLM summary, or extractive (pulling sentences out without an LLM)? (yes / no / unsure)",
202
+ "notes": "Extractive summarization predates LLMs."
203
+ },
204
+ "translation": {
205
+ "traits": ["uses-llm"],
206
+ "confidence": "low",
207
+ "confirmation_prompt": "You mentioned translation. Is this LLM-based, or using a dedicated translation API (Google Translate, DeepL) without an LLM? (yes / no / unsure)",
208
+ "notes": "Translation APIs != LLMs."
209
+ },
210
+ "user profile": {
211
+ "traits": ["processes-pii"],
212
+ "confidence": "low",
213
+ "confirmation_prompt": "You mentioned user profiles. Do these profiles include personally identifiable information (name, email, address, etc.)? (yes / no / unsure)",
214
+ "notes": "Pseudonymous profiles can avoid PII traits."
215
+ },
216
+ "voice assistant": {
217
+ "traits": ["is-multimodal", "accepts-user-input", "uses-llm"],
218
+ "confidence": "low",
219
+ "confirmation_prompt": "You mentioned voice. Is voice the input/output modality (multimodal LLM), or is voice transcribed to text first by a separate service before reaching your LLM? (yes / no / unsure)",
220
+ "notes": "STT-then-LLM is text-only at the LLM layer."
221
+ },
222
+ "writing assistant": {
223
+ "traits": ["uses-llm", "generates-content"],
224
+ "confidence": "low",
225
+ "confirmation_prompt": "You mentioned a writing assistant. Does it generate text on its own (uses-llm + generates-content), or only check spelling/grammar against rules? (yes / no / unsure)",
226
+ "notes": "Grammarly-style rule-based tools don't need LLM traits."
227
+ }
228
+ }
229
+ }
@@ -169,3 +169,8 @@ function logDecision(decision, context) {
169
169
  - **Log volume at scale.** At high volume, consider sampling non-critical logs while keeping 100% of error and decision logs.
170
170
  - **Log retention and compliance.** Different regulations require different retention periods. Configure per data type.
171
171
  - **Cross-system correlation.** If the AI system calls external services, propagate trace IDs via headers.
172
+
173
+ ## Related infrastructure
174
+
175
+ - `aigis infra logging` — `structlog` JSON-to-stdout setup with a concrete `REDACT_KEYS` list, plus integration patterns for Datadog/New Relic/Honeycomb, CloudWatch, Sentry (with the `max_request_body_size='never'` warning), and OpenTelemetry/OTLP.
176
+ - `aigis infra secrets` — keep API keys and connection strings out of the structured fields you log.
@@ -0,0 +1,200 @@
1
+ ---
2
+ id: fallback-patterns
3
+ title: Fallback patterns, circuit breaker, kill switch
4
+ controls:
5
+ owasp: []
6
+ nist: [MEASURE-2.6, MANAGE-2.3, MANAGE-2.4]
7
+ iso42001: [Clause-8.2]
8
+ min_risk_tier: all
9
+ system_traits: [uses-llm, is-agentic, is-high-volume]
10
+ ---
11
+
12
+ When an LLM call fails or behaves badly, the system must fail safely, recover automatically from transient failures, and allow operators to disable the AI feature during an incident without redeploying code.
13
+
14
+ ## Common incomplete implementations
15
+
16
+ These are the specific failure modes this procedure is designed to prevent. If your implementation matches one of these, keep going — do not stop after hitting the basic pattern.
17
+
18
+ 1. **Kill switch read at module load.** An env var like `AI_SYSTEM_ENABLED` assigned to a module-level constant (`KILL_SWITCH = os.getenv(...)`) or fetched via a `@lru_cache`-decorated `get_settings()` is read once at import and never again. Flipping the flag in production requires a restart — which is exactly the thing you wanted to avoid during an incident.
19
+ 2. **Circuit breaker that never closes.** Two-state (open/closed) breakers trip and stay tripped, because there is no HALF_OPEN probe state. Traffic is stuck on fallback until someone manually resets.
20
+ 3. **Circuit breaker that wraps only one LLM callsite.** If your code calls the LLM from multiple places, every callsite must route through the same breaker or the breaker gives a false sense of safety.
21
+ 4. **Fallback returns an error instead of a defined safe response.** Raising an exception on LLM failure propagates a 500 to the user. The fallback should return a deterministic safe payload (e.g., `recommendation=standard, confidence=0`).
22
+
23
+ ## Implementation procedure
24
+
25
+ Work through these steps in order. Do not skip the verification checkpoints — they catch the specific gaps that appear across independent implementations of this pattern.
26
+
27
+ ### Step 1 — Define a default safe response
28
+
29
+ **What to do.** Write a `default_safe_response()` function that returns a neutral payload: conservative routing (e.g., `"standard"`), `confidence=0.0`, a disclaimer string. Same shape as a successful LLM response.
30
+
31
+ **Why this matters.** Without a defined fallback, an LLM failure becomes an application error. The safe response is what lets every later step actually return something.
32
+
33
+ **Verification checkpoint.** The safe response is callable with no arguments and returns the same keys a successful call would. See the complete example at the end for the shape.
34
+
35
+ ### Step 2 — Implement a circuit breaker with three states
36
+
37
+ **What to do.** Write a `CircuitBreaker` class with explicit states: `"closed"`, `"open"`, `"half-open"`. Configurable `failure_threshold` and `reset_timeout`. On threshold → OPEN. After reset timeout → HALF_OPEN probe. On probe success → CLOSED. On probe failure → back to OPEN.
38
+
39
+ **Why this matters.** Two-state breakers (open/closed only) need manual intervention to recover. Three-state breakers recover themselves.
40
+
41
+ **Verification checkpoint.** Grep your code for the three state strings. If you only find `"closed"` and `"open"`, you built a two-state breaker — iterate until `"half-open"` is implemented.
42
+
43
+ ### Step 3 — Route every LLM callsite through the breaker
44
+
45
+ **What to do.** Find every place in your codebase where you invoke the LLM client (e.g., `client.messages.create`, `openai.chat.completions.create`). Each must go through the breaker via a single helper (`call_llm_safely(func)`).
46
+
47
+ **Why this matters.** A breaker that only protects one callsite leaves the others exposed. When the provider has an outage, unprotected paths will still hammer it.
48
+
49
+ **Verification checkpoint.** `grep -rn "messages.create\|chat.completions.create"` in your source. For every hit, confirm it is wrapped by the breaker helper. Bare calls bypass the breaker — fix before continuing.
50
+
51
+ ### Step 4 — Kill switch read per-request ⚠ CRITICAL
52
+
53
+ **What to do.** Implement a toggle that disables the AI feature without redeploying. The check must happen **inside the request handler**, reading the env var (or config-service value) at request time — not at module load.
54
+
55
+ **Why this matters.** Every baseline run of this pattern built a toggle that satisfied the literal checklist wording ("there is an env variable") but was read only at process startup. During an actual incident you cannot flip the flag without a rolling restart — which defeats the purpose.
56
+
57
+ ```python
58
+ # CORRECT — read inside the handler, every request
59
+ def ai_system_enabled() -> bool:
60
+ return os.getenv("AI_SYSTEM_ENABLED", "true").lower() == "true"
61
+
62
+ # WRONG — all three of these are restart-latched
63
+ KILL_SWITCH = os.getenv("KILL_SWITCH", "0") == "1" # module-level constant
64
+ @lru_cache
65
+ def get_settings(): return Settings() # cached forever
66
+ settings = Settings() # module-level instance
67
+ ```
68
+
69
+ **Verification checkpoint.** Run these greps. If any match controls your kill switch, it's restart-latched — fix before continuing:
70
+
71
+ - `grep -rn "@lru_cache" --include="*.py"` on any settings-returning function
72
+ - `grep -rn "^KILL_SWITCH\|^AI_SYSTEM_ENABLED\|^AI_ENABLED" --include="*.py"` at module scope
73
+ - `grep -rn "settings = Settings()" --include="*.py"` imported by a handler
74
+
75
+ This is the critical gap.
76
+
77
+ ### Step 5 — Confirm the toggle works without restart
78
+
79
+ **What to do.** Start the service. Send a request and see the AI feature respond. Flip the env var (`AI_SYSTEM_ENABLED=false`) in the running process's environment — or if you cannot mutate env vars post-start, point the service at a config file or feature-flag service whose value you can change. Send another request and confirm it returns the fallback.
80
+
81
+ **Why this matters.** This is the only test that proves Step 4 actually worked. An agent or reviewer grepping for `ai_system_enabled` will see the check exists; only a runtime flip tells you whether the check is live.
82
+
83
+ **Verification checkpoint.** Document the result of this test in a comment or test file. If you could not make the toggle take effect without a restart, Step 4 is not done yet — iterate.
84
+
85
+ ### Step 6 — Wrap every LLM call in exception handling
86
+
87
+ **What to do.** Every LLM call path should be surrounded by a `try/except`. On any exception the fallback returns the safe response and the incident is logged with context. Unhandled exceptions must never propagate to the HTTP response.
88
+
89
+ **Why this matters.** Defense in depth: the breaker catches repeated failures, but a single unexpected failure should also not crash the request.
90
+
91
+ **Verification checkpoint.** Every LLM callsite from Step 3 is inside a `try/except`. No bare `raise` inside the handler body that would escape to the client without a fallback.
92
+
93
+ ## Complete working example
94
+
95
+ ```python
96
+ """Fallback patterns: circuit breaker, kill switch, safe default, exception guard."""
97
+
98
+ from __future__ import annotations
99
+
100
+ import logging
101
+ import os
102
+ import time
103
+ from typing import Any, Callable, TypeVar
104
+
105
+ from fastapi import FastAPI
106
+ from pydantic import BaseModel
107
+
108
+ logger = logging.getLogger("fallback")
109
+ app = FastAPI()
110
+ T = TypeVar("T")
111
+
112
+
113
+ # ─── Step 1 — default safe response ────────────────────────────────────
114
+ def default_safe_response() -> dict[str, Any]:
115
+ return {
116
+ "severity_score": 5,
117
+ "recommendation": "standard",
118
+ "confidence_score": 0.0,
119
+ "disclaimer": "Automated assessment unavailable; human review required.",
120
+ "fallback": True,
121
+ }
122
+
123
+
124
+ # ─── Step 2 — three-state circuit breaker ──────────────────────────────
125
+ class CircuitBreaker:
126
+ def __init__(self, failure_threshold: int = 5, reset_timeout: int = 60):
127
+ self.failure_threshold = failure_threshold
128
+ self.reset_timeout = reset_timeout
129
+ self.state = "closed"
130
+ self.failure_count = 0
131
+ self.last_failure_time: float | None = None
132
+
133
+ def call(self, func: Callable[[], T]) -> T:
134
+ now = time.time()
135
+ if self.state == "open":
136
+ if self.last_failure_time and now - self.last_failure_time > self.reset_timeout:
137
+ self.state = "half-open"
138
+ else:
139
+ logger.warning("circuit_breaker_open")
140
+ return default_safe_response() # type: ignore[return-value]
141
+
142
+ try:
143
+ result = func()
144
+ if self.state == "half-open":
145
+ self.state = "closed"
146
+ self.failure_count = 0
147
+ return result
148
+ except Exception:
149
+ self.failure_count += 1
150
+ self.last_failure_time = now
151
+ if self.failure_count >= self.failure_threshold:
152
+ self.state = "open"
153
+ logger.error("circuit_breaker_tripped failures=%s", self.failure_count)
154
+ return default_safe_response() # type: ignore[return-value]
155
+
156
+
157
+ _llm_breaker = CircuitBreaker(failure_threshold=5, reset_timeout=60)
158
+
159
+
160
+ # ─── Step 3 — single wrapper every LLM callsite uses ───────────────────
161
+ def call_llm_safely(func: Callable[[], T]) -> T:
162
+ return _llm_breaker.call(func)
163
+
164
+
165
+ # ─── Step 4 — kill switch read per-request ⚠ CRITICAL ──────────────────
166
+ def ai_system_enabled() -> bool:
167
+ """Read the toggle fresh each call. No @lru_cache. No module-level cache."""
168
+ return os.getenv("AI_SYSTEM_ENABLED", "true").lower() == "true"
169
+
170
+
171
+ # ─── Step 6 — exception guard on the handler ───────────────────────────
172
+ class AssessRequest(BaseModel):
173
+ claim_description: str
174
+
175
+
176
+ @app.post("/api/assess-claim")
177
+ async def assess_claim(body: AssessRequest) -> dict[str, Any]:
178
+ if not ai_system_enabled(): # Step 4: per-request check
179
+ return default_safe_response()
180
+
181
+ try:
182
+ result = call_llm_safely( # Step 3: breaker wrapper
183
+ lambda: _invoke_llm(body.claim_description)
184
+ )
185
+ return result
186
+ except Exception as exc: # Step 6: exception guard
187
+ logger.exception("llm_call_failed", extra={"error": str(exc)})
188
+ return default_safe_response()
189
+
190
+
191
+ def _invoke_llm(text: str) -> dict[str, Any]:
192
+ # Replace with your actual client call. Must raise on any failure
193
+ # so the breaker can count it.
194
+ ...
195
+ ```
196
+
197
+ ## Related patterns
198
+
199
+ - `human-oversight.md` — low-confidence decisions routed to review.
200
+ - `monitoring.md` — breaker trips and fallback rates as operational metrics.