@aigis-ai/cli 1.0.3 → 2.0.1

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 (124) hide show
  1. package/CONTRIBUTING.md +53 -0
  2. package/SKILL.md +20 -55
  3. package/bin/aigis.js +446 -59
  4. package/cli-python/LICENSE +21 -0
  5. package/cli-python/README.md +32 -0
  6. package/cli-python/aigis_cli/SKILL.md +70 -0
  7. package/cli-python/aigis_cli/__init__.py +3 -0
  8. package/cli-python/aigis_cli/__pycache__/__init__.cpython-313.pyc +0 -0
  9. package/cli-python/aigis_cli/__pycache__/annotate.cpython-313.pyc +0 -0
  10. package/cli-python/aigis_cli/__pycache__/build.cpython-313.pyc +0 -0
  11. package/cli-python/aigis_cli/__pycache__/checksum.cpython-313.pyc +0 -0
  12. package/cli-python/aigis_cli/__pycache__/classify.cpython-313.pyc +0 -0
  13. package/cli-python/aigis_cli/__pycache__/cli.cpython-313.pyc +0 -0
  14. package/cli-python/aigis_cli/__pycache__/fetch.cpython-313.pyc +0 -0
  15. package/cli-python/aigis_cli/__pycache__/init_ide.cpython-313.pyc +0 -0
  16. package/cli-python/aigis_cli/__pycache__/keywords.cpython-313.pyc +0 -0
  17. package/cli-python/aigis_cli/__pycache__/search.cpython-313.pyc +0 -0
  18. package/cli-python/aigis_cli/annotate.py +45 -0
  19. package/cli-python/aigis_cli/auto_verify.py +518 -0
  20. package/cli-python/aigis_cli/build.py +470 -0
  21. package/cli-python/aigis_cli/checksum.py +22 -0
  22. package/cli-python/aigis_cli/classify.py +192 -0
  23. package/cli-python/aigis_cli/cli.py +618 -0
  24. package/cli-python/aigis_cli/content/index/audit-scan.md +217 -0
  25. package/cli-python/aigis_cli/content/index/auto-verify-rules.json +439 -0
  26. package/cli-python/aigis_cli/content/index/context-rules.json +90 -0
  27. package/cli-python/aigis_cli/content/index/frameworks.md +82 -0
  28. package/cli-python/aigis_cli/content/index/guardrails.json +23 -0
  29. package/cli-python/aigis_cli/content/index/taxonomy.md +81 -0
  30. package/cli-python/aigis_cli/content/resolvers/triggers.json +229 -0
  31. package/{content/implement → cli-python/aigis_cli/content/skills/areas}/audit-logging.md +5 -0
  32. package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +200 -0
  33. package/cli-python/aigis_cli/content/skills/areas/input-validation.md +380 -0
  34. package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +189 -0
  35. package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +246 -0
  36. package/cli-python/aigis_cli/content/skills/core.md +62 -0
  37. package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +202 -0
  38. package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +169 -0
  39. package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +167 -0
  40. package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +86 -0
  41. package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +54 -0
  42. package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +39 -0
  43. package/cli-python/aigis_cli/content/templates/risk-characterization.md +34 -0
  44. package/cli-python/aigis_cli/content/templates/third-party-assessment.md +41 -0
  45. package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +13 -0
  46. package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +13 -0
  47. package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +13 -0
  48. package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +12 -0
  49. package/cli-python/aigis_cli/content/verify/checklist-explainability.md +13 -0
  50. package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +13 -0
  51. package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +14 -0
  52. package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +16 -0
  53. package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +13 -0
  54. package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +14 -0
  55. package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +14 -0
  56. package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +13 -0
  57. package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +12 -0
  58. package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +13 -0
  59. package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +13 -0
  60. package/cli-python/aigis_cli/fetch.py +232 -0
  61. package/cli-python/aigis_cli/init_ide.py +159 -0
  62. package/cli-python/aigis_cli/keywords.py +73 -0
  63. package/cli-python/aigis_cli/search.py +69 -0
  64. package/cli-python/aigis_cli.egg-info/PKG-INFO +59 -0
  65. package/cli-python/aigis_cli.egg-info/SOURCES.txt +56 -0
  66. package/cli-python/aigis_cli.egg-info/dependency_links.txt +1 -0
  67. package/cli-python/aigis_cli.egg-info/entry_points.txt +2 -0
  68. package/cli-python/aigis_cli.egg-info/requires.txt +6 -0
  69. package/cli-python/aigis_cli.egg-info/top_level.txt +1 -0
  70. package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
  71. package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
  72. package/cli-python/pyproject.toml +49 -0
  73. package/content/index/audit-scan.md +21 -207
  74. package/content/index/auto-verify-rules.json +439 -0
  75. package/content/index/context-rules.json +90 -0
  76. package/content/resolvers/triggers.json +229 -0
  77. package/content/skills/areas/audit-logging.md +176 -0
  78. package/content/skills/areas/bias-monitoring.md +172 -0
  79. package/content/skills/areas/confidence-scoring.md +180 -0
  80. package/content/skills/areas/data-integrity.md +257 -0
  81. package/content/skills/areas/explainability.md +174 -0
  82. package/content/skills/areas/fallback-patterns.md +200 -0
  83. package/content/skills/areas/human-oversight.md +220 -0
  84. package/content/skills/areas/input-validation.md +380 -0
  85. package/content/skills/areas/monitoring.md +207 -0
  86. package/content/skills/areas/output-sanitization.md +183 -0
  87. package/content/skills/areas/pii-handling.md +189 -0
  88. package/content/skills/areas/prompt-security.md +153 -0
  89. package/content/skills/areas/rag-security.md +230 -0
  90. package/content/skills/areas/rate-limiting.md +246 -0
  91. package/content/skills/areas/supply-chain.md +193 -0
  92. package/content/skills/core.md +62 -0
  93. package/content/skills/infrastructure/logging.md +202 -0
  94. package/content/skills/infrastructure/rate-limiting.md +169 -0
  95. package/content/skills/infrastructure/secrets.md +167 -0
  96. package/content/skills/workflows/fastapi-llm.md +86 -0
  97. package/docs/resolvers.md +114 -0
  98. package/lib/auto-verify.js +378 -0
  99. package/lib/build.js +629 -0
  100. package/lib/checksum.js +39 -0
  101. package/lib/fetch.js +164 -9
  102. package/lib/init.js +141 -93
  103. package/lib/keywords.js +92 -130
  104. package/lib/special-recognizers.js +370 -0
  105. package/package.json +1 -1
  106. package/scripts/baseline-cursorrules.snapshot.txt +30 -0
  107. package/scripts/bootstrap-step-6-bench.js +85 -0
  108. package/scripts/check-content-sync.js +91 -0
  109. package/scripts/triggers.schema.json +50 -0
  110. package/scripts/validate-triggers.js +176 -0
  111. package/content/implement/fallback-patterns.md +0 -190
  112. package/content/implement/input-validation.md +0 -212
  113. package/content/implement/pii-handling.md +0 -207
  114. package/content/implement/rate-limiting.md +0 -217
  115. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/bias-monitoring.md +0 -0
  116. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/confidence-scoring.md +0 -0
  117. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/data-integrity.md +0 -0
  118. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/explainability.md +0 -0
  119. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/human-oversight.md +0 -0
  120. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/monitoring.md +0 -0
  121. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/output-sanitization.md +0 -0
  122. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/prompt-security.md +0 -0
  123. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/rag-security.md +0 -0
  124. /package/{content/implement → cli-python/aigis_cli/content/skills/areas}/supply-chain.md +0 -0
@@ -0,0 +1,180 @@
1
+ ---
2
+ id: confidence-scoring
3
+ title: Confidence scoring and misinformation prevention
4
+ controls:
5
+ owasp: [LLM09]
6
+ nist: [MAP-2.2, MEASURE-2.5, MEASURE-2.9]
7
+ iso42001: [Annex-A.8]
8
+ min_risk_tier: all
9
+ system_traits: [influences-decisions, is-external, generates-content]
10
+ ---
11
+
12
+ ## What this addresses
13
+
14
+ OWASP LLM09 covers misinformation — confident but incorrect LLM outputs (hallucinations, fabricated citations, false facts). When decisions are based on unverified LLM output, consequences can be severe. This file covers confidence metadata, grounding, and uncertainty disclosure.
15
+
16
+ ## Implementation patterns
17
+
18
+ ### Pattern 1: Structured confidence in every response
19
+
20
+ ```python
21
+ class LLMResponse:
22
+ def __init__(self, content: dict, raw_response: str):
23
+ self.content = content
24
+ self.confidence = self.compute_confidence(raw_response)
25
+ self.grounded = self.check_grounding(content)
26
+
27
+ def compute_confidence(self, raw: str) -> dict:
28
+ return {
29
+ "score": self.extract_confidence_score(raw),
30
+ "level": self.categorize(self.extract_confidence_score(raw)),
31
+ "factors": self.identify_uncertainty_factors(raw)
32
+ }
33
+
34
+ def categorize(self, score: float) -> str:
35
+ if score >= 0.8: return "high"
36
+ if score >= 0.5: return "medium"
37
+ return "low"
38
+
39
+ def to_response(self) -> dict:
40
+ return {
41
+ **self.content,
42
+ "confidence": self.confidence,
43
+ "grounded": self.grounded,
44
+ "disclaimer": self.generate_disclaimer()
45
+ }
46
+
47
+ def generate_disclaimer(self) -> str | None:
48
+ if self.confidence["level"] == "low":
49
+ return "This assessment has low confidence. Human review recommended."
50
+ return None
51
+ ```
52
+
53
+ ```javascript
54
+ class LlmResponse {
55
+ constructor(content, rawResponse) {
56
+ this.content = content;
57
+ this.confidence = this.computeConfidence(rawResponse);
58
+ this.grounded = this.checkGrounding(content);
59
+ }
60
+
61
+ computeConfidence(raw) {
62
+ const score = this.extractConfidenceScore(raw);
63
+ return {
64
+ score,
65
+ level: score >= 0.8 ? 'high' : score >= 0.5 ? 'medium' : 'low',
66
+ factors: this.identifyUncertaintyFactors(raw),
67
+ };
68
+ }
69
+
70
+ toResponse() {
71
+ return {
72
+ ...this.content,
73
+ confidence: this.confidence,
74
+ grounded: this.grounded,
75
+ disclaimer: this.confidence.level === 'low'
76
+ ? 'This assessment has low confidence. Human review recommended.' : null,
77
+ };
78
+ }
79
+ }
80
+ ```
81
+
82
+
83
+ ### Pattern 2: RAG-based grounding verification
84
+
85
+ ```python
86
+ def verify_grounding(llm_output: str, retrieved_sources: list) -> dict:
87
+ """Check if LLM claims are supported by retrieved documents."""
88
+ claims = extract_claims(llm_output)
89
+ grounded_claims = 0
90
+ ungrounded_claims = []
91
+
92
+ for claim in claims:
93
+ supported = any(
94
+ is_supported_by(claim, source["content"])
95
+ for source in retrieved_sources
96
+ )
97
+ if supported:
98
+ grounded_claims += 1
99
+ else:
100
+ ungrounded_claims.append(claim)
101
+
102
+ grounding_ratio = grounded_claims / len(claims) if claims else 0
103
+ return {
104
+ "grounding_ratio": grounding_ratio,
105
+ "total_claims": len(claims),
106
+ "ungrounded_claims": ungrounded_claims,
107
+ "fully_grounded": len(ungrounded_claims) == 0
108
+ }
109
+ ```
110
+
111
+ ```javascript
112
+ function verifyGrounding(llmOutput, retrievedSources) {
113
+ const claims = extractClaims(llmOutput);
114
+ const ungroundedClaims = [];
115
+ let groundedCount = 0;
116
+
117
+ for (const claim of claims) {
118
+ const supported = retrievedSources.some(
119
+ source => isSupportedBy(claim, source.content)
120
+ );
121
+ if (supported) groundedCount++;
122
+ else ungroundedClaims.push(claim);
123
+ }
124
+
125
+ return {
126
+ groundingRatio: claims.length ? groundedCount / claims.length : 0,
127
+ totalClaims: claims.length,
128
+ ungroundedClaims,
129
+ fullyGrounded: ungroundedClaims.length === 0,
130
+ };
131
+ }
132
+ ```
133
+
134
+
135
+ ### Pattern 3: Never present LLM output as definitive fact
136
+
137
+ ```python
138
+ def format_for_display(assessment: dict) -> dict:
139
+ """Frame AI output as a recommendation, not a fact."""
140
+ return {
141
+ "header": "AI-assisted assessment", # Not "Assessment Result"
142
+ "body": assessment["content"],
143
+ "confidence_indicator": assessment["confidence"]["level"],
144
+ "source_attribution": assessment.get("sources", []),
145
+ "footer": "This is an AI-generated recommendation. "
146
+ "Final decisions should be made by qualified personnel."
147
+ }
148
+ ```
149
+
150
+ ```javascript
151
+ function formatForDisplay(assessment) {
152
+ return {
153
+ header: 'AI-assisted assessment', // Not "Assessment Result"
154
+ body: assessment.content,
155
+ confidenceIndicator: assessment.confidence.level,
156
+ sourceAttribution: assessment.sources || [],
157
+ footer: 'This is an AI-generated recommendation. '
158
+ + 'Final decisions should be made by qualified personnel.',
159
+ };
160
+ }
161
+ ```
162
+
163
+
164
+ ## Anti-patterns
165
+
166
+ - **Presenting LLM output without confidence metadata.** Always include confidence.
167
+ - **"The AI determined..." framing.** Use "The AI suggests..." or "Based on available data..."
168
+ - **No source attribution.** When using RAG, cite the sources that informed the response.
169
+ - **Binary confidence (just confident/not confident).** Use a spectrum with actionable thresholds.
170
+
171
+ ## Related files
172
+
173
+ - **human-oversight.md:** When confidence is low, route to human review. Implement human-oversight.md Pattern 2 (decision gate with confidence threshold) to automatically flag low-confidence outputs for human review rather than auto-processing them.
174
+ - **monitoring.md:** Confidence scores should be tracked over time. Use monitoring.md Pattern 1 (key metrics dashboard) to monitor mean confidence and alert when it drops, which may signal model degradation or data drift.
175
+
176
+ ## Edge cases
177
+
178
+ - **Calibration.** LLM confidence scores are often miscalibrated. Validate against ground truth periodically.
179
+ - **Confident hallucinations.** LLMs can be confidently wrong. Grounding verification catches this better than self-reported confidence.
180
+ - **Downstream automation.** If another system consumes the confidence score, ensure it respects low-confidence flags.
@@ -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.