← All Pull Requests

Per-user Google Chat notifications: your own space, your own services only #1

Open opened by Drew Owens

Per-user Google Chat notifications for svcwatch. Opened on Drew's behalf (2026-10-30): "Each user (hydrogen acct) should have the option to set up a gchat space with its own notifications webhook, I should never be notified about John's containers, vice versa."

Nothing on main changes until you merge. No release is published from this PR, and I did not touch any container running svcwatch except Drew's dev container, where I only ran the tests and a throwaway preview.

What it does

  • Your own space, your own services. Each Adom account that runs svcwatch can connect its own Google Chat space through that space's incoming webhook. Alerts cover only the verdicts in that user's own $WD_STATE_DIR (their own service-watchdog.sh) and go only to their own webhook. There is no shared, global or fallback webhook, so Drew never hears about your containers and you never hear about his.

  • When it alerts. It works from the service rollup, so it inherits the watchdog's two-sweep pending-to-down debounce:

    • down: once, when a service first reads down
    • still down: at most once a day while it stays down
    • recovered: once, when a service it alerted about reads ok again
    • pending and unknown never alert

    Each message says what is down, since when (the earliest since of its down checks), why (each failing check's reason), and the fix: press Restart in the dashboard, or the row's start_cmd and the SSH target it runs on. A row with no start command says so.

  • Safe to run after every sweep. A ledger (~/.config/svcwatch/notify-state.json) records what was announced, so a run with nothing new sends nothing.

    • An alert that fails to deliver is not recorded, so the next sweep retries it.
    • Each POST has a 10 s timeout, and only network errors, 429 and 5xx are retried, at most 3 attempts. A 4xx means the webhook itself is wrong.
    • A run stops sending after a 45 s budget and leaves the rest for the next sweep.
    • A lock file stops the cron sweep and a Run sweep click from sending the same alert twice.
  • Setup in the UI. A bell icon opens a Notifications panel:

    • paste the webhook (a password field), then Connect, Send test or Disconnect
    • a per-service mute toggle
    • the last few messages sent
  • CLI. svcwatch notify status | set-webhook | test | mute <svc> | unmute <svc> | run [--background] | clear.

The webhook is treated as a credential

  • Storage. It lives only in ~/.config/svcwatch/notify.json: mode 0600, directory 0700, written atomically. It is never in the package, the page repo, a command line, a log, an endpoint response or the page's HTML.
  • What the page sees. The panel only ever gets a masked space id, spaces/AAQA...RkA.
  • CLI. set-webhook refuses an argv URL and reads stdin.
  • Errors. Every error string is scrubbed of the URL, key and token before it is logged or returned.
  • Validation. Only https://chat.googleapis.com/v1/spaces/<id>/messages?key=..&token=.. is accepted. It refuses look-alike hosts, other ports, userinfo, http, Slack URLs, and anything missing its key or token.
  • Bound to an account. The webhook is bound to the Adom account that connected it (the email from adom-cli carbon user get). If a home directory is ever copied or a container shared, a run under a different account refuses to post.

Where the alerts are sent from

The verdicts are made by each user's own service-watchdog.sh, which is not in this package, so each user adds one line at the end of theirs:

# Google Chat alerts for what this sweep changed (svcwatch notify). Background, with
# the sweep lock (fd 9) closed, so a slow Chat can never hold up or lock out a sweep.
[ -x "$HOME/.local/bin/svcwatch" ] && "$HOME/.local/bin/svcwatch" notify run --background 9>&- >/dev/null 2>&1 || true

9>&- matters. Without it, the backgrounded process inherits the watchdog's flock fd and holds the sweep lock while it posts.

The dashboard's Run sweep button also runs a notification check after its sweep. It is not awaited, so a slow Chat never delays the button's answer. The shared ledger and lock deduplicate it against the cron run.

Until a user connects a webhook, the line is a no-op (notify run answers "notifications are off").

How a user turns it on

  1. In Google Chat, open the space, then Apps & integrations, Webhooks. Add a webhook and copy its URL.
  2. In the Service Containers dashboard, click the bell, paste the URL, press Connect, then Send test. (Or run svcwatch notify set-webhook < file-holding-the-url.)
  3. Add the line above to the end of your ~/bin/service-watchdog.sh.

Files

  • app/notify.js (new): validation, masking and scrubbing, per-user config and ledger, the pure evaluate() rules, bounded post(), run(), sendTest().
  • app/server.js: GET /api/notify, POST|DELETE /api/notify/webhook, POST /api/notify/test, POST /api/notify/mute. JSON bodies on those routes are capped at 8 KB and never logged. Run sweep now runs a notification check after a successful sweep.
  • app/state.js: readState({ stateDir, binDir }) takes optional fixture paths (defaults unchanged), and WD_BIN_DIR overrides /home/adom/bin. Existing callers are untouched.
  • app/cli.js: the notify subcommands, plus help lines.
  • app/index.html: bell button, Notifications panel and its script. It reuses the existing modal, toggle, button and toast styles.
  • README.md, SKILL.md: a Notifications section, commands, endpoints.
  • package.json, app/package.json: 1.1.0, and npm test runs node --test test/notify.test.mjs.
  • test/notify.test.mjs, test/fake-webhook.mjs (new): not in files[], so they do not ship.

Tests

node --test test/notify.test.mjs: 28 passing on Node 18.19. Nothing reaches Google: a fake Chat webhook server records every POST and can answer 5xx, 4xx or hang. Covered:

  • Webhook validation: valid URLs pass; 11 kinds of bad URL are refused.
  • Masking and scrubbing of the URL, key and token.
  • Rules: pending is silent; down alerts once; no repeat the same day; one reminder after 24 h; recovery is announced once; a muted service never alerts and never replays a stale recovery; a row with no start command says so in the fix; a row removed from TARGETS is forgotten.
  • Delivery: 5xx is retried until it succeeds; 4xx is not retried; a hanging server gives up after the bounded attempts.
  • Full runs against a fixture watchdog: pending, then down, deduplicated, daily reminder, recovered, then quiet. An undelivered alert is retried on the next sweep. A run past its time budget defers the rest. Two concurrent runs send one message. No webhook means no request at all. A webhook connected by one account is not used by another.
  • Isolation: two users with their own watchdogs and spaces each receive only their own service.
  • Storage: modes 0600 and 0700; the key, the token and the full space id appear in no endpoint, log line or page (/, /state, /console, /health, /settings, /api/messages, /api/notify).
  • Server routes: connect, a refused bad URL, mute, disconnect, test while disconnected, an oversized body answered with 413.
  • CLI: an argv webhook is refused, stdin is accepted, status, mute, clear; run --background returns at once.

I also opened the panel in a browser against Drew's real (read-only) verdicts. It showed "Off", refused a Slack URL with its message, and listed 14 services with mute toggles.

Things you may want to decide

  • Restart and the notify routes on 0.0.0.0. The server listens on 0.0.0.0 and the notify routes have no auth beyond the container proxy, the same as /api/restart today. Someone who can reach the port could replace the webhook, but only with another chat.googleapis.com webhook.
  • The account check. It uses adom-cli carbon user get. If that call fails, the run still sends (the config is in the user's own home), rather than going silent.
  • A known gap this PR does not cover. A watchdog running inside a container cannot report that container's own restart, because its sweep loop dies with it. Covering that needs a watcher somewhere else (a heartbeat that another container's watchdog checks), which is outside svcwatch.

🤖 Generated with Claude Code

Diff Skip to comments (1)

--- a/app/notify.js+++ b/app/notify.js@@ -0,0 +1,430 @@+// Google Chat alerts for the services YOUR watchdog watches.+//+// Each Adom (Hydrogen) account that runs svcwatch connects its own Chat space+// through its own incoming webhook. There is no shared or global webhook, and+// no fallback to one: a user's alerts cover only the verdicts in their own+// $WD_STATE_DIR (written by their own service-watchdog.sh) and go only to the+// webhook in their own config. So Drew never hears about John's containers and+// John never hears about Drew's.+//+// THE WEBHOOK IS A CREDENTIAL. Anyone holding the URL can post into the space.+// It lives in ~/.config/svcwatch/notify.json (mode 0600, directory 0700), out+// of the package and out of the page repo. It is never put on a command line+// (the CLI reads it from stdin), never logged, never returned by an endpoint+// and never rendered in the dashboard's HTML: the page only ever sees the+// masked space id. Every error string that leaves this module is scrubbed.+//+// WHEN IT ALERTS. The watchdog already debounces: a failing check is "pending"+// on its first sweep and "down" on the second. This module only acts on the+// service rollup, so it inherits that debounce for free:+//   down       once, when a service first reads down+//   repeat     at most once a day while it stays down+//   recovered  once, when a service we alerted about reads ok again+// "pending" and "unknown" never alert. What has been sent is kept in a ledger+// (notify-state.json), which is what makes it run-on-every-sweep safe: a+// second run with nothing new sends nothing. A message that fails to deliver+// is NOT written to the ledger, so the next sweep tries it again.+//+// IT NEVER BLOCKS A SWEEP. The watchdog starts it in the background+// (`svcwatch notify run --background`), each POST has a timeout, retries are+// bounded, and a run stops sending once it has used its time budget; whatever+// is left goes out on the next sweep. A lock file keeps two runs (the cron+// sweep and a "Run sweep" click) from sending the same message twice.++import {+  readFileSync, writeFileSync, mkdirSync, renameSync, chmodSync,+  openSync, closeSync, unlinkSync, statSync, appendFileSync,+} from 'fs';+import { join } from 'path';+import { execFile } from 'child_process';++const DAY_MS = 24 * 3600e3;+const LOCK_STALE_MS = 5 * 60e3;+const MAX_LOG_SENT = 30;++// Paths are read from the environment at call time, not import time, so the+// tests can point a fresh config directory at every case.+export function configDir() {+  return process.env.SVCWATCH_CONFIG_DIR || join(process.env.HOME || '/tmp', '.config', 'svcwatch');+}+const configFile = () => join(configDir(), 'notify.json');+const ledgerFile = () => join(configDir(), 'notify-state.json');+const lockFile = () => join(configDir(), 'notify.lock');+export const logFile = () => join(configDir(), 'notify.log');++// ── the webhook ────────────────────────────────────────────────────────+// A Google Chat incoming webhook, and nothing else: anything that is not+// https://chat.googleapis.com/v1/spaces/<id>/messages?key=..&token=.. is+// refused, so a typo or a pasted look-alike can never receive alerts.+export function validateWebhook(raw) {+  const s = String(raw || '').trim();+  if (!s) return { ok: false, error: 'No webhook given.' };+  if (/\s/.test(s)) return { ok: false, error: 'The webhook contains spaces or line breaks. Paste exactly one URL.' };+  let u;+  try { u = new URL(s); } catch { return { ok: false, error: 'That is not a URL.' }; }+  if (u.protocol !== 'https:') return { ok: false, error: 'A Google Chat webhook starts with https://.' };+  if (u.hostname !== 'chat.googleapis.com' || u.port || u.username || u.password) {+    return { ok: false, error: 'Only Google Chat webhooks (https://chat.googleapis.com/...) are accepted.' };+  }+  if (!/^\/v1\/spaces\/[A-Za-z0-9_-]+\/messages$/.test(u.pathname)) {+    return { ok: false, error: 'The path should look like /v1/spaces/<space id>/messages.' };+  }+  if (!u.searchParams.get('key') || !u.searchParams.get('token')) {+    return { ok: false, error: 'The webhook is missing its key or token. Copy the whole URL from the space\'s Webhooks dialog.' };+  }+  return { ok: true, url: u.toString(), space: u.pathname.split('/')[3] };+}++// "spaces/AAQA...RkA": enough to recognise the space, useless for posting.+export function maskSpace(space) {+  const id = String(space || '');+  if (!id) return '';+  return 'spaces/' + (id.length <= 8 ? id.slice(0, 2) + '...' : id.slice(0, 4) + '...' + id.slice(-3));+}++// Remove the webhook (and its key and token) from any string before it is+// logged, thrown or sent to a browser.+export function scrub(text, webhook) {+  let out = String(text ?? '');+  if (webhook) {+    out = out.split(webhook).join('<webhook>');+    try {+      const u = new URL(webhook);+      for (const k of ['key', 'token']) {+        const v = u.searchParams.get(k);+        if (v) out = out.split(v).join('<' + k + '>');+      }+    } catch {}+  }+  return out.replace(/https:\/\/chat\.googleapis\.com\/\S+/g, '<webhook>');+}++// ── config and ledger on disk ──────────────────────────────────────────+function readJson(path, fallback) {+  try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return fallback; }+}++// Atomic and private: write a 0600 temp file in the same directory, rename.+function writePrivate(path, obj) {+  mkdirSync(configDir(), { recursive: true, mode: 0o700 });+  try { chmodSync(configDir(), 0o700); } catch {}+  const tmp = path + '.' + process.pid + '.tmp';+  writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 });+  chmodSync(tmp, 0o600);+  renameSync(tmp, path);+}++export function loadConfig() {+  const c = readJson(configFile(), null) || {};+  return {+    webhook: typeof c.webhook === 'string' ? c.webhook : '',+    account: typeof c.account === 'string' ? c.account : '',+    connectedAt: c.connectedAt || null,+    mutes: Array.isArray(c.mutes) ? c.mutes.filter(x => typeof x === 'string') : [],+  };+}+function saveConfig(c) { writePrivate(configFile(), c); }++export function loadLedger() {+  const l = readJson(ledgerFile(), null) || {};+  return {+    services: l.services && typeof l.services === 'object' ? l.services : {},+    sent: Array.isArray(l.sent) ? l.sent : [],+    lastRunAt: l.lastRunAt || null,+    lastError: l.lastError || null,+  };+}+function saveLedger(l) { writePrivate(ledgerFile(), l); }++function logLine(msg, webhook) {+  try {+    mkdirSync(configDir(), { recursive: true, mode: 0o700 });+    appendFileSync(logFile(), `[${new Date().toISOString()}] ${scrub(msg, webhook)}\n`, { mode: 0o600 });+  } catch {}+}++// ── whose account is this ──────────────────────────────────────────────+// The webhook is bound to the Adom account that connected it. If the home+// directory is ever copied to someone else's container, or a container is+// shared, a run under a different account refuses to post rather than send+// one person's outages to another person's space.+let accountCache;+export function currentAccount() {+  if (process.env.SVCWATCH_ACCOUNT !== undefined) return Promise.resolve(process.env.SVCWATCH_ACCOUNT || '');+  if (accountCache !== undefined) return Promise.resolve(accountCache);+  return new Promise((resolve) => {+    execFile('adom-cli', ['carbon', 'user', 'get'], { timeout: 8000 }, (err, stdout) => {+      let email = '';+      if (!err) { try { email = JSON.parse(stdout).email || ''; } catch {} }+      accountCache = email;+      resolve(email);+    });+  });+}++export async function setWebhook(raw) {+  const v = validateWebhook(raw);+  if (!v.ok) return v;+  const c = loadConfig();+  c.webhook = v.url;+  c.account = await currentAccount();+  c.connectedAt = new Date().toISOString();+  saveConfig(c);+  logLine(`webhook connected to ${maskSpace(v.space)} for ${c.account || 'an unknown account'}`);+  return { ok: true, space: maskSpace(v.space), account: c.account };+}++export function clearWebhook() {+  const c = loadConfig();+  c.webhook = '';+  c.connectedAt = null;+  saveConfig(c);+  // Forget what was announced, so a later reconnect starts clean instead of+  // sending "recovered" for an outage the new space never heard about.+  const l = loadLedger();+  l.services = {};+  saveLedger(l);+  logLine('webhook disconnected');+  return { ok: true };+}++export function setMuted(label, muted) {+  if (!label || typeof label !== 'string') return { ok: false, error: 'label required' };+  const c = loadConfig();+  const set = new Set(c.mutes);+  if (muted) set.add(label); else set.delete(label);+  c.mutes = [...set].sort();+  saveConfig(c);+  return { ok: true, mutes: c.mutes };+}++// What the dashboard may know. Never the webhook itself.+export function status() {+  const c = loadConfig();+  const l = loadLedger();+  const v = c.webhook ? validateWebhook(c.webhook) : null;+  return {+    connected: !!(v && v.ok),+    space: v && v.ok ? maskSpace(v.space) : '',+    account: c.account || '',+    connectedAt: c.connectedAt,+    mutes: c.mutes,+    alerting: Object.keys(l.services),+    lastRunAt: l.lastRunAt,+    lastError: l.lastError,+    recent: l.sent.slice(-10).reverse(),+  };+}++// ── the rules ──────────────────────────────────────────────────────────+function fmtTime(iso) {+  const d = new Date(iso);+  if (isNaN(d)) return String(iso || 'an unknown time');+  return d.toISOString().slice(0, 16).replace('T', ' ') + ' UTC';+}+function fmtDuration(ms) {+  const m = Math.max(0, Math.round(ms / 60000));+  if (m < 60) return m + 'm';+  const h = Math.floor(m / 60);+  if (h < 48) return h + 'h ' + (m % 60) + 'm';+  return Math.floor(h / 24) + 'd ' + (h % 24) + 'h';+}++// When the service went down: the earliest "since" among its down checks.+function downSince(svc, now) {+  const s = svc.checks.filter(c => c.kind === 'down' && c.since).map(c => c.since).sort()[0];+  return s || new Date(now).toISOString();+}++function why(svc) {+  const bad = svc.checks.filter(c => c.kind === 'down');+  return bad.map(c => `${c.name}: ${c.reason || 'failing'}`).join('; ') || 'a check is failing';+}++function fix(svc) {+  if (svc.startCmd && svc.ssh) {+    return `Press Restart on ${svc.name} in the Service Containers dashboard (svcwatch show). ` ++           `It runs this on ${svc.ssh}: ${svc.startCmd}`;+  }+  if (svc.ssh) {+    return `No start command in TARGETS for ${svc.label}. SSH to ${svc.ssh} and start it by hand, ` ++           `then add its start command to service-watchdog.sh so Restart works next time.`;+  }+  return `No SSH target or start command in TARGETS for ${svc.label}; start it by hand.`;+}++export function messageText(kind, svc, entry, now) {+  const since = entry?.since || downSince(svc, now);+  const dur = fmtDuration(now - new Date(since).getTime());+  if (kind === 'recovered') {+    return `*RECOVERED: ${svc.name}* (${svc.label})\n` ++           `Back up after ${dur}; it was down since ${fmtTime(since)}.`;+  }+  const head = kind === 'repeat' ? 'STILL DOWN' : 'DOWN';+  const tail = kind === 'repeat' ? '\nDaily reminder: this repeats at most once a day until it recovers.' : '';+  return `*${head}: ${svc.name}* (${svc.label})\n` ++         `Down since ${fmtTime(since)} (${dur}).\n` ++         `Why: ${why(svc)}\n` ++         `Fix: ${fix(svc)}` + tail;+}++// Pure: the messages a run should send, given the dashboard state, the+// ledger and the mutes. Each message carries the ledger entry to record once+// it is delivered (null = forget the service).+export function evaluate(services, ledger, mutes, now = Date.now()) {+  const out = [];+  const muted = new Set(mutes || []);+  const seen = new Set();+  for (const svc of services || []) {+    seen.add(svc.label);+    const entry = ledger.services[svc.label];+    if (muted.has(svc.label)) {+      // A muted service sends nothing, ever. Once it is no longer down, drop+      // what we knew so an unmute does not announce a stale recovery.+      if (entry && svc.status !== 'down') out.push({ label: svc.label, kind: 'forget', record: null });+      continue;+    }+    if (svc.status === 'down') {+      if (!entry) {+        const since = downSince(svc, now);+        const rec = { since, firstAlertAt: new Date(now).toISOString(), lastAlertAt: new Date(now).toISOString() };+        out.push({ label: svc.label, kind: 'down', text: messageText('down', svc, rec, now), record: rec });+      } else if (now - new Date(entry.lastAlertAt).getTime() >= DAY_MS) {+        const rec = { ...entry, lastAlertAt: new Date(now).toISOString() };+        out.push({ label: svc.label, kind: 'repeat', text: messageText('repeat', svc, entry, now), record: rec });+      }+    } else if (svc.status === 'ok' && entry) {+      out.push({ label: svc.label, kind: 'recovered', text: messageText('recovered', svc, entry, now), record: null });+    }+    // pending and unknown: the watchdog has not confirmed anything yet.+  }+  // A row removed from TARGETS: forget it quietly.+  for (const label of Object.keys(ledger.services)) {+    if (!seen.has(label)) out.push({ label, kind: 'forget', record: null });+  }+  return out;+}++// ── delivery ───────────────────────────────────────────────────────────+// One POST per message: a timeout on each attempt, at most `attempts`+// attempts, and a retry only when another attempt could help (network+// error, 429, 5xx). A 4xx means the webhook itself is wrong; retrying it+// would only hammer Google.+export async function post(webhook, text, opts = {}) {+  const fetchImpl = opts.fetchImpl || fetch;+  const attempts = opts.attempts ?? 3;+  const timeoutMs = opts.timeoutMs ?? 10000;+  const backoff = opts.backoffMs ?? [1000, 3000];+  let last = '';+  for (let i = 0; i < attempts; i++) {+    const ctl = new AbortController();+    const t = setTimeout(() => ctl.abort(), timeoutMs);+    try {+      const r = await fetchImpl(webhook, {+        method: 'POST',+        headers: { 'content-type': 'application/json; charset=UTF-8' },+        body: JSON.stringify({ text }),+        signal: ctl.signal,+      });+      clearTimeout(t);+      if (r.ok) return { ok: true, status: r.status, attempts: i + 1 };+      last = `Google Chat answered HTTP ${r.status}`;+      if (r.status < 500 && r.status !== 429) return { ok: false, status: r.status, error: last, attempts: i + 1 };+    } catch (e) {+      clearTimeout(t);+      last = e.name === 'AbortError' ? `no answer within ${timeoutMs / 1000}s` : `network error: ${e.message}`;+    }+    if (i < attempts - 1) await new Promise(r => setTimeout(r, backoff[Math.min(i, backoff.length - 1)] || 0));+  }+  return { ok: false, error: scrub(last, webhook), attempts };+}++function lock() {+  mkdirSync(configDir(), { recursive: true, mode: 0o700 });+  try {+    closeSync(openSync(lockFile(), 'wx', 0o600));+    return true;+  } catch (e) {+    if (e.code !== 'EEXIST') return false;+    // A run that died mid-send leaves the lock behind. Five minutes is far+    // longer than any run's budget, so an older lock is abandoned.+    try {+      if (Date.now() - statSync(lockFile()).mtimeMs > LOCK_STALE_MS) {+        unlinkSync(lockFile());+        closeSync(openSync(lockFile(), 'wx', 0o600));+        return true;+      }+    } catch {}+    return false;+  }+}+function unlock() { try { unlinkSync(lockFile()); } catch {} }++// One run: read the verdicts, decide, send, record. Safe to call after every+// sweep and from several places at once.+export async function run(opts = {}) {+  const c = loadConfig();+  const v = c.webhook ? validateWebhook(c.webhook) : null;+  if (!v || !v.ok) return { status: 'not_configured', sent: 0 };++  const account = await currentAccount();+  if (c.account && account && c.account !== account) {+    logLine(`refused: the webhook belongs to ${c.account}, this run is ${account}`);+    return { status: 'wrong_account', sent: 0, owner: c.account, account };+  }++  if (!lock()) return { status: 'busy', sent: 0 };+  try {+    const readState = opts.readState || (await import('./state.js')).readState;+    const now = opts.now ?? Date.now();+    const budgetMs = opts.budgetMs ?? 45000;+    const started = Date.now();+    const st = readState();+    const ledger = loadLedger();+    const plan = evaluate(st.services, ledger, c.mutes, now);++    let sent = 0, failed = 0, deferred = 0;+    let lastError = null;+    for (const m of plan) {+      if (m.kind === 'forget') { delete ledger.services[m.label]; continue; }+      if (Date.now() - started > budgetMs) { deferred++; continue; }+      const r = await post(v.url, m.text, opts);+      if (r.ok) {+        sent++;+        if (m.record) ledger.services[m.label] = m.record; else delete ledger.services[m.label];+        ledger.sent.push({ ts: new Date(now).toISOString(), label: m.label, kind: m.kind });+        logLine(`sent ${m.kind} for ${m.label}`);+      } else {+        failed++;+        lastError = `${m.kind} for ${m.label} not delivered: ${r.error}`;+        logLine(lastError, v.url);+      }+    }+    ledger.sent = ledger.sent.slice(-MAX_LOG_SENT);+    ledger.lastRunAt = new Date(now).toISOString();+    ledger.lastError = lastError;+    saveLedger(ledger);+    return { status: 'ok', sent, failed, deferred, planned: plan.filter(m => m.kind !== 'forget').length };+  } finally {+    unlock();+  }+}++// "Send test": proves the space is connected without touching the ledger.+export async function sendTest(opts = {}) {+  const c = loadConfig();+  const v = c.webhook ? validateWebhook(c.webhook) : null;+  if (!v || !v.ok) return { ok: false, error: 'No webhook connected. Paste one in the Notifications panel first.' };+  const account = await currentAccount();+  if (c.account && account && c.account !== account) {+    return { ok: false, error: `This webhook was connected by ${c.account}; you are ${account}. Connect your own.` };+  }+  const who = c.account || account || 'this account';+  const text = `*svcwatch test* for ${who}\n` ++    `This space will get an alert when one of ${who}'s own services goes down (after the watchdog confirms it on two sweeps), ` ++    `a reminder at most once a day while it stays down, and one message when it recovers.`;+  const r = await post(v.url, text, opts);+  logLine(r.ok ? 'test message sent' : `test message failed: ${r.error}`, v.url);+  return r.ok ? { ok: true } : { ok: false, error: scrub(r.error, v.url) };+}+--- a/app/server.js+++ b/app/server.js@@ -1,399 +1,465 @@⋯ 9 unchanged lines ⋯ import { execFile } from 'child_process';  import { readState } from './state.js';+import * as notify from './notify.js';  const DIR = dirname(fileURLToPath(import.meta.url)); const SLUG = 'svcwatch';⋯ 145 unchanged lines ⋯       if (err && err.killed) { note('error', 'sweep timed out'); return cb(new Error('sweep timed out')); }       note('info', 'sweep complete');       cb(null, { ok: true });+      // Alert on what this sweep changed. Not awaited: a slow or failing+      // Google Chat must never hold up the sweep's answer. The watchdog's own+      // cron sweeps call `svcwatch notify run`; the shared ledger and lock+      // keep the two from sending the same message twice.+      notify.run()+        .then(r => { if (r.sent || r.failed) note(r.failed ? 'error' : 'info', `notifications: ${r.sent} sent, ${r.failed} failed`); })+        .catch(e => note('error', 'notifications: ' + notify.scrub(e.message)));     }); } +// Read a small JSON body. The notification routes carry a credential, so the+// body is never logged and is capped well above any real webhook URL.+function readJsonBody(req, res, cb) {+  let body = '';+  let tooBig = false;+  req.on('data', c => {+    if (tooBig) return;+    body += c;+    if (body.length > 8192) { tooBig = true; body = ''; }+  });+  req.on('end', () => {+    if (tooBig) return send(res, 413, { error: 'body too large' });+    let m;+    try { m = JSON.parse(body || '{}'); } catch { return send(res, 400, { error: 'invalid JSON' }); }+    cb(m);+  });+}+ // ── HTTP ─────────────────────────────────────────────────────────────── function send(res, code, body, type = 'application/json') {   res.writeHead(code, {⋯ 104 unchanged lines ⋯     return;   } +  // ── notifications (per user; see notify.js) ──────────────────────────+  // None of these ever return or log the webhook: the page sees the masked+  // space id, whether it is connected, and the mutes.+  if (p === '/api/notify' && req.method === 'GET') return send(res, 200, notify.status());++  if (p === '/api/notify/webhook' && req.method === 'POST') {+    readJsonBody(req, res, async (m) => {+      const r = await notify.setWebhook(m.webhook);+      if (!r.ok) return send(res, 400, { error: r.error });+      note('info', `notifications: webhook connected to ${r.space}`);+      send(res, 200, notify.status());+    });+    return;+  }++  if (p === '/api/notify/webhook' && req.method === 'DELETE') {+    notify.clearWebhook();+    note('info', 'notifications: webhook disconnected');+    return send(res, 200, notify.status());+  }++  if (p === '/api/notify/test' && req.method === 'POST') {+    notify.sendTest().then(r => {+      note(r.ok ? 'info' : 'error', r.ok ? 'notifications: test message sent' : `notifications: test failed: ${r.error}`);+      send(res, r.ok ? 200 : 502, r.ok ? { ok: true } : { error: r.error });+    }).catch(e => send(res, 500, { error: notify.scrub(e.message) }));+    return;+  }++  if (p === '/api/notify/mute' && req.method === 'POST') {+    readJsonBody(req, res, (m) => {+      const r = notify.setMuted(m.label, !!m.muted);+      if (!r.ok) return send(res, 400, { error: r.error });+      note('info', `notifications: ${m.label} ${m.muted ? 'muted' : 'unmuted'}`);+      send(res, 200, notify.status());+    });+    return;+  }+   if (p === '/api/sweep' && req.method === 'POST') {     broadcast('toast', { kind: 'info', message: 'Running watchdog sweep...' });     runSweep((err) => {⋯ 117 unchanged lines ⋯ for (const sig of ['SIGINT', 'SIGTERM']) {   process.on(sig, () => { saveSnapshot(); deregister(); process.exit(0); }); }+--- a/app/state.js+++ b/app/state.js@@ -1,218 +1,222 @@⋯ 7 unchanged lines ⋯ import { join } from 'path';  export const STATE_DIR = process.env.WD_STATE_DIR || '/home/adom/.watchdog-state';-const BIN = '/home/adom/bin';+// Where the watchdog scripts live. Overridable so the tests can point at a fixture.+const BIN = process.env.WD_BIN_DIR || '/home/adom/bin';  const WATCHDOG_LOGS = [   '/tmp/service-watchdog.log',⋯ 47 unchanged lines ⋯   'wiki-adom-inc': 'wiki.adom.inc', }; -function readTargets() {+function readTargets(bin = BIN) {   const out = {};   try {-    const src = readFileSync(join(BIN, 'service-watchdog.sh'), 'utf8');+    const src = readFileSync(join(bin, 'service-watchdog.sh'), 'utf8');     const block = src.split('TARGETS=(')[1]?.split('\n)')[0] || '';     for (const line of block.split('\n')) {       const m = line.match(/^\s*"([^"]+)"/);⋯ 3 unchanged lines ⋯     }   } catch {}   try {-    const src = readFileSync(join(BIN, 'kicad-watchdog-of-watchdogs.sh'), 'utf8');+    const src = readFileSync(join(bin, 'kicad-watchdog-of-watchdogs.sh'), 'utf8');     const block = src.split('TARGETS=(')[1]?.split('\n)')[0] || '';     for (const line of block.split('\n')) {       const m = line.match(/^\s*"([^"]+)"/);⋯ 44 unchanged lines ⋯   return lines.slice(0, limit); } -export function readState() {-  const targets = readTargets();+// stateDir and binDir default to this user's own watchdog; the tests pass+// fixtures so one process can stand in for two users.+export function readState({ stateDir = STATE_DIR, binDir = BIN } = {}) {+  const targets = readTargets(binDir);   const byLabel = {};    let files = [];-  try { files = readdirSync(STATE_DIR); } catch {}+  try { files = readdirSync(stateDir); } catch {}    for (const f of files) {     if (!f.endsWith('.state')) continue;⋯ 7 unchanged lines ⋯     }     if (!check) continue; -    const st = parseStateFile(join(STATE_DIR, f));+    const st = parseStateFile(join(stateDir, f));     if (!st) continue;      if (MERGE_INTO[label]) { check = 'cred-' + check; label = MERGE_INTO[label]; }⋯ 64 unchanged lines ⋯     log: readLogTail(40),   }; }+--- a/app/cli.js+++ b/app/cli.js@@ -1,300 +1,396 @@⋯ 279 unchanged lines ⋯       return;     } +    // Google Chat alerts for this account's own services (app/notify.js).+    case 'notify': {+      const notify = await import('./notify.js');+      const sub = argv[1] || 'status';++      if (sub === 'status') {+        const st = notify.status();+        if (!st.connected) {+          ok('notifications are off: no Google Chat webhook connected');+          hint('Connect one in the dashboard (bell icon), or: svcwatch notify set-webhook < file-holding-the-url');+          return;+        }+        ok(`notifications on: ${st.space}, connected by ${st.account || 'an unknown account'}`);+        if (st.mutes.length) console.log(dim('muted: ' + st.mutes.join(', ')));+        if (st.alerting.length) console.log(dim('announced as down: ' + st.alerting.join(', ')));+        if (st.lastRunAt) console.log(dim('last run ' + st.lastRunAt));+        if (st.lastError) console.log('WARN: ' + st.lastError);+        return;+      }++      if (sub === 'set-webhook') {+        // A webhook on the command line lands in shell history and in every+        // process listing on the box. Refuse it; read stdin instead.+        if (argv[2]) {+          fail('Do not put the webhook on the command line: it is a credential, and argv is visible to every process.',+               'Paste it in the dashboard (bell icon), or: svcwatch notify set-webhook < file-holding-the-url');+        }+        if (process.stdin.isTTY) console.log('Paste the Google Chat webhook URL, then press Enter:');+        let input = '';+        for await (const chunk of process.stdin) {+          input += chunk;+          if (process.stdin.isTTY && input.includes('\n')) break;+        }+        const r = await notify.setWebhook(input);+        if (!r.ok) fail(r.error, 'In Google Chat: open the space, Apps & integrations, Webhooks, then copy the whole URL.');+        ok(`webhook connected to ${r.space} for ${r.account || 'an unknown account'}`);+        hint('Check it reaches the space: svcwatch notify test');+        return;+      }++      if (sub === 'clear') {+        notify.clearWebhook();+        ok('webhook removed; no more alerts will be sent');+        return;+      }++      if (sub === 'test') {+        const r = await notify.sendTest();+        if (!r.ok) fail(r.error, 'Re-copy the webhook from the space, then: svcwatch notify set-webhook < file');+        ok('test message sent');+        return;+      }++      if (sub === 'mute' || sub === 'unmute') {+        const label = argv[2];+        if (!label) fail('No service given.', `Try: svcwatch notify ${sub} mouser`);+        const r = notify.setMuted(label, sub === 'mute');+        if (!r.ok) fail(r.error, 'List services with: svcwatch status');+        ok(`${label} ${sub}d`);+        return;+      }++      if (sub === 'run') {+        // --background is what the watchdog uses: it returns at once, so a+        // slow Google Chat can never hold up a sweep.+        if (flag('--background')) {+          const child = spawn(process.execPath, [join(DIR, 'cli.js'), 'notify', 'run'],+            { detached: true, stdio: 'ignore' });+          child.unref();+          ok('notification check started in the background');+          return;+        }+        const r = await notify.run();+        if (r.status === 'not_configured') { ok('notifications are off: nothing to do'); return; }+        if (r.status === 'busy') { ok('another notification check is running; it covers this sweep'); return; }+        if (r.status === 'wrong_account') {+          fail(`The webhook belongs to ${r.owner}, but this is ${r.account}. Nothing was sent.`,+               'Connect your own space: svcwatch notify set-webhook < file');+        }+        ok(`${r.sent} sent, ${r.failed} failed` + (r.deferred ? `, ${r.deferred} left for the next sweep` : ''));+        if (r.failed) hint('See why: svcwatch notify status');+        return;+      }++      fail(`Unknown notify command: ${sub}`,+           'Try: svcwatch notify status | set-webhook | test | mute <svc> | unmute <svc> | run [--background] | clear');+      return;+    }+     default: {       console.log(`svcwatch v${VERSION}: the Adom service container dashboard`);       console.log('');⋯ 6 unchanged lines ⋯       console.log('  svcwatch ui toast "..."          raise a toast on the page');       console.log('  svcwatch ui sweep                run a watchdog sweep now');       console.log('  svcwatch ui restart <svc> --reason "..."   restart one service');+      console.log('  svcwatch notify status           your Google Chat alerts: on or off, mutes');+      console.log('  svcwatch notify set-webhook      connect your space (reads the URL from stdin)');+      console.log('  svcwatch notify test             send a test message to your space');+      console.log('  svcwatch notify mute|unmute <svc>  stop or resume alerts for one service');+      console.log('  svcwatch notify run [--background]   alert on what the last sweep changed');+      console.log('  svcwatch notify clear            disconnect your space');       return;     }   } }  main().catch(e => fail(e.message, 'This is a bug in svcwatch. Run with: node cli.js ' + cmd));+--- a/app/index.html+++ b/app/index.html@@ -1,766 +1,924 @@⋯ 301 unchanged lines ⋯   .toggle[aria-pressed="true"]::after { transform:translateX(20px); background:var(--accent); }   .toggle:hover { border-color:var(--text-3); } +  /* ── notifications panel ───────────────────────────────────── */+  input.webhook {+    flex:1; min-width:0; background:var(--elevated); border:1px solid var(--border); color:var(--text);+    border-radius:var(--r-btn); padding:8px; font-family:'JetBrains Mono', monospace; font-size:.8rem;+  }+  input.webhook:hover { border-color:var(--text-3); }+  .nt-actions { display:flex; flex-wrap:wrap; gap:8px; margin-top:10px; }+  .nt-actions .sbtn { margin-left:0; }+  .nt-status { font-size:.85rem; color:var(--text-body); margin:0 0 10px; }+  .nt-status b { color:var(--text); }+  .nt-status.on b { color:var(--accent); }+  .nt-err { color:var(--red, #f87171); font-size:.8rem; margin-top:6px; min-height:1em; }+  .nt-svc { display:flex; align-items:center; justify-content:space-between; gap:12px;+            padding:6px 0; border-bottom:1px solid var(--border); }+  .nt-svc:last-child { border-bottom:none; }+  .nt-svc .lbl { font-size:.88rem; color:var(--text-body); }+  .nt-svc .def { display:block; font-family:'JetBrains Mono', monospace; font-size:.72rem; color:var(--text-2); }+  .nt-recent { font-family:'JetBrains Mono', monospace; font-size:.75rem; color:var(--text-2); }+   /* ── toasts: user feedback and the AI's narration channel ──── */   #toasts {     position:fixed; left:50%; bottom:24px; transform:translateX(-50%); z-index:80;⋯ 57 unchanged lines ⋯   <span class="actions">     <button class="hbtn" id="sweep"       data-tooltip="Runs service-watchdog.sh right now instead of waiting for the next 5 minute cycle. Takes about 30 seconds and re-probes every container.">Run sweep</button>+    <button class="icon-btn" id="notify" aria-label="Notifications"+      data-tooltip="Google Chat alerts for the services your own watchdog watches: connect your space, send a test, mute a service.">+      <svg viewBox="0 0 24 24"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>+    </button>     <button class="icon-btn" id="settings" aria-label="Settings"       data-tooltip="Refresh rate, idle shutdown, and which sections are shown.">       <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.6a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>⋯ 79 unchanged lines ⋯   </div> </div> +<div class="backdrop" id="notify-modal">+  <div class="modal" role="dialog" aria-modal="true" aria-label="Notifications">+    <div class="modal-head">+      <h2>Notifications</h2>+      <button class="icon-btn" id="close-notify" aria-label="Close notifications">+        <svg viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg>+      </button>+    </div>++    <div class="setting">+      <h3>Your Google Chat space</h3>+      <p>Alerts go to a space you choose, through its own incoming webhook, and only cover the+         services your own watchdog watches. Nobody else's services reach your space, and yours+         reach nobody else's. In Google Chat: open the space, then Apps &amp; integrations,+         Webhooks, add one and copy its URL.</p>+      <p class="nt-status" id="nt-status">Checking...</p>+      <div class="row">+        <input class="webhook" id="nt-webhook" type="password" autocomplete="off" spellcheck="false"+          placeholder="https://chat.googleapis.com/v1/spaces/..." aria-label="Google Chat webhook URL">+        <button class="sbtn" id="nt-save"+          data-tooltip="Saves the webhook to ~/.config/svcwatch/notify.json on this container (owner-only). It is never shown again, logged, or sent to this page.">Connect</button>+      </div>+      <div class="nt-err" id="nt-err" role="alert"></div>+      <div class="nt-actions">+        <button class="sbtn" id="nt-test"+          data-tooltip="Posts one test message to your space, so you know alerts will arrive.">Send test</button>+        <button class="sbtn" id="nt-clear"+          data-tooltip="Removes the webhook from this container. No more alerts until you connect one again.">Disconnect</button>+      </div>+    </div>++    <div class="setting">+      <h3>When it alerts</h3>+      <p>Once when a service goes down (after the watchdog confirms it on two sweeps in a row), a+         reminder at most once a day while it stays down, and once when it recovers. Each alert+         says what is down, since when, and how to fix it.</p>+    </div>++    <div class="setting">+      <h3>Services</h3>+      <p>Turn a service off to stop its alerts, for example while you are working on it.</p>+      <div id="nt-services"></div>+    </div>++    <div class="setting" id="nt-recent-wrap" hidden>+      <h3>Recently sent</h3>+      <div class="nt-recent" id="nt-recent"></div>+    </div>+  </div>+</div>+ <div id="toasts"></div>  <script>⋯ 238 unchanged lines ⋯ $('close-settings').onclick = () => $('settings-modal').classList.remove('show'); $('settings-modal').onclick = e => { if (e.target === $('settings-modal')) $('settings-modal').classList.remove('show'); }; document.addEventListener('keydown', e => {-  if (e.key === 'Escape') $('settings-modal').classList.remove('show');+  if (e.key === 'Escape') { $('settings-modal').classList.remove('show'); $('notify-modal').classList.remove('show'); } }); +// ── notifications ──────────────────────────────────────+// The server never sends the webhook back: this panel only ever knows+// whether one is connected, the masked space id, and the mutes.+let NOTIFY = null;+async function loadNotify() {+  try {+    const r = await fetch('api/notify');+    NOTIFY = await r.json();+  } catch { NOTIFY = null; }+  renderNotify();+}+function renderNotify() {+  const st = $('nt-status');+  if (!NOTIFY) { st.className = 'nt-status'; st.textContent = 'Could not read the notification settings.'; return; }+  if (NOTIFY.connected) {+    st.className = 'nt-status on';+    st.innerHTML = '<b>On.</b> Alerts go to ' + esc(NOTIFY.space) ++      (NOTIFY.account ? ', connected by ' + esc(NOTIFY.account) : '') + '.' ++      (NOTIFY.lastError ? '<br>Last problem: ' + esc(NOTIFY.lastError) : '');+  } else {+    st.className = 'nt-status';+    st.innerHTML = '<b>Off.</b> No space connected, so nothing is sent.';+  }+  $('nt-test').disabled = !NOTIFY.connected;+  $('nt-clear').disabled = !NOTIFY.connected;+  $('nt-save').textContent = NOTIFY.connected ? 'Replace' : 'Connect';++  const muted = new Set(NOTIFY.mutes || []);+  const services = (STATE && STATE.services) || [];+  $('nt-services').innerHTML = services.length+    ? services.map(s =>+        '<div class="nt-svc"><span class="lbl">' + esc(s.name) + '<span class="def">' + esc(s.label) + '</span></span>' ++        '<button class="toggle" data-mute="' + esc(s.label) + '" aria-pressed="' + String(!muted.has(s.label)) ++        '" aria-label="Alerts for ' + esc(s.name) + '"></button></div>').join('')+    : '<p class="empty">No services yet: the watchdog has not written any verdicts.</p>';+  for (const b of $('nt-services').querySelectorAll('[data-mute]')) {+    b.onclick = () => setMute(b.dataset.mute, b.getAttribute('aria-pressed') === 'true');+  }++  const recent = NOTIFY.recent || [];+  $('nt-recent-wrap').hidden = !recent.length;+  $('nt-recent').innerHTML = recent.map(r =>+    '<div>' + esc((r.ts || '').replace('T', ' ').slice(0, 16)) + '  ' + esc(r.kind) + '  ' + esc(r.label) + '</div>').join('');+}+async function notifyCall(method, path, body) {+  const r = await fetch(path, {+    method, headers: { 'content-type': 'application/json' },+    body: body ? JSON.stringify(body) : undefined,+  });+  const j = await r.json().catch(() => ({}));+  if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status);+  return j;+}+async function setMute(label, muted) {+  try { NOTIFY = await notifyCall('POST', 'api/notify/mute', { label, muted }); renderNotify(); }+  catch (e) { toast('error', 'Could not change alerts for ' + label + ': ' + e.message); }+}+$('notify').onclick = () => { $('notify-modal').classList.add('show'); $('nt-err').textContent = ''; loadNotify(); };+$('close-notify').onclick = () => $('notify-modal').classList.remove('show');+$('notify-modal').onclick = e => { if (e.target === $('notify-modal')) $('notify-modal').classList.remove('show'); };+$('nt-save').onclick = async () => {+  const input = $('nt-webhook');+  $('nt-err').textContent = '';+  try {+    NOTIFY = await notifyCall('POST', 'api/notify/webhook', { webhook: input.value });+    input.value = '';+    renderNotify();+    toast('success', 'Connected to ' + NOTIFY.space + '. Send a test to check it arrives.');+  } catch (e) { $('nt-err').textContent = e.message; }+};+$('nt-test').onclick = async () => {+  const b = $('nt-test');+  b.disabled = true; b.textContent = 'Sending...';+  try { await notifyCall('POST', 'api/notify/test'); toast('success', 'Test message sent to ' + NOTIFY.space); }+  catch (e) { toast('error', 'Test failed: ' + e.message); }+  finally { b.textContent = 'Send test'; loadNotify(); }+};+$('nt-clear').onclick = async () => {+  if (!confirm('Disconnect your Google Chat space? No alerts will be sent until you connect one again.')) return;+  try { NOTIFY = await notifyCall('DELETE', 'api/notify/webhook'); renderNotify(); toast('info', 'Notifications are off'); }+  catch (e) { toast('error', 'Could not disconnect: ' + e.message); }+};+ $('filter-all').onclick = () => setFilter('all'); $('filter-faults').onclick = () => setFilter('faults'); function setFilter(f) {⋯ 61 unchanged lines ⋯ </script> </body> </html>+--- a/app/package.json+++ b/app/package.json@@ -1,9 +1,9 @@ {   "name": "svcwatch",-  "version": "1.0.1",+  "version": "1.1.0",   "private": true,   "type": "module",   "scripts": {⋯ 3 unchanged lines ⋯--- a/package.json+++ b/package.json@@ -1,66 +1,67 @@⋯ 1 unchanged line ⋯   "slug": "svcwatch",   "title": "Service Containers",   "type": "app",-  "version": "1.0.1",+  "version": "1.1.0",   "description": "One dashboard for every Adom service container: what is healthy, what is down, why, and a restart button that runs the watchdog's own start command. Reads the watchdog's verdicts off disk, so it costs no extra probes and no vendor API quota.",   "tags": [     "cli",⋯ 39 unchanged lines ⋯   },   "scripts": {     "install": "./install.sh",+    "test": "node --test test/notify.test.mjs",     "uninstall": "./uninstall.sh"   },   "hero": {⋯ 13 unchanged lines ⋯--- a/README.md+++ b/README.md@@ -1,51 +1,77 @@⋯ 41 unchanged lines ⋯ svcwatch ui toast "..."        raise a toast on the page svcwatch ui sweep              run a watchdog sweep now svcwatch ui restart <svc> --reason "..."+svcwatch notify status           your Google Chat alerts: on or off, mutes+svcwatch notify set-webhook      connect your space (reads the URL from stdin)+svcwatch notify test             send a test message to your space+svcwatch notify mute|unmute <svc>+svcwatch notify run [--background]   alert on what the last sweep changed+svcwatch notify clear            disconnect your space ```  `ui restart` refuses without a written `--reason`. Restarting a shared service interrupts whoever is using it, so the reason is recorded, not decorative. +## Notifications++Each Adom account that runs svcwatch can send its own alerts to its own Google Chat space. Open the bell icon, paste the space's incoming webhook (in Google Chat: the space, then Apps & integrations, Webhooks), press Connect, then Send test.++- **Only your own services.** Alerts cover the services your own `service-watchdog.sh` watches and go only to your webhook. There is no shared or global webhook, so nobody hears about anyone else's containers.+- **When.** Once when a service goes down (after the watchdog confirms it on two sweeps in a row), a reminder at most once a day while it stays down, and once when it recovers. Each alert says what is down, since when, why, and the fix: the Restart button, or the row's start command and where it runs.+- **Mute** a service in the same panel, for example while you are working on it.+- **The webhook is a credential.** It is stored in `~/.config/svcwatch/notify.json` (owner-only), never in the repo, a command line, a log or the page. The panel shows only the masked space id. The CLI reads it from stdin: `svcwatch notify set-webhook < file`. It is bound to the account that connected it, and a run under another account refuses to post.++Alerts go out from where the verdicts are made. Add this line at the end of your `~/bin/service-watchdog.sh`, after the sweep:++```bash+# Google Chat alerts for what this sweep changed (svcwatch notify). Background, with+# the sweep lock (fd 9) closed, so a slow Chat can never hold up or lock out a sweep.+[ -x "$HOME/.local/bin/svcwatch" ] && "$HOME/.local/bin/svcwatch" notify run --background 9>&- >/dev/null 2>&1 || true+```++The dashboard's Run sweep button notifies on its own. A ledger and a lock keep the two from sending the same alert twice, an alert that fails to deliver is retried on the next sweep, and each run has a time budget.+ ## Adding a service  svcwatch keeps no service list. It reads the `TARGETS` rows in `~/bin/service-watchdog.sh`, so adding a row there makes the card appear with its host, port, SSH target and start command already filled in.+--- a/SKILL.md+++ b/SKILL.md@@ -1,81 +1,93 @@⋯ 40 unchanged lines ⋯ svcwatch ui toast "..."        raise a toast on the page svcwatch ui sweep              run a watchdog sweep now svcwatch ui restart <svc> --reason "..."    restart one service+svcwatch notify status|set-webhook|test|mute <svc>|unmute <svc>|run|clear ```  `ui restart` refuses without a written `--reason`. Restarting a shared service interrupts whoever is using it, so the reason is recorded, not decorative. +## Notifications (per user, Google Chat)++Each Adom account connects its own Chat space through its own incoming webhook; alerts cover only that account's own watchdog verdicts. There is no shared webhook. Down (after the two-sweep debounce), at most one reminder a day while down, and recovered. Each alert names what is down, since when, why, and the fix.++- Connect: the bell icon in the dashboard, or `svcwatch notify set-webhook < file`. NEVER put the webhook in argv, a log, a commit or chat: it is a credential. Only `https://chat.googleapis.com/v1/spaces/<id>/messages?key=..&token=..` is accepted.+- Check: `svcwatch notify status` (masked space, mutes, last error), `svcwatch notify test`.+- Mute: `svcwatch notify mute <svc>` / `unmute <svc>`, or the toggles in the panel.+- Wiring: the user's `service-watchdog.sh` ends with `svcwatch notify run --background 9>&-` (the README has the exact line). The Run sweep button notifies too; a ledger and lock in `~/.config/svcwatch/` deduplicate.+- Endpoints: `GET /api/notify`, `POST|DELETE /api/notify/webhook`, `POST /api/notify/test`, `POST /api/notify/mute`. None of them returns the webhook.+ ## Endpoints  | Route | Purpose |⋯ 27 unchanged lines ⋯ public host, port, SSH target and start command already filled in. A service with no start command in `TARGETS` gets a disabled Restart button and a tooltip saying so, rather than a button that would fail.+--- a/test/notify.test.mjs+++ b/test/notify.test.mjs@@ -0,0 +1,506 @@+// Tests for per-user Google Chat notifications (app/notify.js, the+// /api/notify routes and `svcwatch notify`). Run: node --test test/+//+// Nothing here reaches Google: every delivery goes to test/fake-webhook.mjs.++import test from 'node:test';+import assert from 'node:assert/strict';+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, statSync, existsSync, rmSync } from 'fs';+import { join, dirname } from 'path';+import { tmpdir } from 'os';+import { spawn, spawnSync } from 'child_process';+import { fileURLToPath } from 'url';++import * as notify from '../app/notify.js';+import { readState } from '../app/state.js';+import { startFakeWebhook } from './fake-webhook.mjs';++const APP = join(dirname(fileURLToPath(import.meta.url)), '..', 'app');+const HOUR = 3600e3;+const T0 = Date.parse('2026-10-30T12:00:00Z');++const hook = (space = 'AAQAdrewSpace01', key = 'KEYdrew123', token = 'TOKdrew456') =>+  `https://chat.googleapis.com/v1/spaces/${space}/messages?key=${key}&token=${token}`;++// One user's world: a config dir, a watchdog bin dir with TARGETS, a state dir.+function makeUser(name, targets) {+  const root = mkdtempSync(join(tmpdir(), `svcwatch-${name}-`));+  const user = {+    root,+    config: join(root, 'config'),+    bin: join(root, 'bin'),+    state: join(root, 'state'),+    account: `${name}@adom.inc`,+  };+  mkdirSync(user.bin, { recursive: true });+  mkdirSync(user.state, { recursive: true });+  writeFileSync(join(user.bin, 'service-watchdog.sh'),+    '#!/usr/bin/env bash\nTARGETS=(\n' + targets.map(t => `  "${t}"`).join('\n') + '\n)\n');+  user.verdict = (label, check, line) => writeFileSync(join(user.state, `${label}-${check}.state`), line + '\n');+  user.readState = () => readState({ stateDir: user.state, binDir: user.bin });+  return user;+}++// Make notify.js act as this user for the duration of fn.+async function as(user, fn) {+  const saved = { dir: process.env.SVCWATCH_CONFIG_DIR, acct: process.env.SVCWATCH_ACCOUNT };+  process.env.SVCWATCH_CONFIG_DIR = user.config;+  process.env.SVCWATCH_ACCOUNT = user.account;+  try { return await fn(); }+  finally {+    if (saved.dir === undefined) delete process.env.SVCWATCH_CONFIG_DIR; else process.env.SVCWATCH_CONFIG_DIR = saved.dir;+    if (saved.acct === undefined) delete process.env.SVCWATCH_ACCOUNT; else process.env.SVCWATCH_ACCOUNT = saved.acct;+  }+}++const fast = { attempts: 3, backoffMs: [5, 5], timeoutMs: 500 };++const svc = (over = {}) => ({+  label: 'mouser', name: 'Mouser', ssh: '[email protected]', startCmd: 'bash /srv/start.sh',+  status: 'down',+  checks: [{ key: 'health', name: 'Health', kind: 'down', reason: 'public /health answered 502', since: '2026-10-30T10:00:00Z' }],+  ...over,+});+const empty = () => ({ services: {}, sent: [] });++// ── the webhook ─────────────────────────────────────────────────────────+test('validateWebhook accepts a real Google Chat webhook', () => {+  const r = notify.validateWebhook(hook());+  assert.equal(r.ok, true);+  assert.equal(r.space, 'AAQAdrewSpace01');+  assert.equal(notify.validateWebhook('  ' + hook() + '\n').ok, true, 'surrounding whitespace from a paste is trimmed');+});++test('validateWebhook refuses anything that is not a chat.googleapis.com webhook', () => {+  const bad = [+    '',+    'not a url',+    hook().replace('https://', 'http://'),+    'https://chat.googleapis.com.evil.example/v1/spaces/A/messages?key=k&token=t',+    'https://evil.example/v1/spaces/A/messages?key=k&token=t',+    'https://chat.googleapis.com:8443/v1/spaces/A/messages?key=k&token=t',+    'https://user:[email protected]/v1/spaces/A/messages?key=k&token=t',+    'https://chat.googleapis.com/v1/spaces/A/messages?key=k',+    'https://chat.googleapis.com/v1/spaces/A/messages?token=t',+    'https://chat.googleapis.com/v1/spaces/A/other?key=k&token=t',+    'https://chat.googleapis.com/v1/spaces/../messages?key=k&token=t',+    hook() + ' ' + hook(),+  ];+  for (const b of bad) assert.equal(notify.validateWebhook(b).ok, false, `should refuse: ${b}`);+});++test('maskSpace shows enough to recognise a space and nothing more', () => {+  assert.equal(notify.maskSpace('AAQAnNCsRkA'), 'spaces/AAQA...RkA');+  assert.equal(notify.maskSpace(''), '');+});++test('scrub removes the webhook, its key and its token from any text', () => {+  const w = hook();+  const out = notify.scrub(`failed POST ${w} key=KEYdrew123 token=TOKdrew456`, w);+  for (const secret of [w, 'KEYdrew123', 'TOKdrew456']) assert.ok(!out.includes(secret), `leaked ${secret}`);+  assert.ok(!notify.scrub('see https://chat.googleapis.com/v1/spaces/Z/messages?key=a&token=b').includes('token=b'),+    'an unknown webhook URL is removed too');+});++// ── the rules ───────────────────────────────────────────────────────────+test('a pending service sends nothing: the watchdog has not confirmed it', () => {+  const p = svc({ status: 'pending', checks: [{ name: 'Health', kind: 'pending', reason: 'x', since: '2026-10-30T11:55:00Z' }] });+  assert.deepEqual(notify.evaluate([p], empty(), [], T0), []);+});++test('a down service alerts once, saying what, since when, and the fix', () => {+  const [m, ...rest] = notify.evaluate([svc()], empty(), [], T0);+  assert.equal(rest.length, 0);+  assert.equal(m.kind, 'down');+  assert.match(m.text, /DOWN: Mouser/);+  assert.match(m.text, /Down since 2026-10-30 10:00 UTC \(2h 0m\)/);+  assert.match(m.text, /Why: Health: public \/health answered 502/);+  assert.match(m.text, /Press Restart on Mouser/);+  assert.match(m.text, /john-mouser@adom\.cloud: bash \/srv\/start\.sh/);+  assert.equal(m.record.since, '2026-10-30T10:00:00Z');+});++test('still down the same day: no second alert; a day later: one reminder', () => {+  const ledger = { services: { mouser: { since: '2026-10-30T10:00:00Z', firstAlertAt: new Date(T0).toISOString(), lastAlertAt: new Date(T0).toISOString() } } };+  assert.deepEqual(notify.evaluate([svc()], ledger, [], T0 + 23 * HOUR), []);+  const [m] = notify.evaluate([svc()], ledger, [], T0 + 24 * HOUR);+  assert.equal(m.kind, 'repeat');+  assert.match(m.text, /STILL DOWN: Mouser/);+  assert.match(m.text, /at most once a day/);+});++test('recovery is announced once, only for a service we alerted about', () => {+  const ok = svc({ status: 'ok', checks: [{ name: 'Health', kind: 'ok' }] });+  assert.deepEqual(notify.evaluate([ok], empty(), [], T0), [], 'never alerted, nothing to say');+  const ledger = { services: { mouser: { since: '2026-10-30T10:00:00Z', lastAlertAt: new Date(T0).toISOString() } } };+  const [m] = notify.evaluate([ok], ledger, [], T0 + HOUR);+  assert.equal(m.kind, 'recovered');+  assert.match(m.text, /RECOVERED: Mouser/);+  assert.match(m.text, /Back up after 3h 0m/);+  assert.equal(m.record, null, 'recovery forgets the service');+});++test('a muted service never alerts, and unmuting later does not replay a stale recovery', () => {+  assert.deepEqual(notify.evaluate([svc()], empty(), ['mouser'], T0), []);+  const ledger = { services: { mouser: { since: 'x', lastAlertAt: new Date(T0).toISOString() } } };+  const ok = svc({ status: 'ok', checks: [{ name: 'Health', kind: 'ok' }] });+  const plan = notify.evaluate([ok], ledger, ['mouser'], T0 + HOUR);+  assert.deepEqual(plan.map(m => m.kind), ['forget']);+});++test('a service with no start command gets a fix that says so', () => {+  const [m] = notify.evaluate([svc({ startCmd: '' })], empty(), [], T0);+  assert.match(m.text, /No start command in TARGETS for mouser\. SSH to john-mouser@adom\.cloud/);+});++test('a row removed from TARGETS is forgotten without a message', () => {+  const ledger = { services: { gone: { since: 'x', lastAlertAt: new Date(T0).toISOString() } } };+  assert.deepEqual(notify.evaluate([], ledger, [], T0).map(m => [m.label, m.kind]), [['gone', 'forget']]);+});++// ── delivery ────────────────────────────────────────────────────────────+test('post retries a 5xx and stops at the first success', async () => {+  const fake = await startFakeWebhook();+  try {+    fake.script.push(500, 503);+    const r = await notify.post(hook(), 'hello', { ...fast, fetchImpl: fake.fetchImpl });+    assert.equal(r.ok, true);+    assert.equal(r.attempts, 3);+    assert.equal(fake.calls.length, 3);+    assert.deepEqual(fake.calls[2].body, { text: 'hello' });+  } finally { await fake.close(); }+});++test('post does not retry a 4xx: the webhook itself is wrong', async () => {+  const fake = await startFakeWebhook();+  try {+    fake.script.push(404);+    const r = await notify.post(hook(), 'hello', { ...fast, fetchImpl: fake.fetchImpl });+    assert.equal(r.ok, false);+    assert.equal(fake.calls.length, 1);+    assert.match(r.error, /HTTP 404/);+  } finally { await fake.close(); }+});++test('post gives up after a bounded number of attempts on a hanging server', async () => {+  const fake = await startFakeWebhook();+  try {+    fake.script.push('hang', 'hang', 'hang');+    const t = Date.now();+    const r = await notify.post(hook(), 'hello', { attempts: 3, backoffMs: [5], timeoutMs: 150, fetchImpl: fake.fetchImpl });+    assert.equal(r.ok, false);+    assert.equal(r.attempts, 3);+    assert.match(r.error, /no answer within/);+    assert.ok(Date.now() - t < 3000, 'bounded');+    assert.ok(!r.error.includes('TOKdrew456'));+  } finally { await fake.close(); }+});++// ── a full run against a fixture watchdog ───────────────────────────────+test('run: pending, down, deduped, daily reminder, recovered, quiet', async () => {+  const drew = makeUser('drew', ['mouser|[email protected]|mouser.adom.cloud|8080|https://mouser.adom.cloud/|bash /srv/start.sh']);+  const fake = await startFakeWebhook();+  try {+    await as(drew, async () => {+      assert.equal((await notify.setWebhook(hook())).ok, true);+      const go = (now) => notify.run({ ...fast, fetchImpl: fake.fetchImpl, readState: drew.readState, now });++      drew.verdict('mouser', 'health', 'pending|public /health answered 502|2026-10-30T11:55:00Z');+      assert.equal((await go(T0)).sent, 0, 'pending: nothing yet');++      drew.verdict('mouser', 'health', 'down|public /health answered 502|2026-10-30T11:55:00Z');+      assert.equal((await go(T0 + 5 * 60e3)).sent, 1, 'confirmed down: one alert');+      assert.equal((await go(T0 + 10 * 60e3)).sent, 0, 'next sweep: deduplicated');+      assert.equal((await go(T0 + 20 * HOUR)).sent, 0, 'same day: nothing');+      assert.equal((await go(T0 + 25 * HOUR)).sent, 1, 'a day on: one reminder');++      drew.verdict('mouser', 'health', 'ok');+      assert.equal((await go(T0 + 26 * HOUR)).sent, 1, 'recovered: one message');+      assert.equal((await go(T0 + 27 * HOUR)).sent, 0, 'then quiet');++      const texts = fake.texts();+      assert.equal(texts.length, 3);+      assert.match(texts[0], /^\*DOWN: Mouser\* \(mouser\)/);+      assert.match(texts[0], /Down since 2026-10-30 11:55 UTC/);+      assert.match(texts[0], /drew-mouser@adom\.cloud: bash \/srv\/start\.sh/);+      assert.match(texts[1], /^\*STILL DOWN: Mouser\*/);+      assert.match(texts[2], /^\*RECOVERED: Mouser\*/);+    });+  } finally { await fake.close(); }+});++test('run: an undelivered alert is not recorded, so the next sweep sends it', async () => {+  const drew = makeUser('drew', ['mouser|[email protected]|h|1|u|bash /srv/start.sh']);+  const fake = await startFakeWebhook();+  try {+    await as(drew, async () => {+      await notify.setWebhook(hook());+      drew.verdict('mouser', 'health', 'down|502|2026-10-30T11:55:00Z');+      fake.script.push(500, 500, 500);+      const r1 = await notify.run({ ...fast, fetchImpl: fake.fetchImpl, readState: drew.readState, now: T0 });+      assert.deepEqual([r1.sent, r1.failed], [0, 1]);+      assert.match(notify.status().lastError, /down for mouser not delivered: Google Chat answered HTTP 500/);+      const r2 = await notify.run({ ...fast, fetchImpl: fake.fetchImpl, readState: drew.readState, now: T0 + 300e3 });+      assert.deepEqual([r2.sent, r2.failed], [1, 0]);+      assert.equal(notify.status().lastError, null);+      assert.equal(fake.texts().length, 1);+    });+  } finally { await fake.close(); }+});++test('run: a run that uses up its time budget leaves the rest for the next sweep', async () => {+  const drew = makeUser('drew', ['a|s@x|h|1|u|c', 'b|s@x|h|1|u|c']);+  const fake = await startFakeWebhook();+  try {+    await as(drew, async () => {+      await notify.setWebhook(hook());+      drew.verdict('a', 'health', 'down|x|2026-10-30T11:00:00Z');+      drew.verdict('b', 'health', 'down|x|2026-10-30T11:00:00Z');+      fake.script.push('hang');+      const r = await notify.run({ attempts: 1, timeoutMs: 120, fetchImpl: fake.fetchImpl, readState: drew.readState, now: T0, budgetMs: 50 });+      assert.equal(r.deferred, 1, 'second alert deferred, not dropped');+      const r2 = await notify.run({ ...fast, fetchImpl: fake.fetchImpl, readState: drew.readState, now: T0 + 300e3 });+      assert.equal(r2.sent, 2, 'both go out next sweep');+    });+  } finally { await fake.close(); }+});++test('run: two runs at once (cron sweep and a Run sweep click) send one message', async () => {+  const drew = makeUser('drew', ['mouser|s@x|h|1|u|c']);+  const fake = await startFakeWebhook();+  try {+    await as(drew, async () => {+      await notify.setWebhook(hook());+      drew.verdict('mouser', 'health', 'down|x|2026-10-30T11:00:00Z');+      const opts = { ...fast, fetchImpl: fake.fetchImpl, readState: drew.readState, now: T0 };+      const [a, b] = await Promise.all([notify.run(opts), notify.run(opts)]);+      assert.deepEqual([a.status, b.status].sort(), ['busy', 'ok']);+      assert.equal(fake.texts().length, 1);+      assert.ok(!existsSync(join(drew.config, 'notify.lock')), 'lock released');+    });+  } finally { await fake.close(); }+});++test('run: with no webhook connected nothing is sent and nothing is written', async () => {+  const drew = makeUser('drew', ['mouser|s@x|h|1|u|c']);+  const fake = await startFakeWebhook();+  try {+    await as(drew, async () => {+      drew.verdict('mouser', 'health', 'down|x|2026-10-30T11:00:00Z');+      const r = await notify.run({ ...fast, fetchImpl: fake.fetchImpl, readState: drew.readState, now: T0 });+      assert.equal(r.status, 'not_configured');+      assert.equal(fake.calls.length, 0);+    });+  } finally { await fake.close(); }+});++test('run: a webhook connected by one account is never used by another', async () => {+  const drew = makeUser('drew', ['mouser|s@x|h|1|u|c']);+  const fake = await startFakeWebhook();+  try {+    await as(drew, () => notify.setWebhook(hook()));+    drew.verdict('mouser', 'health', 'down|x|2026-10-30T11:00:00Z');+    // Same config directory (a copied home, a shared container), another account.+    await as({ ...drew, account: '[email protected]' }, async () => {+      const r = await notify.run({ ...fast, fetchImpl: fake.fetchImpl, readState: drew.readState, now: T0 });+      assert.equal(r.status, 'wrong_account');+      assert.equal(r.owner, '[email protected]');+      const t = await notify.sendTest({ ...fast, fetchImpl: fake.fetchImpl });+      assert.equal(t.ok, false);+    });+    assert.equal(fake.calls.length, 0);+  } finally { await fake.close(); }+});++test('isolation: Drew hears only about Drew\'s services, John only about John\'s', async () => {+  const drew = makeUser('drew', ['factoryos|[email protected]|h|1|u|bash fos.sh']);+  const john = makeUser('john', ['mouser|[email protected]|h|1|u|bash mouser.sh']);+  const fake = await startFakeWebhook();+  try {+    await as(drew, () => notify.setWebhook(hook('DREWspace01', 'kd', 'td')));+    await as(john, () => notify.setWebhook(hook('JOHNspace01', 'kj', 'tj')));+    drew.verdict('factoryos', 'health', 'down|x|2026-10-30T11:00:00Z');+    john.verdict('mouser', 'health', 'down|y|2026-10-30T11:00:00Z');+    for (const u of [drew, john]) {+      await as(u, () => notify.run({ ...fast, fetchImpl: fake.fetchImpl, readState: u.readState, now: T0 }));+    }+    const byPath = fake.calls.map(c => [c.path.split('?')[0], c.body.text.split('\n')[0]]);+    assert.deepEqual(byPath, [+      ['/v1/spaces/DREWspace01/messages', '*DOWN: factoryos* (factoryos)'],+      ['/v1/spaces/JOHNspace01/messages', '*DOWN: Mouser* (mouser)'],+    ]);+  } finally { await fake.close(); }+});++// ── storage ─────────────────────────────────────────────────────────────+test('the webhook is stored owner-only and never comes back out', async () => {+  const drew = makeUser('drew', ['mouser|s@x|h|1|u|c']);+  const fake = await startFakeWebhook();+  try {+    await as(drew, async () => {+      const r = await notify.setWebhook(hook());+      assert.deepEqual(r, { ok: true, space: 'spaces/AAQA...e01', account: '[email protected]' });+      assert.equal(statSync(join(drew.config, 'notify.json')).mode & 0o777, 0o600);+      assert.equal(statSync(drew.config).mode & 0o777, 0o700);+      fake.script.push(500, 500, 500);+      await notify.sendTest({ ...fast, fetchImpl: fake.fetchImpl });+      const st = JSON.stringify(notify.status());+      const log = readFileSync(notify.logFile(), 'utf8');+      for (const leak of ['KEYdrew123', 'TOKdrew456', 'chat.googleapis.com']) {+        assert.ok(!st.includes(leak), `status leaked ${leak}`);+        assert.ok(!log.includes(leak), `log leaked ${leak}`);+      }+      assert.equal(notify.status().connected, true);+    });+  } finally { await fake.close(); }+});++test('a bad webhook is refused and nothing is written', async () => {+  const drew = makeUser('drew', []);+  await as(drew, async () => {+    const r = await notify.setWebhook('https://hooks.slack.com/services/T/B/X');+    assert.equal(r.ok, false);+    assert.ok(!existsSync(join(drew.config, 'notify.json')));+  });+});++test('mute and unmute persist, and disconnect forgets what was announced', async () => {+  const drew = makeUser('drew', ['mouser|s@x|h|1|u|c']);+  const fake = await startFakeWebhook();+  try {+    await as(drew, async () => {+      await notify.setWebhook(hook());+      assert.deepEqual(notify.setMuted('mouser', true).mutes, ['mouser']);+      drew.verdict('mouser', 'health', 'down|x|2026-10-30T11:00:00Z');+      assert.equal((await notify.run({ ...fast, fetchImpl: fake.fetchImpl, readState: drew.readState, now: T0 })).sent, 0);+      assert.deepEqual(notify.setMuted('mouser', false).mutes, []);+      assert.equal((await notify.run({ ...fast, fetchImpl: fake.fetchImpl, readState: drew.readState, now: T0 + 1 })).sent, 1);+      assert.deepEqual(notify.status().alerting, ['mouser']);+      notify.clearWebhook();+      assert.equal(notify.status().connected, false);+      assert.deepEqual(notify.status().alerting, []);+    });+  } finally { await fake.close(); }+});++// ── the server routes ───────────────────────────────────────────────────+async function startServer(user) {+  const home = join(user.root, 'home');+  mkdirSync(home, { recursive: true });+  const env = {+    ...process.env, HOME: home, SVCWATCH_CONFIG_DIR: user.config, SVCWATCH_ACCOUNT: user.account,+    WD_STATE_DIR: user.state, WD_BIN_DIR: user.bin,+  };+  const child = spawn(process.execPath, [join(APP, 'server.js'), 'serve', '--port', '0', '--keep-alive', '--ai-thread', 'test'],+    { env, stdio: ['ignore', 'pipe', 'pipe'] });+  const port = await new Promise((resolve, reject) => {+    let out = '';+    const t = setTimeout(() => reject(new Error('server did not start: ' + out)), 10000);+    child.stdout.on('data', d => {+      out += d;+      const m = out.match(/listening on port (\d+)/);+      if (m) { clearTimeout(t); resolve(Number(m[1])); }+    });+  });+  const base = `http://127.0.0.1:${port}`;+  const call = async (method, path, body) => {+    const r = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body ? JSON.stringify(body) : undefined });+    return { status: r.status, text: await r.text() };+  };+  return { call, stop: () => { child.kill('SIGTERM'); } };+}++test('server: connect, mute, disconnect, and the webhook never reaches the page', async () => {+  const drew = makeUser('drew', ['mouser|s@x|mouser.adom.cloud|1|u|c']);+  drew.verdict('mouser', 'health', 'ok');+  const srv = await startServer(drew);+  try {+    let r = await srv.call('GET', '/api/notify');+    assert.equal(JSON.parse(r.text).connected, false);++    r = await srv.call('POST', '/api/notify/webhook', { webhook: 'https://evil.example/v1/spaces/A/messages?key=k&token=t' });+    assert.equal(r.status, 400);+    assert.match(JSON.parse(r.text).error, /Only Google Chat webhooks/);++    r = await srv.call('POST', '/api/notify/webhook', { webhook: hook() });+    assert.equal(r.status, 200);+    const st = JSON.parse(r.text);+    assert.equal(st.connected, true);+    assert.equal(st.space, 'spaces/AAQA...e01');+    assert.equal(st.account, '[email protected]');++    r = await srv.call('POST', '/api/notify/mute', { label: 'mouser', muted: true });+    assert.deepEqual(JSON.parse(r.text).mutes, ['mouser']);++    // Every surface the browser or the AI can read.+    for (const path of ['/', '/api/notify', '/state', '/api/state', '/console', '/health', '/settings', '/api/messages']) {+      const page = await srv.call('GET', path);+      // The key, the token and the unmasked space id. (The page's input+      // placeholder legitimately shows the chat.googleapis.com URL shape.)+      for (const leak of ['KEYdrew123', 'TOKdrew456', 'AAQAdrewSpace01']) {+        assert.ok(!page.text.includes(leak), `${path} leaked ${leak}`);+      }+    }++    r = await srv.call('DELETE', '/api/notify/webhook');+    assert.equal(JSON.parse(r.text).connected, false);+    r = await srv.call('POST', '/api/notify/test');+    assert.equal(r.status, 502);+    assert.match(JSON.parse(r.text).error, /No webhook connected/);++    r = await srv.call('POST', '/api/notify/webhook', { webhook: 'x'.repeat(9000) });+    assert.equal(r.status, 413, 'oversized bodies are refused');+  } finally { srv.stop(); }+});++test('page: the Notifications panel is wired to the routes', () => {+  const html = readFileSync(join(APP, 'index.html'), 'utf8');+  for (const id of ['notify', 'notify-modal', 'nt-webhook', 'nt-save', 'nt-test', 'nt-clear', 'nt-services']) {+    assert.ok(html.includes(`id="${id}"`), `missing #${id}`);+  }+  assert.match(html, /id="nt-webhook" type="password" autocomplete="off"/);+  for (const route of ["'api/notify'", "'api/notify/webhook'", "'api/notify/test'", "'api/notify/mute'"]) {+    assert.ok(html.includes(route), `page never calls ${route}`);+  }+});++// ── the CLI ─────────────────────────────────────────────────────────────+function cli(user, args, input) {+  return spawnSync(process.execPath, [join(APP, 'cli.js'), ...args], {+    env: { ...process.env, SVCWATCH_CONFIG_DIR: user.config, SVCWATCH_ACCOUNT: user.account },+    input, encoding: 'utf8', timeout: 15000,+  });+}++test('cli: refuses a webhook on the command line, takes it on stdin', () => {+  const drew = makeUser('drew', []);+  let r = cli(drew, ['notify', 'set-webhook', hook()]);+  assert.equal(r.status, 1);+  assert.match(r.stderr, /Do not put the webhook on the command line/);+  assert.ok(!existsSync(join(drew.config, 'notify.json')), 'nothing written');++  r = cli(drew, ['notify', 'set-webhook'], hook() + '\n');+  assert.equal(r.status, 0, r.stderr);+  assert.match(r.stdout, /OK: webhook connected to spaces\/AAQA\.\.\.e01 for drew@adom\.inc/);++  r = cli(drew, ['notify', 'status']);+  assert.match(r.stdout, /notifications on: spaces\/AAQA\.\.\.e01/);+  assert.ok(!r.stdout.includes('TOKdrew456'));++  r = cli(drew, ['notify', 'mute', 'mouser']);+  assert.match(r.stdout, /OK: mouser muted/);+  r = cli(drew, ['notify', 'clear']);+  assert.equal(r.status, 0);+  assert.match(cli(drew, ['notify', 'status']).stdout, /notifications are off/);+});++test('cli: run --background returns at once, so it can never hold up a sweep', () => {+  const drew = makeUser('drew', []);+  const t = Date.now();+  const r = cli(drew, ['notify', 'run', '--background']);+  assert.equal(r.status, 0);+  assert.match(r.stdout, /started in the background/);+  assert.ok(Date.now() - t < 5000);+  assert.match(cli(drew, ['notify', 'run']).stdout, /notifications are off: nothing to do/);+});+--- a/test/fake-webhook.mjs+++ b/test/fake-webhook.mjs@@ -0,0 +1,44 @@+// A stand-in for Google Chat's incoming webhook. It records every POST and+// answers with whatever the test scripted: a status per call, or a hang.+//+// The production code only accepts https://chat.googleapis.com/... URLs, so+// tests do not point it somewhere else. Instead they hand notify.js a fetch+// that sends chat.googleapis.com requests here, keeping the real URL (and its+// key and token) in the request so a test can check nothing leaks.++import { createServer } from 'http';++export async function startFakeWebhook() {+  const calls = [];+  const script = [];          // per-call answers: a status number, or 'hang'+  const server = createServer((req, res) => {+    let body = '';+    req.on('data', c => body += c);+    req.on('end', () => {+      let json = null;+      try { json = JSON.parse(body); } catch {}+      const answer = script.length ? script.shift() : 200;+      calls.push({ method: req.method, path: req.url, body: json, answer });+      if (answer === 'hang') return;          // never answer; the client must time out+      res.writeHead(answer, { 'content-type': 'application/json' });+      res.end(answer < 300 ? '{"name":"spaces/x/messages/y"}' : '{"error":{"code":' + answer + '}}');+    });+  });+  await new Promise(r => server.listen(0, '127.0.0.1', r));+  const port = server.address().port;++  const fetchImpl = (url, init) => {+    const u = new URL(url);+    if (u.hostname !== 'chat.googleapis.com') throw new Error('test fetch: refusing ' + u.hostname);+    return fetch(`http://127.0.0.1:${port}${u.pathname}${u.search}`, init);+  };++  return {+    calls,+    script,+    fetchImpl,+    texts: () => calls.filter(c => c.answer === 200).map(c => c.body?.text || ''),+    close: () => new Promise(r => { server.closeAllConnections?.(); server.close(r); }),+  };+}+

Comments

Drew Owens ·

The Notifications panel against Drew's real (read-only) verdicts: Off, a Slack URL refused with its message, and one mute toggle per service. The page shows a stale-watchdog banner because Drew's sweep loop had died in a container restart, which is the self-restart gap noted at the end of the description.

2026-10-30T22-53-25.870

Log in to comment.