-- KB spine: document_summary — summaries + tags per document, half-product of compilation
-- Additive: does not modify 001_envelope.sql, 002_chunks.sql, or 003_chunk_model_key.sql.
-- Version: 004 — document_summary (module 5, phase 3, plan §4)
--
-- 1:N to envelope by model: the same envelope can carry summaries from multiple models
-- (pilot A/B: API vs local GPU); retrieval selects a model via config.

CREATE TABLE IF NOT EXISTS document_summary (
    id              BIGSERIAL   PRIMARY KEY,
    envelope_id     TEXT        NOT NULL REFERENCES envelope(id) ON DELETE CASCADE,
    summary         TEXT        NOT NULL,
    tags            JSONB       NOT NULL DEFAULT '[]',
    model           TEXT        NOT NULL,          -- model that WROTE the summary
    embedding       VECTOR(1024),                  -- NULL until embedded
    embedding_model TEXT,                          -- embedding model (bge-m3); NULL with embedding
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (envelope_id, model)
);

CREATE INDEX IF NOT EXISTS document_summary_envelope_idx
    ON document_summary (envelope_id);
CREATE INDEX IF NOT EXISTS document_summary_embedding_hnsw_idx
    ON document_summary USING hnsw (embedding vector_cosine_ops);
