import { eventBus } from './events.js'; import type { AgentHubEvent } from './events.js'; import { updateStatus } from '../core/services/statusService.js'; /** * Keep `.agenthub/status/latest.md` fresh. Agents are told (golden rule #2) to * read the status snapshot, but it was only regenerated on an explicit * `status --update` — so it drifted stale and misled agents (e.g. showing an * old task list). This subscribes to the in-process event bus and regenerates * the snapshot on every entity change, from both the REST and filesystem-watch * paths, debounced so a burst collapses to one write. * * Presence ('agent') events are ephemeral and don't affect status. Writing the * snapshot lives in `.agenthub/status/` — outside the watched entity dirs — so * it never feeds back into the watcher. */ const DEBOUNCE_MS = 300; export function startStatusAutoRefresh(cwd: string): () => void { let timer: NodeJS.Timeout | undefined; const onChange = (event: AgentHubEvent) => { if (event.type === 'agent') return; if (timer) clearTimeout(timer); timer = setTimeout(() => { timer = undefined; try { updateStatus(cwd); } catch { // best-effort — a failed status refresh must never break the server } }, DEBOUNCE_MS); }; eventBus.on('change', onChange); return () => { if (timer) clearTimeout(timer); eventBus.off('change', onChange); }; }