@aigis-ai/cli 1.0.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.
- package/LICENSE +21 -0
- package/README.md +204 -0
- package/SKILL.md +74 -0
- package/bin/aigis.js +337 -0
- package/content/implement/audit-logging.md +171 -0
- package/content/implement/bias-monitoring.md +172 -0
- package/content/implement/confidence-scoring.md +180 -0
- package/content/implement/data-integrity.md +257 -0
- package/content/implement/explainability.md +174 -0
- package/content/implement/fallback-patterns.md +190 -0
- package/content/implement/human-oversight.md +220 -0
- package/content/implement/input-validation.md +212 -0
- package/content/implement/monitoring.md +207 -0
- package/content/implement/output-sanitization.md +183 -0
- package/content/implement/pii-handling.md +207 -0
- package/content/implement/prompt-security.md +153 -0
- package/content/implement/rag-security.md +230 -0
- package/content/implement/rate-limiting.md +217 -0
- package/content/implement/supply-chain.md +193 -0
- package/content/index/audit-scan.md +403 -0
- package/content/index/frameworks.md +82 -0
- package/content/index/guardrails.json +23 -0
- package/content/index/taxonomy.md +81 -0
- package/content/templates/ai-impact-assessment.md +54 -0
- package/content/templates/intended-purpose-doc.md +39 -0
- package/content/templates/risk-characterization.md +34 -0
- package/content/templates/third-party-assessment.md +41 -0
- package/content/verify/checklist-audit-logging.md +13 -0
- package/content/verify/checklist-bias-monitoring.md +13 -0
- package/content/verify/checklist-confidence-scoring.md +13 -0
- package/content/verify/checklist-data-integrity.md +12 -0
- package/content/verify/checklist-explainability.md +13 -0
- package/content/verify/checklist-fallback-patterns.md +13 -0
- package/content/verify/checklist-human-oversight.md +14 -0
- package/content/verify/checklist-input-validation.md +16 -0
- package/content/verify/checklist-monitoring.md +13 -0
- package/content/verify/checklist-output-sanitization.md +14 -0
- package/content/verify/checklist-pii-handling.md +14 -0
- package/content/verify/checklist-prompt-security.md +13 -0
- package/content/verify/checklist-rag-security.md +12 -0
- package/content/verify/checklist-rate-limiting.md +13 -0
- package/content/verify/checklist-supply-chain.md +13 -0
- package/lib/annotate.js +53 -0
- package/lib/classify.js +185 -0
- package/lib/fetch.js +112 -0
- package/lib/init.js +122 -0
- package/lib/keywords.js +139 -0
- package/lib/search.js +76 -0
- package/package.json +35 -0
|
@@ -0,0 +1,257 @@
|
|
|
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.
|
|
@@ -0,0 +1,174 @@
|
|
|
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.
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: fallback-patterns
|
|
3
|
+
title: Fallback and safe failure patterns
|
|
4
|
+
controls:
|
|
5
|
+
owasp: []
|
|
6
|
+
nist: [MEASURE-2.6, MANAGE-2.3, MANAGE-2.4]
|
|
7
|
+
iso42001: [Clause-8.2]
|
|
8
|
+
min_risk_tier: medium
|
|
9
|
+
system_traits: [is-agentic, is-high-volume, influences-decisions, multi-model-pipeline]
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## What this addresses
|
|
13
|
+
|
|
14
|
+
NIST MEASURE 2.6 requires that AI systems fail safely. MANAGE 2.4 requires mechanisms to disengage systems with inconsistent performance. This file covers graceful degradation, circuit breakers, kill switches, and safe default behaviors.
|
|
15
|
+
|
|
16
|
+
## Implementation patterns
|
|
17
|
+
|
|
18
|
+
### Pattern 1: Default safe response
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
def default_safe_response() -> dict:
|
|
22
|
+
"""Return a safe, neutral response when the LLM fails or output is invalid."""
|
|
23
|
+
return {
|
|
24
|
+
"severity_score": 5, # Middle of range, not extreme in either direction
|
|
25
|
+
"recommendation": "standard", # Routes to normal human review
|
|
26
|
+
"confidence": 0.0, # Zero confidence flags for human review
|
|
27
|
+
"fallback": True,
|
|
28
|
+
"message": "Unable to generate AI assessment. Routed to standard review."
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```javascript
|
|
33
|
+
function defaultSafeResponse() {
|
|
34
|
+
return {
|
|
35
|
+
severityScore: 5,
|
|
36
|
+
recommendation: 'standard',
|
|
37
|
+
confidence: 0.0,
|
|
38
|
+
fallback: true,
|
|
39
|
+
message: 'Unable to generate AI assessment. Routed to standard review.',
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
### Pattern 2: Circuit breaker
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
class CircuitBreaker:
|
|
49
|
+
def __init__(self, failure_threshold: int = 5, reset_timeout: int = 60):
|
|
50
|
+
self.failure_count = 0
|
|
51
|
+
self.failure_threshold = failure_threshold
|
|
52
|
+
self.reset_timeout = reset_timeout
|
|
53
|
+
self.state = "closed" # closed = normal, open = failing, half-open = testing
|
|
54
|
+
self.last_failure_time = None
|
|
55
|
+
|
|
56
|
+
def call(self, func, *args, **kwargs):
|
|
57
|
+
if self.state == "open":
|
|
58
|
+
if time.time() - self.last_failure_time > self.reset_timeout:
|
|
59
|
+
self.state = "half-open"
|
|
60
|
+
else:
|
|
61
|
+
log_event("circuit_breaker_open")
|
|
62
|
+
return default_safe_response()
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
result = func(*args, **kwargs)
|
|
66
|
+
if self.state == "half-open":
|
|
67
|
+
self.state = "closed"
|
|
68
|
+
self.failure_count = 0
|
|
69
|
+
return result
|
|
70
|
+
except Exception as e:
|
|
71
|
+
self.failure_count += 1
|
|
72
|
+
self.last_failure_time = time.time()
|
|
73
|
+
if self.failure_count >= self.failure_threshold:
|
|
74
|
+
self.state = "open"
|
|
75
|
+
log_event("circuit_breaker_tripped", failures=self.failure_count)
|
|
76
|
+
alert_ops_team("Circuit breaker tripped for LLM service")
|
|
77
|
+
return default_safe_response()
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
```javascript
|
|
81
|
+
class CircuitBreaker {
|
|
82
|
+
constructor(failureThreshold = 5, resetTimeout = 60000) {
|
|
83
|
+
this.failureCount = 0;
|
|
84
|
+
this.failureThreshold = failureThreshold;
|
|
85
|
+
this.resetTimeout = resetTimeout;
|
|
86
|
+
this.state = 'closed';
|
|
87
|
+
this.lastFailureTime = null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async call(fn, ...args) {
|
|
91
|
+
if (this.state === 'open') {
|
|
92
|
+
if (Date.now() - this.lastFailureTime > this.resetTimeout)
|
|
93
|
+
this.state = 'half-open';
|
|
94
|
+
else {
|
|
95
|
+
logEvent('circuit_breaker_open');
|
|
96
|
+
return defaultSafeResponse();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
const result = await fn(...args);
|
|
101
|
+
if (this.state === 'half-open') { this.state = 'closed'; this.failureCount = 0; }
|
|
102
|
+
return result;
|
|
103
|
+
} catch (e) {
|
|
104
|
+
this.failureCount++;
|
|
105
|
+
this.lastFailureTime = Date.now();
|
|
106
|
+
if (this.failureCount >= this.failureThreshold) {
|
|
107
|
+
this.state = 'open';
|
|
108
|
+
logEvent('circuit_breaker_tripped', { failures: this.failureCount });
|
|
109
|
+
alertOpsTeam('Circuit breaker tripped');
|
|
110
|
+
}
|
|
111
|
+
return defaultSafeResponse();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
### Pattern 3: Kill switch
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
class KillSwitch:
|
|
122
|
+
"""Emergency shutdown mechanism. Can be triggered manually or by automated monitoring."""
|
|
123
|
+
|
|
124
|
+
def __init__(self, config_source: str):
|
|
125
|
+
self.config_source = config_source
|
|
126
|
+
|
|
127
|
+
def is_active(self) -> bool:
|
|
128
|
+
# Check external config (e.g., feature flag service, Redis, config file)
|
|
129
|
+
return self.load_config().get("ai_system_enabled", True)
|
|
130
|
+
|
|
131
|
+
def check_automated_triggers(self, metrics: dict) -> bool:
|
|
132
|
+
"""Automatically disable if metrics breach thresholds."""
|
|
133
|
+
if metrics.get("error_rate_7d", 0) > 0.15: # >15% error rate
|
|
134
|
+
self.disable("automated: error_rate exceeded 15%")
|
|
135
|
+
return False
|
|
136
|
+
if metrics.get("override_rate_7d", 0) > 0.40: # >40% human overrides
|
|
137
|
+
self.disable("automated: override_rate exceeded 40%")
|
|
138
|
+
return False
|
|
139
|
+
return True
|
|
140
|
+
|
|
141
|
+
def disable(self, reason: str):
|
|
142
|
+
self.save_config({"ai_system_enabled": False, "disabled_reason": reason})
|
|
143
|
+
alert_ops_team(f"AI system killed: {reason}")
|
|
144
|
+
log_event("kill_switch_activated", reason=reason)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
```javascript
|
|
148
|
+
class KillSwitch {
|
|
149
|
+
constructor(configSource) {
|
|
150
|
+
this.configSource = configSource;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async isActive() {
|
|
154
|
+
const config = await this.loadConfig();
|
|
155
|
+
return config.aiSystemEnabled !== false;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async checkAutomatedTriggers(metrics) {
|
|
159
|
+
if ((metrics.errorRate7d || 0) > 0.15) {
|
|
160
|
+
await this.disable('automated: error_rate exceeded 15%');
|
|
161
|
+
return false;
|
|
162
|
+
}
|
|
163
|
+
if ((metrics.overrideRate7d || 0) > 0.40) {
|
|
164
|
+
await this.disable('automated: override_rate exceeded 40%');
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async disable(reason) {
|
|
171
|
+
await this.saveConfig({ aiSystemEnabled: false, disabledReason: reason });
|
|
172
|
+
await alertOpsTeam('AI system killed: ' + reason);
|
|
173
|
+
logEvent('kill_switch_activated', { reason });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
## Anti-patterns
|
|
180
|
+
|
|
181
|
+
- **No fallback behavior defined.** Every AI call must have a defined failure path.
|
|
182
|
+
- **Crashing on LLM errors.** Catch exceptions and return safe defaults.
|
|
183
|
+
- **No kill switch.** There must always be a way to shut the system down quickly.
|
|
184
|
+
- **Kill switch requires code deployment.** Use external config that can be toggled without deploying.
|
|
185
|
+
|
|
186
|
+
## Edge cases
|
|
187
|
+
|
|
188
|
+
- **Partial failures.** The LLM returns valid JSON but the content is nonsensical. Output schema validation catches structural issues; confidence scoring catches content issues.
|
|
189
|
+
- **Cascading failures.** In multi-model pipelines, one model failing can cascade. Each stage needs independent fallback.
|
|
190
|
+
- **Recovery after kill switch.** Define a process for re-enabling: run evaluation suite, gradual rollout, monitoring period.
|