-- Per-thread heartbeat for daemon liveness visibility.
--
-- Each daemon thread (main, advice, rules-sync, jobs) updates its own
-- row roughly every iteration. Dashboard reads this to render daemon
-- status — green if recent, yellow if stale, red if very stale or
-- missing. This lets the user see "main is alive but jobs thread is
-- dead" rather than just "PID exists".

create table if not exists public.worker_heartbeat (
    client_id     text        not null,
    thread        text        not null,
    last_beat_at  timestamptz not null default now(),
    primary key (client_id, thread)
);

alter table public.worker_heartbeat enable row level security;

drop policy if exists "auth read heartbeat" on public.worker_heartbeat;
create policy "auth read heartbeat"
    on public.worker_heartbeat
    for select
    to authenticated
    using (true);

-- Daemon writes via service-role which bypasses RLS.

alter publication supabase_realtime add table public.worker_heartbeat;
