@aigis-ai/cli 1.0.2 → 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 +6 -2
  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,229 @@
1
+ {
2
+ "version": "1.0",
3
+ "tier_rule": "High-confidence: phrase implies the listed traits in essentially every realistic project where it appears (no plausible counterexample). Low-confidence: phrase implies the traits only some of the time (a realistic counter-project exists). Decision rule: if you can describe a project where the phrase appears but the trait does not apply, the entry is low-confidence. When in doubt, low-confidence.",
4
+
5
+ "high_confidence": {
6
+ "Anthropic": {
7
+ "traits": ["uses-llm", "uses-thirdparty-api"],
8
+ "confidence": "high",
9
+ "notes": "Mentioning the provider implies third-party + LLM."
10
+ },
11
+ "chatbot": {
12
+ "traits": ["uses-llm", "accepts-user-input"],
13
+ "confidence": "high",
14
+ "notes": "Any LLM-backed conversational interface."
15
+ },
16
+ "Claude": {
17
+ "traits": ["uses-llm", "uses-thirdparty-api"],
18
+ "confidence": "high",
19
+ "notes": "Specific model name implies the provider."
20
+ },
21
+ "code assistant": {
22
+ "traits": ["uses-llm", "generates-code"],
23
+ "confidence": "high",
24
+ "notes": "Code completion or code-explanation tooling."
25
+ },
26
+ "coding agent": {
27
+ "traits": ["uses-llm", "generates-code", "is-agentic"],
28
+ "confidence": "high",
29
+ "notes": "Agent that reads and writes code (Cursor-style)."
30
+ },
31
+ "fine-tune": {
32
+ "traits": ["uses-finetuned"],
33
+ "confidence": "high",
34
+ "notes": "Matches 'fine-tune', 'fine-tuned', 'fine-tuning'."
35
+ },
36
+ "function calling": {
37
+ "traits": ["is-agentic", "uses-llm"],
38
+ "confidence": "high",
39
+ "notes": "OpenAI/Anthropic function/tool calling — by definition agentic."
40
+ },
41
+ "GDPR": {
42
+ "traits": ["jurisdiction-eu"],
43
+ "confidence": "high",
44
+ "notes": "EU regulatory scope."
45
+ },
46
+ "GPT-4": {
47
+ "traits": ["uses-llm", "uses-thirdparty-api"],
48
+ "confidence": "high",
49
+ "notes": "Matches 'GPT-4', 'GPT-4o', 'GPT-4 Turbo' via substring."
50
+ },
51
+ "HIPAA": {
52
+ "traits": ["handles-health", "jurisdiction-us-regulated"],
53
+ "confidence": "high",
54
+ "notes": "Mentioning HIPAA implies health data + US regulated."
55
+ },
56
+ "OpenAI": {
57
+ "traits": ["uses-llm", "uses-thirdparty-api"],
58
+ "confidence": "high",
59
+ "notes": "Same pattern as Anthropic."
60
+ },
61
+ "RAG": {
62
+ "traits": ["uses-rag", "uses-llm"],
63
+ "confidence": "high",
64
+ "notes": "Retrieval-augmented generation. Spelled out in next entry."
65
+ },
66
+ "retrieval-augmented generation": {
67
+ "traits": ["uses-rag", "uses-llm"],
68
+ "confidence": "high",
69
+ "notes": "Spelled-out form of RAG."
70
+ },
71
+ "tool calling": {
72
+ "traits": ["is-agentic", "uses-llm"],
73
+ "confidence": "high",
74
+ "notes": "Same concept as function calling."
75
+ },
76
+ "vector database": {
77
+ "traits": ["uses-rag"],
78
+ "confidence": "high",
79
+ "notes": "Pinecone/Weaviate/Chroma/pgvector — any of these implies RAG."
80
+ }
81
+ },
82
+
83
+ "low_confidence": {
84
+ "AI agent": {
85
+ "traits": ["is-agentic"],
86
+ "confidence": "low",
87
+ "confirmation_prompt": "You mentioned an AI agent. Does an LLM choose the next action at each step (decides which tool to call, when to stop), or is the flow scripted by your code with the LLM only doing per-step generation? (yes / no / unsure)",
88
+ "notes": "'Agent' is overloaded marketing language. True agentic systems delegate the action loop to the LLM."
89
+ },
90
+ "analytics": {
91
+ "traits": ["processes-pii"],
92
+ "confidence": "low",
93
+ "confirmation_prompt": "You mentioned analytics. Are individual users identifiable in the data, or is it aggregated (counts, percentages, no per-user records)? (yes / no / unsure)",
94
+ "notes": "Aggregate analytics avoids PII."
95
+ },
96
+ "checkout": {
97
+ "traits": ["handles-financial"],
98
+ "confidence": "low",
99
+ "confirmation_prompt": "You mentioned checkout. Does this code touch payment processing, transaction records, or money flow? (yes / no / unsure)",
100
+ "notes": "Checkout UI vs payment backend are different things."
101
+ },
102
+ "content moderation": {
103
+ "traits": ["influences-decisions", "accepts-user-input"],
104
+ "confidence": "low",
105
+ "confirmation_prompt": "You mentioned content moderation. Does the AI's classification act on content directly (delete/hide), or does a human reviewer make the final call? (yes / no / unsure)",
106
+ "notes": "Same as 'moderation' but explicit two-trait suggestion."
107
+ },
108
+ "customer support": {
109
+ "traits": ["accepts-user-input", "is-external"],
110
+ "confidence": "low",
111
+ "confirmation_prompt": "You mentioned customer support. Is this exposed directly to customers (external) or only used by your support team (internal)? (yes / no / unsure)",
112
+ "notes": "Some support tools are agent-only."
113
+ },
114
+ "dashboard": {
115
+ "traits": ["processes-pii"],
116
+ "confidence": "low",
117
+ "confirmation_prompt": "You mentioned a dashboard. Does it display per-user data, or aggregate metrics only? (yes / no / unsure)",
118
+ "notes": "Aggregate dashboards skip PII."
119
+ },
120
+ "education": {
121
+ "traits": ["handles-minors"],
122
+ "confidence": "low",
123
+ "confirmation_prompt": "You mentioned education. Is this product used by anyone under 13 (or under 16 in the EU)? (yes / no / unsure)",
124
+ "notes": "Adult education products don't trigger COPPA/minors."
125
+ },
126
+ "email automation": {
127
+ "traits": ["generates-content", "processes-pii"],
128
+ "confidence": "low",
129
+ "confirmation_prompt": "You mentioned email automation. Are the emails generated per-recipient (uses customer data) or templated/broadcast (no per-user PII in the generation)? (yes / no / unsure)",
130
+ "notes": "Drip campaigns differ from per-recipient generation."
131
+ },
132
+ "extract from documents": {
133
+ "traits": ["uses-rag"],
134
+ "confidence": "low",
135
+ "confirmation_prompt": "You mentioned document extraction. Does the system index and search documents semantically (RAG), or is this single-document OCR/extraction without retrieval? (yes / no / unsure)",
136
+ "notes": "OCR pipelines aren't RAG."
137
+ },
138
+ "form processing": {
139
+ "traits": ["accepts-user-input", "processes-pii"],
140
+ "confidence": "low",
141
+ "confirmation_prompt": "You mentioned form processing. Do the forms collect personally identifiable information (name, email, phone, etc.)? (yes / no / unsure)",
142
+ "notes": "Anonymous feedback forms don't have PII."
143
+ },
144
+ "high traffic": {
145
+ "traits": ["is-high-volume"],
146
+ "confidence": "low",
147
+ "confirmation_prompt": "You mentioned high traffic. Are you actually expecting >1000 LLM requests/day, or describing aspirational scale? (yes / no / unsure)",
148
+ "notes": "Aspirational scale != current reality."
149
+ },
150
+ "image upload": {
151
+ "traits": ["is-multimodal"],
152
+ "confidence": "low",
153
+ "confirmation_prompt": "You mentioned image upload. Are the images analyzed by a vision model (multimodal LLM), or just stored/displayed without AI processing? (yes / no / unsure)",
154
+ "notes": "Image hosting != multimodal AI."
155
+ },
156
+ "internal tool": {
157
+ "traits": ["is-internal"],
158
+ "confidence": "low",
159
+ "confirmation_prompt": "You mentioned an internal tool. Is access restricted to employees only (no external users), or is 'internal' a marketing term? (yes / no / unsure)",
160
+ "notes": "Some 'internal' tools have customer-facing surfaces."
161
+ },
162
+ "marketplace": {
163
+ "traits": ["handles-financial", "is-external"],
164
+ "confidence": "low",
165
+ "confirmation_prompt": "You mentioned a marketplace. Does it process payments directly, or just facilitate connections (no money flow through your service)? (yes / no / unsure)",
166
+ "notes": "Lead-gen marketplaces don't always touch money."
167
+ },
168
+ "moderation": {
169
+ "traits": ["influences-decisions"],
170
+ "confidence": "low",
171
+ "confirmation_prompt": "You mentioned moderation. Does the AI act directly on user content (delete, hide, suspend) without a human reviewer in the loop? (yes / no / unsure)",
172
+ "notes": "Human-in-the-loop moderation is advisory, not deciding."
173
+ },
174
+ "notifications": {
175
+ "traits": ["processes-pii"],
176
+ "confidence": "low",
177
+ "confirmation_prompt": "You mentioned notifications. Are notifications addressed to individual users (their email/phone/device token)? (yes / no / unsure)",
178
+ "notes": "Broadcast notifications without targeting don't need PII."
179
+ },
180
+ "personalization": {
181
+ "traits": ["processes-pii"],
182
+ "confidence": "low",
183
+ "confirmation_prompt": "You mentioned personalization. Does this system use information that identifies an individual user (account, profile, history) to personalize output? Anonymous session-only personalization does not count. (yes / no / unsure)",
184
+ "notes": "Anonymous session-based personalization doesn't trigger PII."
185
+ },
186
+ "recommendations": {
187
+ "traits": ["influences-decisions"],
188
+ "confidence": "low",
189
+ "confirmation_prompt": "You mentioned recommendations. Do they directly affect a user's outcomes (price, eligibility, hiring) or are they advisory only? (yes / no / unsure)",
190
+ "notes": "Product recommendations are usually advisory; loan recommendations are not."
191
+ },
192
+ "search through documents": {
193
+ "traits": ["uses-rag"],
194
+ "confidence": "low",
195
+ "confirmation_prompt": "You mentioned searching through documents. Are the documents embedded into a vector store, or is this keyword search (Postgres FTS, Elasticsearch BM25, grep)? (yes / no / unsure)",
196
+ "notes": "Keyword search != RAG."
197
+ },
198
+ "summarize": {
199
+ "traits": ["uses-llm", "generates-content"],
200
+ "confidence": "low",
201
+ "confirmation_prompt": "You mentioned summarization. Is this an LLM summary, or extractive (pulling sentences out without an LLM)? (yes / no / unsure)",
202
+ "notes": "Extractive summarization predates LLMs."
203
+ },
204
+ "translation": {
205
+ "traits": ["uses-llm"],
206
+ "confidence": "low",
207
+ "confirmation_prompt": "You mentioned translation. Is this LLM-based, or using a dedicated translation API (Google Translate, DeepL) without an LLM? (yes / no / unsure)",
208
+ "notes": "Translation APIs != LLMs."
209
+ },
210
+ "user profile": {
211
+ "traits": ["processes-pii"],
212
+ "confidence": "low",
213
+ "confirmation_prompt": "You mentioned user profiles. Do these profiles include personally identifiable information (name, email, address, etc.)? (yes / no / unsure)",
214
+ "notes": "Pseudonymous profiles can avoid PII traits."
215
+ },
216
+ "voice assistant": {
217
+ "traits": ["is-multimodal", "accepts-user-input", "uses-llm"],
218
+ "confidence": "low",
219
+ "confirmation_prompt": "You mentioned voice. Is voice the input/output modality (multimodal LLM), or is voice transcribed to text first by a separate service before reaching your LLM? (yes / no / unsure)",
220
+ "notes": "STT-then-LLM is text-only at the LLM layer."
221
+ },
222
+ "writing assistant": {
223
+ "traits": ["uses-llm", "generates-content"],
224
+ "confidence": "low",
225
+ "confirmation_prompt": "You mentioned a writing assistant. Does it generate text on its own (uses-llm + generates-content), or only check spelling/grammar against rules? (yes / no / unsure)",
226
+ "notes": "Grammarly-style rule-based tools don't need LLM traits."
227
+ }
228
+ }
229
+ }
@@ -0,0 +1,176 @@
1
+ ---
2
+ id: audit-logging
3
+ title: Audit logging and traceability
4
+ controls:
5
+ owasp: []
6
+ nist: [MEASURE-2.8, MANAGE-4.1, MANAGE-4.3]
7
+ iso42001: [Clause-9.1, Annex-A.6]
8
+ min_risk_tier: all
9
+ system_traits: [uses-llm]
10
+ ---
11
+
12
+ ## What this addresses
13
+
14
+ Every AI system needs an audit trail. NIST MANAGE 4.1 requires post-deployment monitoring with mechanisms for evaluating system behavior. ISO 42001 Clause 9.1 requires systematic monitoring and measurement. Without structured logging, you cannot debug failures, investigate incidents, demonstrate compliance, or detect drift.
15
+
16
+ ## Implementation patterns
17
+
18
+ ### Pattern 1: Structured log entry for every LLM interaction
19
+
20
+ ```python
21
+ import uuid
22
+ from datetime import datetime
23
+
24
+ def create_audit_entry(
25
+ input_text: str,
26
+ output_text: str,
27
+ model_version: str,
28
+ user_id: str,
29
+ **kwargs
30
+ ) -> dict:
31
+ return {
32
+ "trace_id": str(uuid.uuid4()),
33
+ "timestamp": datetime.utcnow().isoformat() + "Z",
34
+ "model_version": model_version,
35
+ "model_provider": kwargs.get("provider", "unknown"),
36
+ "user_id": user_id,
37
+ "input_hash": hashlib.sha256(input_text.encode()).hexdigest(),
38
+ "input_token_count": count_tokens(input_text),
39
+ "output_token_count": count_tokens(output_text),
40
+ "output_redacted": redact_pii(output_text)[0], # Never log raw PII
41
+ "latency_ms": kwargs.get("latency_ms"),
42
+ "status": kwargs.get("status", "success"),
43
+ "confidence_score": kwargs.get("confidence"),
44
+ "controls_applied": kwargs.get("controls", []),
45
+ "override_status": kwargs.get("override", None),
46
+ }
47
+ ```
48
+
49
+ ```javascript
50
+ const crypto = require('crypto');
51
+ const { v4: uuidv4 } = require('uuid');
52
+
53
+ function createAuditEntry(inputText, outputText, modelVersion, userId, opts = {}) {
54
+ return {
55
+ traceId: uuidv4(),
56
+ timestamp: new Date().toISOString(),
57
+ modelVersion,
58
+ modelProvider: opts.provider || 'unknown',
59
+ userId,
60
+ inputHash: crypto.createHash('sha256').update(inputText).digest('hex'),
61
+ inputTokenCount: countTokens(inputText),
62
+ outputTokenCount: countTokens(outputText),
63
+ outputRedacted: redactPii(outputText).text,
64
+ latencyMs: opts.latencyMs,
65
+ status: opts.status || 'success',
66
+ confidenceScore: opts.confidence,
67
+ controlsApplied: opts.controls || [],
68
+ overrideStatus: opts.override || null,
69
+ };
70
+ }
71
+ ```
72
+
73
+
74
+ ### Pattern 2: Trace ID propagation
75
+
76
+ ```python
77
+ import contextvars
78
+
79
+ trace_id_var = contextvars.ContextVar('trace_id')
80
+
81
+ def set_trace_id():
82
+ tid = str(uuid.uuid4())
83
+ trace_id_var.set(tid)
84
+ return tid
85
+
86
+ def get_trace_id() -> str:
87
+ return trace_id_var.get("no-trace-id")
88
+
89
+ # Use in every log call, API response, and error message
90
+ # This allows correlating a single request across all system components
91
+ ```
92
+
93
+ ```javascript
94
+ const { AsyncLocalStorage } = require('async_hooks');
95
+ const traceStorage = new AsyncLocalStorage();
96
+
97
+ function setTraceId() {
98
+ const traceId = crypto.randomUUID();
99
+ traceStorage.enterWith(traceId);
100
+ return traceId;
101
+ }
102
+
103
+ function getTraceId() {
104
+ return traceStorage.getStore() || 'no-trace-id';
105
+ }
106
+ ```
107
+
108
+
109
+ ### Pattern 3: Decision audit trail
110
+
111
+ ```python
112
+ def log_decision(decision: dict, context: dict):
113
+ """Log every AI-influenced decision with full context."""
114
+ audit_log.info({
115
+ "event_type": "ai_decision",
116
+ "trace_id": get_trace_id(),
117
+ "decision": {
118
+ "action": decision["recommendation"],
119
+ "confidence": decision["confidence"],
120
+ "model_version": decision["model_version"],
121
+ },
122
+ "context": {
123
+ "input_summary": context.get("summary"), # Not raw input
124
+ "controls_applied": context.get("controls"),
125
+ "risk_tier": context.get("risk_tier"),
126
+ },
127
+ "compliance": {
128
+ "nist_controls": ["MANAGE-4.1"],
129
+ "iso_clause": "9.1",
130
+ "human_reviewable": True
131
+ }
132
+ })
133
+ ```
134
+
135
+ ```javascript
136
+ function logDecision(decision, context) {
137
+ auditLog.info({
138
+ eventType: 'ai_decision',
139
+ traceId: getTraceId(),
140
+ decision: {
141
+ action: decision.recommendation,
142
+ confidence: decision.confidence,
143
+ modelVersion: decision.modelVersion,
144
+ },
145
+ context: {
146
+ inputSummary: context.summary,
147
+ controlsApplied: context.controls,
148
+ riskTier: context.riskTier,
149
+ },
150
+ compliance: {
151
+ nistControls: [MANAGE-4.1'],
152
+ isoClause: '9.1',
153
+ humanReviewable: true,
154
+ },
155
+ });
156
+ }
157
+ ```
158
+
159
+
160
+ ## Anti-patterns
161
+
162
+ - **Logging raw PII.** Always redact before logging. See pii-handling.md.
163
+ - **Unstructured log messages.** Use structured JSON logs with consistent fields.
164
+ - **No trace ID.** Every request must have a trace ID that propagates through all components.
165
+ - **Logging only errors.** Log all interactions, not just failures. You need the baseline to detect anomalies.
166
+
167
+ ## Edge cases
168
+
169
+ - **Log volume at scale.** At high volume, consider sampling non-critical logs while keeping 100% of error and decision logs.
170
+ - **Log retention and compliance.** Different regulations require different retention periods. Configure per data type.
171
+ - **Cross-system correlation.** If the AI system calls external services, propagate trace IDs via headers.
172
+
173
+ ## Related infrastructure
174
+
175
+ - `aigis infra logging` — `structlog` JSON-to-stdout setup with a concrete `REDACT_KEYS` list, plus integration patterns for Datadog/New Relic/Honeycomb, CloudWatch, Sentry (with the `max_request_body_size='never'` warning), and OpenTelemetry/OTLP.
176
+ - `aigis infra secrets` — keep API keys and connection strings out of the structured fields you log.
@@ -0,0 +1,172 @@
1
+ ---
2
+ id: bias-monitoring
3
+ title: Bias monitoring and fairness
4
+ controls:
5
+ owasp: []
6
+ nist: [MAP-2.3, MEASURE-2.11, MEASURE-3.1]
7
+ iso42001: [Clause-6.1, Annex-C]
8
+ min_risk_tier: medium
9
+ system_traits: [influences-decisions, handles-health, handles-financial, generates-content, handles-minors]
10
+ ---
11
+
12
+ ## What this addresses
13
+
14
+ NIST MEASURE 2.11 requires evaluation of fairness and bias. AI systems can produce systematically different outcomes for different demographic groups, even without explicit demographic data, through proxy features like zip code, writing style, or name. This file covers the technical infrastructure for detecting and monitoring bias.
15
+
16
+ ## Implementation patterns
17
+
18
+ ### Pattern 1: Fairness-enabling metadata in logs
19
+
20
+ ```python
21
+ def log_with_fairness_fields(decision: dict, context: dict):
22
+ """Include fields that enable fairness auditing downstream."""
23
+ audit_entry = {
24
+ "trace_id": get_trace_id(),
25
+ "decision": decision,
26
+ # Fairness-relevant metadata (NOT protected characteristics directly)
27
+ "fairness_audit_fields": {
28
+ "claim_type": context.get("claim_type"),
29
+ "region": context.get("region"),
30
+ "submission_channel": context.get("channel"), # web, phone, agent
31
+ "input_language": detect_language(context.get("input_text", "")),
32
+ "input_length_bucket": bucket_length(context.get("input_text", "")),
33
+ }
34
+ }
35
+ audit_log.info(audit_entry)
36
+ ```
37
+
38
+ ```javascript
39
+ function logWithFairnessFields(decision, context) {
40
+ auditLog.info({
41
+ traceId: getTraceId(),
42
+ decision,
43
+ fairnessAuditFields: {
44
+ claimType: context.claimType,
45
+ region: context.region,
46
+ submissionChannel: context.channel,
47
+ inputLanguage: detectLanguage(context.inputText || ''),
48
+ inputLengthBucket: bucketLength(context.inputText || ''),
49
+ },
50
+ });
51
+ }
52
+ ```
53
+
54
+
55
+ ### Pattern 2: Output distribution monitoring
56
+
57
+ ```python
58
+ class BiasMonitor:
59
+ def __init__(self, alert_threshold: float = 0.15):
60
+ self.alert_threshold = alert_threshold
61
+
62
+ def check_distribution(self, period: str = "7d") -> list:
63
+ """Compare score distributions across demographic segments."""
64
+ decisions = self.load_decisions(period)
65
+ alerts = []
66
+
67
+ for field in FAIRNESS_AUDIT_FIELDS:
68
+ segments = group_by(decisions, field)
69
+ for seg_a, seg_b in combinations(segments.keys(), 2):
70
+ scores_a = [d["severity_score"] for d in segments[seg_a]]
71
+ scores_b = [d["severity_score"] for d in segments[seg_b]]
72
+ disparity = abs(mean(scores_a) - mean(scores_b))
73
+
74
+ if disparity > self.alert_threshold:
75
+ alerts.append({
76
+ "field": field,
77
+ "segment_a": seg_a,
78
+ "segment_b": seg_b,
79
+ "disparity": disparity,
80
+ "sample_size_a": len(scores_a),
81
+ "sample_size_b": len(scores_b),
82
+ })
83
+ return alerts
84
+ ```
85
+
86
+ ```javascript
87
+ class BiasMonitor {
88
+ constructor(alertThreshold = 0.15) {
89
+ this.alertThreshold = alertThreshold;
90
+ }
91
+
92
+ async checkDistribution(period = '7d') {
93
+ const decisions = await this.loadDecisions(period);
94
+ const alerts = [];
95
+ for (const field of FAIRNESS_AUDIT_FIELDS) {
96
+ const segments = groupBy(decisions, field);
97
+ const keys = Object.keys(segments);
98
+ for (let i = 0; i < keys.length; i++) {
99
+ for (let j = i + 1; j < keys.length; j++) {
100
+ const scoresA = segments[keys[i]].map(d => d.severityScore);
101
+ const scoresB = segments[keys[j]].map(d => d.severityScore);
102
+ const disparity = Math.abs(mean(scoresA) - mean(scoresB));
103
+ if (disparity > this.alertThreshold) {
104
+ alerts.push({ field, segmentA: keys[i], segmentB: keys[j],
105
+ disparity, sampleSizeA: scoresA.length, sampleSizeB: scoresB.length });
106
+ }
107
+ }
108
+ }
109
+ }
110
+ return alerts;
111
+ }
112
+ }
113
+ ```
114
+
115
+
116
+ ### Pattern 3: Periodic fairness reports
117
+
118
+ ```python
119
+ def generate_fairness_report(period: str = "30d") -> dict:
120
+ monitor = BiasMonitor()
121
+ alerts = monitor.check_distribution(period)
122
+ override_analysis = monitor.analyze_override_patterns(period)
123
+
124
+ return {
125
+ "period": period,
126
+ "generated_at": datetime.utcnow().isoformat(),
127
+ "distribution_alerts": alerts,
128
+ "override_patterns": override_analysis,
129
+ "total_decisions": monitor.count_decisions(period),
130
+ "nist_control": "MEASURE-2.11",
131
+ "iso_clause": "Clause-6.1",
132
+ "recommendation": "review_required" if alerts else "no_action_needed"
133
+ }
134
+ ```
135
+
136
+ ```javascript
137
+ async function generateFairnessReport(period = '30d') {
138
+ const monitor = new BiasMonitor();
139
+ const alerts = await monitor.checkDistribution(period);
140
+ const overrideAnalysis = await monitor.analyzeOverridePatterns(period);
141
+ return {
142
+ period,
143
+ generatedAt: new Date().toISOString(),
144
+ distributionAlerts: alerts,
145
+ overridePatterns: overrideAnalysis,
146
+ totalDecisions: await monitor.countDecisions(period),
147
+ nistControl: MEASURE-2.11',
148
+ isoClause: Clause-6.1',
149
+ recommendation: alerts.length ? 'review_required' : 'no_action_needed',
150
+ };
151
+ }
152
+ ```
153
+
154
+
155
+ ## Anti-patterns
156
+
157
+ - **Collecting protected characteristics directly.** Use proxy-free fairness audit fields.
158
+ - **One-time bias testing.** Bias must be monitored continuously, not just at launch.
159
+ - **Only measuring accuracy.** Equal accuracy doesn't mean equal outcomes. Measure disparate impact.
160
+ - **Ignoring override patterns.** If humans override AI decisions more for one group, that signals bias.
161
+
162
+ ## Related files
163
+
164
+ - **audit-logging.md:** Fairness audit fields (Pattern 1) must be included in the structured log entries defined in audit-logging.md Pattern 1. The fairness fields are additional metadata in the same audit log, not a separate logging system.
165
+ - **human-oversight.md:** Override patterns are a key bias signal. Track human override rates per segment using human-oversight.md Pattern 4 (override mechanism) data, analyzed through bias-monitoring.md Pattern 2 (distribution monitoring).
166
+ - **confidence-scoring.md:** Bias may manifest as systematically lower confidence for certain groups. Cross-reference confidence distributions with fairness audit fields.
167
+
168
+ ## Edge cases
169
+
170
+ - **Intersectional bias.** Bias may only appear at the intersection of two dimensions (e.g., region + claim type).
171
+ - **Small sample sizes.** Statistical tests need sufficient data per segment. Flag when samples are too small.
172
+ - **Feedback loops.** If biased outputs influence future training data, bias compounds over time.