Compare commits
1 Commits
burn/255-1
...
fix/syntax
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f23c8758a |
9
deploy/synapse/.gitignore
vendored
9
deploy/synapse/.gitignore
vendored
@@ -1,9 +0,0 @@
|
||||
# Secrets — never commit
|
||||
.env
|
||||
synapse-credentials.env
|
||||
|
||||
# Backups
|
||||
backups/
|
||||
|
||||
# Generated config backups
|
||||
homeserver.yaml.bak
|
||||
@@ -1,82 +0,0 @@
|
||||
# Synapse Homeserver — Docker Compose Stack
|
||||
# Matrix Phase 1: Deploy Synapse on Ezra VPS
|
||||
#
|
||||
# Usage:
|
||||
# cd deploy/synapse
|
||||
# ./setup.sh # first-time deploy (generates config + keys)
|
||||
# docker compose up -d # start
|
||||
# docker compose logs -f # follow logs
|
||||
# docker compose down # stop
|
||||
#
|
||||
# Secrets:
|
||||
# Never commit .env to version control.
|
||||
# setup.sh generates secrets automatically.
|
||||
|
||||
services:
|
||||
synapse-db:
|
||||
image: postgres:16-alpine
|
||||
container_name: synapse-db
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- synapse_db:/var/lib/postgresql/data
|
||||
environment:
|
||||
POSTGRES_USER: synapse
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||
POSTGRES_INITDB_ARGS: "--encoding=UTF8 --lc-collate=C --lc-ctype=C"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U synapse"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- synapse_net
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "20m"
|
||||
max-file: "3"
|
||||
|
||||
synapse:
|
||||
image: matrixdotorg/synapse:latest
|
||||
container_name: synapse
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
synapse-db:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- synapse_data:/data
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
SYNAPSE_CONFIG_PATH: /data/homeserver.yaml
|
||||
ports:
|
||||
- "127.0.0.1:8008:8008" # Client-server API (localhost only)
|
||||
- "8448:8448" # Federation (public)
|
||||
networks:
|
||||
- synapse_net
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fSs", "http://localhost:8008/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
logging:
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "50m"
|
||||
max-file: "5"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "2.0"
|
||||
memory: 2G
|
||||
reservations:
|
||||
memory: 512M
|
||||
|
||||
volumes:
|
||||
synapse_data:
|
||||
synapse_db:
|
||||
|
||||
networks:
|
||||
synapse_net:
|
||||
driver: bridge
|
||||
@@ -1,101 +0,0 @@
|
||||
# Synapse Homeserver Configuration
|
||||
# Generated by setup.sh — edit with care.
|
||||
#
|
||||
# Docs: https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html
|
||||
|
||||
# Server name — your Matrix domain (e.g. matrix.example.com)
|
||||
server_name: "SERVER_NAME_PLACEHOLDER"
|
||||
|
||||
# Signing key — generated by setup.sh
|
||||
signing_key_path: "/data/signing.key"
|
||||
|
||||
# Trusted key servers (empty = trust only ourselves for our own keys)
|
||||
trusted_key_servers: []
|
||||
|
||||
# Report stats to matrix.org (no for sovereignty)
|
||||
report_stats: false
|
||||
|
||||
# Listeners
|
||||
listeners:
|
||||
- port: 8008
|
||||
tls: false
|
||||
type: http
|
||||
x_forwarded: true
|
||||
resources:
|
||||
- names: [client, federation]
|
||||
compress: false
|
||||
|
||||
# Database — PostgreSQL
|
||||
database:
|
||||
name: psycopg2
|
||||
args:
|
||||
user: synapse
|
||||
password: "${POSTGRES_PASSWORD}"
|
||||
database: synapse
|
||||
host: synapse-db
|
||||
cp_min: 5
|
||||
cp_max: 10
|
||||
|
||||
# Media store
|
||||
media_store_path: "/data/media_store"
|
||||
|
||||
# Upload limits
|
||||
max_upload_size: "50M"
|
||||
|
||||
# URL previews (disable to reduce attack surface)
|
||||
url_preview_enabled: false
|
||||
|
||||
# Enable room list publishing
|
||||
enable_room_list_search: true
|
||||
|
||||
# Turn off public registration by default (create users via admin API)
|
||||
enable_registration: false
|
||||
enable_registration_without_verification: false
|
||||
|
||||
# Rate limiting
|
||||
rc_message:
|
||||
per_second: 0.2
|
||||
burst_count: 10
|
||||
|
||||
rc_registration:
|
||||
per_second: 0.1
|
||||
burst_count: 3
|
||||
|
||||
rc_login:
|
||||
address:
|
||||
per_second: 0.05
|
||||
burst_count: 2
|
||||
account:
|
||||
per_second: 0.05
|
||||
burst_count: 2
|
||||
failed_attempts:
|
||||
per_second: 0.15
|
||||
burst_count: 3
|
||||
|
||||
# Retention — keep messages for 90 days by default
|
||||
retention:
|
||||
enabled: true
|
||||
default_policy:
|
||||
min_lifetime: 1d
|
||||
max_lifetime: 90d
|
||||
|
||||
# Logging
|
||||
log_config: "/data/log.config"
|
||||
|
||||
# Metrics (optional — enable if running Prometheus)
|
||||
enable_metrics: false
|
||||
|
||||
# Presence
|
||||
use_presence: true
|
||||
|
||||
# Federation
|
||||
federation_verify_certificates: true
|
||||
federation_sender_instances: 1
|
||||
|
||||
# Appservice config directory
|
||||
app_service_config_files: []
|
||||
|
||||
# Experimental features
|
||||
experimental_features:
|
||||
# MSC3440: Threading support
|
||||
msc3440_enabled: true
|
||||
@@ -1,33 +0,0 @@
|
||||
# Synapse logging configuration
|
||||
# https://matrix-org.github.io/synapse/latest/usage/configuration/config_documentation.html#log_config
|
||||
|
||||
version: 1
|
||||
|
||||
formatters:
|
||||
precise:
|
||||
format: '%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s'
|
||||
|
||||
handlers:
|
||||
console:
|
||||
class: logging.StreamHandler
|
||||
formatter: precise
|
||||
level: INFO
|
||||
stream: ext://sys.stdout
|
||||
|
||||
file:
|
||||
class: logging.handlers.RotatingFileHandler
|
||||
formatter: precise
|
||||
filename: /data/homeserver.log
|
||||
maxBytes: 104857600 # 100MB
|
||||
backupCount: 3
|
||||
level: INFO
|
||||
|
||||
loggers:
|
||||
synapse.storage.SQL:
|
||||
level: WARNING
|
||||
synapse.http.client:
|
||||
level: INFO
|
||||
|
||||
root:
|
||||
level: INFO
|
||||
handlers: [console, file]
|
||||
@@ -1,131 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Synapse Homeserver — Management Utilities
|
||||
# Usage: ./manage.sh <command>
|
||||
#
|
||||
# Commands:
|
||||
# status Show container status and health
|
||||
# restart Restart Synapse (preserves data)
|
||||
# logs Tail Synapse logs
|
||||
# create-user <username> <password> [admin]
|
||||
# backup Create timestamped backup of data volumes
|
||||
# update Pull latest Synapse image and recreate
|
||||
# teardown Stop and remove everything (DESTRUCTIVE)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
CYAN='\033[0;36m'
|
||||
NC='\033[0m'
|
||||
|
||||
info() { echo -e "${GREEN}[MANAGE]${NC} $*"; }
|
||||
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }
|
||||
|
||||
COMMAND="${1:-help}"
|
||||
|
||||
case "$COMMAND" in
|
||||
status)
|
||||
info "Container status:"
|
||||
docker compose ps
|
||||
echo ""
|
||||
info "Synapse health:"
|
||||
curl -sfS http://127.0.0.1:8008/health && echo "" || echo "Not responding"
|
||||
echo ""
|
||||
info "Disk usage:"
|
||||
docker system df -v 2>/dev/null | grep -E "synapse|VOLUME" || true
|
||||
;;
|
||||
|
||||
restart)
|
||||
info "Restarting Synapse..."
|
||||
docker compose restart synapse
|
||||
info "Waiting for health check..."
|
||||
sleep 5
|
||||
curl -sfS http://127.0.0.1:8008/health && echo "" && info "Synapse is healthy" || warn "Not responding yet"
|
||||
;;
|
||||
|
||||
logs)
|
||||
shift
|
||||
LINES="${1:-100}"
|
||||
info "Tailing Synapse logs (last $LINES lines)..."
|
||||
docker compose logs -f --tail="$LINES" synapse
|
||||
;;
|
||||
|
||||
create-user)
|
||||
USERNAME="${2:?Usage: manage.sh create-user <username> <password> [admin]}"
|
||||
PASSWORD="${3:?Usage: manage.sh create-user <username> <password> [admin]}"
|
||||
IS_ADMIN="${4:-false}"
|
||||
info "Creating user @$USERNAME..."
|
||||
ADMIN_FLAG=""
|
||||
if [ "$IS_ADMIN" = "admin" ] || [ "$IS_ADMIN" = "true" ]; then
|
||||
ADMIN_FLAG="--admin"
|
||||
fi
|
||||
docker compose exec -T synapse register_new_matrix_user \
|
||||
http://localhost:8008 \
|
||||
-c /data/homeserver.yaml \
|
||||
-u "$USERNAME" \
|
||||
-p "$PASSWORD" \
|
||||
$ADMIN_FLAG \
|
||||
--no-extra-prompt
|
||||
;;
|
||||
|
||||
backup)
|
||||
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
|
||||
BACKUP_DIR="./backups/${TIMESTAMP}"
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
info "Backing up PostgreSQL..."
|
||||
docker compose exec -T synapse-db pg_dump -U synapse > "${BACKUP_DIR}/synapse_db.sql"
|
||||
info "Backing up Synapse data volume..."
|
||||
docker run --rm \
|
||||
-v synapse_data:/source:ro \
|
||||
-v "$(pwd)/${BACKUP_DIR}:/backup" \
|
||||
alpine tar czf /backup/synapse_data.tar.gz -C /source .
|
||||
info "Backup complete: $BACKUP_DIR"
|
||||
ls -lh "$BACKUP_DIR"
|
||||
;;
|
||||
|
||||
update)
|
||||
info "Pulling latest Synapse image..."
|
||||
docker compose pull synapse
|
||||
info "Recreating containers..."
|
||||
docker compose up -d --force-recreate synapse
|
||||
info "Waiting for health..."
|
||||
sleep 10
|
||||
curl -sfS http://127.0.0.1:8008/health && echo "" && info "Updated and healthy" || warn "Check logs"
|
||||
;;
|
||||
|
||||
teardown)
|
||||
echo -e "${RED}WARNING: This will stop and remove all Synapse containers and volumes.${NC}"
|
||||
echo -e "${RED}ALL DATA WILL BE LOST. This cannot be undone.${NC}"
|
||||
echo ""
|
||||
read -p "Type 'yes-delete-everything' to confirm: " CONFIRM
|
||||
if [ "$CONFIRM" = "yes-delete-everything" ]; then
|
||||
info "Stopping containers..."
|
||||
docker compose down -v
|
||||
info "Removing volumes..."
|
||||
docker volume rm synapse_data synapse_db 2>/dev/null || true
|
||||
info "Teardown complete."
|
||||
else
|
||||
info "Aborted."
|
||||
fi
|
||||
;;
|
||||
|
||||
help|*)
|
||||
echo "Synapse Homeserver Management"
|
||||
echo ""
|
||||
echo "Usage: ./manage.sh <command>"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " status Show container status and health"
|
||||
echo " restart Restart Synapse"
|
||||
echo " logs [lines] Tail Synapse logs (default: 100)"
|
||||
echo " create-user <u> <p> [admin] Create a new Matrix user"
|
||||
echo " backup Backup database + data volume"
|
||||
echo " update Pull latest image and recreate"
|
||||
echo " teardown Stop and remove everything (DESTRUCTIVE)"
|
||||
;;
|
||||
esac
|
||||
@@ -1,211 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Synapse Homeserver — One-Shot Setup Script
|
||||
# Matrix Phase 1: Deploy Synapse on Ezra VPS
|
||||
#
|
||||
# Usage:
|
||||
# ./setup.sh <server_name> [admin_user] [admin_password]
|
||||
#
|
||||
# Example:
|
||||
# ./setup.sh matrix.timmy-time.xyz hermes-bot 'secure-pass-123'
|
||||
#
|
||||
# What it does:
|
||||
# 1. Generates .env with secrets
|
||||
# 2. Prepares homeserver.yaml with correct server name
|
||||
# 3. Generates signing key
|
||||
# 4. Starts Synapse + PostgreSQL via Docker Compose
|
||||
# 5. Waits for Synapse to be healthy
|
||||
# 6. Registers admin user + bot account
|
||||
# 7. Outputs Matrix credentials for hermes-agent
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
# --- Colors ---
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
CYAN='\033[0;36m'
|
||||
NC='\033[0m'
|
||||
|
||||
info() { echo -e "${GREEN}[SETUP]${NC} $*"; }
|
||||
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }
|
||||
|
||||
# --- Args ---
|
||||
SERVER_NAME="${1:?Usage: $0 <server_name> [admin_user] [admin_password]}"
|
||||
ADMIN_USER="${2:-timmy-admin}"
|
||||
ADMIN_PASS="${3:-$(openssl rand -hex 16)}"
|
||||
BOT_USER="${4:-hermes-bot}"
|
||||
BOT_PASS="${5:-$(openssl rand -hex 16)}"
|
||||
|
||||
echo -e "${CYAN}"
|
||||
echo "╔══════════════════════════════════════════════════╗"
|
||||
echo "║ Synapse Homeserver — Matrix Phase 1 Deploy ║"
|
||||
echo "╚══════════════════════════════════════════════════╝"
|
||||
echo -e "${NC}"
|
||||
info "Server name: $SERVER_NAME"
|
||||
info "Admin user: @$ADMIN_USER:$SERVER_NAME"
|
||||
info "Bot user: @$BOT_USER:$SERVER_NAME"
|
||||
echo ""
|
||||
|
||||
# --- Preflight ---
|
||||
info "Preflight checks..."
|
||||
command -v docker >/dev/null 2>&1 || error "docker not found. Install Docker first."
|
||||
command -v docker compose version >/dev/null 2>&1 || error "docker compose not found. Install Docker Compose plugin."
|
||||
info "Docker: $(docker --version | head -1)"
|
||||
info "Compose: $(docker compose version | head -1)"
|
||||
|
||||
# --- Generate .env ---
|
||||
info "Generating .env..."
|
||||
POSTGRES_PASSWORD=$(openssl rand -hex 24)
|
||||
REGISTRATION_SECRET=$(openssl rand -hex 16)
|
||||
|
||||
cat > .env <<EOF
|
||||
# Synapse deployment — generated $(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
# DO NOT COMMIT THIS FILE
|
||||
|
||||
POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
|
||||
SYNAPSE_SERVER_NAME=${SERVER_NAME}
|
||||
SYNAPSE_REPORT_STATS=no
|
||||
REGISTRATION_SECRET=${REGISTRATION_SECRET}
|
||||
EOF
|
||||
chmod 600 .env
|
||||
info ".env written with secure permissions"
|
||||
|
||||
# --- Prepare homeserver.yaml ---
|
||||
info "Preparing homeserver.yaml..."
|
||||
sed -i.bak "s/SERVER_NAME_PLACEHOLDER/${SERVER_NAME}/g" homeserver.yaml
|
||||
rm -f homeserver.yaml.bak
|
||||
info "Server name set to: $SERVER_NAME"
|
||||
|
||||
# --- Generate signing key ---
|
||||
info "Generating signing key..."
|
||||
# Synapse will generate its own key on first run if missing
|
||||
# But we pre-create the data volume structure
|
||||
docker volume create synapse_data >/dev/null 2>&1 || true
|
||||
docker volume create synapse_db >/dev/null 2>&1 || true
|
||||
|
||||
# --- Start the stack ---
|
||||
info "Starting Synapse + PostgreSQL..."
|
||||
docker compose up -d
|
||||
|
||||
# --- Wait for Synapse to be healthy ---
|
||||
info "Waiting for Synapse to start (up to 120s)..."
|
||||
MAX_WAIT=120
|
||||
ELAPSED=0
|
||||
while [ $ELAPSED -lt $MAX_WAIT ]; do
|
||||
if curl -sfS http://127.0.0.1:8008/health >/dev/null 2>&1; then
|
||||
info "Synapse is healthy!"
|
||||
break
|
||||
fi
|
||||
sleep 3
|
||||
ELAPSED=$((ELAPSED + 3))
|
||||
if [ $((ELAPSED % 15)) -eq 0 ]; then
|
||||
info "Still waiting... (${ELAPSED}s)"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ $ELAPSED -ge $MAX_WAIT ]; then
|
||||
warn "Synapse did not respond within ${MAX_WAIT}s. Check logs:"
|
||||
echo " docker compose logs synapse"
|
||||
error "Aborting registration."
|
||||
fi
|
||||
|
||||
# --- Register admin user ---
|
||||
info "Registering admin user @$ADMIN_USER:$SERVER_NAME..."
|
||||
docker compose exec -T synapse register_new_matrix_user \
|
||||
http://localhost:8008 \
|
||||
-c /data/homeserver.yaml \
|
||||
-u "$ADMIN_USER" \
|
||||
-p "$ADMIN_PASS" \
|
||||
--admin \
|
||||
--no-extra-prompt 2>&1 || {
|
||||
# User might already exist if re-running
|
||||
warn "Admin user registration returned non-zero (may already exist)"
|
||||
}
|
||||
|
||||
# --- Register bot user ---
|
||||
info "Registering bot user @$BOT_USER:$SERVER_NAME..."
|
||||
docker compose exec -T synapse register_new_matrix_user \
|
||||
http://localhost:8008 \
|
||||
-c /data/homeserver.yaml \
|
||||
-u "$BOT_USER" \
|
||||
-p "$BOT_PASS" \
|
||||
--no-admin \
|
||||
--no-extra-prompt 2>&1 || {
|
||||
warn "Bot user registration returned non-zero (may already exist)"
|
||||
}
|
||||
|
||||
# --- Get bot access token ---
|
||||
info "Acquiring bot access token..."
|
||||
BOT_TOKEN_RESPONSE=$(curl -sfS -X POST "http://127.0.0.1:8008/_matrix/client/v3/login" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{
|
||||
\"type\": \"m.login.password\",
|
||||
\"identifier\": {
|
||||
\"type\": \"m.id.user\",
|
||||
\"user\": \"${BOT_USER}\"
|
||||
},
|
||||
\"password\": \"${BOT_PASS}\",
|
||||
\"device_name\": \"Hermes Agent\"
|
||||
}")
|
||||
|
||||
BOT_ACCESS_TOKEN=$(echo "$BOT_TOKEN_RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])" 2>/dev/null || echo "FAILED_TO_EXTRACT")
|
||||
BOT_DEVICE_ID=$(echo "$BOT_TOKEN_RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['device_id'])" 2>/dev/null || echo "UNKNOWN")
|
||||
|
||||
if [ "$BOT_ACCESS_TOKEN" = "FAILED_TO_EXTRACT" ]; then
|
||||
warn "Could not extract bot access token automatically."
|
||||
warn "Login manually: curl -X POST http://127.0.0.1:8008/_matrix/client/v3/login ..."
|
||||
fi
|
||||
|
||||
# --- Write credentials file ---
|
||||
CREDENTIALS_FILE="synapse-credentials.env"
|
||||
cat > "$CREDENTIALS_FILE" <<EOF
|
||||
# Synapse Credentials — generated $(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
# Add these to hermes-agent's ~/.hermes/.env
|
||||
|
||||
# Matrix integration
|
||||
MATRIX_HOMESERVER=http://${SERVER_NAME}:8008
|
||||
MATRIX_ACCESS_TOKEN=${BOT_ACCESS_TOKEN}
|
||||
MATRIX_USER_ID=@${BOT_USER}:${SERVER_NAME}
|
||||
MATRIX_DEVICE_ID=${BOT_DEVICE_ID}
|
||||
MATRIX_ENCRYPTION=true
|
||||
|
||||
# Admin credentials (for user management)
|
||||
SYNAPSE_ADMIN_USER=@${ADMIN_USER}:${SERVER_NAME}
|
||||
SYNAPSE_ADMIN_PASSWORD=${ADMIN_PASS}
|
||||
|
||||
# Bot credentials
|
||||
SYNAPSE_BOT_USER=@${BOT_USER}:${SERVER_NAME}
|
||||
SYNAPSE_BOT_PASSWORD=${BOT_PASS}
|
||||
EOF
|
||||
chmod 600 "$CREDENTIALS_FILE"
|
||||
info "Credentials written to: $CREDENTIALS_FILE"
|
||||
|
||||
# --- Summary ---
|
||||
echo ""
|
||||
echo -e "${GREEN}╔══════════════════════════════════════════════════╗${NC}"
|
||||
echo -e "${GREEN}║ Synapse Deployed Successfully! ║${NC}"
|
||||
echo -e "${GREEN}╚══════════════════════════════════════════════════╝${NC}"
|
||||
echo ""
|
||||
echo -e " Server: ${CYAN}https://${SERVER_NAME}${NC}"
|
||||
echo -e " Client API: ${CYAN}http://127.0.0.1:8008${NC}"
|
||||
echo -e " Federation: ${CYAN}https://${SERVER_NAME}:8448${NC}"
|
||||
echo ""
|
||||
echo -e " Admin: ${YELLOW}@${ADMIN_USER}:${SERVER_NAME}${NC}"
|
||||
echo -e " Bot: ${YELLOW}@${BOT_USER}:${SERVER_NAME}${NC}"
|
||||
echo -e " Bot Token: ${YELLOW}${BOT_ACCESS_TOKEN:0:20}...${NC}"
|
||||
echo ""
|
||||
echo -e " Credentials: ${CYAN}${SCRIPT_DIR}/${CREDENTIALS_FILE}${NC}"
|
||||
echo ""
|
||||
echo -e "${GREEN}Next steps:${NC}"
|
||||
echo " 1. Point DNS: ${SERVER_NAME} → $(curl -s ifconfig.me 2>/dev/null || echo '<VPS_IP>')"
|
||||
echo " 2. Set up TLS: nginx/certbot reverse proxy for :8008 and :8448"
|
||||
echo " 3. Copy credentials to hermes-agent: cp ${CREDENTIALS_FILE} ~/.hermes/.env"
|
||||
echo " 4. Start hermes: hermes gateway --platform matrix"
|
||||
echo ""
|
||||
echo " Manage: docker compose logs -f | docker compose restart | docker compose down"
|
||||
echo " Users: docker compose exec synapse register_new_matrix_user http://localhost:8008 -c /data/homeserver.yaml -u <user> -p <pass>"
|
||||
echo ""
|
||||
@@ -1,251 +0,0 @@
|
||||
# Synapse Homeserver Deployment Guide
|
||||
|
||||
## Matrix Phase 1: Deploy Synapse on Ezra VPS
|
||||
|
||||
Part of [Epic #269: Matrix Integration — Sovereign Messaging for Timmy](https://forge.alexanderwhitestone.com/Timmy_Foundation/hermes-agent/issues/269).
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ Ezra VPS (143.198.27.163) │
|
||||
│ │
|
||||
│ ┌──────────┐ ┌─────────────────────────┐ │
|
||||
│ │ Nginx │────▶│ Synapse (Docker) │ │
|
||||
│ │ :443→8008│ │ Client API: localhost:8008│ │
|
||||
│ │ :8448→8448│ │ Federation: 0.0.0.0:8448│ │
|
||||
│ └──────────┘ └──────────┬──────────────┘ │
|
||||
│ │ │
|
||||
│ ┌────────▼──────────┐ │
|
||||
│ │ PostgreSQL 16 │ │
|
||||
│ │ (Docker volume) │ │
|
||||
│ └───────────────────┘ │
|
||||
│ │
|
||||
│ ┌──────────────────────────────────────────┐ │
|
||||
│ │ hermes-agent (gateway) │ │
|
||||
│ │ MATRIX_HOMESERVER=http://localhost:8008 │ │
|
||||
│ └──────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker + Docker Compose plugin on Ezra VPS
|
||||
- SSH access: `ssh root@143.198.27.163`
|
||||
- DNS A record pointing to the VPS IP
|
||||
- (Recommended) Nginx + Certbot for TLS termination
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# SSH into Ezra
|
||||
ssh root@143.198.27.163
|
||||
|
||||
# Clone hermes-agent (if not present)
|
||||
cd /root
|
||||
git clone https://forge.alexanderwhitestone.com/Timmy_Foundation/hermes-agent.git
|
||||
cd hermes-agent/deploy/synapse
|
||||
|
||||
# Deploy Synapse
|
||||
chmod +x setup.sh
|
||||
./setup.sh matrix.timmy-time.xyz
|
||||
|
||||
# This will:
|
||||
# 1. Generate .env with database password
|
||||
# 2. Prepare homeserver.yaml
|
||||
# 3. Start Synapse + PostgreSQL via Docker Compose
|
||||
# 4. Wait for health
|
||||
# 5. Register admin + bot accounts
|
||||
# 6. Acquire bot access token
|
||||
# 7. Write synapse-credentials.env
|
||||
```
|
||||
|
||||
## Step-by-Step
|
||||
|
||||
### 1. DNS Configuration
|
||||
|
||||
Point your Matrix domain to Ezra's IP:
|
||||
|
||||
```
|
||||
Type Name Value
|
||||
A matrix 143.198.27.163
|
||||
```
|
||||
|
||||
Federation uses SRV records for port discovery, but direct `:8448` works without them.
|
||||
|
||||
### 2. Deploy Synapse
|
||||
|
||||
```bash
|
||||
cd /root/hermes-agent/deploy/synapse
|
||||
./setup.sh matrix.timmy-time.xyz hermes-bot 'your-secure-password'
|
||||
```
|
||||
|
||||
Arguments:
|
||||
| Arg | Default | Description |
|
||||
|-----|---------|-------------|
|
||||
| `server_name` | (required) | Matrix domain (e.g., `matrix.timmy-time.xyz`) |
|
||||
| `admin_user` | `timmy-admin` | Admin account username |
|
||||
| `admin_password` | (random) | Admin account password |
|
||||
| `bot_user` | `hermes-bot` | Bot account username |
|
||||
| `bot_password` | (random) | Bot account password |
|
||||
|
||||
### 3. TLS Termination (Nginx)
|
||||
|
||||
Install Nginx + Certbot:
|
||||
|
||||
```bash
|
||||
apt install -y nginx certbot python3-certbot-nginx
|
||||
|
||||
# Client-server API
|
||||
cat > /etc/nginx/sites-available/matrix <<'EOF'
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name matrix.timmy-time.xyz;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/matrix.timmy-time.xyz/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/matrix.timmy-time.xyz/privkey.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8008;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
client_max_body_size 50M;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8448 ssl http2;
|
||||
server_name matrix.timmy-time.xyz;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/matrix.timmy-time.xyz/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/matrix.timmy-time.xyz/privkey.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8008;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
|
||||
ln -sf /etc/nginx/sites-available/matrix /etc/nginx/sites-enabled/
|
||||
nginx -t && systemctl reload nginx
|
||||
|
||||
# Get cert
|
||||
certbot --nginx -d matrix.timmy-time.xyz
|
||||
```
|
||||
|
||||
### 4. Wire Hermes Agent
|
||||
|
||||
Copy the generated credentials to hermes-agent's environment:
|
||||
|
||||
```bash
|
||||
# From synapse-credentials.env, add to ~/.hermes/.env:
|
||||
MATRIX_HOMESERVER=https://matrix.timmy-time.xyz
|
||||
MATRIX_ACCESS_TOKEN=<from synapse-credentials.env>
|
||||
MATRIX_USER_ID=@hermes-bot:matrix.timmy-time.xyz
|
||||
MATRIX_DEVICE_ID=<from synapse-credentials.env>
|
||||
MATRIX_ENCRYPTION=true
|
||||
```
|
||||
|
||||
Then start the gateway:
|
||||
|
||||
```bash
|
||||
hermes gateway --platform matrix
|
||||
```
|
||||
|
||||
### 5. Verify
|
||||
|
||||
```bash
|
||||
# Check Synapse health
|
||||
curl -s https://matrix.timmy-time.xyz/_matrix/client/versions
|
||||
|
||||
# Check federation
|
||||
curl -s https://matrix.timmy-time.xyz:8448/_matrix/federation/v1/version
|
||||
|
||||
# Check bot is connected
|
||||
# (should appear online in Element or any Matrix client)
|
||||
```
|
||||
|
||||
## Management
|
||||
|
||||
Use the management script for day-to-day operations:
|
||||
|
||||
```bash
|
||||
cd /root/hermes-agent/deploy/synapse
|
||||
|
||||
./manage.sh status # container health
|
||||
./manage.sh logs # tail logs
|
||||
./manage.sh restart # restart Synapse
|
||||
./manage.sh backup # backup DB + data
|
||||
./manage.sh update # pull latest image
|
||||
./manage.sh create-user alice 'password123'
|
||||
./manage.sh create-user admin 'secret' admin
|
||||
```
|
||||
|
||||
## Backups
|
||||
|
||||
```bash
|
||||
./manage.sh backup
|
||||
# Creates: backups/YYYYMMDD_HHMMSS/
|
||||
# ├── synapse_db.sql (PostgreSQL dump)
|
||||
# └── synapse_data.tar.gz (media store + keys)
|
||||
```
|
||||
|
||||
Automate with cron:
|
||||
|
||||
```bash
|
||||
# Daily backup at 3 AM
|
||||
0 3 * * * cd /root/hermes-agent/deploy/synapse && ./manage.sh backup >> /var/log/synapse-backup.log 2>&1
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Synapse won't start
|
||||
```bash
|
||||
docker compose logs synapse
|
||||
# Common: PostgreSQL not ready. Wait for healthcheck.
|
||||
```
|
||||
|
||||
### Bot can't connect
|
||||
```bash
|
||||
# Verify token is valid
|
||||
curl -H "Authorization: Bearer $MATRIX_ACCESS_TOKEN" \
|
||||
https://matrix.timmy-time.xyz/_matrix/client/v3/account/whoami
|
||||
```
|
||||
|
||||
### Federation not working
|
||||
```bash
|
||||
# Check port 8448 is open
|
||||
ss -tlnp | grep 8448
|
||||
# Check firewall
|
||||
ufw status
|
||||
```
|
||||
|
||||
### High memory usage
|
||||
```bash
|
||||
# Check resource limits in docker-compose.yml
|
||||
docker stats synapse
|
||||
# Tune in homeserver.yaml: event_cache_size, caches
|
||||
```
|
||||
|
||||
## Security Notes
|
||||
|
||||
- Registration is disabled by default (`enable_registration: false`)
|
||||
- Rate limiting is enforced on login, registration, and messages
|
||||
- Federation certificate verification is enabled
|
||||
- `.env` and `synapse-credentials.env` are `chmod 600`
|
||||
- Client API binds to `127.0.0.1` only (use Nginx for public access)
|
||||
- Consider: firewall rules, fail2ban, regular backups
|
||||
|
||||
## References
|
||||
|
||||
- [Synapse Documentation](https://matrix-org.github.io/synapse/latest/)
|
||||
- [Matrix Spec](https://spec.matrix.org/)
|
||||
- [Epic #269: Matrix Integration](https://forge.alexanderwhitestone.com/Timmy_Foundation/hermes-agent/issues/269)
|
||||
- [Issue #272: Deploy Synapse on Ezra](https://forge.alexanderwhitestone.com/Timmy_Foundation/hermes-agent/issues/272)
|
||||
- [Hermes Matrix Setup Guide](docs/matrix-setup.md)
|
||||
@@ -648,51 +648,6 @@ def load_gateway_config() -> GatewayConfig:
|
||||
return config
|
||||
|
||||
|
||||
# Known-weak placeholder tokens from .env.example, tutorials, etc.
|
||||
_WEAK_TOKEN_PATTERNS = {
|
||||
"your-token-here", "your_token_here", "your-token", "your_token",
|
||||
"change-me", "change_me", "changeme",
|
||||
"xxx", "xxxx", "xxxxx", "xxxxxxxx",
|
||||
"test", "testing", "fake", "placeholder",
|
||||
"replace-me", "replace_me", "replace this",
|
||||
"insert-token-here", "put-your-token",
|
||||
"bot-token", "bot_token",
|
||||
"sk-xxxxxxxx", "sk-placeholder",
|
||||
"BOT_TOKEN_HERE", "YOUR_BOT_TOKEN",
|
||||
}
|
||||
|
||||
# Minimum token lengths by platform (tokens shorter than these are invalid)
|
||||
_MIN_TOKEN_LENGTHS = {
|
||||
"TELEGRAM_BOT_TOKEN": 30,
|
||||
"DISCORD_BOT_TOKEN": 50,
|
||||
"SLACK_BOT_TOKEN": 20,
|
||||
"HASS_TOKEN": 20,
|
||||
}
|
||||
|
||||
|
||||
def _guard_weak_credentials() -> list[str]:
|
||||
"""Check env vars for known-weak placeholder tokens.
|
||||
|
||||
Returns a list of warning messages for any weak credentials found.
|
||||
"""
|
||||
warnings = []
|
||||
for env_var, min_len in _MIN_TOKEN_LENGTHS.items():
|
||||
value = os.getenv(env_var, "").strip()
|
||||
if not value:
|
||||
continue
|
||||
if value.lower() in _WEAK_TOKEN_PATTERNS:
|
||||
warnings.append(
|
||||
f"{env_var} is set to a placeholder value ('{value[:20]}'). "
|
||||
f"Replace it with a real token."
|
||||
)
|
||||
elif len(value) < min_len:
|
||||
warnings.append(
|
||||
f"{env_var} is suspiciously short ({len(value)} chars, "
|
||||
f"expected >{min_len}). May be truncated or invalid."
|
||||
)
|
||||
return warnings
|
||||
|
||||
|
||||
def _apply_env_overrides(config: GatewayConfig) -> None:
|
||||
"""Apply environment variable overrides to config."""
|
||||
|
||||
@@ -986,7 +941,3 @@ def _apply_env_overrides(config: GatewayConfig) -> None:
|
||||
config.default_reset_policy.at_hour = int(reset_hour)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Guard against weak placeholder tokens from .env.example copies
|
||||
for warning in _guard_weak_credentials():
|
||||
logger.warning("Weak credential: %s", warning)
|
||||
|
||||
@@ -540,29 +540,6 @@ def handle_function_call(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Poka-yoke: validate tool handler return type.
|
||||
# Handlers MUST return a JSON string. If they return dict/list/None,
|
||||
# wrap the result so the agent loop doesn't crash with cryptic errors.
|
||||
if not isinstance(result, str):
|
||||
logger.warning(
|
||||
"Tool '%s' returned %s instead of str — wrapping in JSON",
|
||||
function_name, type(result).__name__,
|
||||
)
|
||||
result = json.dumps(
|
||||
{"output": str(result), "_type_warning": f"Tool returned {type(result).__name__}, expected str"},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
else:
|
||||
# Validate it's parseable JSON
|
||||
try:
|
||||
json.loads(result)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
logger.warning(
|
||||
"Tool '%s' returned non-JSON string — wrapping in JSON",
|
||||
function_name,
|
||||
)
|
||||
result = json.dumps({"output": result}, ensure_ascii=False)
|
||||
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
|
||||
@@ -12,7 +12,7 @@ Config in $HERMES_HOME/config.yaml (profile-scoped):
|
||||
auto_extract: false
|
||||
default_trust: 0.5
|
||||
min_trust_threshold: 0.3
|
||||
temporal_decay_half_life: 60
|
||||
temporal_decay_half_life: 0
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -152,7 +152,6 @@ class HolographicMemoryProvider(MemoryProvider):
|
||||
{"key": "auto_extract", "description": "Auto-extract facts at session end", "default": "false", "choices": ["true", "false"]},
|
||||
{"key": "default_trust", "description": "Default trust score for new facts", "default": "0.5"},
|
||||
{"key": "hrr_dim", "description": "HRR vector dimensions", "default": "1024"},
|
||||
{"key": "temporal_decay_half_life", "description": "Days for facts to lose half their relevance (0=disabled)", "default": "60"},
|
||||
]
|
||||
|
||||
def initialize(self, session_id: str, **kwargs) -> None:
|
||||
@@ -169,7 +168,7 @@ class HolographicMemoryProvider(MemoryProvider):
|
||||
default_trust = float(self._config.get("default_trust", 0.5))
|
||||
hrr_dim = int(self._config.get("hrr_dim", 1024))
|
||||
hrr_weight = float(self._config.get("hrr_weight", 0.3))
|
||||
temporal_decay = int(self._config.get("temporal_decay_half_life", 60))
|
||||
temporal_decay = int(self._config.get("temporal_decay_half_life", 0))
|
||||
|
||||
self._store = MemoryStore(db_path=db_path, default_trust=default_trust, hrr_dim=hrr_dim)
|
||||
self._retriever = FactRetriever(
|
||||
|
||||
@@ -98,15 +98,7 @@ class FactRetriever:
|
||||
|
||||
# Optional temporal decay
|
||||
if self.half_life > 0:
|
||||
decay = self._temporal_decay(fact.get("updated_at") or fact.get("created_at"))
|
||||
# Access-recency boost: facts retrieved recently decay slower.
|
||||
# A fact accessed within 1 half-life gets up to 1.5x the decay
|
||||
# factor, tapering to 1.0x (no boost) after 2 half-lives.
|
||||
last_accessed = fact.get("last_accessed_at")
|
||||
if last_accessed:
|
||||
access_boost = self._access_recency_boost(last_accessed)
|
||||
decay = min(1.0, decay * access_boost)
|
||||
score *= decay
|
||||
score *= self._temporal_decay(fact.get("updated_at") or fact.get("created_at"))
|
||||
|
||||
fact["score"] = score
|
||||
scored.append(fact)
|
||||
@@ -599,41 +591,3 @@ class FactRetriever:
|
||||
return math.pow(0.5, age_days / self.half_life)
|
||||
except (ValueError, TypeError):
|
||||
return 1.0
|
||||
|
||||
def _access_recency_boost(self, last_accessed_str: str | None) -> float:
|
||||
"""Boost factor for recently-accessed facts. Range [1.0, 1.5].
|
||||
|
||||
Facts accessed within 1 half-life get up to 1.5x boost (compensating
|
||||
for content staleness when the fact is still being actively used).
|
||||
Boost decays linearly to 1.0 (no boost) at 2 half-lives.
|
||||
|
||||
Returns 1.0 if half-life is disabled or timestamp is missing.
|
||||
"""
|
||||
if not self.half_life or not last_accessed_str:
|
||||
return 1.0
|
||||
|
||||
try:
|
||||
if isinstance(last_accessed_str, str):
|
||||
ts = datetime.fromisoformat(last_accessed_str.replace("Z", "+00:00"))
|
||||
else:
|
||||
ts = last_accessed_str
|
||||
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
|
||||
age_days = (datetime.now(timezone.utc) - ts).total_seconds() / 86400
|
||||
if age_days < 0:
|
||||
return 1.5 # Future timestamp = just accessed
|
||||
|
||||
half_lives_since_access = age_days / self.half_life
|
||||
|
||||
if half_lives_since_access <= 1.0:
|
||||
# Within 1 half-life: linearly from 1.5 (just now) to 1.0 (at 1 HL)
|
||||
return 1.0 + 0.5 * (1.0 - half_lives_since_access)
|
||||
elif half_lives_since_access <= 2.0:
|
||||
# Between 1 and 2 half-lives: linearly from 1.0 to 1.0 (no boost)
|
||||
return 1.0
|
||||
else:
|
||||
return 1.0
|
||||
except (ValueError, TypeError):
|
||||
return 1.0
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
"""Tests for weak credential guard in gateway/config.py."""
|
||||
|
||||
import os
|
||||
import pytest
|
||||
|
||||
from gateway.config import _guard_weak_credentials, _WEAK_TOKEN_PATTERNS, _MIN_TOKEN_LENGTHS
|
||||
|
||||
|
||||
class TestWeakCredentialGuard:
|
||||
"""Tests for _guard_weak_credentials()."""
|
||||
|
||||
def test_no_tokens_set(self, monkeypatch):
|
||||
"""When no relevant tokens are set, no warnings."""
|
||||
for var in _MIN_TOKEN_LENGTHS:
|
||||
monkeypatch.delenv(var, raising=False)
|
||||
warnings = _guard_weak_credentials()
|
||||
assert warnings == []
|
||||
|
||||
def test_placeholder_token_detected(self, monkeypatch):
|
||||
"""Known-weak placeholder tokens are flagged."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "your-token-here")
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 1
|
||||
assert "TELEGRAM_BOT_TOKEN" in warnings[0]
|
||||
assert "placeholder" in warnings[0].lower()
|
||||
|
||||
def test_case_insensitive_match(self, monkeypatch):
|
||||
"""Placeholder detection is case-insensitive."""
|
||||
monkeypatch.setenv("DISCORD_BOT_TOKEN", "FAKE")
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 1
|
||||
assert "DISCORD_BOT_TOKEN" in warnings[0]
|
||||
|
||||
def test_short_token_detected(self, monkeypatch):
|
||||
"""Suspiciously short tokens are flagged."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "abc123") # 6 chars, min is 30
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 1
|
||||
assert "short" in warnings[0].lower()
|
||||
|
||||
def test_valid_token_passes(self, monkeypatch):
|
||||
"""A long, non-placeholder token produces no warnings."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "1234567890:ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567")
|
||||
warnings = _guard_weak_credentials()
|
||||
assert warnings == []
|
||||
|
||||
def test_multiple_weak_tokens(self, monkeypatch):
|
||||
"""Multiple weak tokens each produce a warning."""
|
||||
monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "change-me")
|
||||
monkeypatch.setenv("DISCORD_BOT_TOKEN", "xx") # short
|
||||
warnings = _guard_weak_credentials()
|
||||
assert len(warnings) == 2
|
||||
@@ -1,209 +0,0 @@
|
||||
"""Tests for temporal decay and access-recency boost in holographic memory (#241)."""
|
||||
|
||||
import math
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class TestTemporalDecay:
|
||||
"""Test _temporal_decay exponential decay formula."""
|
||||
|
||||
def _make_retriever(self, half_life=60):
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
store = MagicMock()
|
||||
return FactRetriever(store=store, temporal_decay_half_life=half_life)
|
||||
|
||||
def test_fresh_fact_no_decay(self):
|
||||
"""A fact updated today should have decay ≈ 1.0."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
decay = r._temporal_decay(now)
|
||||
assert decay > 0.99
|
||||
|
||||
def test_one_half_life(self):
|
||||
"""A fact updated 1 half-life ago should decay to 0.5."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=60)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.5) < 0.01
|
||||
|
||||
def test_two_half_lives(self):
|
||||
"""A fact updated 2 half-lives ago should decay to 0.25."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=120)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.25) < 0.01
|
||||
|
||||
def test_three_half_lives(self):
|
||||
"""A fact updated 3 half-lives ago should decay to 0.125."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=180)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.125) < 0.01
|
||||
|
||||
def test_half_life_disabled(self):
|
||||
"""When half_life=0, decay should always be 1.0."""
|
||||
r = self._make_retriever(half_life=0)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=365)).isoformat()
|
||||
assert r._temporal_decay(old) == 1.0
|
||||
|
||||
def test_none_timestamp(self):
|
||||
"""Missing timestamp should return 1.0 (no decay)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._temporal_decay(None) == 1.0
|
||||
|
||||
def test_empty_timestamp(self):
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._temporal_decay("") == 1.0
|
||||
|
||||
def test_invalid_timestamp(self):
|
||||
"""Malformed timestamp should return 1.0 (fail open)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._temporal_decay("not-a-date") == 1.0
|
||||
|
||||
def test_future_timestamp(self):
|
||||
"""Future timestamp should return 1.0 (no decay for future dates)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
future = (datetime.now(timezone.utc) + timedelta(days=10)).isoformat()
|
||||
assert r._temporal_decay(future) == 1.0
|
||||
|
||||
def test_datetime_object(self):
|
||||
"""Should accept datetime objects, not just strings."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = datetime.now(timezone.utc) - timedelta(days=60)
|
||||
decay = r._temporal_decay(old)
|
||||
assert abs(decay - 0.5) < 0.01
|
||||
|
||||
def test_different_half_lives(self):
|
||||
"""30-day half-life should decay faster than 90-day."""
|
||||
r30 = self._make_retriever(half_life=30)
|
||||
r90 = self._make_retriever(half_life=90)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=45)).isoformat()
|
||||
assert r30._temporal_decay(old) < r90._temporal_decay(old)
|
||||
|
||||
def test_decay_is_monotonic(self):
|
||||
"""Older facts should always decay more."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc)
|
||||
d1 = r._temporal_decay((now - timedelta(days=10)).isoformat())
|
||||
d2 = r._temporal_decay((now - timedelta(days=30)).isoformat())
|
||||
d3 = r._temporal_decay((now - timedelta(days=60)).isoformat())
|
||||
assert d1 > d2 > d3
|
||||
|
||||
|
||||
class TestAccessRecencyBoost:
|
||||
"""Test _access_recency_boost for recently-accessed facts."""
|
||||
|
||||
def _make_retriever(self, half_life=60):
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
store = MagicMock()
|
||||
return FactRetriever(store=store, temporal_decay_half_life=half_life)
|
||||
|
||||
def test_just_accessed_max_boost(self):
|
||||
"""A fact accessed just now should get maximum boost (1.5)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
boost = r._access_recency_boost(now)
|
||||
assert boost > 1.45 # Near 1.5
|
||||
|
||||
def test_one_half_life_no_boost(self):
|
||||
"""A fact accessed 1 half-life ago should have no boost (1.0)."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=60)).isoformat()
|
||||
boost = r._access_recency_boost(old)
|
||||
assert abs(boost - 1.0) < 0.01
|
||||
|
||||
def test_half_way_boost(self):
|
||||
"""A fact accessed 0.5 half-lives ago should get ~1.25 boost."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat()
|
||||
boost = r._access_recency_boost(old)
|
||||
assert abs(boost - 1.25) < 0.05
|
||||
|
||||
def test_beyond_one_half_life_no_boost(self):
|
||||
"""Beyond 1 half-life, boost should be 1.0."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=90)).isoformat()
|
||||
boost = r._access_recency_boost(old)
|
||||
assert boost == 1.0
|
||||
|
||||
def test_disabled_no_boost(self):
|
||||
"""When half_life=0, boost should be 1.0."""
|
||||
r = self._make_retriever(half_life=0)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
assert r._access_recency_boost(now) == 1.0
|
||||
|
||||
def test_none_timestamp(self):
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._access_recency_boost(None) == 1.0
|
||||
|
||||
def test_invalid_timestamp(self):
|
||||
r = self._make_retriever(half_life=60)
|
||||
assert r._access_recency_boost("bad") == 1.0
|
||||
|
||||
def test_boost_range(self):
|
||||
"""Boost should always be in [1.0, 1.5]."""
|
||||
r = self._make_retriever(half_life=60)
|
||||
now = datetime.now(timezone.utc)
|
||||
for days in [0, 1, 15, 30, 45, 59, 60, 90, 365]:
|
||||
ts = (now - timedelta(days=days)).isoformat()
|
||||
boost = r._access_recency_boost(ts)
|
||||
assert 1.0 <= boost <= 1.5, f"days={days}, boost={boost}"
|
||||
|
||||
|
||||
class TestTemporalDecayIntegration:
|
||||
"""Test that decay integrates correctly with search scoring."""
|
||||
|
||||
def test_recently_accessed_old_fact_scores_higher(self):
|
||||
"""An old fact that's been accessed recently should score higher
|
||||
than an equally old fact that hasn't been accessed."""
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
store = MagicMock()
|
||||
r = FactRetriever(store=store, temporal_decay_half_life=60)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
old_date = (now - timedelta(days=120)).isoformat() # 2 half-lives old
|
||||
recent_access = (now - timedelta(days=10)).isoformat() # accessed 10 days ago
|
||||
old_access = (now - timedelta(days=200)).isoformat() # accessed 200 days ago
|
||||
|
||||
# Old fact, recently accessed
|
||||
decay1 = r._temporal_decay(old_date)
|
||||
boost1 = r._access_recency_boost(recent_access)
|
||||
effective1 = min(1.0, decay1 * boost1)
|
||||
|
||||
# Old fact, not recently accessed
|
||||
decay2 = r._temporal_decay(old_date)
|
||||
boost2 = r._access_recency_boost(old_access)
|
||||
effective2 = min(1.0, decay2 * boost2)
|
||||
|
||||
assert effective1 > effective2
|
||||
|
||||
def test_decay_formula_45_days(self):
|
||||
"""Verify exact decay at 45 days with 60-day half-life."""
|
||||
from plugins.memory.holographic.retrieval import FactRetriever
|
||||
r = FactRetriever(store=MagicMock(), temporal_decay_half_life=60)
|
||||
old = (datetime.now(timezone.utc) - timedelta(days=45)).isoformat()
|
||||
decay = r._temporal_decay(old)
|
||||
expected = math.pow(0.5, 45/60)
|
||||
assert abs(decay - expected) < 0.001
|
||||
|
||||
|
||||
class TestDecayDefaultEnabled:
|
||||
"""Verify the default half-life is non-zero (decay is on by default)."""
|
||||
|
||||
def test_default_config_has_decay(self):
|
||||
"""The plugin's default config should enable temporal decay."""
|
||||
from plugins.memory.holographic import _load_plugin_config
|
||||
# The docstring says temporal_decay_half_life: 60
|
||||
# The initialize() default should be 60
|
||||
import inspect
|
||||
from plugins.memory.holographic import HolographicMemoryProvider
|
||||
src = inspect.getsource(HolographicMemoryProvider.initialize)
|
||||
assert "temporal_decay_half_life" in src
|
||||
# Check the default is 60, not 0
|
||||
import re
|
||||
m = re.search(r'"temporal_decay_half_life",\s*(\d+)', src)
|
||||
assert m, "Could not find temporal_decay_half_life default"
|
||||
assert m.group(1) == "60", f"Default is {m.group(1)}, expected 60"
|
||||
@@ -137,78 +137,3 @@ class TestBackwardCompat:
|
||||
def test_tool_to_toolset_map(self):
|
||||
assert isinstance(TOOL_TO_TOOLSET_MAP, dict)
|
||||
assert len(TOOL_TO_TOOLSET_MAP) > 0
|
||||
|
||||
|
||||
class TestToolReturnTypeValidation:
|
||||
"""Poka-yoke: tool handlers must return JSON strings."""
|
||||
|
||||
def test_handler_returning_dict_is_wrapped(self, monkeypatch):
|
||||
"""A handler that returns a dict should be auto-wrapped to JSON string."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
# Register a bad handler that returns dict instead of str
|
||||
registry.register(
|
||||
name="__test_bad_dict",
|
||||
toolset="test",
|
||||
schema={"name": "__test_bad_dict", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: {"this is": "a dict not a string"},
|
||||
)
|
||||
result = handle_function_call("__test_bad_dict", {})
|
||||
parsed = json.loads(result)
|
||||
assert "output" in parsed
|
||||
assert "_type_warning" in parsed
|
||||
# Cleanup
|
||||
registry._tools.pop("__test_bad_dict", None)
|
||||
|
||||
def test_handler_returning_none_is_wrapped(self, monkeypatch):
|
||||
"""A handler that returns None should be auto-wrapped."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
registry.register(
|
||||
name="__test_bad_none",
|
||||
toolset="test",
|
||||
schema={"name": "__test_bad_none", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: None,
|
||||
)
|
||||
result = handle_function_call("__test_bad_none", {})
|
||||
parsed = json.loads(result)
|
||||
assert "_type_warning" in parsed
|
||||
registry._tools.pop("__test_bad_none", None)
|
||||
|
||||
def test_handler_returning_non_json_string_is_wrapped(self):
|
||||
"""A handler returning a plain string (not JSON) should be wrapped."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
registry.register(
|
||||
name="__test_bad_plain",
|
||||
toolset="test",
|
||||
schema={"name": "__test_bad_plain", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: "just a plain string, not json",
|
||||
)
|
||||
result = handle_function_call("__test_bad_plain", {})
|
||||
parsed = json.loads(result)
|
||||
assert "output" in parsed
|
||||
registry._tools.pop("__test_bad_plain", None)
|
||||
|
||||
def test_handler_returning_valid_json_passes_through(self):
|
||||
"""A handler returning valid JSON string passes through unchanged."""
|
||||
from tools.registry import registry
|
||||
from model_tools import handle_function_call
|
||||
import json
|
||||
|
||||
registry.register(
|
||||
name="__test_good",
|
||||
toolset="test",
|
||||
schema={"name": "__test_good", "description": "test", "parameters": {"type": "object", "properties": {}}},
|
||||
handler=lambda args, **kw: json.dumps({"status": "ok", "data": [1, 2, 3]}),
|
||||
)
|
||||
result = handle_function_call("__test_good", {})
|
||||
parsed = json.loads(result)
|
||||
assert parsed == {"status": "ok", "data": [1, 2, 3]}
|
||||
registry._tools.pop("__test_good", None)
|
||||
|
||||
@@ -144,8 +144,7 @@ class TestMemoryStoreReplace:
|
||||
def test_replace_no_match(self, store):
|
||||
store.add("memory", "fact A")
|
||||
result = store.replace("memory", "nonexistent", "new")
|
||||
assert result["success"] is True
|
||||
assert result["result"] == "no_match"
|
||||
assert result["success"] is False
|
||||
|
||||
def test_replace_ambiguous_match(self, store):
|
||||
store.add("memory", "server A runs nginx")
|
||||
@@ -178,8 +177,7 @@ class TestMemoryStoreRemove:
|
||||
|
||||
def test_remove_no_match(self, store):
|
||||
result = store.remove("memory", "nonexistent")
|
||||
assert result["success"] is True
|
||||
assert result["result"] == "no_match"
|
||||
assert result["success"] is False
|
||||
|
||||
def test_remove_empty_old_text(self, store):
|
||||
result = store.remove("memory", " ")
|
||||
|
||||
@@ -260,12 +260,8 @@ class MemoryStore:
|
||||
entries = self._entries_for(target)
|
||||
matches = [(i, e) for i, e in enumerate(entries) if old_text in e]
|
||||
|
||||
if not matches:
|
||||
return {
|
||||
"success": True,
|
||||
"result": "no_match",
|
||||
"message": f"No entry matched '{old_text}'. The search substring was not found in any existing entry.",
|
||||
}
|
||||
if len(matches) == 0:
|
||||
return {"success": False, "error": f"No entry matched '{old_text}'."}
|
||||
|
||||
if len(matches) > 1:
|
||||
# If all matches are identical (exact duplicates), operate on the first one
|
||||
@@ -314,12 +310,8 @@ class MemoryStore:
|
||||
entries = self._entries_for(target)
|
||||
matches = [(i, e) for i, e in enumerate(entries) if old_text in e]
|
||||
|
||||
if not matches:
|
||||
return {
|
||||
"success": True,
|
||||
"result": "no_match",
|
||||
"message": f"No entry matched '{old_text}'. The search substring was not found in any existing entry.",
|
||||
}
|
||||
if len(matches) == 0:
|
||||
return {"success": False, "error": f"No entry matched '{old_text}'."}
|
||||
|
||||
if len(matches) > 1:
|
||||
# If all matches are identical (exact duplicates), remove the first one
|
||||
@@ -457,30 +449,30 @@ def memory_tool(
|
||||
Returns JSON string with results.
|
||||
"""
|
||||
if store is None:
|
||||
return tool_error("Memory is not available. It may be disabled in config or this environment.", success=False)
|
||||
return json.dumps({"success": False, "error": "Memory is not available. It may be disabled in config or this environment."}, ensure_ascii=False)
|
||||
|
||||
if target not in ("memory", "user"):
|
||||
return tool_error(f"Invalid target '{target}'. Use 'memory' or 'user'.", success=False)
|
||||
return json.dumps({"success": False, "error": f"Invalid target '{target}'. Use 'memory' or 'user'."}, ensure_ascii=False)
|
||||
|
||||
if action == "add":
|
||||
if not content:
|
||||
return tool_error("Content is required for 'add' action.", success=False)
|
||||
return json.dumps({"success": False, "error": "Content is required for 'add' action."}, ensure_ascii=False)
|
||||
result = store.add(target, content)
|
||||
|
||||
elif action == "replace":
|
||||
if not old_text:
|
||||
return tool_error("old_text is required for 'replace' action.", success=False)
|
||||
return json.dumps({"success": False, "error": "old_text is required for 'replace' action."}, ensure_ascii=False)
|
||||
if not content:
|
||||
return tool_error("content is required for 'replace' action.", success=False)
|
||||
return json.dumps({"success": False, "error": "content is required for 'replace' action."}, ensure_ascii=False)
|
||||
result = store.replace(target, old_text, content)
|
||||
|
||||
elif action == "remove":
|
||||
if not old_text:
|
||||
return tool_error("old_text is required for 'remove' action.", success=False)
|
||||
return json.dumps({"success": False, "error": "old_text is required for 'remove' action."}, ensure_ascii=False)
|
||||
result = store.remove(target, old_text)
|
||||
|
||||
else:
|
||||
return tool_error(f"Unknown action '{action}'. Use: add, replace, remove", success=False)
|
||||
return json.dumps({"success": False, "error": f"Unknown action '{action}'. Use: add, replace, remove"}, ensure_ascii=False)
|
||||
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
|
||||
@@ -547,7 +539,7 @@ MEMORY_SCHEMA = {
|
||||
|
||||
|
||||
# --- Registry ---
|
||||
from tools.registry import registry, tool_error
|
||||
from tools.registry import registry
|
||||
|
||||
registry.register(
|
||||
name="memory",
|
||||
|
||||
Reference in New Issue
Block a user