#!/bin/bash
# sync-memory-context.sh
# Syncs ~/.agents/memory/CURRENT.md into AGENTS.md's memory section
# Run this on heartbeat or daily cron

WORKSPACE="${CLAWDBOT_WORKSPACE:-$HOME/clawd}"
AGENTS_FILE="$WORKSPACE/AGENTS.md"
MEMORY_SOURCE="$HOME/.agents/memory/CURRENT.md"
MARKER_START="<!-- MEMORY_CONTEXT_START -->"
MARKER_END="<!-- MEMORY_CONTEXT_END -->"

# Check if memory source exists
if [[ ! -f "$MEMORY_SOURCE" ]]; then
    echo "Memory source not found: $MEMORY_SOURCE"
    exit 0
fi

# Read memory content
MEMORY_CONTENT=$(cat "$MEMORY_SOURCE")

# Check if AGENTS.md exists
if [[ ! -f "$AGENTS_FILE" ]]; then
    echo "AGENTS.md not found: $AGENTS_FILE"
    exit 1
fi

# Read current AGENTS.md
AGENTS_CONTENT=$(cat "$AGENTS_FILE")

# Build the new memory section
NEW_SECTION="$MARKER_START
## Memory Context (auto-synced)

$MEMORY_CONTENT
$MARKER_END"

# Check if markers already exist
if grep -q "$MARKER_START" "$AGENTS_FILE"; then
    # Replace existing section using perl for multi-line replacement
    perl -i -0pe "s/$MARKER_START.*?$MARKER_END/$MARKER_START\n## Memory Context (auto-synced)\n\n$MEMORY_CONTENT\n$MARKER_END/s" "$AGENTS_FILE" 2>/dev/null
    
    # If perl failed, use a different approach
    if [[ $? -ne 0 ]]; then
        # Create temp file with new content
        awk -v start="$MARKER_START" -v end="$MARKER_END" -v new="$NEW_SECTION" '
            $0 ~ start { skip=1; print new; next }
            $0 ~ end { skip=0; next }
            !skip { print }
        ' "$AGENTS_FILE" > "$AGENTS_FILE.tmp" && mv "$AGENTS_FILE.tmp" "$AGENTS_FILE"
    fi
    echo "Updated memory section in AGENTS.md"
else
    # Append new section at end of file
    echo "" >> "$AGENTS_FILE"
    echo "$NEW_SECTION" >> "$AGENTS_FILE"
    echo "Added memory section to AGENTS.md"
fi
