clawdie-ai/scripts/memory/memory-hydrate-pg.sh

135 lines
2.8 KiB
Bash
Executable file

#!/usr/bin/env bash
# memory-hydrate-pg.sh — Generate MEMORY.md from ai_brain database
#
# Usage:
# ./memory-hydrate-pg.sh [output-path]
#
# Default output: stdout (pipe to file or use argument)
# Example:
# ./memory-hydrate-pg.sh /path/to/MEMORY.md
. "$(dirname "$0")/common.sh"
OUTPUT="${1:-}"
# ── Gather data ──
TOTAL_MEMORIES=$(pg -c "SELECT count(*) FROM memories;")
TOTAL_CHUNKS=$(pg -c "SELECT count(*) FROM memory_chunks;")
DISPLAY_DATE_SQL=$(pg_display_date_expr "created_at")
# High-importance memories (importance >= 4)
IMPORTANT=$(pg -c "
SELECT '- ' || left(summary, 120) ||
CASE WHEN length(summary) > 120 THEN '...' ELSE '' END ||
' (' || ${DISPLAY_DATE_SQL} || ', imp=' || importance || ')'
FROM memories
WHERE importance >= 4
ORDER BY importance DESC, created_at DESC
LIMIT 15;
")
# Recent memories (last 10, any importance)
RECENT=$(pg -c "
SELECT '- ' || left(summary, 120) ||
CASE WHEN length(summary) > 120 THEN '...' ELSE '' END ||
' (' || ${DISPLAY_DATE_SQL} || ', imp=' || importance || ')'
FROM memories
ORDER BY created_at DESC
LIMIT 10;
")
# Top topics (most frequently used)
TOP_TOPICS=$(pg -c "
SELECT '- **' || topic || '** (' || cnt || ' memories)'
FROM (
SELECT unnest(topics) AS topic, count(*) AS cnt
FROM memories
GROUP BY topic
ORDER BY cnt DESC
LIMIT 10
) t;
")
# Key decisions (from the decisions array field)
DECISIONS=$(pg -c "
SELECT '- ' || decision
FROM (
SELECT DISTINCT unnest(decisions) AS decision
FROM memories
WHERE array_length(decisions, 1) > 0
ORDER BY decision
LIMIT 15
) d;
")
# Key facts
KEY_FACTS=$(pg -c "
SELECT '- ' || fact
FROM (
SELECT DISTINCT unnest(key_facts) AS fact
FROM memories
WHERE array_length(key_facts, 1) > 0
ORDER BY fact
LIMIT 15
) f;
")
# ── Generate Markdown ──
generate() {
cat <<HEADER
# Clawdie Memory (auto-generated)
> Hydrated from \`ai_brain\` on $(format_display_timestamp_now)
> Total: $TOTAL_MEMORIES memories, $TOTAL_CHUNKS chunks
HEADER
if [ -n "$IMPORTANT" ]; then
cat <<SECTION
## Important Memories
$IMPORTANT
SECTION
fi
if [ -n "$DECISIONS" ]; then
cat <<SECTION
## Key Decisions
$DECISIONS
SECTION
fi
if [ -n "$KEY_FACTS" ]; then
cat <<SECTION
## Key Facts
$KEY_FACTS
SECTION
fi
if [ -n "$TOP_TOPICS" ]; then
cat <<SECTION
## Top Topics
$TOP_TOPICS
SECTION
fi
if [ -n "$RECENT" ]; then
cat <<SECTION
## Recent Memories
$RECENT
SECTION
fi
}
if [ -n "$OUTPUT" ]; then
generate > "$OUTPUT"
echo "Hydrated MEMORY.md → $OUTPUT ($TOTAL_MEMORIES memories)" >&2
else
generate
fi