Amit Arora f496048c13
feat(02-use-cases): integrate AgentCore Memory with SRE Agent for intelligent context-aware incident response (#210)
* feat: integrate long-term memory system into SRE agent

- Add AgentCore Memory integration with three memory strategies:
  * User preferences (escalation, notification, workflow preferences)
  * Infrastructure knowledge (dependencies, patterns, baselines)
  * Investigation summaries (timeline, actions, findings)

- Implement memory tools for save/retrieve operations
- Add automatic memory capture through hooks and pattern recognition
- Extend agent state to support memory context
- Integrate memory-aware planning in supervisor agent
- Add comprehensive test coverage for memory functionality
- Create detailed documentation with usage examples

This transforms the SRE agent from stateless to learning assistant
that becomes more valuable over time by remembering user preferences,
infrastructure patterns, and investigation outcomes.

Addresses issue #164

* feat: environment variable config, agent routing fixes, and project organization

- Move USER_ID/SESSION_ID from metadata parsing to environment variables
- Add .memory_id to .gitignore for local memory state
- Update .gitignore to use .scratchpad/ folder instead of .scratchpad.md
- Fix agent routing issues with supervisor prompt and graph node naming
- Add conversation memory tracking for all agents and supervisor
- Improve agent metadata system with centralized constants
- Add comprehensive logging and debugging for agent tool access
- Update deployment script to pass user_id/session_id in payload
- Create .scratchpad/ folder structure for better project organization

* feat: enhance SRE agent with automatic report archiving and error fixes

- Add automatic archiving system for reports by date
- Include user_id in report filenames for better organization
- Fix Pydantic validation error with string-to-list conversion for investigation steps
- Add content length truncation for memory storage to prevent validation errors
- Remove status line from report output for cleaner formatting
- Implement date-based folder organization (YYYY-MM-DD format)
- Add memory content length limits configuration in constants

Key improvements:
- Reports now auto-archive old files when saving new ones
- User-specific filenames: query_user_id_UserName_YYYYMMDD_HHMMSS.md
- Robust error handling for memory content length limits
- Backward compatibility with existing filename formats

* feat: fix memory retrieval system for cross-session searches and user personalization

Key fixes and improvements:
- Fix case preservation in actor_id sanitization (Carol remains Carol, not carol)
- Enable cross-session memory searches for infrastructure and investigation memories
- Add XML parsing support for investigation summaries stored in XML format
- Enhance user preference integration throughout the system
- Add comprehensive debug logging for memory retrieval processes
- Update prompts to support user-specific communication styles and preferences

Memory system now properly:
- Preserves user case in memory namespaces (/sre/users/Carol vs /sre/users/carol)
- Searches across all sessions for planning context vs session-specific for current state
- Parses both JSON and XML formatted investigation memories
- Adapts investigation approach based on user preferences and historical patterns
- Provides context-aware planning using infrastructure knowledge and past investigations

* feat: enhance SRE agent with user-specific memory isolation and anti-hallucination measures

Memory System Improvements:
- Fix memory isolation to retrieve only user-specific memories (Alice doesn't see Carol's data)
- Implement proper namespace handling for cross-session vs session-specific searches
- Add detailed logging for memory retrieval debugging and verification
- Remove verbose success logs, keep only error logs for cleaner output

Anti-Hallucination Enhancements:
- Add tool output validation requirements to agent prompts
- Implement timestamp fabrication prevention (use 2024-* format from backend)
- Require tool attribution for all metrics and findings in reports
- Add backend data alignment patterns for consistent data references
- Update supervisor aggregation prompts to flag unverified claims

Code Organization:
- Extract hardcoded prompts from supervisor.py to external prompt files
- Add missing session_id parameters to SaveInfrastructureTool and SaveInvestigationTool
- Improve memory client namespace documentation and cross-session search logic
- Reduce debug logging noise while maintaining error tracking

Verification Complete:
- Memory isolation working correctly (only user-specific data retrieval)
- Cross-session memory usage properly configured for planning and investigations
- Memory integration confirmed in report generation pipeline
- Anti-hallucination measures prevent fabricated metrics and timestamps

* feat: organize utility scripts in dedicated scripts folder

Script Organization:
- Move manage_memories.py to scripts/ folder with updated import paths
- Move configure_gateway.sh to scripts/ folder with corrected PROJECT_ROOT path
- Copy user_config.yaml to scripts/ folder for self-contained script usage

Path Fixes:
- Update manage_memories.py to import sre_agent module from correct relative path
- Fix .memory_id file path resolution for new script location
- Update configure_gateway.sh PROJECT_ROOT to point to correct parent directory
- Add fallback logic to find user_config.yaml in scripts/ or project root

Script Improvements:
- Update help text and examples to use 'uv run python scripts/' syntax
- Make manage_memories.py executable with proper permissions
- Maintain backward compatibility for custom config file paths
- Self-contained scripts folder with all required dependencies

Verification:
- All scripts work correctly from new location
- Memory management functions operate properly
- Gateway configuration handles paths correctly
- User preferences loading works from scripts directory

* docs: update SSL certificate paths to use /opt/ssl standard location

- Update README.md to reference /opt/ssl for SSL certificate paths
- Update docs/demo-environment.md to use /opt/ssl paths
- Clean up scripts/configure_gateway.sh SSL fallback paths
- Remove duplicate and outdated SSL path references
- Establish /opt/ssl as the standard SSL certificate location

This ensures consistent SSL certificate management across all
documentation and scripts, supporting the established /opt/ssl
directory with proper ubuntu:ubuntu ownership.

* feat: enhance memory system with infrastructure parsing fix and user personalization analysis

Infrastructure Memory Parsing Improvements:
- Fix infrastructure memory parsing to handle both JSON and plain text formats
- Convert plain text memories to structured InfrastructureKnowledge objects
- Change warning logs to debug level for normal text-to-structure conversion
- Ensure all infrastructure memories are now retrievable and usable

User Personalization Documentation:
- Add comprehensive memory system analysis comparing Alice vs Carol reports
- Create docs/examples/ folder with real investigation reports demonstrating personalization
- Document side-by-side communication differences based on user preferences
- Show how same technical incident produces different reports for different user roles

Example Reports Added:
- Alice's technical detailed investigation report (technical role preferences)
- Carol's business-focused executive summary report (executive role preferences)
- Memory system analysis with extensive side-by-side comparisons

This demonstrates the memory system's ability to:
- Maintain technical accuracy while adapting presentation style
- Apply user-specific escalation procedures and communication channels
- Build institutional knowledge about recurring infrastructure patterns
- Personalize identical technical incidents for different organizational roles

* feat: enhance memory system with automatic pattern extraction and improved logging

## Memory System Enhancements
- **Individual agent memory integration**: Every agent response now triggers automatic memory pattern extraction through on_agent_response() hooks
- **Enhanced conversation logging**: Added detailed message breakdown showing USER/ASSISTANT/TOOL message counts and tool names called
- **Fixed infrastructure extraction**: Resolved hardcoded agent name issues by using SREConstants for agent identification
- **Comprehensive memory persistence**: All agent responses and tool executions stored as conversation memory with proper session tracking

## Tool Architecture Clarification
- **Centralized memory access**: Confirmed only supervisor agent has direct access to memory tools (retrieve_memory, save_*)
- **Individual agent focus**: Individual agents have NO memory tools, only domain-specific tools (5 tools each for metrics, logs, k8s, runbooks)
- **Automatic pattern recognition**: Memory capture happens automatically through hooks, not manual tool calls by individual agents

## Documentation Updates
- **Updated memory-system.md**: Comprehensive design documentation reflecting current implementation
- **Added example analyses**: Created flight-booking-analysis.md and api-response-time-analysis.md in docs/examples/
- **Enhanced README.md**: Added memory system overview and personalized investigation examples
- **Updated .gitignore**: Now ignores entire reports/ folder instead of just .md files

## Implementation Improvements
- **Event ID tracking**: All memory operations generate and log event IDs for verification
- **Pattern extraction confirmation**: Logs confirm pattern extraction working for all agent types
- **Memory save verification**: Comprehensive logging shows successful saves across all memory types
- **Script enhancements**: manage_memories.py now handles duplicate removal and improved user management

* docs: enhance memory system documentation with planning agent memory usage examples

- Add real agent.log snippets showing planning agent retrieving and using memory context
- Document XML-structured prompts for improved Claude model interaction
- Explain JSON response format enforcement and infrastructure knowledge extraction
- Add comprehensive logging and monitoring details
- Document actor ID design for proper memory namespace isolation
- Fix ASCII flow diagram alignment for better readability
- Remove temporal framing and present features as current design facts

* docs: add AWS documentation links and clean up memory system documentation

- Add hyperlink to Amazon Bedrock AgentCore Memory main documentation
- Link to Memory Getting Started Guide for the three memory strategies
- Remove Legacy Pattern Recognition section from documentation (code remains)
- Remove Error Handling and Fallbacks section to focus on core functionality
- Keep implementation details in code while streamlining public documentation

* docs: reorganize memory-system.md to eliminate redundancies

- Merged Memory Tool Architecture and Planning sections into unified section
- Consolidated all namespace/actor_id explanations in architecture section
- Combined pattern recognition and memory capture content
- Created dedicated Agent Memory Integration section with examples
- Removed ~15-20% redundant content while improving clarity
- Improved document structure for better navigation

* style: apply ruff formatting and fix code style issues

- Applied ruff auto-formatting to all Python files
- Fixed 383 style issues automatically
- Remaining issues require manual intervention:
  - 29 ruff errors (bare except, unused variables, etc.)
  - 61 mypy type errors (missing annotations, implicit Optional)
- Verified memory system functionality matches documentation
- Confirmed user personalization working correctly in reports

* docs: make benefits section more succinct in memory-system.md

- Consolidated 12 bullet points into 5 focused benefits
- Removed redundant three-category structure (Users/Teams/Operations)
- Maintained all key value propositions while improving readability
- Reduced section length by ~60% while preserving essential information

* feat: add comprehensive cleanup script with memory deletion

- Added cleanup.sh script to delete all AWS resources (gateway, runtime, memory)
- Integrated memory deletion using bedrock_agentcore MemoryClient
- Added proper error handling and graceful fallbacks
- Updated execution order: servers → gateway → memory → runtime → local files
- Added memory deletion to README.md cleanup instructions
- Includes confirmation prompts and --force option for automation

* fix: preserve .env, .venv, and reports in cleanup script

- Modified cleanup script to only remove AWS-generated configuration files
- Preserved .env files for development continuity
- Preserved .venv directories to avoid reinstalling dependencies
- Preserved reports/ directory containing investigation history
- Files removed: gateway URIs, tokens, agent ARNs, memory IDs only
- Updated documentation to clarify preserved vs removed files

* fix: use correct bedrock-agentcore-control client for gateway operations

- Changed boto3 client from 'bedrock-agentcore' to 'bedrock-agentcore-control'
- Fixes 'list_gateways' method not found error during gateway deletion
- Both gateway and runtime deletion now use the correct control plane client

* docs: add memory system initialization timing guidance

- Added note that memory system takes 10-12 minutes to be ready
- Added steps to check memory status with list command after 10 minutes
- Added instruction to run update command again once memory is ready
- Provides clear workflow for memory system setup and prevents user confusion

* docs: comprehensive documentation update and cleanup

- Remove unused root .env and .env.example files (not referenced by any code)
- Update configuration.md with comprehensive config file documentation
- Add configuration overview table with setup instructions and auto-generation info
- Consolidate specialized-agents.md content into system-components.md
- Update system-components.md with complete AgentCore architecture
- Add detailed sections for AgentCore Runtime, Gateway, and Memory primitives
- Remove cli-reference.md (excessive documentation for limited use)
- Update README.md to reference configuration guide in setup section
- Clean up documentation links and organization

The documentation now provides a clear, consolidated view of the system
architecture and configuration with proper cross-references and setup guidance.

* feat: improve runtime deployment and invocation robustness

- Increase deletion wait time to 150s for agent runtime cleanup
- Add retry logic with exponential backoff for MCP rate limiting (429 errors)
- Add session_id and user_id to agent state for memory retrieval
- Filter out /ping endpoint logs to reduce noise
- Increase boto3 read timeout to 5 minutes for long-running operations
- Add clear error messages for agent name conflicts
- Update README to clarify virtual environment requirement for scripts
- Fix session ID generation to meet 33+ character requirement

These changes improve reliability when deploying and invoking agents,
especially under heavy load or with complex queries that take time.

* chore: remove accidentally committed reports folder

Removed 130+ markdown report files from the reports/ directory that were
accidentally committed. The .gitignore already includes reports/ to prevent
future commits of these generated files.
2025-08-06 17:49:56 -04:00

369 lines
11 KiB
Bash
Executable File
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# Cleanup Script for SRE Agent
# Deletes AgentCore Gateway, Gateway Targets, and Agent Runtime
set -e
# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
# Default values - can be overridden with environment variables or arguments
DEFAULT_GATEWAY_NAME="sre-agent-gateway"
DEFAULT_RUNTIME_NAME="sre-agent"
DEFAULT_REGION="us-east-1"
# Parse command line arguments
GATEWAY_NAME="${GATEWAY_NAME:-$DEFAULT_GATEWAY_NAME}"
RUNTIME_NAME="${RUNTIME_NAME:-$DEFAULT_RUNTIME_NAME}"
REGION="${REGION:-$DEFAULT_REGION}"
FORCE_DELETE=false
# Function to read gateway name from config.yaml
read_gateway_name_from_config() {
local config_file="$PROJECT_ROOT/gateway/config.yaml"
if [ -f "$config_file" ]; then
# Extract gateway_name from YAML, handling quoted and unquoted values
local gateway_name=$(grep "^gateway_name:" "$config_file" | cut -d':' -f2- | sed 's/^[ \t]*//' | sed 's/^"\([^"]*\)".*/\1/' | sed 's/[ \t]*#.*//')
if [ -n "$gateway_name" ]; then
echo "$gateway_name"
return 0
fi
fi
# Return empty string if not found
echo ""
return 1
}
# Function to show usage
show_usage() {
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " --gateway-name NAME Gateway name to delete (default: auto-detect from gateway/config.yaml)"
echo " --runtime-name NAME Runtime name to delete (default: $DEFAULT_RUNTIME_NAME)"
echo " --region REGION AWS region (default: $DEFAULT_REGION)"
echo " --force Skip confirmation prompts"
echo " --help, -h Show this help message"
echo ""
echo "Environment Variables:"
echo " GATEWAY_NAME Override default gateway name"
echo " RUNTIME_NAME Override default runtime name"
echo " REGION Override default AWS region"
echo ""
echo "Description:"
echo " This script performs complete cleanup of SRE Agent AWS resources:"
echo " 1. Stops backend servers"
echo " 2. Deletes all gateway targets"
echo " 3. Deletes the AgentCore Gateway"
echo " 4. Deletes memory resources"
echo " 5. Deletes the AgentCore Runtime"
echo " 6. Removes generated files"
echo ""
echo "Examples:"
echo " $0 # Use defaults"
echo " $0 --gateway-name my-gateway --force # Custom gateway, no prompts"
echo " GATEWAY_NAME=test-gw $0 # Using environment variable"
}
# Function to confirm deletion
confirm_deletion() {
if [ "$FORCE_DELETE" = true ]; then
return 0
fi
echo "⚠️ WARNING: This will permanently delete the following AWS resources:"
echo " - Gateway: $GATEWAY_NAME"
echo " - Runtime: $RUNTIME_NAME"
echo " - Memory resources (if they exist)"
echo " - Region: $REGION"
echo ""
echo " This action cannot be undone!"
echo ""
read -p "Are you sure you want to continue? (type 'yes' to confirm): " confirmation
if [ "$confirmation" != "yes" ]; then
echo "❌ Cleanup cancelled by user"
exit 1
fi
}
# Function to stop backend servers
stop_backend_servers() {
echo "🛑 Stopping backend servers..."
if [ -f "$PROJECT_ROOT/backend/scripts/stop_demo_backend.sh" ]; then
cd "$PROJECT_ROOT"
bash backend/scripts/stop_demo_backend.sh || echo "⚠️ Backend stop script failed or servers not running"
else
echo "⚠️ Backend stop script not found, continuing..."
fi
}
# Function to delete gateway and targets
delete_gateway() {
echo "🗑️ Deleting AgentCore Gateway and targets..."
# Use the gateway deletion functionality from main.py
cd "$PROJECT_ROOT/gateway"
# Check if gateway exists and delete it
python3 -c "
import sys
import boto3
from botocore.exceptions import ClientError
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
# Import the deletion functions from main.py
sys.path.append('.')
from main import _check_gateway_exists, _delete_gateway
try:
client = boto3.client('bedrock-agentcore-control', region_name='$REGION')
# Check if gateway exists
gateway_id = _check_gateway_exists(client, '$GATEWAY_NAME')
if gateway_id:
print(f'🗑️ Deleting gateway: $GATEWAY_NAME (ID: {gateway_id})')
_delete_gateway(client, gateway_id)
print('✅ Gateway and all targets deleted successfully')
else:
print(' Gateway \"$GATEWAY_NAME\" not found, skipping deletion')
except ClientError as e:
print(f'❌ Failed to delete gateway: {e}')
sys.exit(1)
except Exception as e:
print(f'❌ Unexpected error deleting gateway: {e}')
sys.exit(1)
"
}
# Function to delete agent runtime
delete_agent_runtime() {
echo "🗑️ Deleting AgentCore Runtime..."
# Use the runtime deletion functionality from deploy_agent_runtime.py
cd "$PROJECT_ROOT/deployment"
python3 -c "
import sys
import boto3
from botocore.exceptions import ClientError
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
# Import the deletion functions from deploy_agent_runtime.py
sys.path.append('.')
from deploy_agent_runtime import _get_agent_runtime_id_by_name, _delete_agent_runtime
try:
client = boto3.client('bedrock-agentcore-control', region_name='$REGION')
# Get runtime ID by name
runtime_id = _get_agent_runtime_id_by_name(client, '$RUNTIME_NAME')
if runtime_id:
print(f'🗑️ Deleting runtime: $RUNTIME_NAME (ID: {runtime_id})')
success = _delete_agent_runtime(client, runtime_id)
if success:
print('✅ Agent runtime deleted successfully')
else:
print('❌ Failed to delete agent runtime')
sys.exit(1)
else:
print(' Runtime \"$RUNTIME_NAME\" not found, skipping deletion')
except ClientError as e:
print(f'❌ Failed to delete runtime: {e}')
sys.exit(1)
except Exception as e:
print(f'❌ Unexpected error deleting runtime: {e}')
sys.exit(1)
"
}
# Function to delete memory resources
delete_memory() {
echo "🗑️ Deleting Memory Resources..."
cd "$PROJECT_ROOT"
# Check if .memory_id file exists
if [ ! -f ".memory_id" ]; then
echo " No .memory_id file found, skipping memory deletion"
return 0
fi
MEMORY_ID=$(cat .memory_id | tr -d '\n\r' | xargs)
if [ -z "$MEMORY_ID" ]; then
echo "⚠️ Memory ID file is empty, skipping memory deletion"
return 0
fi
echo "🗑️ Deleting memory resource: $MEMORY_ID"
# Use the memory deletion functionality from manage_memories.py
python3 -c "
import sys
import logging
from pathlib import Path
# Add project root to path
project_root = Path('.')
sys.path.insert(0, str(project_root))
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
try:
from bedrock_agentcore.memory import MemoryClient
memory_id = '$MEMORY_ID'
print(f'🗑️ Deleting memory resource: {memory_id}')
memory_client = MemoryClient(region_name='$REGION')
result = memory_client.delete_memory_and_wait(
memory_id=memory_id, max_wait=300, poll_interval=10
)
print('✅ Memory resource deleted successfully')
except ImportError as e:
print(f'⚠️ Could not import memory client: {e}')
print(' Memory deletion skipped - ensure dependencies are installed')
except Exception as e:
print(f'❌ Failed to delete memory resource: {e}')
# Don't exit with error as this shouldn't stop the cleanup process
print('⚠️ Continuing with cleanup despite memory deletion failure')
"
}
# Function to clean up generated files
cleanup_local_files() {
echo "🧹 Cleaning up generated files..."
cd "$PROJECT_ROOT"
# Remove gateway files
if [ -f "gateway/.gateway_uri" ]; then
rm -f gateway/.gateway_uri
echo "✅ Removed gateway/.gateway_uri"
fi
if [ -f "gateway/.access_token" ]; then
rm -f gateway/.access_token
echo "✅ Removed gateway/.access_token"
fi
# Remove agent runtime files
if [ -f "deployment/.agent_arn" ]; then
rm -f deployment/.agent_arn
echo "✅ Removed deployment/.agent_arn"
fi
# Remove memory ID file
if [ -f ".memory_id" ]; then
rm -f .memory_id
echo "✅ Removed .memory_id"
fi
}
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
--gateway-name)
GATEWAY_NAME="$2"
shift 2
;;
--runtime-name)
RUNTIME_NAME="$2"
shift 2
;;
--region)
REGION="$2"
shift 2
;;
--force)
FORCE_DELETE=true
shift
;;
--help|-h)
show_usage
exit 0
;;
*)
echo "❌ Unknown argument: $1"
echo "Use --help for usage information"
exit 1
;;
esac
done
# Try to auto-detect gateway name from config if not explicitly set
if [ "$GATEWAY_NAME" = "$DEFAULT_GATEWAY_NAME" ]; then
CONFIG_GATEWAY_NAME=$(read_gateway_name_from_config)
if [ -n "$CONFIG_GATEWAY_NAME" ]; then
GATEWAY_NAME="$CONFIG_GATEWAY_NAME"
fi
fi
# Main execution
echo "🧹 SRE Agent Cleanup Script"
echo "=========================="
echo ""
echo "Configuration:"
echo " Gateway Name: $GATEWAY_NAME"
if [ -n "$CONFIG_GATEWAY_NAME" ] && [ "$GATEWAY_NAME" = "$CONFIG_GATEWAY_NAME" ]; then
echo " (auto-detected from gateway/config.yaml)"
fi
echo " Runtime Name: $RUNTIME_NAME"
echo " Region: $REGION"
echo ""
# Confirm deletion unless --force is used
confirm_deletion
echo "🚀 Starting cleanup process..."
echo ""
# Step 1: Stop backend servers
stop_backend_servers
echo ""
# Step 2: Delete gateway and targets
delete_gateway
echo ""
# Step 3: Delete memory resources
delete_memory
echo ""
# Step 4: Delete agent runtime
delete_agent_runtime
echo ""
# Step 5: Clean up generated files
cleanup_local_files
echo ""
echo "✅ Cleanup completed successfully!"
echo ""
echo "📋 Summary of actions performed:"
echo " ✅ Stopped backend servers"
echo " ✅ Deleted AgentCore Gateway and all targets"
echo " ✅ Deleted memory resources"
echo " ✅ Deleted AgentCore Runtime"
echo " ✅ Removed generated files"
echo ""
echo "🎯 All SRE Agent AWS resources have been removed."