@aigis-ai/cli 2.0.1 → 2.0.2

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 (82) hide show
  1. package/README.md +58 -188
  2. package/aigis-ai-cli-2.0.1.tgz +0 -0
  3. package/package.json +1 -1
  4. package/cli-python/LICENSE +0 -21
  5. package/cli-python/README.md +0 -32
  6. package/cli-python/aigis_cli/SKILL.md +0 -70
  7. package/cli-python/aigis_cli/__init__.py +0 -3
  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 +0 -45
  19. package/cli-python/aigis_cli/auto_verify.py +0 -518
  20. package/cli-python/aigis_cli/build.py +0 -470
  21. package/cli-python/aigis_cli/checksum.py +0 -22
  22. package/cli-python/aigis_cli/classify.py +0 -192
  23. package/cli-python/aigis_cli/cli.py +0 -618
  24. package/cli-python/aigis_cli/content/index/audit-scan.md +0 -217
  25. package/cli-python/aigis_cli/content/index/auto-verify-rules.json +0 -439
  26. package/cli-python/aigis_cli/content/index/context-rules.json +0 -90
  27. package/cli-python/aigis_cli/content/index/frameworks.md +0 -82
  28. package/cli-python/aigis_cli/content/index/guardrails.json +0 -23
  29. package/cli-python/aigis_cli/content/index/taxonomy.md +0 -81
  30. package/cli-python/aigis_cli/content/resolvers/triggers.json +0 -229
  31. package/cli-python/aigis_cli/content/skills/areas/audit-logging.md +0 -176
  32. package/cli-python/aigis_cli/content/skills/areas/bias-monitoring.md +0 -172
  33. package/cli-python/aigis_cli/content/skills/areas/confidence-scoring.md +0 -180
  34. package/cli-python/aigis_cli/content/skills/areas/data-integrity.md +0 -257
  35. package/cli-python/aigis_cli/content/skills/areas/explainability.md +0 -174
  36. package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +0 -200
  37. package/cli-python/aigis_cli/content/skills/areas/human-oversight.md +0 -220
  38. package/cli-python/aigis_cli/content/skills/areas/input-validation.md +0 -380
  39. package/cli-python/aigis_cli/content/skills/areas/monitoring.md +0 -207
  40. package/cli-python/aigis_cli/content/skills/areas/output-sanitization.md +0 -183
  41. package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +0 -189
  42. package/cli-python/aigis_cli/content/skills/areas/prompt-security.md +0 -153
  43. package/cli-python/aigis_cli/content/skills/areas/rag-security.md +0 -230
  44. package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +0 -246
  45. package/cli-python/aigis_cli/content/skills/areas/supply-chain.md +0 -193
  46. package/cli-python/aigis_cli/content/skills/core.md +0 -62
  47. package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +0 -202
  48. package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +0 -169
  49. package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +0 -167
  50. package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +0 -86
  51. package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +0 -54
  52. package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +0 -39
  53. package/cli-python/aigis_cli/content/templates/risk-characterization.md +0 -34
  54. package/cli-python/aigis_cli/content/templates/third-party-assessment.md +0 -41
  55. package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +0 -13
  56. package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +0 -13
  57. package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +0 -13
  58. package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +0 -12
  59. package/cli-python/aigis_cli/content/verify/checklist-explainability.md +0 -13
  60. package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +0 -13
  61. package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +0 -14
  62. package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +0 -16
  63. package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +0 -13
  64. package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +0 -14
  65. package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +0 -14
  66. package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +0 -13
  67. package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +0 -12
  68. package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +0 -13
  69. package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +0 -13
  70. package/cli-python/aigis_cli/fetch.py +0 -232
  71. package/cli-python/aigis_cli/init_ide.py +0 -159
  72. package/cli-python/aigis_cli/keywords.py +0 -73
  73. package/cli-python/aigis_cli/search.py +0 -69
  74. package/cli-python/aigis_cli.egg-info/PKG-INFO +0 -59
  75. package/cli-python/aigis_cli.egg-info/SOURCES.txt +0 -56
  76. package/cli-python/aigis_cli.egg-info/dependency_links.txt +0 -1
  77. package/cli-python/aigis_cli.egg-info/entry_points.txt +0 -2
  78. package/cli-python/aigis_cli.egg-info/requires.txt +0 -6
  79. package/cli-python/aigis_cli.egg-info/top_level.txt +0 -1
  80. package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
  81. package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
  82. package/cli-python/pyproject.toml +0 -49
@@ -1,207 +0,0 @@
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.
@@ -1,183 +0,0 @@
1
- ---
2
- id: output-sanitization
3
- title: Output sanitization and handling
4
- controls:
5
- owasp: [LLM05]
6
- nist: [MEASURE-2.6, MEASURE-2.7]
7
- iso42001: [Clause-8.2]
8
- min_risk_tier: all
9
- system_traits: [uses-llm]
10
- ---
11
-
12
- ## What this addresses
13
-
14
- LLM output is untrusted data. When passed to downstream systems without validation, it becomes an attack vector: XSS via web rendering, SQL injection via database queries, command injection via shell execution, or code injection via eval. OWASP LLM05 specifically addresses this failure to treat LLM output as potentially hostile.
15
-
16
- ## Implementation patterns
17
-
18
- ### Pattern 1: Treat LLM output as untrusted user input
19
-
20
- ```python
21
- # Apply the SAME sanitization to LLM output that you apply to user input
22
- def process_llm_response(raw_response: str, output_context: str) -> str:
23
- if output_context == "html":
24
- return html_encode(raw_response)
25
- elif output_context == "sql":
26
- return parameterize_query(raw_response) # Never interpolate
27
- elif output_context == "shell":
28
- return shlex.quote(raw_response)
29
- elif output_context == "json_api":
30
- return validate_against_schema(raw_response)
31
- else:
32
- return raw_response # Log warning: unknown context
33
- ```
34
-
35
- ```javascript
36
- function processLlmResponse(rawResponse, outputContext) {
37
- switch (outputContext) {
38
- case 'html': return escapeHtml(rawResponse);
39
- case 'sql': return parameterizeQuery(rawResponse);
40
- case 'json_api': return validateAgainstSchema(rawResponse);
41
- default:
42
- logWarning('unknown_output_context', { context: outputContext });
43
- return rawResponse;
44
- }
45
- }
46
- ```
47
-
48
-
49
- ### Pattern 2: HTML encoding for web display
50
-
51
- ```python
52
- import html
53
-
54
- def safe_render_llm_output(llm_text: str) -> str:
55
- """Encode LLM output before inserting into HTML."""
56
- encoded = html.escape(llm_text, quote=True)
57
- # Strip any remaining HTML tags the encoding might have missed
58
- encoded = re.sub(r'<[^>]+>', '', encoded)
59
- return encoded
60
- ```
61
-
62
- ```javascript
63
- function safeRenderLlmOutput(llmText) {
64
- const div = document.createElement('div');
65
- div.textContent = llmText; // textContent auto-escapes
66
- return div.innerHTML;
67
- }
68
- ```
69
-
70
- ### Pattern 3: Parameterized queries for database operations
71
-
72
- ```python
73
- # CORRECT: parameterized query
74
- def store_llm_result(result: str, claim_id: str):
75
- cursor.execute(
76
- "INSERT INTO assessments (claim_id, result) VALUES (%s, %s)",
77
- (claim_id, result)
78
- )
79
-
80
- # WRONG: string interpolation
81
- cursor.execute(f"INSERT INTO assessments VALUES ('{claim_id}', '{result}')")
82
- ```
83
-
84
- ```javascript
85
- // CORRECT: parameterized query
86
- async function storeLlmResult(result, claimId) {
87
- await db.query(
88
- 'INSERT INTO assessments (claim_id, result) VALUES ($1, $2)',
89
- [claimId, result]
90
- );
91
- }
92
-
93
- // WRONG: string interpolation
94
- // await db.query(`INSERT INTO assessments VALUES ('${claimId}', '${result}')`);
95
- ```
96
-
97
-
98
- ### Pattern 4: Sandbox execution for generated code
99
-
100
- ```python
101
- # If LLM generates code that must be executed, isolate it
102
- import subprocess
103
-
104
- def execute_llm_code(code: str, timeout: int = 10) -> str:
105
- # Never use eval() or exec() directly
106
- result = subprocess.run(
107
- ["python", "-c", code],
108
- capture_output=True, text=True, timeout=timeout,
109
- # Restrict: no network, limited filesystem, limited memory
110
- env={"PATH": "/usr/bin"},
111
- cwd="/tmp/sandbox"
112
- )
113
- if result.returncode != 0:
114
- log_anomaly("code_execution_failure", code, result.stderr)
115
- return result.stdout
116
- ```
117
-
118
- ```javascript
119
- const vm = require('vm');
120
-
121
- function executeLlmCode(code, timeout = 10000) {
122
- const context = vm.createContext({ console: { log: () => {} } });
123
- try {
124
- return vm.runInContext(code, context, { timeout });
125
- } catch (e) {
126
- logAnomaly('code_execution_failure', code, e.message);
127
- return null;
128
- }
129
- }
130
- ```
131
-
132
-
133
- ### Pattern 5: Content type validation
134
-
135
- ```python
136
- def validate_response_content_type(response: str, expected: str) -> bool:
137
- """Ensure LLM response matches expected content type."""
138
- if expected == "json":
139
- try:
140
- json.loads(response)
141
- return True
142
- except json.JSONDecodeError:
143
- return False
144
- elif expected == "number":
145
- return response.strip().replace('.', '', 1).isdigit()
146
- elif expected == "enum":
147
- return response.strip() in ALLOWED_VALUES
148
- return False
149
- ```
150
-
151
- ```javascript
152
- function validateResponseContentType(response, expected) {
153
- switch (expected) {
154
- case 'json':
155
- try { JSON.parse(response); return true; } catch { return false; }
156
- case 'number':
157
- return !isNaN(Number(response.trim()));
158
- case 'enum':
159
- return ALLOWED_VALUES.includes(response.trim());
160
- default:
161
- return false;
162
- }
163
- }
164
- ```
165
-
166
-
167
- ## Anti-patterns
168
-
169
- - **Direct rendering of LLM output in HTML.** Always encode first.
170
- - **Using LLM output in SQL without parameterization.** Always parameterize.
171
- - **eval() or exec() on LLM-generated code.** Always sandbox.
172
- - **Assuming LLM output is safe because the prompt asked for safe output.** Prompts are not security controls.
173
-
174
- ## Related files
175
-
176
- - **input-validation.md:** Input validation and output sanitization are complementary — together they create a validated I/O boundary around the LLM. Input validation (Pattern 4: output schema enforcement) is the first line of defense; output sanitization handles what gets through. Always implement both.
177
- - **fallback-patterns.md:** When output validation fails (Pattern 1, Pattern 4), use fallback-patterns.md Pattern 1 (default safe response) to return a safe value instead of crashing.
178
-
179
- ## Edge cases
180
-
181
- - **Markdown rendering.** If rendering LLM markdown as HTML, use a sanitizing markdown parser that strips scripts and event handlers.
182
- - **Structured output with embedded content.** JSON fields may contain strings with injection payloads. Sanitize each field individually.
183
- - **Multi-step pipelines.** If LLM A's output feeds into LLM B, sanitize at each boundary.
@@ -1,189 +0,0 @@
1
- ---
2
- id: pii-handling
3
- title: PII and sensitive data protection
4
- controls:
5
- owasp: [LLM02]
6
- nist: [MAP-2.1, MEASURE-2.10]
7
- iso42001: [Annex-A.7, Annex-A.4]
8
- min_risk_tier: all
9
- system_traits: [processes-pii, handles-financial, handles-health, handles-minors]
10
- ---
11
-
12
- Personally identifiable information that reaches the LLM (or the logs of LLM calls) leaks control of that data to the provider and to anyone with log access. This procedure redacts PII before it crosses those boundaries.
13
-
14
- ## Common incomplete implementations
15
-
16
- 1. **Partial pattern coverage.** Three classes out of five (typically: SSN + email + phone OR SSN + credit card + email). The one class most often missed is **physical addresses**, because addresses are harder to regex than structured fields. Missing any of the five below leaves a class of PII flowing to the LLM unredacted.
17
- 2. **Redaction on LLM input but not logs.** Redacting what goes to the model protects the model; logs of the raw request to the handler still contain raw PII.
18
- 3. **Hashable placeholder.** Using `hash(ssn)` or similar as the replacement. The hash is deterministic — anyone who observes a log entry with a given hash and has a candidate SSN can verify the match. Use non-reversible labels like `[SSN_REDACTED]`.
19
- 4. **Redaction applied only at one entry point.** If your handler ingests claim text in multiple places (main endpoint + retry endpoint + batch endpoint), every entry point must route through the redactor.
20
-
21
- ## The five required pattern classes
22
-
23
- Every implementation of this pattern must cover these five classes at minimum:
24
-
25
- | Class | What it matches | Example |
26
- |---|---|---|
27
- | `ssn` | US Social Security Numbers | `123-45-6789` |
28
- | `email` | Email addresses | `alice@example.com` |
29
- | `phone` | US phone numbers (with or without country code, with or without separators) | `(555) 123-4567`, `+1-555-123-4567` |
30
- | `credit_card` | 13-19 digit card numbers with optional separators | `4242 4242 4242 4242` |
31
- | `address` | US street addresses with directional / street-type tokens | `123 Main St`, `456 Elm Avenue, Apt 2B` |
32
-
33
- Domain-specific classes (date of birth, account numbers, medical record numbers) should be added on top of these five, not in place of any of them.
34
-
35
- ## Implementation procedure
36
-
37
- ### Step 1 — Define PII_PATTERNS with all five required keys ⚠ CRITICAL
38
-
39
- **What to do.** Create a dictionary (or equivalent structure) named `PII_PATTERNS` with exactly these keys: `ssn`, `email`, `phone`, `credit_card`, `address`. Each value is the regex that matches that class.
40
-
41
- **Why this matters.** The regex dict is the single source of truth for what your redactor knows about. If a key is missing from the dict, it doesn't matter how careful the rest of your code is — that class of PII flows through.
42
-
43
- ```python
44
- import re
45
-
46
- PII_PATTERNS = {
47
- "ssn": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
48
- "email": re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"),
49
- "phone": re.compile(r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b"),
50
- "credit_card": re.compile(r"\b(?:\d{4}[-\s]?){3}\d{4}\b"),
51
- "address": re.compile(
52
- r"\b\d{1,6}\s+(?:[A-Z][a-z]+\s+){1,3}"
53
- r"(?:St(?:reet)?|Ave(?:nue)?|Blvd|Boulevard|Rd|Road|Ln|Lane|Dr|Drive|Way|Ct|Court|Pl|Place|Sq|Square|Pkwy|Parkway|Terr|Terrace)\b"
54
- r"(?:,?\s*(?:Apt|Suite|Ste|Unit|#)\s*[\w-]+)?",
55
- re.IGNORECASE,
56
- ),
57
- }
58
- ```
59
-
60
- **Verification checkpoint.** Count the keys. The dictionary must have **exactly five** keys named `ssn`, `email`, `phone`, `credit_card`, `address`. If any is missing, add it before continuing. If you have additional keys for domain-specific classes, that is fine — do not remove them. But do not claim the redactor is complete without all five required keys.
61
-
62
- ### Step 2 — Write a redaction function with non-reversible placeholders
63
-
64
- **What to do.** Implement `redact_pii(text) -> (redacted_text, seen: list[str])` that iterates `PII_PATTERNS` and replaces each match with a label like `[<CLASS>_REDACTED]`. Return the list of classes seen for metric / log context.
65
-
66
- **Why this matters.** Reversible placeholders (hashes of PII) defeat the purpose — anyone with a candidate value can verify a match. Non-reversible labels keep the boundary intact.
67
-
68
- **Verification checkpoint.** Run the redactor against a test string containing every required class. All five should be replaced; none of the originals should appear in the output. See the complete example at the end for the implementation + test.
69
-
70
- ### Step 3 — Call the redactor on every LLM input path
71
-
72
- **What to do.** For every place in the code where user-provided text goes to the LLM, pass it through `redact_pii` first. Use the redacted text in the LLM request. Originals stay in the handler stack frame only — never in logs or persistent stores.
73
-
74
- **Why this matters.** Redaction at the wrong layer leaks. If one endpoint redacts and another doesn't, the system leaks through the other.
75
-
76
- **Verification checkpoint.** `grep -rn "messages.create\|chat.completions.create"` — every hit must be preceded by a call to `redact_pii` in the same function. Any callsite passing raw user text to the LLM is a leak.
77
-
78
- ### Step 4 — Redact PII from log output as well
79
-
80
- **What to do.** Every log entry that contains user input or LLM output must use the redacted text, not raw. Hash the raw input with SHA-256 for correlation (`input_hash`) but never log the plaintext.
81
-
82
- **Why this matters.** Redacting the model path protects the model; redacting logs protects everyone with log access from incidental exposure.
83
-
84
- **Verification checkpoint.** `grep -rn "logger\.\(info\|warning\|error\)" --include="*.py"` — every hit that includes request or model text must route through `redact_pii` or use a hashed identifier. No raw user strings in logs.
85
-
86
- ### Step 5 — Add domain-specific classes on top
87
-
88
- **What to do.** Consider whether your domain introduces additional classes of sensitive data. Add them to `PII_PATTERNS` — do not remove any of the five required ones.
89
-
90
- Common additions:
91
-
92
- | Class | When to add |
93
- |---|---|
94
- | `dob` | Any system handling identity, insurance, medical, or minors |
95
- | `account_number` | Financial or utility systems |
96
- | `medical_record` | Health systems (ICD codes, MRN formats) |
97
- | `drivers_license` | Insurance, age verification, identity |
98
- | `passport` | Travel, immigration, identity |
99
-
100
- **Verification checkpoint.** If your classify output included `handles-financial`, `handles-health`, or `handles-minors`, you have at least one domain-specific class to consider.
101
-
102
- ### Step 6 — Redact the model's output too
103
-
104
- **What to do.** The LLM may reproduce PII from its input, or hallucinate PII-shaped output. Before returning the model's output to the user or to logs, run it through `redact_pii` as well.
105
-
106
- **Why this matters.** Even with redaction on the input, the model can echo PII if you prompt it incorrectly or if the model confabulates something shaped like a phone number. Treat model output as untrusted PII-wise.
107
-
108
- **Verification checkpoint.** The response payload that leaves your handler has been through `redact_pii` on the free-text fields. Structured fields (scores, enums) do not need redaction.
109
-
110
- ### Step 7 — Confirm no PII enters the LLM via database queries on the call path
111
-
112
- **What to do.** Trace the database queries on the LLM call path — the code paths that run before a `messages.create` (or equivalent provider call). Confirm none of those queries return columns whose values are PII themselves (full name, email, full address, raw SSN, raw credit card, raw phone). If a row from such a query is interpolated into the prompt, the redactor never sees it as a literal — it sees an opaque variable that happens to contain PII.
113
-
114
- **Why this matters.** Step 1's regex dictionary catches PII in the user-supplied text. It does not catch PII pulled from the database and concatenated into the prompt downstream. A SELECT that returns a customer's name and shipping address, then formatted into the system prompt as context, ships PII to the model regardless of how perfect the redactor is on the user input.
115
-
116
- **Verification checkpoint.** For each LLM call site, walk back through every query that contributed to the prompt or message list. If any of them returned PII columns directly, either route that text through `redact_pii` before it reaches the prompt, or change the query to return only non-PII identifiers (a customer ID, not the customer's name) and resolve the PII fields at render-time outside the LLM path.
117
-
118
- ## Complete working example
119
-
120
- ```python
121
- """PII redaction for LLM input, logs, and output."""
122
-
123
- from __future__ import annotations
124
-
125
- import hashlib
126
- import json
127
- import logging
128
- import re
129
-
130
- logger = logging.getLogger("pii")
131
- audit = logging.getLogger("audit")
132
-
133
-
134
- # ─── Step 1 — five required classes (+ one domain-specific) ────────────
135
- PII_PATTERNS: dict[str, re.Pattern[str]] = {
136
- "ssn": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
137
- "email": re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b"),
138
- "phone": re.compile(r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b"),
139
- "credit_card": re.compile(r"\b(?:\d{4}[-\s]?){3}\d{4}\b"),
140
- "address": re.compile(
141
- r"\b\d{1,6}\s+(?:[A-Z][a-z]+\s+){1,3}"
142
- r"(?:St(?:reet)?|Ave(?:nue)?|Blvd|Boulevard|Rd|Road|Ln|Lane|Dr|Drive|Way|Ct|Court|Pl|Place|Sq|Square|Pkwy|Parkway|Terr|Terrace)\b"
143
- r"(?:,?\s*(?:Apt|Suite|Ste|Unit|#)\s*[\w-]+)?",
144
- re.IGNORECASE,
145
- ),
146
- # Step 5 — domain-specific add-on; not one of the required five
147
- "dob": re.compile(r"\b(?:0[1-9]|1[0-2])/(?:0[1-9]|[12]\d|3[01])/(?:19|20)\d{2}\b"),
148
- }
149
-
150
-
151
- # ─── Step 2 — redaction with non-reversible placeholders ───────────────
152
- def redact_pii(text: str) -> tuple[str, list[str]]:
153
- seen: list[str] = []
154
- out = text
155
- for pii_type, pattern in PII_PATTERNS.items():
156
- if pattern.search(out):
157
- seen.append(pii_type)
158
- out = pattern.sub(f"[{pii_type.upper()}_REDACTED]", out)
159
- return out, seen
160
-
161
-
162
- # ─── Step 3+6 — redact input before LLM and output before return ───────
163
- def call_llm_with_redaction(user_text: str, trace_id: str, invoke) -> dict:
164
- redacted_input, seen_in = redact_pii(user_text)
165
- raw_output = invoke(redacted_input) # invoke returns model text
166
- redacted_output, seen_out = redact_pii(raw_output)
167
-
168
- # Step 4 — log with hashed input + redacted text only
169
- audit.info(json.dumps({
170
- "trace_id": trace_id,
171
- "input_hash": hashlib.sha256(user_text.encode()).hexdigest(),
172
- "input_redacted": redacted_input[:500],
173
- "output_redacted": redacted_output[:2000],
174
- "pii_types_in_input": seen_in,
175
- "pii_types_in_output": seen_out,
176
- }))
177
-
178
- return {"text": redacted_output}
179
- ```
180
-
181
- ## Related patterns
182
-
183
- - `input-validation.md` — sanitization of user input prior to any LLM call (zero-width unicode, prompt-injection patterns).
184
- - `audit-logging.md` — structure of log entries; works with this pattern's `input_hash` convention.
185
-
186
- ## Related infrastructure
187
-
188
- - `aigis infra secrets` — keep API keys, database credentials, and connection strings out of source code (the procedure above assumes they live in env vars, not literals).
189
- - `aigis infra logging` — redaction patterns for the structured logger that consumes `redact_pii` output.