@aigis-ai/cli 2.0.1 → 2.1.0

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 (111) hide show
  1. package/README.md +97 -178
  2. package/bin/aigis.js +139 -8
  3. package/content/resolvers/triggers.json +363 -41
  4. package/content/skills/areas/audit-logging.md +33 -0
  5. package/content/skills/areas/bias-monitoring.md +34 -0
  6. package/content/skills/areas/confidence-scoring.md +23 -0
  7. package/content/skills/areas/data-integrity.md +25 -0
  8. package/content/skills/areas/eu-ai-act-art-13-deployer-transparency.md +133 -0
  9. package/content/skills/areas/eu-ai-act-art-50-transparency-disclosure.md +134 -0
  10. package/content/skills/areas/eu-ai-act-art-73-incident-reporting.md +149 -0
  11. package/content/skills/areas/eu-ai-act-art-9-risk-management.md +141 -0
  12. package/content/skills/areas/fallback-patterns.md +28 -0
  13. package/content/skills/areas/human-oversight.md +38 -0
  14. package/content/skills/areas/input-validation.md +27 -0
  15. package/content/skills/areas/monitoring.md +29 -0
  16. package/content/skills/areas/prompt-security.md +29 -0
  17. package/content/templates/eu-ai-act-annex-iv.md +193 -0
  18. package/docs/frontmatter-schema.md +75 -0
  19. package/docs/screenshots/README.md +17 -0
  20. package/docs/screenshots/agent-flow.png +0 -0
  21. package/docs/screenshots/setup.png +0 -0
  22. package/docs/screenshots/verify.png +0 -0
  23. package/lib/auto-verify.js +70 -1
  24. package/lib/build.js +101 -12
  25. package/lib/classify.js +8 -2
  26. package/lib/init.js +269 -5
  27. package/lib/jurisdiction.js +137 -0
  28. package/lib/report.js +331 -0
  29. package/package.json +1 -1
  30. package/scripts/area-controls-baseline.json +188 -0
  31. package/scripts/area-frontmatter.schema.json +61 -0
  32. package/scripts/validate-area-frontmatter.js +228 -0
  33. package/cli-python/LICENSE +0 -21
  34. package/cli-python/README.md +0 -32
  35. package/cli-python/aigis_cli/SKILL.md +0 -70
  36. package/cli-python/aigis_cli/__init__.py +0 -3
  37. package/cli-python/aigis_cli/__pycache__/__init__.cpython-313.pyc +0 -0
  38. package/cli-python/aigis_cli/__pycache__/annotate.cpython-313.pyc +0 -0
  39. package/cli-python/aigis_cli/__pycache__/build.cpython-313.pyc +0 -0
  40. package/cli-python/aigis_cli/__pycache__/checksum.cpython-313.pyc +0 -0
  41. package/cli-python/aigis_cli/__pycache__/classify.cpython-313.pyc +0 -0
  42. package/cli-python/aigis_cli/__pycache__/cli.cpython-313.pyc +0 -0
  43. package/cli-python/aigis_cli/__pycache__/fetch.cpython-313.pyc +0 -0
  44. package/cli-python/aigis_cli/__pycache__/init_ide.cpython-313.pyc +0 -0
  45. package/cli-python/aigis_cli/__pycache__/keywords.cpython-313.pyc +0 -0
  46. package/cli-python/aigis_cli/__pycache__/search.cpython-313.pyc +0 -0
  47. package/cli-python/aigis_cli/annotate.py +0 -45
  48. package/cli-python/aigis_cli/auto_verify.py +0 -518
  49. package/cli-python/aigis_cli/build.py +0 -470
  50. package/cli-python/aigis_cli/checksum.py +0 -22
  51. package/cli-python/aigis_cli/classify.py +0 -192
  52. package/cli-python/aigis_cli/cli.py +0 -618
  53. package/cli-python/aigis_cli/content/index/audit-scan.md +0 -217
  54. package/cli-python/aigis_cli/content/index/auto-verify-rules.json +0 -439
  55. package/cli-python/aigis_cli/content/index/context-rules.json +0 -90
  56. package/cli-python/aigis_cli/content/index/frameworks.md +0 -82
  57. package/cli-python/aigis_cli/content/index/guardrails.json +0 -23
  58. package/cli-python/aigis_cli/content/index/taxonomy.md +0 -81
  59. package/cli-python/aigis_cli/content/resolvers/triggers.json +0 -229
  60. package/cli-python/aigis_cli/content/skills/areas/audit-logging.md +0 -176
  61. package/cli-python/aigis_cli/content/skills/areas/bias-monitoring.md +0 -172
  62. package/cli-python/aigis_cli/content/skills/areas/confidence-scoring.md +0 -180
  63. package/cli-python/aigis_cli/content/skills/areas/data-integrity.md +0 -257
  64. package/cli-python/aigis_cli/content/skills/areas/explainability.md +0 -174
  65. package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +0 -200
  66. package/cli-python/aigis_cli/content/skills/areas/human-oversight.md +0 -220
  67. package/cli-python/aigis_cli/content/skills/areas/input-validation.md +0 -380
  68. package/cli-python/aigis_cli/content/skills/areas/monitoring.md +0 -207
  69. package/cli-python/aigis_cli/content/skills/areas/output-sanitization.md +0 -183
  70. package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +0 -189
  71. package/cli-python/aigis_cli/content/skills/areas/prompt-security.md +0 -153
  72. package/cli-python/aigis_cli/content/skills/areas/rag-security.md +0 -230
  73. package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +0 -246
  74. package/cli-python/aigis_cli/content/skills/areas/supply-chain.md +0 -193
  75. package/cli-python/aigis_cli/content/skills/core.md +0 -62
  76. package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +0 -202
  77. package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +0 -169
  78. package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +0 -167
  79. package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +0 -86
  80. package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +0 -54
  81. package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +0 -39
  82. package/cli-python/aigis_cli/content/templates/risk-characterization.md +0 -34
  83. package/cli-python/aigis_cli/content/templates/third-party-assessment.md +0 -41
  84. package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +0 -13
  85. package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +0 -13
  86. package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +0 -13
  87. package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +0 -12
  88. package/cli-python/aigis_cli/content/verify/checklist-explainability.md +0 -13
  89. package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +0 -13
  90. package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +0 -14
  91. package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +0 -16
  92. package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +0 -13
  93. package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +0 -14
  94. package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +0 -14
  95. package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +0 -13
  96. package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +0 -12
  97. package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +0 -13
  98. package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +0 -13
  99. package/cli-python/aigis_cli/fetch.py +0 -232
  100. package/cli-python/aigis_cli/init_ide.py +0 -159
  101. package/cli-python/aigis_cli/keywords.py +0 -73
  102. package/cli-python/aigis_cli/search.py +0 -69
  103. package/cli-python/aigis_cli.egg-info/PKG-INFO +0 -59
  104. package/cli-python/aigis_cli.egg-info/SOURCES.txt +0 -56
  105. package/cli-python/aigis_cli.egg-info/dependency_links.txt +0 -1
  106. package/cli-python/aigis_cli.egg-info/entry_points.txt +0 -2
  107. package/cli-python/aigis_cli.egg-info/requires.txt +0 -6
  108. package/cli-python/aigis_cli.egg-info/top_level.txt +0 -1
  109. package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
  110. package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
  111. package/cli-python/pyproject.toml +0 -49
@@ -1,257 +0,0 @@
1
- ---
2
- id: data-integrity
3
- title: Data integrity and poisoning prevention
4
- controls:
5
- owasp: [LLM04]
6
- nist: [MAP-2.3, MEASURE-2.6]
7
- iso42001: [Annex-A.7]
8
- min_risk_tier: all
9
- system_traits: [uses-rag, uses-finetuned]
10
- ---
11
-
12
- ## What this addresses
13
-
14
- OWASP LLM04 covers data and model poisoning — manipulation of training, fine-tuning, or RAG data to introduce biases, backdoors, or vulnerabilities. Particularly critical when using external data sources for retrieval-augmented generation.
15
-
16
- ## Implementation patterns
17
-
18
- ### Pattern 1: Data provenance tracking
19
-
20
- ```python
21
- class DataProvenanceTracker:
22
- def record_ingestion(self, source: str, data: bytes, metadata: dict) -> str:
23
- doc_id = generate_id()
24
- record = {
25
- "doc_id": doc_id,
26
- "source": source,
27
- "ingested_at": datetime.utcnow().isoformat(),
28
- "checksum": hashlib.sha256(data).hexdigest(),
29
- "size_bytes": len(data),
30
- "ingested_by": metadata.get("user"),
31
- "source_verified": metadata.get("verified", False)
32
- }
33
- self.provenance_store.insert(record)
34
- return doc_id
35
-
36
- def verify_integrity(self, doc_id: str, data: bytes) -> bool:
37
- record = self.provenance_store.get(doc_id)
38
- current_checksum = hashlib.sha256(data).hexdigest()
39
- return current_checksum == record["checksum"]
40
- ```
41
-
42
- ```javascript
43
- const crypto = require('crypto');
44
-
45
- class DataProvenanceTracker {
46
- async recordIngestion(source, data, metadata) {
47
- const docId = generateId();
48
- const record = {
49
- docId,
50
- source,
51
- ingestedAt: new Date().toISOString(),
52
- checksum: crypto.createHash('sha256').update(data).digest('hex'),
53
- sizeBytes: data.length,
54
- ingestedBy: metadata.user,
55
- sourceVerified: metadata.verified || false,
56
- };
57
- await this.provenanceStore.insert(record);
58
- return docId;
59
- }
60
-
61
- async verifyIntegrity(docId, data) {
62
- const record = await this.provenanceStore.get(docId);
63
- const currentChecksum = crypto.createHash('sha256').update(data).digest('hex');
64
- return currentChecksum === record.checksum;
65
- }
66
- }
67
- ```
68
-
69
-
70
- ### Pattern 2: RAG data validation pipeline
71
-
72
- ```python
73
- def validate_before_embedding(document: dict) -> bool:
74
- """Validate documents before they enter the vector store."""
75
- # Check source trustworthiness
76
- if document["source"] not in TRUSTED_SOURCES:
77
- log_event("untrusted_source_rejected", source=document["source"])
78
- return False
79
- # Check for injection patterns in content
80
- if check_injection_patterns(document["content"])["flagged"]:
81
- log_event("suspicious_content_rejected", doc_id=document["id"])
82
- return False
83
- # Check document freshness
84
- if document.get("last_updated"):
85
- age_days = (datetime.utcnow() - document["last_updated"]).days
86
- if age_days > MAX_DOCUMENT_AGE_DAYS:
87
- log_event("stale_document_flagged", doc_id=document["id"], age=age_days)
88
- return False
89
- return True
90
- ```
91
-
92
- ```javascript
93
- async function validateBeforeEmbedding(document) {
94
- if (!TRUSTED_SOURCES.includes(document.source)) {
95
- logEvent('untrusted_source_rejected', { source: document.source });
96
- return false;
97
- }
98
- if (checkInjectionPatterns(document.content).flagged) {
99
- logEvent('suspicious_content_rejected', { docId: document.id });
100
- return false;
101
- }
102
- if (document.lastUpdated) {
103
- const ageDays = (Date.now() - new Date(document.lastUpdated)) / 86400000;
104
- if (ageDays > MAX_DOCUMENT_AGE_DAYS) {
105
- logEvent('stale_document_flagged', { docId: document.id, age: Math.round(ageDays) });
106
- return false;
107
- }
108
- }
109
- return true;
110
- }
111
- ```
112
-
113
-
114
- ### Pattern 3: Fine-tuning data checksums
115
-
116
- ```python
117
- def prepare_training_data(dataset_path: str) -> dict:
118
- """Create checksummed, versioned training data package."""
119
- data = load_dataset(dataset_path)
120
- return {
121
- "data": data,
122
- "version": generate_version(),
123
- "checksum": hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest(),
124
- "record_count": len(data),
125
- "created_at": datetime.utcnow().isoformat(),
126
- "schema_version": TRAINING_DATA_SCHEMA_VERSION
127
- }
128
- ```
129
-
130
- ```javascript
131
- const crypto = require('crypto');
132
-
133
- function prepareTrainingData(dataset) {
134
- const serialized = JSON.stringify(dataset, Object.keys(dataset).sort());
135
- return {
136
- data: dataset,
137
- version: generateVersion(),
138
- checksum: crypto.createHash('sha256').update(serialized).digest('hex'),
139
- recordCount: dataset.length,
140
- createdAt: new Date().toISOString(),
141
- schemaVersion: TRAINING_DATA_SCHEMA_VERSION,
142
- };
143
- }
144
- ```
145
-
146
-
147
-
148
- ### Pattern 4: Anomaly detection on embedding distributions
149
-
150
- ```python
151
- import numpy as np
152
-
153
- class EmbeddingDistributionMonitor:
154
- def __init__(self, baseline_embeddings: np.ndarray):
155
- self.baseline_mean = np.mean(baseline_embeddings, axis=0)
156
- self.baseline_std = np.std(baseline_embeddings, axis=0)
157
-
158
- def check_batch(self, new_embeddings: np.ndarray, threshold: float = 3.0) -> dict:
159
- new_mean = np.mean(new_embeddings, axis=0)
160
- z_scores = np.abs((new_mean - self.baseline_mean) / (self.baseline_std + 1e-8))
161
- anomalous_dims = np.sum(z_scores > threshold)
162
- is_anomalous = anomalous_dims > len(z_scores) * 0.1 # >10% dims shifted
163
- if is_anomalous:
164
- log_security_event("embedding_distribution_shift",
165
- anomalous_dims=int(anomalous_dims),
166
- max_z=float(np.max(z_scores)))
167
- return {"anomalous": is_anomalous, "anomalous_dimensions": int(anomalous_dims)}
168
- ```
169
-
170
- ```javascript
171
- class EmbeddingDistributionMonitor {
172
- constructor(baselineEmbeddings) {
173
- this.baselineMean = this.mean(baselineEmbeddings);
174
- this.baselineStd = this.std(baselineEmbeddings);
175
- }
176
-
177
- checkBatch(newEmbeddings, threshold = 3.0) {
178
- const newMean = this.mean(newEmbeddings);
179
- const zScores = this.baselineMean.map((bm, i) =>
180
- Math.abs((newMean[i] - bm) / (this.baselineStd[i] + 1e-8))
181
- );
182
- const anomalousDims = zScores.filter(z => z > threshold).length;
183
- const isAnomalous = anomalousDims > zScores.length * 0.1;
184
- if (isAnomalous)
185
- logSecurityEvent('embedding_distribution_shift', { anomalousDims });
186
- return { anomalous: isAnomalous, anomalousDimensions: anomalousDims };
187
- }
188
-
189
- mean(matrix) { /* compute column means */ }
190
- std(matrix) { /* compute column stds */ }
191
- }
192
- ```
193
-
194
- ### Pattern 5: Batch rollback for poisoned data
195
-
196
- ```python
197
- class DataBatchManager:
198
- def ingest_batch(self, batch_id: str, documents: list) -> dict:
199
- """Ingest with rollback capability."""
200
- ingested_ids = []
201
- try:
202
- for doc in documents:
203
- if not validate_before_embedding(doc):
204
- raise ValueError(f"Validation failed for doc {doc['id']}")
205
- doc_id = self.vector_store.upsert(doc)
206
- ingested_ids.append(doc_id)
207
- self.batch_store.record(batch_id, ingested_ids, status="complete")
208
- return {"status": "complete", "count": len(ingested_ids)}
209
- except Exception as e:
210
- self.rollback(batch_id, ingested_ids)
211
- return {"status": "rolled_back", "error": str(e)}
212
-
213
- def rollback(self, batch_id: str, doc_ids: list):
214
- for doc_id in doc_ids:
215
- self.vector_store.delete(doc_id)
216
- self.batch_store.record(batch_id, doc_ids, status="rolled_back")
217
- log_event("batch_rolled_back", batch_id=batch_id, count=len(doc_ids))
218
- ```
219
-
220
- ```javascript
221
- class DataBatchManager {
222
- async ingestBatch(batchId, documents) {
223
- const ingestedIds = [];
224
- try {
225
- for (const doc of documents) {
226
- if (!(await validateBeforeEmbedding(doc)))
227
- throw new Error('Validation failed for doc ' + doc.id);
228
- const docId = await this.vectorStore.upsert(doc);
229
- ingestedIds.push(docId);
230
- }
231
- await this.batchStore.record(batchId, ingestedIds, 'complete');
232
- return { status: 'complete', count: ingestedIds.length };
233
- } catch (e) {
234
- await this.rollback(batchId, ingestedIds);
235
- return { status: 'rolled_back', error: e.message };
236
- }
237
- }
238
-
239
- async rollback(batchId, docIds) {
240
- for (const docId of docIds) await this.vectorStore.delete(docId);
241
- await this.batchStore.record(batchId, docIds, 'rolled_back');
242
- logEvent('batch_rolled_back', { batchId, count: docIds.length });
243
- }
244
- }
245
- ```
246
-
247
- ## Anti-patterns
248
-
249
- - **Ingesting data from unverified sources into RAG.** Validate source trustworthiness.
250
- - **No checksums on training data.** Always verify data integrity before training.
251
- - **No monitoring for anomalous model behavior after data updates.** Track output distributions.
252
-
253
- ## Edge cases
254
-
255
- - **Adversarial documents.** Documents crafted to influence RAG retrieval (SEO-like attacks on vector search).
256
- - **Slow poisoning.** Gradual introduction of biased data over time. Monitor distribution shifts.
257
- - **Third-party data feeds.** External data sources can be compromised. Validate at every sync.
@@ -1,174 +0,0 @@
1
- ---
2
- id: explainability
3
- title: Explainability and transparency
4
- controls:
5
- owasp: []
6
- nist: [MEASURE-2.8, MEASURE-2.9]
7
- iso42001: [Annex-A.8, Clause-7.4]
8
- min_risk_tier: high
9
- system_traits: [influences-decisions, handles-health, jurisdiction-eu]
10
- ---
11
-
12
- ## What this addresses
13
-
14
- NIST MEASURE 2.9 requires that AI models are explained, validated, and documented. ISO 42001 Annex A.8 covers information for interested parties — stakeholders need to understand how AI decisions are made. The EU AI Act requires explainability for high-risk systems.
15
-
16
- ## Implementation patterns
17
-
18
- ### Pattern 1: Decision explanation generation
19
-
20
- ```python
21
- def generate_explanation(decision: dict, context: dict) -> dict:
22
- """Generate a human-readable explanation of the AI decision."""
23
- return {
24
- "decision": decision["recommendation"],
25
- "explanation": {
26
- "primary_factors": extract_key_factors(context["input"], decision),
27
- "confidence_basis": explain_confidence(decision["confidence"]),
28
- "limitations": [
29
- "Assessment based only on claim description text",
30
- "Does not account for claim history or policy details",
31
- "Should be reviewed by a qualified adjuster"
32
- ]
33
- },
34
- "model_info": {
35
- "model_type": "Large language model (text analysis)",
36
- "version": decision["model_version"],
37
- "training_description": "General-purpose model, not fine-tuned on claims data"
38
- }
39
- }
40
- ```
41
-
42
- ```javascript
43
- function generateExplanation(decision, context) {
44
- return {
45
- decision: decision.recommendation,
46
- explanation: {
47
- primaryFactors: extractKeyFactors(context.input, decision),
48
- confidenceBasis: explainConfidence(decision.confidence),
49
- limitations: [
50
- 'Assessment based only on claim description text',
51
- 'Does not account for claim history or policy details',
52
- 'Should be reviewed by a qualified adjuster',
53
- ],
54
- },
55
- modelInfo: {
56
- modelType: 'Large language model (text analysis)',
57
- version: decision.modelVersion,
58
- trainingDescription: 'General-purpose model, not fine-tuned on claims data',
59
- },
60
- };
61
- }
62
- ```
63
-
64
-
65
- ### Pattern 2: Model card generation
66
-
67
- ```python
68
- def generate_model_card() -> dict:
69
- """Structured model documentation per NIST MEASURE 2.9."""
70
- return {
71
- "model_name": "Claims Severity Assessor",
72
- "version": MODEL_VERSION,
73
- "intended_use": "Advisory assessment of insurance claim severity",
74
- "not_intended_for": [
75
- "Autonomous claim decisions without human review",
76
- "Assessment of claim validity or fraud detection",
77
- "Processing claims involving legal disputes"
78
- ],
79
- "known_limitations": [
80
- "Performance degrades on claims under 20 words",
81
- "Does not handle multi-incident claims well",
82
- "May show bias toward formal writing styles"
83
- ],
84
- "performance_metrics": load_latest_evaluation_results(),
85
- "fairness_evaluation": load_latest_fairness_report(),
86
- "last_evaluated": get_last_evaluation_date(),
87
- "contact": "ai-risk-team@company.com"
88
- }
89
- ```
90
-
91
- ```javascript
92
- function generateModelCard() {
93
- return {
94
- modelName: 'Claims Severity Assessor',
95
- version: MODEL_VERSION,
96
- intendedUse: 'Advisory assessment of insurance claim severity',
97
- notIntendedFor: [
98
- 'Autonomous claim decisions without human review',
99
- 'Assessment of claim validity or fraud detection',
100
- 'Processing claims involving legal disputes',
101
- ],
102
- knownLimitations: [
103
- 'Performance degrades on claims under 20 words',
104
- 'Does not handle multi-incident claims well',
105
- 'May show bias toward formal writing styles',
106
- ],
107
- performanceMetrics: loadLatestEvaluationResults(),
108
- fairnessEvaluation: loadLatestFairnessReport(),
109
- lastEvaluated: getLastEvaluationDate(),
110
- contact: 'ai-risk-team@company.com',
111
- };
112
- }
113
- ```
114
-
115
-
116
- ### Pattern 3: Audit-friendly decision records
117
-
118
- ```python
119
- def create_decision_record(decision: dict, explanation: dict, context: dict) -> dict:
120
- """Complete record for compliance audit per ISO 42001 Clause 9.1."""
121
- return {
122
- "record_id": generate_id(),
123
- "timestamp": datetime.utcnow().isoformat(),
124
- "decision": decision,
125
- "explanation": explanation,
126
- "input_summary": summarize(context["input"]), # Not raw input
127
- "controls_applied": context["controls"],
128
- "risk_tier": context["risk_tier"],
129
- "human_reviewable": True,
130
- "appeal_available": True,
131
- "appeal_endpoint": "/api/v1/appeal",
132
- "retention_period_days": 365,
133
- "framework_references": {
134
- "nist": ["MEASURE-2.8", "MEASURE-2.9"],
135
- "iso42001": ["Annex-A.8", "Clause-9.1"]
136
- }
137
- }
138
- ```
139
-
140
- ```javascript
141
- function createDecisionRecord(decision, explanation, context) {
142
- return {
143
- recordId: generateId(),
144
- timestamp: new Date().toISOString(),
145
- decision,
146
- explanation,
147
- inputSummary: summarize(context.input),
148
- controlsApplied: context.controls,
149
- riskTier: context.riskTier,
150
- humanReviewable: true,
151
- appealAvailable: true,
152
- appealEndpoint: '/api/v1/appeal',
153
- retentionPeriodDays: 365,
154
- frameworkReferences: {
155
- nist: [MEASURE-2.8, MEASURE-2.9],
156
- iso42001: [Annex-A.8, Clause-9.1],
157
- },
158
- };
159
- }
160
- ```
161
-
162
-
163
- ## Anti-patterns
164
-
165
- - **"Black box" AI decisions.** Every consequential decision must be explainable.
166
- - **Technical jargon in explanations.** Explanations must be understandable by the affected person.
167
- - **No model card.** High-risk systems need documented model information.
168
- - **Explanations generated post-hoc only.** Build explanation capability into the system from the start.
169
-
170
- ## Edge cases
171
-
172
- - **Explanation fidelity.** LLM-generated explanations may not accurately reflect why the model produced its output. Use structured factor extraction where possible.
173
- - **Trade secrets vs. transparency.** You can explain decision factors without revealing the full system prompt or model architecture.
174
- - **Multi-model explanations.** In pipelines, each model's contribution should be traceable.
@@ -1,200 +0,0 @@
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.