Files
loki/home/watcher.ts
CatoandClaude Fable 5.1 95c40a9cd8 refactor: rename the product from FleetCrown to Loki (#695)
The product, its assistant, the repo, the host and every unit on the box now
share one name. 638 files, ~3,000 mentions: UI copy, config, env keys
(FLEETCROWN_* -> LOKI_*), systemd units (fleetcrown-* -> loki-*), docs,
articles, the deploy workflow other repos reuse, and nine file names.

- Three article slugs carried the old name and had been shared; permanent
  redirects keep those links alive (next.config.ts).
- test-no-retired-name.sh now also forbids the old product name across the
  whole repo, so the rename cannot creep back through templates and examples.
- ASSISTANT_STACK collapses the product and the assistant into one entry,
  because they are now the same name.

Infra was cut over ahead of this merge: /opt/loki, loki-* units, the `loki`
database and role, loki.orangecat.ch (old host 308s to it; /api, /widget,
/embed keep proxying), GitHub repos bitbaum/loki and bitbaum/loki-releases.
The Resend sending domain stays fleetcrown.orangecat.ch until the new domain
is verified in DNS.


Claude-Session: https://claude.ai/code/session_016YJVAanfj8keVSXyZnTemh

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 16:13:10 -07:00

346 lines
12 KiB
TypeScript

#!/usr/bin/env -S npx tsx
/**
* Watcher — M3 Bridge.
*
* Watches ~/.loki/sessions/<TAB>.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 orchestrator
* learns about the run without modifying the agent's stop hooks.
*
* This is deliberately observer-only — it never injects or mutates a session,
* it only derives a `worker.idle` signal from session-file changes. Fleet
* Runner embeds this watcher; the worker (worker.ts) acts on the events.
* (The original bash daemon + agent-hook-bridge.sh it once ran alongside
* were retired on 2026-06-11 — see content/thoughts/killing-the-bash-daemon.md.)
*
* Run: npx tsx home/watcher.ts
* Verify: edit any ~/.loki/sessions/*.md (or wait for a real agent to
* finish) and tail ~/.<APP_SLUG>/events.jsonl
*/
import fs from "node:fs";
import path from "node:path";
import { APP_NAME, APP_SLUG } from "@/config/brand";
import { FLEET_SESSIONS_DISPLAY_PATH, migrateLegacyHandoffs } from "@/lib/session-paths";
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 ${FLEET_SESSIONS_DISPLAY_PATH}/*.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 ${FLEET_SESSIONS_DISPLAY_PATH})`);
process.exit(0);
}
// Migrate before seeding mtimes so legacy handoffs never replay as fresh events.
const SESSIONS_DIR = migrateLegacyHandoffs();
/** 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 | working> # 'ready' = done, auto-inject may fire
// done: <one sentence>
// next: <one sentence>
// tests: <N pass · N fail, or 'no suite'>
// todos: <count> TODOs
// health: <good | needs attention | critical>
const FIELDS = ["status", "done", "next", "tests", "todos", "health"] as const;
function parseHandoff(content: string): Handoff {
const result: Record<string, string> = {};
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<string, number>();
const pendingFlush = new Map<string, NodeJS.Timeout>();
/**
* 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<string> = new Set();
let acceptUnregistered = false;
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<string>();
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 (!acceptUnregistered && !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; acceptUnregistered?: boolean } = {}): {
close: () => void;
} {
onIdleSubscriber = opts.onIdle ?? null;
acceptUnregistered = opts.acceptUnregistered ?? false;
// 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 && !acceptUnregistered) {
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;
acceptUnregistered = false;
};
// 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("Loki.md") === "Loki",
},
{
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 };