File size: 5,989 Bytes
ed537ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
-- WS-1 Three-tier memory β€” run in Supabase SQL editor
-- Safe to re-run (all statements are idempotent).

-- ─────────────────────────────────────────────────────────────
-- 1. Episodic layer: one row per conversation session
-- ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS memory_episodes (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id         UUID REFERENCES profiles(id) ON DELETE CASCADE,
  conversation_id UUID REFERENCES ai_conversations(id) ON DELETE SET NULL,
  summary         TEXT NOT NULL,
  embedding       VECTOR(384),
  importance      FLOAT DEFAULT 1.0,
  consolidated    BOOLEAN DEFAULT FALSE,
  created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_episodes_user_created
  ON memory_episodes(user_id, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_episodes_embedding
  ON memory_episodes USING ivfflat (embedding vector_cosine_ops)
  WITH (lists = 20);

CREATE UNIQUE INDEX IF NOT EXISTS idx_episodes_conv
  ON memory_episodes(conversation_id)
  WHERE conversation_id IS NOT NULL;

-- ─────────────────────────────────────────────────────────────
-- 2. Semantic layer: consolidated, long-lived user facts
-- ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS user_facts (
  id                  UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id             UUID REFERENCES profiles(id) ON DELETE CASCADE,
  fact                TEXT NOT NULL,
  embedding           VECTOR(384),
  importance          FLOAT DEFAULT 1.0,
  source_episode_ids  UUID[] DEFAULT '{}',
  consolidated_at     TIMESTAMPTZ DEFAULT NOW(),
  last_reinforced_at  TIMESTAMPTZ DEFAULT NOW(),
  access_count        INT DEFAULT 0
);

CREATE INDEX IF NOT EXISTS idx_facts_user
  ON user_facts(user_id);

CREATE INDEX IF NOT EXISTS idx_facts_embedding
  ON user_facts USING ivfflat (embedding vector_cosine_ops)
  WITH (lists = 10);

-- ─────────────────────────────────────────────────────────────
-- 3. Decay-weighted retrieval across both tables
--
--    score = cosine_sim(q, m) Γ— exp(βˆ’Ξ» Γ— age_days) Γ— importance
--
--    Ξ»_ep   = 0.05  β†’ half-life β‰ˆ 14 days  (fresh episodes decay faster)
--    Ξ»_fact = 0.005 β†’ half-life β‰ˆ 140 days (facts persist much longer)
--
--    Cites: MemGPT (Packer 2023), generative-agents memory-stream (Park 2023)
-- ─────────────────────────────────────────────────────────────
CREATE OR REPLACE FUNCTION match_memory(
  p_user_id       UUID,
  query_embedding VECTOR(384),
  lambda_ep       FLOAT DEFAULT 0.05,
  lambda_fact     FLOAT DEFAULT 0.005,
  match_count     INT   DEFAULT 5
)
RETURNS TABLE (
  id         UUID,
  source     TEXT,
  content    TEXT,
  importance FLOAT,
  age_days   FLOAT,
  score      FLOAT
)
LANGUAGE sql STABLE AS $$
  SELECT
    id,
    'episode'::TEXT AS source,
    summary         AS content,
    importance,
    EXTRACT(EPOCH FROM (NOW() - created_at)) / 86400.0 AS age_days,
    (1 - (embedding <=> query_embedding))
      * EXP(-lambda_ep * EXTRACT(EPOCH FROM (NOW() - created_at)) / 86400.0)
      * importance AS score
  FROM memory_episodes
  WHERE user_id = p_user_id
    AND consolidated = FALSE
    AND embedding IS NOT NULL

  UNION ALL

  SELECT
    id,
    'fact'::TEXT AS source,
    fact         AS content,
    importance,
    EXTRACT(EPOCH FROM (NOW() - consolidated_at)) / 86400.0 AS age_days,
    (1 - (embedding <=> query_embedding))
      * EXP(-lambda_fact * EXTRACT(EPOCH FROM (NOW() - consolidated_at)) / 86400.0)
      * importance AS score
  FROM user_facts
  WHERE user_id = p_user_id
    AND embedding IS NOT NULL

  ORDER BY score DESC
  LIMIT match_count;
$$;

-- ─────────────────────────────────────────────────────────────
-- 4. Helper: increment fact access_count atomically
-- ─────────────────────────────────────────────────────────────
CREATE OR REPLACE FUNCTION increment_fact_access(p_fact_id UUID)
RETURNS void LANGUAGE sql SECURITY DEFINER AS $$
  UPDATE user_facts SET access_count = access_count + 1 WHERE id = p_fact_id;
$$;

-- ─────────────────────────────────────────────────────────────
-- 5. RLS policies
-- ─────────────────────────────────────────────────────────────
ALTER TABLE memory_episodes ENABLE ROW LEVEL SECURITY;
ALTER TABLE user_facts      ENABLE ROW LEVEL SECURITY;

-- Users can only see and delete their own rows; writes go through service role
CREATE POLICY "episodes_select" ON memory_episodes FOR SELECT USING (auth.uid() = user_id);
CREATE POLICY "episodes_delete" ON memory_episodes FOR DELETE USING (auth.uid() = user_id);

CREATE POLICY "facts_select" ON user_facts FOR SELECT USING (auth.uid() = user_id);
CREATE POLICY "facts_delete" ON user_facts FOR DELETE USING (auth.uid() = user_id);