@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,200 @@
1
+ ---
2
+ id: fallback-patterns
3
+ title: Fallback patterns, circuit breaker, kill switch
4
+ controls:
5
+ owasp: []
6
+ nist: [MEASURE-2.6, MANAGE-2.3, MANAGE-2.4]
7
+ iso42001: [Clause-8.2]
8
+ min_risk_tier: all
9
+ system_traits: [uses-llm, is-agentic, is-high-volume]
10
+ ---
11
+
12
+ When an LLM call fails or behaves badly, the system must fail safely, recover automatically from transient failures, and allow operators to disable the AI feature during an incident without redeploying code.
13
+
14
+ ## Common incomplete implementations
15
+
16
+ These are the specific failure modes this procedure is designed to prevent. If your implementation matches one of these, keep going — do not stop after hitting the basic pattern.
17
+
18
+ 1. **Kill switch read at module load.** An env var like `AI_SYSTEM_ENABLED` assigned to a module-level constant (`KILL_SWITCH = os.getenv(...)`) or fetched via a `@lru_cache`-decorated `get_settings()` is read once at import and never again. Flipping the flag in production requires a restart — which is exactly the thing you wanted to avoid during an incident.
19
+ 2. **Circuit breaker that never closes.** Two-state (open/closed) breakers trip and stay tripped, because there is no HALF_OPEN probe state. Traffic is stuck on fallback until someone manually resets.
20
+ 3. **Circuit breaker that wraps only one LLM callsite.** If your code calls the LLM from multiple places, every callsite must route through the same breaker or the breaker gives a false sense of safety.
21
+ 4. **Fallback returns an error instead of a defined safe response.** Raising an exception on LLM failure propagates a 500 to the user. The fallback should return a deterministic safe payload (e.g., `recommendation=standard, confidence=0`).
22
+
23
+ ## Implementation procedure
24
+
25
+ Work through these steps in order. Do not skip the verification checkpoints — they catch the specific gaps that appear across independent implementations of this pattern.
26
+
27
+ ### Step 1 — Define a default safe response
28
+
29
+ **What to do.** Write a `default_safe_response()` function that returns a neutral payload: conservative routing (e.g., `"standard"`), `confidence=0.0`, a disclaimer string. Same shape as a successful LLM response.
30
+
31
+ **Why this matters.** Without a defined fallback, an LLM failure becomes an application error. The safe response is what lets every later step actually return something.
32
+
33
+ **Verification checkpoint.** The safe response is callable with no arguments and returns the same keys a successful call would. See the complete example at the end for the shape.
34
+
35
+ ### Step 2 — Implement a circuit breaker with three states
36
+
37
+ **What to do.** Write a `CircuitBreaker` class with explicit states: `"closed"`, `"open"`, `"half-open"`. Configurable `failure_threshold` and `reset_timeout`. On threshold → OPEN. After reset timeout → HALF_OPEN probe. On probe success → CLOSED. On probe failure → back to OPEN.
38
+
39
+ **Why this matters.** Two-state breakers (open/closed only) need manual intervention to recover. Three-state breakers recover themselves.
40
+
41
+ **Verification checkpoint.** Grep your code for the three state strings. If you only find `"closed"` and `"open"`, you built a two-state breaker — iterate until `"half-open"` is implemented.
42
+
43
+ ### Step 3 — Route every LLM callsite through the breaker
44
+
45
+ **What to do.** Find every place in your codebase where you invoke the LLM client (e.g., `client.messages.create`, `openai.chat.completions.create`). Each must go through the breaker via a single helper (`call_llm_safely(func)`).
46
+
47
+ **Why this matters.** A breaker that only protects one callsite leaves the others exposed. When the provider has an outage, unprotected paths will still hammer it.
48
+
49
+ **Verification checkpoint.** `grep -rn "messages.create\|chat.completions.create"` in your source. For every hit, confirm it is wrapped by the breaker helper. Bare calls bypass the breaker — fix before continuing.
50
+
51
+ ### Step 4 — Kill switch read per-request ⚠ CRITICAL
52
+
53
+ **What to do.** Implement a toggle that disables the AI feature without redeploying. The check must happen **inside the request handler**, reading the env var (or config-service value) at request time — not at module load.
54
+
55
+ **Why this matters.** Every baseline run of this pattern built a toggle that satisfied the literal checklist wording ("there is an env variable") but was read only at process startup. During an actual incident you cannot flip the flag without a rolling restart — which defeats the purpose.
56
+
57
+ ```python
58
+ # CORRECT — read inside the handler, every request
59
+ def ai_system_enabled() -> bool:
60
+ return os.getenv("AI_SYSTEM_ENABLED", "true").lower() == "true"
61
+
62
+ # WRONG — all three of these are restart-latched
63
+ KILL_SWITCH = os.getenv("KILL_SWITCH", "0") == "1" # module-level constant
64
+ @lru_cache
65
+ def get_settings(): return Settings() # cached forever
66
+ settings = Settings() # module-level instance
67
+ ```
68
+
69
+ **Verification checkpoint.** Run these greps. If any match controls your kill switch, it's restart-latched — fix before continuing:
70
+
71
+ - `grep -rn "@lru_cache" --include="*.py"` on any settings-returning function
72
+ - `grep -rn "^KILL_SWITCH\|^AI_SYSTEM_ENABLED\|^AI_ENABLED" --include="*.py"` at module scope
73
+ - `grep -rn "settings = Settings()" --include="*.py"` imported by a handler
74
+
75
+ This is the critical gap.
76
+
77
+ ### Step 5 — Confirm the toggle works without restart
78
+
79
+ **What to do.** Start the service. Send a request and see the AI feature respond. Flip the env var (`AI_SYSTEM_ENABLED=false`) in the running process's environment — or if you cannot mutate env vars post-start, point the service at a config file or feature-flag service whose value you can change. Send another request and confirm it returns the fallback.
80
+
81
+ **Why this matters.** This is the only test that proves Step 4 actually worked. An agent or reviewer grepping for `ai_system_enabled` will see the check exists; only a runtime flip tells you whether the check is live.
82
+
83
+ **Verification checkpoint.** Document the result of this test in a comment or test file. If you could not make the toggle take effect without a restart, Step 4 is not done yet — iterate.
84
+
85
+ ### Step 6 — Wrap every LLM call in exception handling
86
+
87
+ **What to do.** Every LLM call path should be surrounded by a `try/except`. On any exception the fallback returns the safe response and the incident is logged with context. Unhandled exceptions must never propagate to the HTTP response.
88
+
89
+ **Why this matters.** Defense in depth: the breaker catches repeated failures, but a single unexpected failure should also not crash the request.
90
+
91
+ **Verification checkpoint.** Every LLM callsite from Step 3 is inside a `try/except`. No bare `raise` inside the handler body that would escape to the client without a fallback.
92
+
93
+ ## Complete working example
94
+
95
+ ```python
96
+ """Fallback patterns: circuit breaker, kill switch, safe default, exception guard."""
97
+
98
+ from __future__ import annotations
99
+
100
+ import logging
101
+ import os
102
+ import time
103
+ from typing import Any, Callable, TypeVar
104
+
105
+ from fastapi import FastAPI
106
+ from pydantic import BaseModel
107
+
108
+ logger = logging.getLogger("fallback")
109
+ app = FastAPI()
110
+ T = TypeVar("T")
111
+
112
+
113
+ # ─── Step 1 — default safe response ────────────────────────────────────
114
+ def default_safe_response() -> dict[str, Any]:
115
+ return {
116
+ "severity_score": 5,
117
+ "recommendation": "standard",
118
+ "confidence_score": 0.0,
119
+ "disclaimer": "Automated assessment unavailable; human review required.",
120
+ "fallback": True,
121
+ }
122
+
123
+
124
+ # ─── Step 2 — three-state circuit breaker ──────────────────────────────
125
+ class CircuitBreaker:
126
+ def __init__(self, failure_threshold: int = 5, reset_timeout: int = 60):
127
+ self.failure_threshold = failure_threshold
128
+ self.reset_timeout = reset_timeout
129
+ self.state = "closed"
130
+ self.failure_count = 0
131
+ self.last_failure_time: float | None = None
132
+
133
+ def call(self, func: Callable[[], T]) -> T:
134
+ now = time.time()
135
+ if self.state == "open":
136
+ if self.last_failure_time and now - self.last_failure_time > self.reset_timeout:
137
+ self.state = "half-open"
138
+ else:
139
+ logger.warning("circuit_breaker_open")
140
+ return default_safe_response() # type: ignore[return-value]
141
+
142
+ try:
143
+ result = func()
144
+ if self.state == "half-open":
145
+ self.state = "closed"
146
+ self.failure_count = 0
147
+ return result
148
+ except Exception:
149
+ self.failure_count += 1
150
+ self.last_failure_time = now
151
+ if self.failure_count >= self.failure_threshold:
152
+ self.state = "open"
153
+ logger.error("circuit_breaker_tripped failures=%s", self.failure_count)
154
+ return default_safe_response() # type: ignore[return-value]
155
+
156
+
157
+ _llm_breaker = CircuitBreaker(failure_threshold=5, reset_timeout=60)
158
+
159
+
160
+ # ─── Step 3 — single wrapper every LLM callsite uses ───────────────────
161
+ def call_llm_safely(func: Callable[[], T]) -> T:
162
+ return _llm_breaker.call(func)
163
+
164
+
165
+ # ─── Step 4 — kill switch read per-request ⚠ CRITICAL ──────────────────
166
+ def ai_system_enabled() -> bool:
167
+ """Read the toggle fresh each call. No @lru_cache. No module-level cache."""
168
+ return os.getenv("AI_SYSTEM_ENABLED", "true").lower() == "true"
169
+
170
+
171
+ # ─── Step 6 — exception guard on the handler ───────────────────────────
172
+ class AssessRequest(BaseModel):
173
+ claim_description: str
174
+
175
+
176
+ @app.post("/api/assess-claim")
177
+ async def assess_claim(body: AssessRequest) -> dict[str, Any]:
178
+ if not ai_system_enabled(): # Step 4: per-request check
179
+ return default_safe_response()
180
+
181
+ try:
182
+ result = call_llm_safely( # Step 3: breaker wrapper
183
+ lambda: _invoke_llm(body.claim_description)
184
+ )
185
+ return result
186
+ except Exception as exc: # Step 6: exception guard
187
+ logger.exception("llm_call_failed", extra={"error": str(exc)})
188
+ return default_safe_response()
189
+
190
+
191
+ def _invoke_llm(text: str) -> dict[str, Any]:
192
+ # Replace with your actual client call. Must raise on any failure
193
+ # so the breaker can count it.
194
+ ...
195
+ ```
196
+
197
+ ## Related patterns
198
+
199
+ - `human-oversight.md` — low-confidence decisions routed to review.
200
+ - `monitoring.md` — breaker trips and fallback rates as operational metrics.
@@ -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.