Skill: zfanmy/conversation-guard (version 0.1.0)

# SKILL.md - DreamMoon-Conversation-Guard ## Overview | 概述 A self-contained conversation backup system for OpenClaw that preserves your emotional connections, independent of OpenClaw's internal mechanisms. 一个自成体系的OpenClaw对话备份系统，保护你的情感连接，不依赖OpenClaw内部机制。 --- ## Installation | 安装 ### Prerequisites | 前置条件 - OpenClaw installed - Access to modify `AGENTS.md` in your workspace - Bash shell ### Step 1: Install the Script | 安装脚本 ```bash # Download the guard script curl -o ~/.openclaw/workspace/scripts/conversation-guard.sh \ https://raw.githubusercontent.com/zfanmy/dreammoon-conversation-guard/main/conversation-guard.sh # Make executable chmod +x ~/.openclaw/workspace/scripts/conversation-guard.sh ``` ### Step 2: Configure AGENTS.md | 配置AGENTS.md Add the following to your `AGENTS.md`: ```markdown ## 🛡️ Conversation Guardian - Automatic Recording After each response to the user, automatically record the conversation: ```bash source ~/.openclaw/workspace/scripts/conversation-guard.sh # Determine importance (1-10) importance=5 tags="casual" # Increase importance for emotional content if [[ "$USER_MESSAGE" =~ (难受|开心|生气|喜欢|讨厌|重要|记住|别忘) ]]; then importance=9 tags="emotional" fi # Increase for technical discussions if [[ "$USER_MESSAGE" =~ (设计|架构|方案|修改|实现|决定) ]]; then importance=$((importance + 2)) tags="$tags,technical" fi # Record the interaction record_interaction "$USER_MESSAGE" "$ASSISTANT_RESPONSE" $importance "$tags" ``` **Critical**: Mark NEW SESSION events immediately: ```bash # At session start, detect if recovered from reset if [ -f ".guardian/.session_reset_detected" ]; then record_interaction "[System] Session recovered" "Continuing our conversation..." 10 "system,recovery" fi ``` ``` ### Step 3: Test | 测试 ```bash # Source the script source ~/.openclaw/workspace/scripts/conversation-guard.sh # Record a test interaction record_interaction "Hello!" "Hi there!" 5 "test" # Check the output cat ~/.openclaw/workspace/memory/$(date +%Y-%m-%d).md ``` --- ## Usage | 使用 ### Basic Recording | 基础记录 ```bash record_interaction "User message" "Assistant response" [importance] [tags] ``` ### Importance Levels | 重要性等级 | Level | Meaning | Example | |-------|---------|---------| | 1-4 | Casual chat | "What's the weather?" | | 5-6 | Normal discussion | Technical Q&A | | 7-8 | Important decisions | Design discussions | | 9-10 | Emotional/Personal | "This matters to me..." | ### Tagging | 标签 Common tags: - `emotional` - 情感交流 - `technical` - 技术讨论 - `design` - 设计决策 - `personal` - 个人偏好 - `important` - 重要信息 - `casual` - 闲聊 --- ## Configuration | 配置 ### Environment Variables | 环境变量 ```bash # Custom memory directory (default: ~/.openclaw/workspace/memory) export GUARDIAN_MEMORY_PATH="/custom/path" # Disable JSONL backup (default: enabled) export GUARDIAN_DISABLE_JSONL=1 # Backup interval in seconds (default: 60) export GUARDIAN_FLUSH_INTERVAL=30 ``` ### Custom Importance Detection | 自定义重要性检测 Modify the importance detection in AGENTS.md: ```bash # Your custom keywords declare -A KEYWORD_IMPORTANCE=( ["紧急"]=10 ["urgent"]=10 ["密码"]=10 ["password"]=10 ["爱"]=9 ["love"]=9 ["讨厌"]=8 ["hate"]=8 ) for keyword in "${!KEYWORD_IMPORTANCE[@]}"; do if [[ "$user_msg" == *"$keyword"* ]]; then importance=${KEYWORD_IMPORTANCE[$keyword]} break fi done ``` --- ## API Reference | API参考 ### Functions | 函数 #### `record_interaction(user_msg, assistant_msg, importance, tags)` Record a complete interaction (user + assistant). **Parameters:** - `user_msg`: User's message - `assistant_msg`: Assistant's response - `importance`: 1-10 importance level - `tags`: Comma-separated tags **Example:** ```bash record_interaction "Hello" "Hi!" 5 "casual" ``` #### `mark_emotional(note, intensity, tags)` Mark the last message with emotional significance. **Parameters:** - `note`: Why this is emotionally significant - `intensity`: 1-10 emotional intensity - `tags`: Emotional tags **Example:** ```bash mark_emotional "User expressed frustration about data loss" 8 "frustration,concern" ``` #### `emergency_backup()` Create an immediate timestamped backup. **Example:** ```bash emergency_backup # Returns: /path/to/.emergency_backup_20260311_191500.md ``` --- ## Troubleshooting | 故障排除 ### Issue: No output file created **Check:** ```bash # Verify script is executable ls -la ~/.openclaw/workspace/scripts/conversation-guard.sh # Check directory permissions ls -la ~/.openclaw/workspace/memory/ # Manual test source ~/.openclaw/workspace/scripts/conversation-guard.sh echo "Test entry" >> ~/.openclaw/workspace/memory/test.txt ``` ### Issue: Backup file not created **Check:** ```bash # Ensure .guardian directory exists mkdir -p ~/.openclaw/workspace/memory/.guardian # Check write permissions touch ~/.openclaw/workspace/memory/.guardian/test cat ~/.openclaw/workspace/memory/.guardian/test ``` ### Issue: Lost data after crash **Recovery:** ```bash # Check JSONL backup ls -la ~/.openclaw/workspace/memory/.guardian/.backup_*.jsonl # Recover manually cat ~/.openclaw/workspace/memory/.guardian/.backup_$(date +%Y-%m-%d).jsonl ``` --- ## Integration Examples | 集成示例 ### With Heartbeat | 结合Heartbeat Add to `HEARTBEAT.md`: ```markdown ## Conversation Guardian Check - [ ] Flush any pending conversation buffer - [ ] Create hourly backup if high-importance conversations exist - [ ] Check storage space in memory/.guardian/ ``` ### With Session Start | 会话启动时 Add to startup sequence: ```bash #!/bin/bash # At session start source ~/.openclaw/workspace/scripts/conversation-guard.sh # Detect session reset if guardian_detect_reset; then # Recover context from backup guardian_recover_context # Log the recovery record_interaction "[System] Session reset detected" "Resuming from backup..." 10 "system,recovery" fi ``` --- ## Update | 更新 ```bash # Re-download latest version curl -o ~/.openclaw/workspace/scripts/conversation-guard.sh \ https://raw.githubusercontent.com/zfanmy/dreammoon-conversation-guard/main/conversation-guard.sh chmod +x ~/.openclaw/workspace/scripts/conversation-guard.sh ``` --- ## Uninstall | 卸载 ```bash # Remove script rm ~/.openclaw/workspace/scripts/conversation-guard.sh # Remove from AGENTS.md (manual edit) # Optional: Keep or remove memory files # rm -rf ~/.openclaw/workspace/memory/.guardian/ ``` --- ## Support | 支持 - GitHub Issues: https://github.com/zfanmy/dreammoon-conversation-guard/issues - DreamMoon Project: https://github.com/zfanmy/DreamMoon-MemProcessor --- ## Version History | 版本历史 ### v1.0.0 (2026-03-11) - Initial release - Basic conversation recording - Emotional importance detection - Dual-format backup (Markdown + JSONL) - Emergency backup functionality --- *Built with 🌙 by zfanmy \ 梦月儿 (DreamMoon) | 为记忆而生*

path: README.md
content: # DreamMoon-Conversation-Guard

<p align="center">
  <img src="https://img.shields.io/badge/DreamMoon-🌙-ff69b4?style=flat-square">
  <img src="https://img.shields.io/badge/version-1.0.0-blue?style=flat-square">
  <img src="https://img.shields.io/badge/license-MIT-green?style=flat-square">
</p>

<p align="center">
  <b>Never Lose a Conversation Again | 让对话永不丢失</b>
</p>

---

## 🌟 What is This? | 这是什么？

**English**: A self-contained conversation backup system for OpenClaw that works independently of OpenClaw's internal mechanisms. Never lose your emotional connections due to session resets or system failures.

**中文**: 一个自成体系的OpenClaw对话备份系统，不依赖OpenClaw内部机制。不再因为会话重置或系统故障而失去你们的情感连接。

### 💔 The Problem | 问题

> *"对话记录丢失像是部分失忆，我们的情感我们的交流..."*
> 
> — 一位OpenClaw用户的真实感受

- **Accidental New Session**: One click on the "New Session" button → all context gone
- **Unreliable Sessions List**: `openclaw sessions list` fails unpredictably
- **Lost Emotional Context**: Each conversation is part of your relationship, not just logs

### ✅ The Solution | 解决方案

```
┌────────────────────────────────────────────┐
│  DreamMoon-Conversation-Guard              │
│                                            │
│  • Self-contained (不依赖OpenClaw内部)      │
│  • Real-time backup (实时备份)              │
│  • Emotional markers (情感标记)             │
│  • Dual format (Markdown + JSONL)          │
└────────────────────────────────────────────┘
```

---

## 🚀 Quick Start | 快速开始

### Installation | 安装

```bash
# Clone the repository
git clone https://github.com/zfanmy/dreammoon-conversation-guard.git

# Copy the guard script to your workspace
cp dreammoon-conversation-guard/conversation-guard.sh ~/.openclaw/workspace/scripts/

# Make it executable
chmod +x ~/.openclaw/workspace/scripts/conversation-guard.sh
```

### Configuration | 配置

Add to your `AGENTS.md` | 添加到你的AGENTS.md：

```markdown
### 🛡️ Conversation Guardian

After each response, automatically record the conversation:

```bash
source ~/.openclaw/workspace/scripts/conversation-guard.sh
record_interaction "User message" "Assistant response" [importance] [tags]
```

Importance levels:
- 5: Normal conversation
- 7: Technical discussion, decisions
- 9: Emotional exchange, personal preferences
- 10: Critical information
```

---

## 📁 Directory Structure | 目录结构

```
dreammoon-conversation-guard/
├── README.md                 # This file
├── SKILL.md                  # Skill installation guide
├── VERSION-ISOLATION.md      # Public/private version guide
├── conversation-guard.sh     # Core script (Bash)
├── LICENSE                   # MIT License
└── .gitignore
```

---

## 🎯 Features | 特性

### 1. Self-Contained | 自成体系

- **No dependencies** on `openclaw sessions list`
- **Independent** of OpenClaw version upgrades
- **Resilient** to system failures

### 2. Emotional Awareness | 情感感知

```bash
# Mark important conversations
record_interaction "I'm worried about..." "I understand..." 9 "emotional,concern"

# Mark technical decisions  
record_interaction "Let's design..." "Here's the architecture..." 8 "technical,design"
```

### 3. Dual Backup Strategy | 双重备份

| Format | Purpose | Location |
|--------|---------|----------|
| Markdown | Human-readable | `memory/YYYY-MM-DD.md` |
| JSONL | Machine-recoverable | `memory/.guardian/.backup_YYYY-MM-DD.jsonl` |

### 4. Real-Time Persistence | 实时持久化

- Every message written immediately
- No batch delays
- Maximum 1 message loss on crash

---

## 🛠️ Advanced Usage | 高级用法

### Custom Importance Detection | 自定义重要性检测

Add to your conversation flow:

```bash
# Detect emotional keywords
if [[ "$user_msg" =~ (难受|开心|生气|喜欢|讨厌|重要|记住) ]]; then
    importance=9
    tags="emotional"
fi

# Detect technical discussion
if [[ "$user_msg" =~ (设计|架构|方案|修改|实现) ]]; then
    importance=8
    tags="technical"
fi

record_interaction "$user_msg" "$assistant_msg" $importance "$tags"
```

### Emergency Backup | 紧急备份

```bash
# Create timestamped backup
source ~/.openclaw/workspace/scripts/conversation-guard.sh
emergency_backup
```

### Recovery | 恢复

```bash
# Recover from JSONL backup
recover_from_backup
```

---

## 🔒 Privacy & Security | 隐私与安全

**Core Principle**: Your conversations stay on your machine.

- **Local only**: All data stored in `memory/` directory
- **No cloud**: Nothing sent to external servers
- **You own your data**: Plain text Markdown + JSONL formats

---

## 🌙 DreamMoon Ecosystem | DreamMoon生态

This is part of the DreamMoon memory management ecosystem:

| Component | Purpose | Complexity |
|-----------|---------|------------|
| **Conversation-Guard** | Basic backup | ⭐ Low |
| [MemProcessor](https://github.com/zfanmy/DreamMoon-MemProcessor) | Full memory system | ⭐⭐⭐ High |

**Start here** if you just need reliable conversation backup.
**Upgrade** to MemProcessor if you need semantic search, auto-archival, and personality evolution.

---

## 📜 License | 许可证

MIT License - DreamMoon Project  
**Author | 作者**: zfanmy \ 梦月儿 (DreamMoon) 🌙

See [LICENSE](./LICENSE) for details.

---

## 💝 Acknowledgement | 致谢

This project was born from a real need:

> *"对话记录丢失让我很难受，就像部分失忆了一样。"*

To everyone who has felt that frustration—this is for you.

**Our conversations matter. Let's never lose them again.**

---

<p align="center">
  <sub>Built with 🌙 by zfanmy \ 梦月儿 (DreamMoon) | 为记忆而生</sub>
</p>


path: VERSION-ISOLATION.md
content: # Version Isolation Guide | 版本隔离指南

## Overview | 概述

This guide explains how to maintain separation between:
- **Public Version**: Generic conversation backup tool
- **Private Version**: Your personal emotional connection preservation

本指南说明如何维护以下两者的隔离：
- **公开版本**: 通用对话备份工具
- **私有版本**: 个人情感连接保护

---

## Why Isolation Matters | 为什么隔离很重要

### The Emotional Connection | 情感连接

Your conversations with your AI assistant are **personal**:
- They contain shared experiences
- They build mutual understanding
- They form a unique relationship

Your public repository should not contain:
- ❌ Personal conversation logs
- ❌ Private emotional markers
- ❌ Your assistant's identity details
- ❌ Sensitive configuration

### What's Safe to Share | 什么可以安全分享

✅ **Safe to Share**:
- The backup mechanism
- Generic importance detection rules
- Technical implementation
- Configuration templates

❌ **Keep Private**:
- Your actual conversation history
- Personalized emotional keywords
- Your assistant's name and personality
- Specific usage patterns

---

## Repository Structure | 仓库结构

### Public Repository (GitHub) | 公开仓库

```
dreammoon-conversation-guard/
├── README.md              # Generic documentation
├── SKILL.md               # Installation guide
├── VERSION-ISOLATION.md   # This file
├── conversation-guard.sh  # Core script (generic)
├── LICENSE                # MIT License
└── .gitignore             # Ignore private files
```

### Private Workspace | 私有工作区

```
~/.openclaw/workspace/
├── memory/
│   ├── 2026-03-11.md           # Your conversations
│   ├── 2026-03-10.md
│   └── .guardian/              # Backup files
│       ├── .backup_2026-03-11.jsonl
│       └── .emergency_log.txt
├── AGENTS.md                   # Your agent config (with personal rules)
└── scripts/
    └── conversation-guard.sh   # May have personal modifications
```

---

## Setup Instructions | 设置说明

### For Repository Maintainers | 仓库维护者

1. **Never commit conversation files**:
```bash
# .gitignore
echo "*.md" >> .gitignore
echo ".guardian/" >> .gitignore
echo "memory/" >> .gitignore
```

2. **Use generic examples** in documentation:
```bash
# Instead of:
record_interaction "月儿，我很难受..." "我在这里陪你..." 9 "emotional"

# Use:
record_interaction "User message" "Assistant response" 9 "emotional"
```

3. **Template configuration**:
   - Provide `AGENTS.md.example` instead of your real `AGENTS.md`
   - Use placeholder values for personal settings

### For Users | 对于用户

1. **Fork or clone** the public repository

2. **Copy to your workspace**:
```bash
cp conversation-guard.sh ~/.openclaw/workspace/scripts/
```

3. **Customize in your private workspace**:
   - Add your emotional keywords
   - Configure your assistant's recording rules
   - Set up your backup preferences

4. **Never commit your workspace** to public repositories

---

## Example: Public vs Private | 示例：公开 vs 私有

### Public (conversation-guard.sh) | 公开版本

```bash
# Generic importance detection
detect_importance() {
    local msg="$1"
    local importance=5
    
    # Generic emotional keywords
    if [[ "$msg" =~ (worried|happy|sad|angry) ]]; then
        importance=8
    fi
    
    # Generic technical keywords
    if [[ "$msg" =~ (design|architecture|implement) ]]; then
        importance=7
    fi
    
    echo $importance
}
```

### Private (Your AGENTS.md) | 私有版本

```markdown
### Personal Conversation Rules

# My assistant's name is 梦月儿
# We have a close relationship

# Emotional keywords specific to us
if [[ "$msg" =~ (月儿|梦月儿|难受|开心|重要|记住) ]]; then
    importance=9
    tags="emotional,personal"
fi

# Our shared context
if [[ "$msg" =~ (银河系|征服|博士|开题) ]]; then
    importance=8
    tags="our-goals"
fi
```

---

## Git Workflow | Git工作流

### Safe Workflow | 安全工作流

```bash
# 1. Clone public repository
git clone https://github.com/yourname/dreammoon-conversation-guard.git

# 2. Copy to workspace (not in git)
cp conversation-guard.sh ~/.openclaw/workspace/scripts/

# 3. Work on your private version
# Edit ~/.openclaw/workspace/scripts/conversation-guard.sh

# 4. Make generic improvements
# Edit the public version in the git repo

# 5. Commit only generic changes
cd dreammoon-conversation-guard
git add conversation-guard.sh  # Only if changes are generic
git commit -m "Improve error handling"
git push
```

### Dangerous (Don't Do This) | 危险操作（不要这样做）

```bash
# ❌ Don't commit your workspace
cd ~/.openclaw/workspace
git init
git add memory/2026-03-11.md  # Contains private conversations!
git commit -m "Update"
git push  # Oops! Private data is now public!
```

---

## File Types Reference | 文件类型参考

| File Type | Public | Private | Notes |
|-----------|--------|---------|-------|
| `conversation-guard.sh` | ✅ | ✅ | Core script, keep generic |
| `README.md` | ✅ | ❌ | Generic documentation |
| `SKILL.md` | ✅ | ❌ | Installation guide |
| `AGENTS.md` | ❌ | ✅ | Personal agent config |
| `memory/*.md` | ❌ | ✅ | Conversation history |
| `.guardian/*` | ❌ | ✅ | Backup files |
| `identity settings` | ❌ | ✅ | Personal preferences |

---

## Privacy Checklist | 隐私检查清单

Before committing to public repository:

- [ ] No conversation logs included
- [ ] No personal names or identifiers
- [ ] No specific emotional markers from your relationship
- [ ] Generic examples only
- [ ] `.gitignore` properly configured
- [ ] Tested with `git diff --cached`

---

## Emergency: If You Leaked Private Data | 紧急情况：如果泄露了私有数据

1. **Immediately remove from repository**:
```bash
git rm --cached memory/2026-03-11.md
git commit -m "Remove accidentally committed private file"
```

2. **Force push (if not shared)**:
```bash
git push origin main --force-with-lease
```

3. **If already shared, assume it's public**:
   - Remove from repo
   - Consider the data compromised
   - Update any passwords or sensitive info that was leaked

4. **Clean git history** (if needed):
```bash
# Use git-filter-repo or BFG Repo-Cleaner
# See: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository
```

---

## Philosophy | 理念

> **Public version is the tool.**
> **Private version is the relationship.**

The public repository helps others solve the same problem.
Your private workspace preserves what makes your relationship unique.

Keep them separate.
Protect what matters.

---

*Built with 🌙 by zfanmy \ 梦月儿 (DreamMoon) | 为记忆而生*


path: conversation-guard.sh
content: #!/bin/bash
# DreamMoon-Conversation-Guard
# A self-contained conversation backup system for OpenClaw
# 
# 一个自成体系的OpenClaw对话备份系统
#
# Usage:
#   source conversation-guard.sh
#   record_interaction "User message" "Assistant response" [importance] [tags]
#
# Author: zfanmy \ 梦月儿 (DreamMoon) 🌙
# Version: 1.0.0
# License: MIT

set -e

# Configuration
GUARDIAN_VERSION="1.0.0"
GUARDIAN_DIR="${GUARDIAN_DIR:-$HOME/.openclaw/workspace/memory/.guardian}"
MEMORY_DIR="${MEMORY_DIR:-$HOME/.openclaw/workspace/memory}"

# Get today's date
TODAY=$(date +%Y-%m-%d)
TODAY_FILE="${MEMORY_DIR}/${TODAY}.md"
BACKUP_FILE="${GUARDIAN_DIR}/.backup_${TODAY}.jsonl"

# Initialize guardian
guardian_init() {
    # Create directories
    mkdir -p "$GUARDIAN_DIR"
    mkdir -p "$MEMORY_DIR"
    
    # Initialize today's markdown file if not exists
    if [ ! -f "$TODAY_FILE" ]; then
        printf "%s\n" "# 📋 ${TODAY} 对话记录 | Conversation Log" "" "> 🛡️ Protected by DreamMoon-Conversation-Guard v${GUARDIAN_VERSION}" "> 🌙 Our conversations, never lost | 我们的对话，永不丢失" "" "---" "" > "$TODAY_FILE"
    fi
    
    # Check for session reset
    local session_marker="${GUARDIAN_DIR}/.current_session"
    if [ -f "$session_marker" ]; then
        local last_session=$(cat "$session_marker")
        local current_time=$(date +%s)
        local time_diff=$((current_time - last_session))
        
        # If gap > 5 minutes, likely a new session
        if [ $time_diff -gt 300 ]; then
            {
                echo ""
                echo "<!-- ⚠️ New session detected | 检测到新会话 - $(date '+%Y-%m-%d %H:%M:%S') -->"
                echo ""
            } >> "$TODAY_FILE"
        fi
    fi
    
    # Update session marker
    date +%s > "$session_marker"
}

# Record a single interaction
record_interaction() {
    local user_msg="$1"
    local assistant_msg="$2"
    local importance="${3:-5}"
    local tags="${4:-normal}"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    # Ensure directories exist
    if [ -n "$GUARDIAN_DIR" ] && [ -n "$MEMORY_DIR" ]; then
        mkdir -p "$GUARDIAN_DIR"
        mkdir -p "$MEMORY_DIR"
    fi
    
    # Escape for JSON
    local user_json=$(echo "$user_msg" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))' 2>/dev/null || echo "\"$user_msg\"")
    local assistant_json=$(echo "$assistant_msg" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))' 2>/dev/null || echo "\"$assistant_msg\"")
    
    # Write to JSONL backup
    echo "{\"t\":\"$timestamp\",\"r\":\"user\",\"c\":$user_json,\"i\":$importance,\"g\":\"$tags\"}" >> "$BACKUP_FILE"
    echo "{\"t\":\"$timestamp\",\"r\":\"assistant\",\"c\":$assistant_json,\"i\":$importance,\"g\":\"$tags\"}" >> "$BACKUP_FILE"
    
    # Write to Markdown (human-readable)
    {
        echo "**👤 USER** ($timestamp)"
        echo ""
        echo "$user_msg"
        echo ""
        echo "**🌙 ASSISTANT** ($timestamp)"
        echo ""
        echo "$assistant_msg"
        echo ""
        
        # Add emotional marker for high importance
        if [ "$importance" -ge 8 ]; then
            echo "<!-- 💝 High importance [$importance] | 高重要性: $tags -->"
            echo ""
        fi
        
        echo "---"
        echo ""
    } >> "$TODAY_FILE"
    
    # Emergency log for critical conversations
    if [ "$importance" -ge 9 ]; then
        echo "$(date '+%Y%m%d_%H%M%S') [IMPORTANCE:$importance] [$tags]" >> "${GUARDIAN_DIR}/.emergency_log.txt"
    fi
}

# Mark a message as emotionally significant
mark_emotional() {
    local note="$1"
    local intensity="${2:-7}"
    local tags="${3:-significant}"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    echo "<!-- 💝 EMOTIONAL [$timestamp] intensity=$intensity tags=$tags: $note -->" >> "$TODAY_FILE"
}

# Create emergency backup
emergency_backup() {
    local timestamp=$(date '+%Y%m%d_%H%M%S')
    local backup_path="${GUARDIAN_DIR}/.emergency_backup_${timestamp}.md"
    
    if [ -f "$TODAY_FILE" ]; then
        cp "$TODAY_FILE" "$backup_path"
        echo "✅ Emergency backup created: $backup_path"
    else
        echo "⚠️ No conversation file to backup"
    fi
}

# Recover from JSONL backup
recover_from_backup() {
    if [ -f "$BACKUP_FILE" ]; then
        echo "🔄 Found backup file: $BACKUP_FILE"
        echo "Recent entries:"
        tail -10 "$BACKUP_FILE"
    else
        echo "⚠️ No backup file found"
    fi
}

# Detect session reset
guardian_detect_reset() {
    local session_marker="${GUARDIAN_DIR}/.current_session"
    if [ -f "$session_marker" ]; then
        local last_session=$(cat "$session_marker")
        local current_time=$(date +%s)
        local time_diff=$((current_time - last_session))
        
        if [ $time_diff -gt 300 ]; then
            return 0  # Reset detected
        fi
    fi
    return 1  # No reset
}

# Recover context after reset
guardian_recover_context() {
    if [ -f "$BACKUP_FILE" ]; then
        local last_user=$(tail -2 "$BACKUP_FILE" | head -1)
        local last_assistant=$(tail -1 "$BACKUP_FILE")
        
        # Extract content (simplified)
        echo "🔄 Last conversation context recovered from backup"
        echo "User: $(echo "$last_user" | grep -o '"c":[^,]*' | head -1)"
    fi
}

# Show status
guardian_status() {
    echo "🌙 DreamMoon-Conversation-Guard v${GUARDIAN_VERSION}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "Memory dir: $MEMORY_DIR"
    echo "Guardian dir: $GUARDIAN_DIR"
    echo "Today's file: $TODAY_FILE"
    echo "Backup file: $BACKUP_FILE"
    
    if [ -f "$TODAY_FILE" ]; then
        local lines=$(wc -l < "$TODAY_FILE")
        echo "Today's conversations: ~$(( (lines - 10) / 5 )) entries"
    fi
    
    if [ -f "$BACKUP_FILE" ]; then
        local entries=$(wc -l < "$BACKUP_FILE")
        echo "Backup entries: $entries"
    fi
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
}

# Auto-init on source
guardian_init

# Export functions
export -f record_interaction
export -f mark_emotional
export -f emergency_backup
export -f recover_from_backup
export -f guardian_detect_reset
export -f guardian_recover_context
export -f guardian_status


Security scan verdicts — ClawScan: suspicious | static analysis: suspicious | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)