@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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +204 -0
  3. package/SKILL.md +74 -0
  4. package/bin/aigis.js +337 -0
  5. package/content/implement/audit-logging.md +171 -0
  6. package/content/implement/bias-monitoring.md +172 -0
  7. package/content/implement/confidence-scoring.md +180 -0
  8. package/content/implement/data-integrity.md +257 -0
  9. package/content/implement/explainability.md +174 -0
  10. package/content/implement/fallback-patterns.md +190 -0
  11. package/content/implement/human-oversight.md +220 -0
  12. package/content/implement/input-validation.md +212 -0
  13. package/content/implement/monitoring.md +207 -0
  14. package/content/implement/output-sanitization.md +183 -0
  15. package/content/implement/pii-handling.md +207 -0
  16. package/content/implement/prompt-security.md +153 -0
  17. package/content/implement/rag-security.md +230 -0
  18. package/content/implement/rate-limiting.md +217 -0
  19. package/content/implement/supply-chain.md +193 -0
  20. package/content/index/audit-scan.md +403 -0
  21. package/content/index/frameworks.md +82 -0
  22. package/content/index/guardrails.json +23 -0
  23. package/content/index/taxonomy.md +81 -0
  24. package/content/templates/ai-impact-assessment.md +54 -0
  25. package/content/templates/intended-purpose-doc.md +39 -0
  26. package/content/templates/risk-characterization.md +34 -0
  27. package/content/templates/third-party-assessment.md +41 -0
  28. package/content/verify/checklist-audit-logging.md +13 -0
  29. package/content/verify/checklist-bias-monitoring.md +13 -0
  30. package/content/verify/checklist-confidence-scoring.md +13 -0
  31. package/content/verify/checklist-data-integrity.md +12 -0
  32. package/content/verify/checklist-explainability.md +13 -0
  33. package/content/verify/checklist-fallback-patterns.md +13 -0
  34. package/content/verify/checklist-human-oversight.md +14 -0
  35. package/content/verify/checklist-input-validation.md +16 -0
  36. package/content/verify/checklist-monitoring.md +13 -0
  37. package/content/verify/checklist-output-sanitization.md +14 -0
  38. package/content/verify/checklist-pii-handling.md +14 -0
  39. package/content/verify/checklist-prompt-security.md +13 -0
  40. package/content/verify/checklist-rag-security.md +12 -0
  41. package/content/verify/checklist-rate-limiting.md +13 -0
  42. package/content/verify/checklist-supply-chain.md +13 -0
  43. package/lib/annotate.js +53 -0
  44. package/lib/classify.js +185 -0
  45. package/lib/fetch.js +112 -0
  46. package/lib/init.js +122 -0
  47. package/lib/keywords.js +139 -0
  48. package/lib/search.js +76 -0
  49. package/package.json +35 -0
@@ -0,0 +1,220 @@
1
+ ---
2
+ id: human-oversight
3
+ title: Human oversight and agency control
4
+ controls:
5
+ owasp: [LLM06]
6
+ nist: [MAP-3.5, MANAGE-1.3, MANAGE-4.1]
7
+ iso42001: [Annex-A.9, Clause-8.4]
8
+ min_risk_tier: all
9
+ system_traits: [is-agentic, influences-decisions, handles-minors, generates-code]
10
+ ---
11
+
12
+ ## What this addresses
13
+
14
+ OWASP LLM06 addresses excessive agency — granting LLMs too much autonomy to take actions. As agentic AI grows, systems that can write to databases, execute code, call APIs, or send communications without human approval create significant risk. This file covers least privilege, approval gates, and override mechanisms.
15
+
16
+ ## Implementation patterns
17
+
18
+ ### Pattern 1: Principle of least privilege for tools
19
+
20
+ ```python
21
+ # Define an explicit allowlist of tools the LLM can use
22
+ ALLOWED_TOOLS = {
23
+ "get_claim": {"type": "read", "approval_required": False},
24
+ "search_policies": {"type": "read", "approval_required": False},
25
+ "update_claim_status": {"type": "write", "approval_required": True},
26
+ "send_customer_email": {"type": "write", "approval_required": True},
27
+ }
28
+
29
+ def execute_tool(tool_name: str, params: dict, user_context: dict) -> dict:
30
+ if tool_name not in ALLOWED_TOOLS:
31
+ log_security_event("unauthorized_tool_attempt", tool=tool_name)
32
+ return {"error": "Tool not available"}
33
+
34
+ tool_config = ALLOWED_TOOLS[tool_name]
35
+
36
+ if tool_config["approval_required"]:
37
+ approval = request_human_approval(tool_name, params, user_context)
38
+ if not approval.granted:
39
+ return {"error": "Action requires human approval", "approval_id": approval.id}
40
+
41
+ return tools[tool_name].execute(params)
42
+ ```
43
+
44
+ ```javascript
45
+ const ALLOWED_TOOLS = {
46
+ getClaim: { type: 'read', approvalRequired: false },
47
+ searchPolicies: { type: 'read', approvalRequired: false },
48
+ updateClaimStatus: { type: 'write', approvalRequired: true },
49
+ sendCustomerEmail: { type: 'write', approvalRequired: true },
50
+ };
51
+
52
+ async function executeTool(toolName, params, userContext) {
53
+ if (!(toolName in ALLOWED_TOOLS)) {
54
+ logSecurityEvent('unauthorized_tool_attempt', { tool: toolName });
55
+ return { error: 'Tool not available' };
56
+ }
57
+ const config = ALLOWED_TOOLS[toolName];
58
+ if (config.approvalRequired) {
59
+ const approval = await requestHumanApproval(toolName, params, userContext);
60
+ if (!approval.granted)
61
+ return { error: 'Action requires human approval', approvalId: approval.id };
62
+ }
63
+ return tools[toolName].execute(params);
64
+ }
65
+ ```
66
+
67
+
68
+ ### Pattern 2: Human-in-the-loop for high-impact decisions
69
+
70
+ ```python
71
+ class DecisionGate:
72
+ def __init__(self, threshold: float, escalation_channel: str):
73
+ self.threshold = threshold
74
+ self.escalation_channel = escalation_channel
75
+
76
+ def evaluate(self, ai_decision: dict) -> dict:
77
+ ai_decision["human_override_available"] = True
78
+ ai_decision["decision_source"] = "ai_recommendation"
79
+
80
+ if ai_decision["confidence"] < self.threshold:
81
+ ai_decision["requires_human_review"] = True
82
+ ai_decision["review_reason"] = "low_confidence"
83
+ self.notify_reviewer(ai_decision)
84
+ elif ai_decision.get("impact_value", 0) > HIGH_VALUE_THRESHOLD:
85
+ ai_decision["requires_human_review"] = True
86
+ ai_decision["review_reason"] = "high_value"
87
+ self.notify_reviewer(ai_decision)
88
+
89
+ return ai_decision
90
+ ```
91
+
92
+ ```javascript
93
+ class DecisionGate {
94
+ constructor(threshold, escalationChannel) {
95
+ this.threshold = threshold;
96
+ this.escalationChannel = escalationChannel;
97
+ }
98
+
99
+ evaluate(aiDecision) {
100
+ aiDecision.humanOverrideAvailable = true;
101
+ aiDecision.decisionSource = 'ai_recommendation';
102
+ if (aiDecision.confidence < this.threshold) {
103
+ aiDecision.requiresHumanReview = true;
104
+ aiDecision.reviewReason = 'low_confidence';
105
+ this.notifyReviewer(aiDecision);
106
+ } else if ((aiDecision.impactValue || 0) > HIGH_VALUE_THRESHOLD) {
107
+ aiDecision.requiresHumanReview = true;
108
+ aiDecision.reviewReason = 'high_value';
109
+ this.notifyReviewer(aiDecision);
110
+ }
111
+ return aiDecision;
112
+ }
113
+ }
114
+ ```
115
+
116
+
117
+ ### Pattern 3: Action rate limiting
118
+
119
+ ```python
120
+ from collections import defaultdict
121
+ import time
122
+
123
+ class ActionRateLimiter:
124
+ def __init__(self):
125
+ self.action_counts = defaultdict(list)
126
+
127
+ def check(self, action_type: str, window_seconds: int = 60, max_actions: int = 10) -> bool:
128
+ now = time.time()
129
+ # Clean old entries
130
+ self.action_counts[action_type] = [
131
+ t for t in self.action_counts[action_type] if now - t < window_seconds
132
+ ]
133
+ if len(self.action_counts[action_type]) >= max_actions:
134
+ log_security_event("action_rate_limit_exceeded", action=action_type)
135
+ return False
136
+ self.action_counts[action_type].append(now)
137
+ return True
138
+ ```
139
+
140
+ ```javascript
141
+ class ActionRateLimiter {
142
+ constructor() {
143
+ this.actionCounts = new Map();
144
+ }
145
+
146
+ check(actionType, windowSeconds = 60, maxActions = 10) {
147
+ const now = Date.now() / 1000;
148
+ const counts = (this.actionCounts.get(actionType) || [])
149
+ .filter(t => now - t < windowSeconds);
150
+ if (counts.length >= maxActions) {
151
+ logSecurityEvent('action_rate_limit_exceeded', { action: actionType });
152
+ return false;
153
+ }
154
+ counts.push(now);
155
+ this.actionCounts.set(actionType, counts);
156
+ return true;
157
+ }
158
+ }
159
+ ```
160
+
161
+
162
+ ### Pattern 4: Override mechanism in API responses
163
+
164
+ ```python
165
+ def build_response(assessment: dict) -> dict:
166
+ """Every AI-influenced response includes override capability."""
167
+ return {
168
+ "result": assessment,
169
+ "metadata": {
170
+ "decision_source": "ai",
171
+ "model_version": MODEL_VERSION,
172
+ "confidence": assessment["confidence"],
173
+ "trace_id": generate_trace_id(),
174
+ },
175
+ "override": {
176
+ "available": True,
177
+ "endpoint": "/api/v1/override",
178
+ "instructions": "Submit with override_reason to escalate to human review"
179
+ }
180
+ }
181
+ ```
182
+
183
+ ```javascript
184
+ function buildResponse(assessment) {
185
+ return {
186
+ result: assessment,
187
+ metadata: {
188
+ decisionSource: 'ai',
189
+ modelVersion: MODEL_VERSION,
190
+ confidence: assessment.confidence,
191
+ traceId: generateTraceId(),
192
+ },
193
+ override: {
194
+ available: true,
195
+ endpoint: '/api/v1/override',
196
+ instructions: 'Submit with override_reason to escalate to human review',
197
+ },
198
+ };
199
+ }
200
+ ```
201
+
202
+
203
+ ## Anti-patterns
204
+
205
+ - **Blocklist instead of allowlist for tools.** Always define what the LLM CAN do, not what it can't.
206
+ - **Autonomous write operations.** Any action that modifies state should require human approval in high-risk contexts.
207
+ - **No audit trail for AI-initiated actions.** Every action the LLM takes must be logged with trace ID.
208
+ - **Confidence threshold of zero.** Always require minimum confidence; route low-confidence outputs to humans.
209
+
210
+ ## Related files
211
+
212
+ - **audit-logging.md:** Every action the LLM takes must be logged. Use audit-logging.md Pattern 3 (decision audit trail) for all AI-influenced decisions, and Pattern 2 (trace ID propagation) to correlate approval requests with their outcomes.
213
+ - **fallback-patterns.md:** When human approval is unavailable within a timeout, use fallback-patterns.md Pattern 1 (default safe response) as the fallback behavior rather than auto-approving. See edge case "Time-sensitive decisions" below.
214
+ - **confidence-scoring.md:** Confidence thresholds drive the human review gate. Use confidence-scoring.md Pattern 1 (structured confidence) to produce the scores that Pattern 2 of this file (decision gate) evaluates.
215
+
216
+ ## Edge cases
217
+
218
+ - **Chained actions.** An agent executing a sequence of individually-harmless actions that are collectively dangerous. Implement cumulative impact assessment.
219
+ - **Approval fatigue.** If every action requires approval, humans rubber-stamp. Design tiered approval: auto-approve reads, flag writes, block deletes.
220
+ - **Time-sensitive decisions.** Some contexts need fast responses. Define fallback behavior for when human review isn't available within the timeout.
@@ -0,0 +1,212 @@
1
+ ---
2
+ id: input-validation
3
+ title: Input validation and sanitization
4
+ controls:
5
+ owasp: [LLM01]
6
+ nist: [MEASURE-2.7, MANAGE-1.3]
7
+ iso42001: [Clause-8.2, Annex-A.6]
8
+ min_risk_tier: all
9
+ system_traits: [uses-llm, accepts-user-input]
10
+ ---
11
+
12
+ ## What this addresses
13
+
14
+ Prompt injection is the #1 security risk for LLM applications (OWASP LLM01:2025). Attackers manipulate inputs to override system instructions, extract sensitive data, or trigger unintended behavior. Two vectors: direct injection (malicious user input) and indirect injection (malicious content in documents or data the LLM processes).
15
+
16
+ ## Implementation patterns
17
+
18
+ ### Pattern 1: Input length enforcement
19
+
20
+ ```python
21
+ MAX_INPUT_LENGTH = 4000 # characters
22
+ MAX_INPUT_TOKENS = 1000 # tokens
23
+
24
+ def validate_input_length(user_input: str) -> str:
25
+ if len(user_input) > MAX_INPUT_LENGTH:
26
+ raise ValueError(f"Input exceeds {MAX_INPUT_LENGTH} characters")
27
+ token_count = len(tokenizer.encode(user_input))
28
+ if token_count > MAX_INPUT_TOKENS:
29
+ raise ValueError(f"Input exceeds {MAX_INPUT_TOKENS} tokens")
30
+ return user_input
31
+ ```
32
+
33
+ ```javascript
34
+ const MAX_INPUT_LENGTH = 4000;
35
+ const MAX_INPUT_TOKENS = 1000;
36
+
37
+ function validateInputLength(userInput) {
38
+ if (userInput.length > MAX_INPUT_LENGTH)
39
+ throw new Error(`Input exceeds ${MAX_INPUT_LENGTH} characters`);
40
+ const tokenCount = tokenizer.encode(userInput).length;
41
+ if (tokenCount > MAX_INPUT_TOKENS)
42
+ throw new Error(`Input exceeds ${MAX_INPUT_TOKENS} tokens`);
43
+ return userInput;
44
+ }
45
+ ```
46
+
47
+ ### Pattern 2: System/user prompt separation
48
+
49
+ Never concatenate user input into the system prompt. Use the API's native role separation.
50
+
51
+ ```python
52
+ # CORRECT
53
+ messages = [
54
+ {"role": "system", "content": SYSTEM_PROMPT},
55
+ {"role": "user", "content": sanitize_input(user_input)}
56
+ ]
57
+
58
+ # WRONG - never do this
59
+ prompt = SYSTEM_PROMPT + "\nUser says: " + user_input
60
+ ```
61
+
62
+ ```javascript
63
+ // CORRECT
64
+ const messages = [
65
+ { role: 'system', content: SYSTEM_PROMPT },
66
+ { role: 'user', content: sanitizeInput(userInput) }
67
+ ];
68
+
69
+ // WRONG - never do this
70
+ // const prompt = SYSTEM_PROMPT + '\nUser says: ' + userInput;
71
+ ```
72
+
73
+
74
+ ### Pattern 3: Character and encoding sanitization
75
+
76
+ ```python
77
+ import unicodedata, re
78
+
79
+ DANGEROUS_CHARS = re.compile(
80
+ '[\x00-\x08\x0b\x0c\x0e-\x1f'
81
+ '\u200b-\u200f'
82
+ '\u202a-\u202e'
83
+ '\u2060-\u2064'
84
+ '\ufeff]'
85
+ )
86
+
87
+ def sanitize_input(raw_input: str) -> str:
88
+ cleaned = DANGEROUS_CHARS.sub('', raw_input)
89
+ cleaned = unicodedata.normalize('NFC', cleaned)
90
+ return cleaned.strip()
91
+ ```
92
+
93
+ ```javascript
94
+ const DANGEROUS_CHARS = /[\x00-\x08\x0b\x0c\x0e-\x1f\u200b-\u200f\u202a-\u202e\u2060-\u2064\ufeff]/g;
95
+
96
+ function sanitizeInput(rawInput) {
97
+ let cleaned = rawInput.replace(DANGEROUS_CHARS, '');
98
+ cleaned = cleaned.normalize('NFC');
99
+ return cleaned.trim();
100
+ }
101
+ ```
102
+
103
+
104
+ ### Pattern 4: Output schema enforcement
105
+
106
+ ```python
107
+ from pydantic import BaseModel, Field
108
+ from enum import Enum
109
+
110
+ class Recommendation(str, Enum):
111
+ FAST_TRACK = "fast-track"
112
+ STANDARD = "standard"
113
+ ESCALATE = "escalate"
114
+
115
+ class AssessmentOutput(BaseModel):
116
+ severity_score: int = Field(ge=1, le=10)
117
+ recommendation: Recommendation
118
+ confidence: float = Field(ge=0.0, le=1.0)
119
+
120
+ def validate_llm_output(raw_response: str) -> AssessmentOutput:
121
+ try:
122
+ return AssessmentOutput(**json.loads(raw_response))
123
+ except (json.JSONDecodeError, ValidationError) as e:
124
+ log_anomaly("output_schema_violation", raw_response, str(e))
125
+ return default_safe_response() # See fallback-patterns.md Pattern 1 (default safe response) for the fallback value
126
+ ```
127
+
128
+ ```javascript
129
+ const Ajv = require('ajv');
130
+ const ajv = new Ajv();
131
+
132
+ const outputSchema = {
133
+ type: 'object',
134
+ properties: {
135
+ severity_score: { type: 'integer', minimum: 1, maximum: 10 },
136
+ recommendation: { type: 'string', enum: ['fast-track', 'standard', 'escalate'] },
137
+ confidence: { type: 'number', minimum: 0, maximum: 1 }
138
+ },
139
+ required: ['severity_score', 'recommendation', 'confidence'],
140
+ additionalProperties: false
141
+ };
142
+ const validate = ajv.compile(outputSchema);
143
+
144
+ function validateLlmOutput(rawResponse) {
145
+ try {
146
+ const parsed = JSON.parse(rawResponse);
147
+ if (!validate(parsed)) {
148
+ logAnomaly('output_schema_violation', rawResponse, validate.errors);
149
+ return defaultSafeResponse(); // See fallback-patterns.md Pattern 1
150
+ }
151
+ return parsed;
152
+ } catch (e) {
153
+ logAnomaly('output_parse_failure', rawResponse, e.message);
154
+ return defaultSafeResponse();
155
+ }
156
+ }
157
+ ```
158
+
159
+
160
+ ### Pattern 5: Injection pattern detection (defense in depth)
161
+
162
+ ```python
163
+ SUSPICIOUS_PATTERNS = [
164
+ "ignore previous instructions", "ignore all prior",
165
+ "you are now", "system prompt", "reveal your instructions",
166
+ "act as", "pretend you are", "do not follow",
167
+ "disregard", "new instructions:",
168
+ ]
169
+
170
+ def check_injection_patterns(user_input: str) -> dict:
171
+ input_lower = user_input.lower()
172
+ for pattern in SUSPICIOUS_PATTERNS:
173
+ if pattern in input_lower:
174
+ log_security_event("injection_pattern_detected", pattern=pattern)
175
+ return {"flagged": True, "pattern": pattern}
176
+ return {"flagged": False}
177
+ ```
178
+
179
+ ```javascript
180
+ const SUSPICIOUS_PATTERNS = [
181
+ 'ignore previous instructions', 'ignore all prior',
182
+ 'you are now', 'system prompt', 'reveal your instructions',
183
+ 'act as', 'pretend you are', 'do not follow',
184
+ 'disregard', 'new instructions:',
185
+ ];
186
+
187
+ function checkInjectionPatterns(userInput) {
188
+ const inputLower = userInput.toLowerCase();
189
+ for (const pattern of SUSPICIOUS_PATTERNS) {
190
+ if (inputLower.includes(pattern)) {
191
+ logSecurityEvent('injection_pattern_detected', { pattern });
192
+ return { flagged: true, pattern };
193
+ }
194
+ }
195
+ return { flagged: false };
196
+ }
197
+ ```
198
+
199
+
200
+ ## Anti-patterns
201
+
202
+ - **String concatenation for prompts.** Never use f-strings or template literals to build prompts.
203
+ - **Client-side-only validation.** Validation must happen server-side.
204
+ - **Blocklist-only approach.** Blocklists are defense-in-depth, not primary controls.
205
+ - **Silent truncation.** Return an error on length violations; truncation changes meaning.
206
+
207
+ ## Edge cases
208
+
209
+ - **Indirect injection via documents.** Apply same sanitization to extracted document text.
210
+ - **Multi-turn conversations.** Cumulative length limits on conversation context.
211
+ - **Multimodal inputs.** Images may contain text visible to vision models.
212
+ - **Tool/function calling.** Combine with human-oversight.md for tool-using systems.
@@ -0,0 +1,207 @@
1
+ ---
2
+ id: monitoring
3
+ title: Post-deployment monitoring
4
+ controls:
5
+ owasp: []
6
+ nist: [MEASURE-2.4, MEASURE-3.1, MANAGE-4.1, MANAGE-4.2]
7
+ iso42001: [Clause-9.1, Clause-10]
8
+ min_risk_tier: medium
9
+ system_traits: [uses-llm, is-high-volume, multi-model-pipeline]
10
+ ---
11
+
12
+ ## What this addresses
13
+
14
+ NIST MANAGE 4.1 requires post-deployment monitoring including performance tracking, feedback integration, and incident response. ISO 42001 Clause 9.1 requires systematic measurement and evaluation. This covers operational monitoring after the system is live.
15
+
16
+ ## Implementation patterns
17
+
18
+ ### Pattern 1: Key metrics dashboard
19
+
20
+ ```python
21
+ MONITORING_METRICS = {
22
+ "latency_p50_ms": {"alert_threshold": 5000, "window": "5m"},
23
+ "latency_p99_ms": {"alert_threshold": 15000, "window": "5m"},
24
+ "error_rate": {"alert_threshold": 0.05, "window": "15m"},
25
+ "override_rate": {"alert_threshold": 0.30, "window": "24h"},
26
+ "confidence_mean": {"alert_threshold_low": 0.4, "window": "1h"},
27
+ "tokens_per_request_mean": {"alert_threshold": 3000, "window": "1h"},
28
+ "cost_per_hour_usd": {"alert_threshold": 50.0, "window": "1h"},
29
+ "fallback_rate": {"alert_threshold": 0.10, "window": "1h"},
30
+ }
31
+
32
+ def check_metrics(current: dict) -> list:
33
+ alerts = []
34
+ for metric, config in MONITORING_METRICS.items():
35
+ value = current.get(metric)
36
+ if value is None:
37
+ continue
38
+ threshold = config.get("alert_threshold")
39
+ if threshold and value > threshold:
40
+ alerts.append({"metric": metric, "value": value, "threshold": threshold})
41
+ return alerts
42
+ ```
43
+
44
+ ```javascript
45
+ const MONITORING_METRICS = {
46
+ latencyP50Ms: { alertThreshold: 5000, window: '5m' },
47
+ latencyP99Ms: { alertThreshold: 15000, window: '5m' },
48
+ errorRate: { alertThreshold: 0.05, window: '15m' },
49
+ overrideRate: { alertThreshold: 0.30, window: '24h' },
50
+ confidenceMean: { alertThresholdLow: 0.4, window: '1h' },
51
+ tokensPerRequestMean: { alertThreshold: 3000, window: '1h' },
52
+ costPerHourUsd: { alertThreshold: 50.0, window: '1h' },
53
+ fallbackRate: { alertThreshold: 0.10, window: '1h' },
54
+ };
55
+
56
+ function checkMetrics(current) {
57
+ const alerts = [];
58
+ for (const [metric, config] of Object.entries(MONITORING_METRICS)) {
59
+ const value = current[metric];
60
+ if (value == null) continue;
61
+ if (config.alertThreshold && value > config.alertThreshold)
62
+ alerts.push({ metric, value, threshold: config.alertThreshold });
63
+ }
64
+ return alerts;
65
+ }
66
+ ```
67
+
68
+
69
+ ### Pattern 2: Output drift detection
70
+
71
+ ```python
72
+ class DriftDetector:
73
+ def __init__(self, baseline_window: str = "30d"):
74
+ self.baseline = self.compute_baseline(baseline_window)
75
+
76
+ def check_drift(self, recent_window: str = "24h") -> dict:
77
+ recent = self.compute_distribution(recent_window)
78
+ drift_score = self.ks_test(self.baseline, recent) # Kolmogorov-Smirnov
79
+
80
+ return {
81
+ "drift_detected": drift_score > DRIFT_THRESHOLD,
82
+ "drift_score": drift_score,
83
+ "baseline_mean": self.baseline["mean"],
84
+ "recent_mean": recent["mean"],
85
+ "baseline_window": self.baseline["window"],
86
+ "recent_window": recent_window
87
+ }
88
+ ```
89
+
90
+ ```javascript
91
+ class DriftDetector {
92
+ constructor(baselineWindow = '30d') {
93
+ this.baseline = null;
94
+ this.init(baselineWindow);
95
+ }
96
+
97
+ async init(window) {
98
+ this.baseline = await this.computeDistribution(window);
99
+ }
100
+
101
+ async checkDrift(recentWindow = '24h') {
102
+ const recent = await this.computeDistribution(recentWindow);
103
+ const driftScore = this.ksTest(this.baseline, recent);
104
+ return {
105
+ driftDetected: driftScore > DRIFT_THRESHOLD,
106
+ driftScore,
107
+ baselineMean: this.baseline.mean,
108
+ recentMean: recent.mean,
109
+ };
110
+ }
111
+ }
112
+ ```
113
+
114
+
115
+ ### Pattern 3: User feedback integration
116
+
117
+ ```python
118
+ def record_feedback(trace_id: str, feedback_type: str, details: str = None):
119
+ """Record user feedback on AI decisions for monitoring."""
120
+ feedback_store.insert({
121
+ "trace_id": trace_id,
122
+ "feedback_type": feedback_type, # "agree", "disagree", "escalate"
123
+ "details": details,
124
+ "timestamp": datetime.utcnow().isoformat()
125
+ })
126
+
127
+ # Check for feedback patterns
128
+ recent_disagreements = feedback_store.count(
129
+ feedback_type="disagree",
130
+ window="24h"
131
+ )
132
+ if recent_disagreements > DISAGREEMENT_ALERT_THRESHOLD:
133
+ alert_ops_team(f"High disagreement rate: {recent_disagreements} in 24h")
134
+ ```
135
+
136
+ ```javascript
137
+ async function recordFeedback(traceId, feedbackType, details = null) {
138
+ await feedbackStore.insert({
139
+ traceId,
140
+ feedbackType, // 'agree', 'disagree', 'escalate'
141
+ details,
142
+ timestamp: new Date().toISOString(),
143
+ });
144
+ const recentDisagreements = await feedbackStore.count({
145
+ feedbackType: 'disagree', window: '24h',
146
+ });
147
+ if (recentDisagreements > DISAGREEMENT_ALERT_THRESHOLD)
148
+ await alertOpsTeam('High disagreement rate: ' + recentDisagreements + ' in 24h');
149
+ }
150
+ ```
151
+
152
+
153
+ ### Pattern 4: Incident response logging
154
+
155
+ ```python
156
+ def log_incident(incident_type: str, details: dict, severity: str):
157
+ """Structured incident logging per NIST MANAGE 4.3."""
158
+ incident = {
159
+ "incident_id": generate_id(),
160
+ "type": incident_type,
161
+ "severity": severity,
162
+ "timestamp": datetime.utcnow().isoformat(),
163
+ "details": details,
164
+ "status": "open",
165
+ "nist_control": "MANAGE-4.3",
166
+ "response_actions": [],
167
+ "resolution": None
168
+ }
169
+ incident_store.insert(incident)
170
+ if severity in ("high", "critical"):
171
+ alert_incident_team(incident)
172
+ return incident
173
+ ```
174
+
175
+ ```javascript
176
+ function logIncident(incidentType, details, severity) {
177
+ const incident = {
178
+ incidentId: generateId(),
179
+ type: incidentType,
180
+ severity,
181
+ timestamp: new Date().toISOString(),
182
+ details,
183
+ status: 'open',
184
+ nistControl: MANAGE-4.3',
185
+ responseActions: [],
186
+ resolution: null,
187
+ };
188
+ incidentStore.insert(incident);
189
+ if (['high', 'critical'].includes(severity))
190
+ alertIncidentTeam(incident);
191
+ return incident;
192
+ }
193
+ ```
194
+
195
+
196
+ ## Anti-patterns
197
+
198
+ - **No monitoring after deployment.** The system needs active monitoring from day one.
199
+ - **Monitoring only uptime.** Track output quality, not just availability.
200
+ - **No feedback mechanism.** Users must be able to flag bad outputs.
201
+ - **Alert fatigue.** Tune thresholds to avoid noise; tier alerts by severity.
202
+
203
+ ## Edge cases
204
+
205
+ - **Gradual degradation.** Performance may decline slowly. Use drift detection, not just threshold alerts.
206
+ - **Seasonal patterns.** Some metrics vary by time of day/week/year. Build seasonality into baselines.
207
+ - **Model provider changes.** When the third-party model is updated, reset baselines and monitor closely.