-- kb_apply prerequisites -- run ONCE as the postgres superuser at deploy time.
--
-- Stage 2 of the KB apply pipeline (scripts/apply_proposal.py) connects as the
-- narrow kb_apply role and stamps applied_by_agent_id as a real FK. The FK is
-- resolved from public.agents by handle, so before the first apply:
--   1. a 'kb-apply' service-agent row must exist (one-time bootstrap fixture),
--   2. kb_apply needs SELECT on public.agents to resolve it (never INSERT),
--   3. the one-active-strategy invariant must be enforced by a unique index.
--
-- Every statement is idempotent; re-running the file is a no-op. It grants no
-- write on public.agents to kb_apply -- the service-agent row is written here,
-- once, by the superuser, and the runtime role only ever reads it.

begin;

-- 1. Service-agent fixture. This INSERT is the one-time superuser bootstrap;
--    kb_apply itself never gains INSERT on public.agents (SELECT only, below).
insert into public.agents (id, handle, kind)
values ('44444444-4444-4444-4444-444444444444', 'kb-apply', 'service')
on conflict (handle) do nothing;

-- 2. Allow the apply tool to resolve applied_by_agent_id. Read-only, no INSERT.
grant select on public.agents to kb_apply;

-- 3. Enforce "one active strategy per agent" at the database. Already present on
--    current prod as one_active_strategy_per_agent; IF NOT EXISTS documents and
--    guarantees the dependency for fresh environments (no-op where it exists).
create unique index if not exists one_active_strategy_per_agent
    on public.strategies (agent_id) where active;

commit;
