-- 记忆管理(旗舰版):支持用户个人记忆/部门记忆/全局记忆的多层记忆集合,
-- 内容向量化后按语义召回(与知识库共用 Ollama embedding);支持向其他
-- 用户授权(shared_with);按重要度与最近访问时间做衰减清理。
CREATE TABLE IF NOT EXISTS gateway.memory_entries (
    id uuid PRIMARY KEY,
    owner_kind text NOT NULL CHECK (owner_kind IN ('user', 'department', 'global')),
    owner_id text NOT NULL DEFAULT '',
    category text NOT NULL DEFAULT 'general',
    content text NOT NULL,
    importance int NOT NULL DEFAULT 5 CHECK (importance BETWEEN 1 AND 10),
    embedding vector(1024),
    shared_with uuid[] NOT NULL DEFAULT '{}',
    source text NOT NULL DEFAULT '',
    last_accessed_at timestamptz,
    created_by uuid,
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
);

CREATE INDEX IF NOT EXISTS memory_entries_owner_idx
    ON gateway.memory_entries (owner_kind, owner_id, created_at DESC);
CREATE INDEX IF NOT EXISTS memory_entries_shared_idx
    ON gateway.memory_entries USING gin (shared_with);
CREATE INDEX IF NOT EXISTS memory_entries_vector_idx
    ON gateway.memory_entries USING hnsw (embedding vector_cosine_ops);
