-- =============================================================================
-- 007 - Document title and authorising role on doc_chunks.
--
-- WHY: ProcedureIdentity requires a title and an authorising role, and until
-- now neither was stored anywhere. The model was asked to supply them, read
-- them off whatever chunk retrieval happened to return, and returned "" when
-- the header chunk was not among them - which was most of the time, because
-- find_procedure ranked chunks by similarity to the question and a title block
-- does not resemble "how do I lift the interlock".
--
-- These belong in the row for the same reason doc_number and revision do: they
-- are facts about the controlled document, established once when a human
-- confirms the header at ingest, not something to re-derive per question from
-- whatever text happened to be retrieved.
--
-- Denormalised onto every chunk, exactly like doc_number/revision/
-- effective_date already are. The alternative is a documents table and a join
-- on the retrieval hot path; the corpus is small, ingestion replaces every
-- chunk of a source_file in one transaction (ingest.py rule 4), so the columns
-- cannot drift within a document.
--
-- NOT INCLUDED: controlled_copy_location. That is a fact about the site's
-- document management system, not about any one document - it would be the
-- same string on every row. It lives in CONTROLLED_COPY_LOCATION in
-- ~/ai/api.env instead. Letting the model invent it was how an operator could
-- be told to fetch a controlled copy from a place that does not exist.
--
-- Existing rows get NULL and keep working: citation() falls back to
-- section_title and then to source_file, which is what it did before. Re-run
-- `ai-ingest --all` to populate them.
-- =============================================================================

ALTER TABLE doc_chunks ADD COLUMN IF NOT EXISTS doc_title        text;
ALTER TABLE doc_chunks ADD COLUMN IF NOT EXISTS authorising_role text;

COMMENT ON COLUMN doc_chunks.doc_title IS
    'Document title from the confirmed header. NULL for rows ingested before '
    'migration 007; re-ingest to populate.';
COMMENT ON COLUMN doc_chunks.authorising_role IS
    'Role that authorises work under this document, from the confirmed header. '
    'Advisory only - it does not grant anything and is not an authorisation '
    'check.';

-- ingest_rw already holds INSERT/DELETE on doc_chunks, so no grant changes.
-- agent_ro already holds SELECT on the table, which covers new columns.
