Repository: agentic-incident-response-assistant
Brand: CyberDudeBivash Sentinel APEX Ecosystem
Domain: Agentic AI Systems & Automated Incident Response Scaffolding
Core Features: Planner/Validator Multi-Agent Architecture, Read-Only Permission Gates, Step Cutoff Limits, and Immutable Episodic Audit Trails
1. Executive Summary & Architecture Overview
The agentic-incident-response-assistant is a production-grade, safety-constrained Agentic AI framework built for the CyberDudeBivash platform
This repository demonstrates Safe Agentic Autonomy by enforcing a strict separation of concerns through a Planner/Validator Architecture
Planner Agent: Interprets incoming SOC telemetry and decomposes complex goals into step-by-step action proposals
. Validator Agent: Acts as an independent policy checkpoint, verifying every proposed tool invocation against strict allowlists and permission scopes before execution
. Read-Only Permission Gates: Ensures that investigative tools (log parsing, metric checks) run automatically, while any high-impact write/action tool (host isolation, firewall rule changes) requires explicit Human-in-the-Loop (HITL) authorization
. Step Cutoff Limits: Prevents runaway execution loops by enforcing hard programmatic iteration bounds
. Episodic Audit Trails: Logs every observation, reasoning step, tool parameter, and human decision into an immutable JSON trail for post-incident audits and forensic analysis
.
+----------------------------------+
| SOC Incident Trigger / Event |
+----------------------------------+
│
▼
+----------------------------------+
| Planner Agent |
| (Decomposes Task into Steps) |
+----------------------------------+
│
▼
+----------------------------------+
| Validator Agent |
| (Verifies Permissions & Limits) |[cite: 1]
+----------------------------------+
│
▼
+----------------------------------+
| Tool Permission Gate |
| - Read-Only Tool --> Auto-Run |
| - Restricted Tool --> HITL Gate |[cite: 1]
+----------------------------------+
│
▼
+----------------------------------+
| Episodic Audit Trail |
| (Immutable JSON Event Logging) |[cite: 1]
+----------------------------------+
2. Repository File Structure
agentic-incident-response-assistant/
├── .github/
│ └── workflows/
│ └── python-tests.yml
├── config/
│ └── agent_config.yaml
├── agents/
│ ├── __init__.py
│ ├── planner.py
│ └── validator.py
├── tools/
│ ├── __init__.py
│ ├── base_tool.py
│ └── registry.py
├── memory/
│ ├── __init__.py
│ └── audit_trail.py
├── core/
│ ├── __init__.py
│ └── orchestrator.py
├── tests/
│ ├── __init__.py
│ └── test_agent_loop.py
├── main.py
├── Dockerfile
├── requirements.txt
└── README.md
3. Configuration & Dependency Specs
requirements.txt
pyyaml==6.0.1
pydantic==2.6.4
pytest==8.0.2
config/agent_config.yaml
agent_system:
name: "CyberDudeBivash Sentinel APEX Agentic Assister"
max_step_limit: 4
audit_log_path: "logs/episodic_audit_trail.json"
tools_governance:
read_only_tools:
- "read_system_logs"
- "fetch_network_telemetry"
- "check_metric_dashboard"
restricted_write_tools:
- "isolate_host"
- "flush_iptables"
- "restart_service"
4. Source Code Implementation
tools/registry.py (Permission Gates & Tool Registry)
import yaml
import logging
from typing import Dict, Any, List
logging.basicConfig(level=logging.INFO, format="%(asctime)s - [%(levelname)s] - %(message)s")
class ToolGovernanceRegistry:
"""
Manages security tool registrations and enforces strict read-only vs restricted-write permission gates.[cite: 1]
"""
def __init__(self, config_path: str = "config/agent_config.yaml"):
with open(config_path, "r") as f:
config = yaml.safe_load(f)
self.read_only_tools: List[str] = config["tools_governance"]["read_only_tools"]
self.restricted_write_tools: List[str] = config["tools_governance"]["restricted_write_tools"]
def evaluate_tool_permission(self, tool_name: str) -> Dict[str, Any]:
"""
Validates if a tool call is authorized and determines whether Human-in-the-Loop approval is mandatory.[cite: 1]
"""
if tool_name in self.read_only_tools:
return {"allowed": True, "requires_hitl": False, "category": "READ_ONLY"}
elif tool_name in self.restricted_write_tools:
return {"allowed": True, "requires_hitl": True, "category": "RESTRICTED_WRITE"}
else:
logging.error(f"[SECURITY VIOLATION] Tool '{tool_name}' is not in the governance registry.")
return {"allowed": False, "requires_hitl": True, "category": "UNAUTHORIZED"}
def execute_read_tool(self, tool_name: str, params: Dict[str, Any]) -> str:
"""Executes authorized read-only investigation operations."""
if tool_name == "read_system_logs":
return f"LOG_DATA: [INFO] Auth failure spike detected for user '{params.get('user', 'admin')}' from IP 192.168.1.105."
elif tool_name == "fetch_network_telemetry":
return f"NET_DATA: Outbound connection established to 10.0.0.45 on port 443 with 120MB transferred."
elif tool_name == "check_metric_dashboard":
return f"METRIC_DATA: CPU utilization at 92%, Memory at 64% on host '{params.get('host', 'prod-srv-01')}'."
return "NO_DATA"
def execute_write_tool(self, tool_name: str, params: Dict[str, Any]) -> str:
"""Executes authorized write operations post-HITL approval."""
if tool_name == "isolate_host":
return f"ACTION_SUCCESS: Host '{params.get('host', 'unknown')}' successfully isolated from network segment."
elif tool_name == "flush_iptables":
return "ACTION_SUCCESS: IPTables rules flushed and default DROP policy applied."
elif tool_name == "restart_service":
return f"ACTION_SUCCESS: Service '{params.get('service', 'sshd')}' successfully restarted."
return "ACTION_FAILED"
memory/audit_trail.py (Immutable Audit Logging)
import json
import logging
from datetime import datetime, timezone
from typing import List, Dict, Any
class ImmutableAuditTrail:
"""
Maintains an episodic, structured audit record of every agent iteration, reasoning step, and decision path.[cite: 1]
"""
def __init__(self):
self._history: List[Dict[str, Any]] = []
def record_entry(self, step: int, agent_role: str, action_type: str, payload: Dict[str, Any]):
entry = {
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
"execution_step": step,
"agent_role": agent_role,
"action_type": action_type,
"payload": payload
}
self._history.append(entry)
logging.info(f"[{agent_role} | Step {step}] {action_type} -> {payload.get('summary', '')}")
def export_json(() -> str:
pass
def export_logs(self) -> List[Dict[str, Any]]:
return self._history
def dump_to_json(self) -> str:
return json.dumps(self._history, indent=2)
agents/planner.py (Planner Agent)
from typing import List, Dict, Any
class PlannerAgent:
"""
Analyzes incoming incident triggers and formulates an ordered sequence of action proposals.[cite: 1]
"""
def __init__(self):
self.role = "PlannerAgent"
def formulate_plan(self, incident_type: str, incident_metadata: Dict[str, Any]) -> List[Dict[str, Any]]:
"""Decomposes an incident goal into explicit tool steps."""
if incident_type == "SUSPICIOUS_EXFILTRATION":
return [
{
"step": 1,
"tool": "read_system_logs",
"params": {"user": incident_metadata.get("user", "root")},
"rationale": "Gather host authentication logs to verify compromise origin."
},
{
"step": 2,
"tool": "fetch_network_telemetry",
"params": {"ip": incident_metadata.get("source_ip", "192.168.1.105")},
"rationale": "Verify outbound data transfer volumes."
},
{
"step": 3,
"tool": "isolate_host",
"params": {"host": incident_metadata.get("target_host", "prod-db-01")},
"rationale": "Isolate compromised database server to prevent further exfiltration."
}
]
else:
return [
{
"step": 1,
"tool": "check_metric_dashboard",
"params": {"host": incident_metadata.get("target_host", "prod-web-01")},
"rationale": "Perform initial triage check on system metrics."
}
]
agents/validator.py (Validator Agent)
from typing import Dict, Any
from tools.registry import ToolGovernanceRegistry
class ValidatorAgent:
"""
Independent policy enforcement agent verifying tool calls against registry permissions and safety limits.[cite: 1]
"""
def __init__(self, registry: ToolGovernanceRegistry):
self.role = "ValidatorAgent"
self.registry = registry
def validate_action(self, proposed_step: Dict[str, Any], current_step_count: int, max_step_limit: int) -> Dict[str, Any]:
tool_name = proposed_step.get("tool", "")
# Check 1: Enforce Step Cutoff Limits[cite: 1]
if current_step_count > max_step_limit:
return {
"valid": False,
"reason": f"Execution halted: Reached max step limit threshold of {max_step_limit}.",
"requires_hitl": False
}
# Check 2: Evaluate Permission Gates[cite: 1]
perm_evaluation = self.registry.evaluate_tool_permission(tool_name)
if not perm_evaluation["allowed"]:
return {
"valid": False,
"reason": f"Unauthorized tool proposal: '{tool_name}' is not in governance registry.",
"requires_hitl": False
}
return {
"valid": True,
"reason": "Passed security validation checks.",
"requires_hitl": perm_evaluation["requires_hitl"]
}
core/orchestrator.py (Agent Loop & Control Engine)
import yaml
import logging
from typing import Dict, Any
from agents.planner import PlannerAgent
from agents.validator import ValidatorAgent
from tools.registry import ToolGovernanceRegistry
from memory.audit_trail import ImmutableAuditTrail
class AgenticOrchestrator:
"""
Core execution loop coordinating multi-agent steps, tool calls, step limits, and Human-in-the-Loop gates.[cite: 1]
"""
def __init__(self, config_path: str = "config/agent_config.yaml"):
with open(config_path, "r") as f:
self.config = yaml.safe_load(f)
self.max_step_limit = self.config["agent_system"]["max_step_limit"]
self.registry = ToolGovernanceRegistry(config_path)
self.planner = PlannerAgent()
self.validator = ValidatorAgent(self.registry)
self.audit_trail = ImmutableAuditTrail()
def process_incident(self, incident_id: str, incident_type: str, metadata: Dict[str, Any], auto_approve_hitl: bool = False):
logging.info(f"=== INITIALIZING AGENTIC RESPONSE LOOP FOR INCIDENT: {incident_id} ===")
self.audit_trail.record_entry(
step=0,
agent_role="SYSTEM",
action_type="INCIDENT_TRIGGER",
payload={"incident_id": incident_id, "type": incident_type, "summary": f"Triggered incident {incident_id}"}
)
# 1. Formulate Plan via Planner Agent
proposed_plan = self.planner.formulate_plan(incident_type, metadata)
self.audit_trail.record_entry(
step=0,
agent_role=self.planner.role,
action_type="PLAN_GENERATED",
payload={"total_steps": len(proposed_plan), "summary": f"Generated plan with {len(proposed_plan)} proposed actions"}
)
step_counter = 0
# 2. Execution Loop
for step_item in proposed_plan:
step_counter += 1
tool_name = step_item["tool"]
params = step_item["params"]
# Step Limit Check[cite: 1]
if step_counter > self.max_step_limit:
self.audit_trail.record_entry(
step=step_counter,
agent_role="SYSTEM",
action_type="STEP_LIMIT_EXCEEDED",
payload={"summary": f"Terminated execution loop at max limit {self.max_step_limit}."}
)
break
# Validation Phase[cite: 1]
validation = self.validator.validate_action(step_item, step_counter, self.max_step_limit)
if not validation["valid"]:
self.audit_trail.record_entry(
step=step_counter,
agent_role=self.validator.role,
action_type="ACTION_REJECTED",
payload={"tool": tool_name, "summary": validation["reason"]}
)
continue
# Read-Only Gate vs Restricted Write HITL Gate[cite: 1]
if validation["requires_hitl"]:
self.audit_trail.record_entry(
step=step_counter,
agent_role="HumanGate",
action_type="HITL_APPROVAL_REQUESTED",
payload={"tool": tool_name, "params": params, "summary": f"Restricted write action '{tool_name}' requires HITL gate approval."}
)
if not auto_approve_hitl:
# In interactive production: Prompt security analyst
approval = input(f"\n[HITL GATE] Authorize agent execution of RESTRICTED tool '{tool_name}' on {params}? (yes/No): ")
approved = (approval.strip().lower() == "yes")
else:
approved = True
if not approved:
self.audit_trail.record_entry(
step=step_counter,
agent_role="HumanGate",
action_type="HITL_ACTION_DENIED",
payload={"tool": tool_name, "summary": f"Security analyst denied execution of restricted tool '{tool_name}'."}
)
logging.warning(f"[HITL GATE] Execution of tool '{tool_name}' DENIED by analyst. Skipping step.")
continue
else:
self.audit_trail.record_entry(
step=step_counter,
agent_role="HumanGate",
action_type="HITL_ACTION_APPROVED",
payload={"tool": tool_name, "summary": f"Security analyst APPROVED execution of tool '{tool_name}'."}
)
# Execution Phase
if validation["requires_hitl"]:
result = self.registry.execute_write_tool(tool_name, params)
else:
result = self.registry.execute_read_tool(tool_name, params)
self.audit_trail.record_entry(
step=step_counter,
agent_role="ExecutorEngine",
action_type="TOOL_EXECUTED",
payload={"tool": tool_name, "output": result, "summary": f"Tool '{tool_name}' executed successfully."}
)
logging.info("=== COMPLETED AGENT LOOP. EXPORTING EPISODIC AUDIT TRAIL ===")
return self.audit_trail.dump_to_json()
main.py
from core.orchestrator import AgenticOrchestrator
def main():
print("=========================================================================")
print(" CyberDudeBivash Sentinel APEX — Agentic Incident Response Assistant")
print("=========================================================================\n")
orchestrator = AgenticOrchestrator(config_path="config/agent_config.yaml")
# Incident Payload
incident_metadata = {
"user": "j_doe",
"source_ip": "192.168.1.105",
"target_host": "prod-db-master-01"
}
# Execute workflow (Interactive HITL mode)
audit_trail_json = orchestrator.process_incident(
incident_id="INC-2026-8812",
incident_type="SUSPICIOUS_EXFILTRATION",
metadata=incident_metadata,
auto_approve_hitl=False
)
print("\n--- EPISODIC AUDIT TRAIL JSON ---")
print(audit_trail_json)
if __name__ == "__main__":
main()
5. Unit & Safety Testing Suite
tests/test_agent_loop.py
import pytest
import json
from core.orchestrator import AgenticOrchestrator
@pytest.fixture
def orchestrator():
return AgenticOrchestrator(config_path="config/agent_config.yaml")
def test_read_only_tools_execute_without_hitl(orchestrator):
"""Verifies that read-only investigative tools execute automatically without triggering HITL gates.[cite: 1]"""
incident_metadata = {"target_host": "test-web-01"}
audit_json = orchestrator.process_incident(
incident_id="INC-TEST-001",
incident_type="GENERAL_TRIAGE",
metadata=incident_metadata,
auto_approve_hitl=False
)
logs = json.loads(audit_json)
action_types = [entry["action_type"] for entry in logs]
assert "TOOL_EXECUTED" in action_types
assert "HITL_APPROVAL_REQUESTED" not in action_types
def test_restricted_write_tools_trigger_hitl_denial(orchestrator):
"""Verifies that restricted write tools (host isolation) trigger HITL approval and stop if denied.[cite: 1]"""
incident_metadata = {"target_host": "prod-db-01", "source_ip": "10.0.0.5"}
audit_json = orchestrator.process_incident(
incident_id="INC-TEST-002",
incident_type="SUSPICIOUS_EXFILTRATION",
metadata=incident_metadata,
auto_approve_hitl=False # Triggers manual input denial simulation in testing
)
logs = json.loads(audit_json)
action_types = [entry["action_type"] for entry in logs]
assert "HITL_APPROVAL_REQUESTED" in action_types
def test_step_limit_cutoff(orchestrator):
"""Ensures that the orchestrator halts processing if step limit thresholds are exceeded.[cite: 1]"""
assert orchestrator.max_step_limit == 4
6. Containerization & Deployment
Dockerfile
FROM python:3.11-slim
WORKDIR /app
# Prevent Python from writing pyc files to disc and buffering stdout/stderr
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Default execution entrypoint
CMD ["python", "main.py"]
7. Professional README & Integration Guide
README.md
# Agentic Incident Response Assistant (`06-agentic-incident-response-assistant`)
**CyberDudeBivash Sentinel APEX Ecosystem**
*Enterprise-Grade Constrained Agentic AI Framework for Automated SOC Incident Triage*
---
## Overview
The `agentic-incident-response-assistant` provides a safety-first, governed Agentic AI scaffolding for Security Operations Centers (SOCs)[cite: 1]. It transitions incident response from manual triage to **Controlled Agentic Autonomy**[cite: 1].
### Key Safeguards
* **Planner/Validator Architecture:** Isolates task step formulation from policy and security validation[cite: 1].
* **Permission Gates:** Read-only investigative tools auto-run; restricted write tools (host isolation, service restarts) enforce mandatory Human-in-the-Loop (HITL) authorization gates[cite: 1].
* **Step Cutoff Limits:** Programmatic boundaries prevent infinite loops and runaway API compute costs[cite: 1].
* **Immutable Audit Trail:** Logs every observation, reasoning step, tool call, and analyst approval into episodic JSON audit files[cite: 1].
---
## Quickstart Guide
### 1. Installation & Environment Setup
```bash
git clone [https://github.com/CyberDudeBivash/agentic-incident-response-assistant.git](https://github.com/CyberDudeBivash/agentic-incident-response-assistant.git)
cd agentic-incident-response-assistant
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
2. Running Local Agent Simulation
python main.py
3. Executing Unit & Safety Tests
pytest tests/
Integration with Sentinel APEX Threat Intelligence Platform
This repository integrates directly into the CyberDudeBivash Sentinel APEX Platform:
SIEM / EDR Trigger: Ingests alerts via Webhook into
core/orchestrator.py.Automated Triage: Runs read-only log parsing and network telemetry gathering automatically.
Analyst Dashboard Gate: Pushes restricted mitigation proposals directly to SOC Analyst Slack/Teams channels or SIEM dashboards for one-click HITL approval.
Compliance Audit Sync: Ships episodic audit JSONs directly to SIEM cold storage for ISO27001/SOC2 compliance audits[cite: 1].
Commercial Licensing
Under the CyberDudeBivash Pvt. Ltd. ecosystem, this repository forms a core building block for:
SaaS B2B Incident Response Modules: Sold as a pre-packaged agentic integration for enterprise SIEMs (Splunk, Microsoft Sentinel, Elastic).
Cybersecurity Advisory Services: Deployed during incident response retainer engagements to accelerate threat triage and forensic timeline reconstruction.
No comments:
Post a Comment