#!/usr/bin/env -S npx tsx /** * Watcher — M3 Bridge. * * Watches ~/.claude/sessions/.md for changes. When an agent writes * its end-of-session handoff (done/next/tests/todos/health), this process * emits a `worker.idle` event into the JSONL event log so the Brain learns * about the run without modifying the agent's stop-hook scripts. * * This is deliberately observer-only: * - existing scripts/fleetcrown-daemon.sh + scripts/agent-hook-bridge.sh * keep running unchanged * - existing /tmp/agent-* sentinels keep being written * - the new Brain just gets a parallel view via the JSONL log * * M4 starts phasing out the legacy paths once this proves stable. * * Run: npx tsx home/watcher.ts * Verify: edit any ~/.claude/sessions/*.md (or wait for a real agent to * finish) and tail ~/./events.jsonl */ import fs from "node:fs"; import path from "node:path"; import os from "node:os"; import { APP_NAME, APP_SLUG } from "@/config/brand"; import { appendEvent } from "./emit"; import { loadProjects, projectsConfPath } from "./projects"; import type { Handoff } from "@/lib/events"; // Library vs CLI gate. // When required/imported as a module (or called with --start from desktop main), // we export startWatcher() and do not print+exit. // Direct `npx tsx home/watcher.ts` (no args) prints usage and exits. // --self-test runs the pure parser tests. const isDirectCli = import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith("watcher.ts"); if (isDirectCli && !process.argv.includes("--start") && !process.argv.includes("--self-test")) { console.log(`${APP_NAME} watcher — Bridge layer of the home/ stack. Watches ~/.claude/sessions/*.md and emits worker.idle events into ~/.${APP_SLUG}/events.jsonl. Usage: npx tsx home/watcher.ts --start (boot the watcher) npx tsx home/watcher.ts --self-test (run inline tests, no I/O) Env: APP_SESSIONS_DIR override sessions dir (default ~/.claude/sessions)`); process.exit(0); } // Override via APP_SESSIONS_DIR for testing — production tails Claude's real dir. const SESSIONS_DIR = process.env.APP_SESSIONS_DIR ?? path.join(os.homedir(), ".claude", "sessions"); /** Drop changes smaller than this (handles editor save-during-typing). */ const DEBOUNCE_MS = 250; // ── Parse the session.md handoff format ────────────────────────────────────── // Format (per project CLAUDE.md): // status: # 'ready' = done, auto-inject may fire // done: // next: // tests: // todos: TODOs // health: const FIELDS = ["status", "done", "next", "tests", "todos", "health"] as const; function parseHandoff(content: string): Handoff { const result: Record = {}; for (const field of FIELDS) { const m = content.match(new RegExp(`^${field}:\\s*(.*?)\\s*$`, "m")); result[field] = m?.[1] ?? ""; } return result as Handoff; } // ── Watcher state ──────────────────────────────────────────────────────────── /** Last-seen mtime per session file. Skips duplicate fs.watch fires. */ const lastMtime = new Map(); const pendingFlush = new Map(); /** * Lowercase project names from agent-projects.conf, loaded at boot. Anything * outside this set (Tab #1.md, Logo.md, ad-hoc scratch sessions) is ignored * so the brain's state stays a curated view, not a junk drawer. User * restarts the watcher after editing the conf file. */ let registeredLower: Set = new Set(); function tabFromFilename(filename: string): string | null { if (!filename.endsWith(".md")) return null; return filename.slice(0, -3); } /** Skip-emit reasons surfaced via console for first-run debuggability. */ const skipLogged = new Set(); function logSkipOnce(filename: string, reason: string) { if (skipLogged.has(filename)) return; skipLogged.add(filename); console.log(`[watcher] skipping ${filename} — ${reason}`); } /** * Subscriber called in addition to the JSONL append whenever a registered * project's session.md flips to a complete handoff. Lets embedders (desktop * Fleet Runner) surface OS notifications without re-tailing the event log. * Errors in the subscriber are swallowed so a bad callback can't break the * event-log path — the log remains the authoritative source. */ export type OnIdle = (event: { project: string; handoff: Handoff }) => void; let onIdleSubscriber: OnIdle | null = null; function readAndEmit(filename: string) { const tab = tabFromFilename(filename); if (!tab) return; // Filter to registered projects only — strips scratch tabs like Tab #1.md // and prevents the brain's state map from accumulating ad-hoc entries. if (!registeredLower.has(tab.toLowerCase())) { logSkipOnce(filename, `not in ${projectsConfPath()}`); return; } const filePath = path.join(SESSIONS_DIR, filename); let stat: fs.Stats; try { stat = fs.statSync(filePath); } catch { return; } if (!stat.isFile()) return; const mtime = stat.mtimeMs; if ((lastMtime.get(filename) ?? 0) === mtime) return; lastMtime.set(filename, mtime); let content: string; try { content = fs.readFileSync(filePath, "utf8"); } catch { return; } const handoff = parseHandoff(content); // A session.md file always contains all 5 fields once the agent writes a // proper handoff. Empty/half-written files (mid-edit) get skipped so we // don't emit a no-signal event. if (!handoff.done && !handoff.next && !handoff.health) return; appendEvent({ kind: "worker.idle", project: tab, handoff, }); console.log(`[watcher] worker.idle ${tab} · ${handoff.done.slice(0, 60)}…`); if (onIdleSubscriber) { try { onIdleSubscriber({ project: tab, handoff }); } catch (e) { console.warn(`[watcher] onIdle subscriber threw: ${(e as Error).message}`); } } } function scheduleFlush(filename: string) { const existing = pendingFlush.get(filename); if (existing) clearTimeout(existing); pendingFlush.set(filename, setTimeout(() => { pendingFlush.delete(filename); readAndEmit(filename); }, DEBOUNCE_MS)); } // ── Boot ───────────────────────────────────────────────────────────────────── export function startWatcher(opts: { onIdle?: OnIdle } = {}): { close: () => void } { onIdleSubscriber = opts.onIdle ?? null; if (!fs.existsSync(SESSIONS_DIR)) { console.error(`[watcher] ${SESSIONS_DIR} does not exist — is Claude installed?`); // In library mode (desktop) we don't want to kill the whole process. // Return a no-op closer; caller can decide to surface to user. return { close: () => { onIdleSubscriber = null; } }; } // Load the registry. Empty registry isn't fatal — it just means nothing // will ever pass the filter; first run gets a clear log line. const projects = loadProjects(); registeredLower = new Set(Array.from(projects.keys())); // Seed lastMtime from existing files without emitting — only react to changes // from this process forward. (We don't want every boot to re-emit the last // handoff of every project.) for (const file of fs.readdirSync(SESSIONS_DIR)) { if (!file.endsWith(".md")) continue; try { const stat = fs.statSync(path.join(SESSIONS_DIR, file)); lastMtime.set(file, stat.mtimeMs); } catch { /* file deleted between readdir and stat — skip */ } } console.log(`[watcher] ${APP_NAME} bridge watching ${SESSIONS_DIR}`); console.log(`[watcher] registry: ${registeredLower.size} project(s) from ${projectsConfPath()}`); console.log(`[watcher] seeded ${lastMtime.size} session files; emitting on change`); console.log(`[watcher] events → ~/.${APP_SLUG}/events.jsonl`); if (registeredLower.size === 0) { console.log(`[watcher] WARN: empty registry — no session.md changes will emit. Add entries to ${projectsConfPath()}.`); } const w = fs.watch(SESSIONS_DIR, (eventType, filename) => { if (!filename) return; if (eventType !== "change" && eventType !== "rename") return; scheduleFlush(filename); }); w.on("error", (err) => console.error("[watcher] fs.watch error:", err)); const close = () => { try { w.close(); } catch { /* ignore */ } for (const t of pendingFlush.values()) clearTimeout(t); pendingFlush.clear(); onIdleSubscriber = null; }; // Only install process signal handlers when running as the direct CLI process. // When embedded (desktop main), the app owns lifecycle and will call close(). if (isDirectCli) { const shutdown = (sig: string) => { console.log(`[watcher] ${sig} — shutting down`); close(); process.exit(0); }; process.on("SIGINT", () => shutdown("SIGINT")); process.on("SIGTERM", () => shutdown("SIGTERM")); } return { close }; } // ── Self-test ──────────────────────────────────────────────────────────────── // Run with: npx tsx home/watcher.ts --self-test // Pure unit tests for the parsers — no fs.watch, no real session dir. function selfTest() { type Case = { name: string; run: () => boolean }; const cases: Case[] = [ { name: "parseHandoff extracts all five fields from a well-formed session.md", run: () => { const h = parseHandoff([ "done: Built thing X", "next: Test thing X", "tests: 3 pass · 0 fail", "todos: 0 TODOs", "health: good", "", ].join("\n")); return h.done === "Built thing X" && h.next === "Test thing X" && h.tests === "3 pass · 0 fail" && h.todos === "0 TODOs" && h.health === "good"; }, }, { name: "parseHandoff handles missing fields gracefully (empty string default)", run: () => { const h = parseHandoff("done: only this one\n"); return h.done === "only this one" && h.next === "" && h.health === ""; }, }, { name: "parseHandoff trims trailing whitespace from values", run: () => { const h = parseHandoff("health: good \n"); return h.health === "good"; }, }, { name: "parseHandoff doesn't get fooled by field names embedded inside other values", run: () => { // "done: implementing next: foo behavior" — next regex shouldn't // match because the line starts with 'done:', not 'next:'. const h = parseHandoff([ "done: implementing next: foo behavior", "next: actually do it", "", ].join("\n")); return h.done === "implementing next: foo behavior" && h.next === "actually do it"; }, }, { name: "parseHandoff returns all-empty Handoff for a blank session.md", run: () => { const h = parseHandoff(""); return h.done === "" && h.next === "" && h.tests === "" && h.todos === "" && h.health === ""; }, }, { name: "tabFromFilename strips the .md extension", run: () => tabFromFilename("FleetCrown.md") === "FleetCrown", }, { name: "tabFromFilename returns null for non-.md files", run: () => tabFromFilename("README.txt") === null && tabFromFilename("noextension") === null, }, { name: "tabFromFilename preserves multi-word tab names verbatim", run: () => tabFromFilename("Tab #1.md") === "Tab #1" && tabFromFilename("Revamp-Info.md") === "Revamp-Info", }, ]; let pass = 0, fail = 0; for (const c of cases) { if (c.run()) { console.log(` ✓ ${c.name}`); pass++; } else { console.log(` ✗ ${c.name}`); fail++; } } console.log(`\n${pass}/${pass + fail} passed`); if (fail > 0) process.exit(1); } if (process.argv.includes("--self-test")) { selfTest(); } else if (isDirectCli || process.argv.includes("--start")) { startWatcher(); } // Also export the pure helpers so embedders (desktop) or tests can use them directly if needed. export { parseHandoff, tabFromFilename, readAndEmit };