Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.28.3 feat(recipes): restart-sweep — detect dropped Telegram messages after gateway restarts (#675)

garrytan-agentse744eda66c9f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe18c7f887..4ce0aafe49 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,86 @@
All notable changes to GBrain will be documented in this file.
+## [0.28.3] - 2026-05-06
+
+## **`gbrain integrations show restart-sweep` — detect dropped Telegram messages after OpenClaw gateway restarts.**
+## **Self-contained recipe: copy the script into your host repo, set three env vars, wire a 5-minute cron. Cooldown-gated so the same dropped session doesn't spam you.**
+
+When the OpenClaw gateway restarts, webhook-delivered Telegram messages that haven't been processed yet get dropped permanently. Long-poll bots can replay missed updates via `getUpdates`. Webhook bots cannot. The new `restart-sweep` recipe reads OpenClaw's session state, finds sessions with `abortedLastRun: true`, and alerts you on Telegram (or stdout) so you know when something was lost. The script is inlined in the recipe so the agent installer is self-contained.
+
+Three pieces of correctness that the original PR missed: the alert message double-escaped newlines so Telegram saw literal `\n` characters; the shell-interpolated `exec()` was command-injectable on `OPENCLAW_TELEGRAM_GROUP`; the idempotency state collapsed when `/tmp/bootstrap-services.log` was missing because the restart-time fallback changed every run, so the same stale session would re-alert every 5 minutes forever. All fixed. The cooldown layer keys on `(sessionKey, lastAlertedAt)` with a 6h re-alert threshold — works whether the bootstrap log is stable or missing.
+
+### What you get
+
+| Capability | Before | After |
+|---|---|---|
+| Detect dropped Telegram messages after gateway restarts | Manual eyeballing | `gbrain integrations doctor restart-sweep` |
+| Idempotent re-alerting | None — re-alerts every 5 min | 6h cooldown per sessionKey |
+| Shell-injection surface in alert path | `exec()` of interpolated string | `execFile` argv array |
+| State file location | Hardcoded `/tmp/restart-sweep.log` | `~/.gbrain/integrations/restart-sweep/` (honors `GBRAIN_HOME`) |
+| Tests | 14 (vitest, semantically bogus due to import-time env snapshot) | 27 (bun:test, constructor-time env reads) |
+
+### What this means for you
+
+If you run OpenClaw with Telegram in webhook mode:
+
+```bash
+gbrain integrations show restart-sweep
+```
+
+Follow the recipe body. The agent will copy the script into your host repo, configure cron, and verify health. Default behavior is conservative — only `abortedLastRun` sessions alert. Set `OPENCLAW_RESTART_SWEEP_AGGRESSIVE=1` to enable the timing-based heuristic (active-before, silent-after) when you want maximum sensitivity.
+
+Long-poll Telegram bots, non-Telegram message backends, and deployments that don't restart the gateway don't need this — the recipe stays invisible until you set the OpenClaw envs.
+
+## To take advantage of v0.28.3
+
+`gbrain upgrade` picks up the new recipe automatically. To install it:
+
+1. **Browse the recipe:**
+ ```bash
+ gbrain integrations show restart-sweep
+ ```
+2. **Set the secrets** in your host's `.env`:
+ ```bash
+ OPENCLAW_OWNER_IDS=<your user IDs>
+ OPENCLAW_TELEGRAM_GROUP=<your target group>
+ OPENCLAW_ALERT_TOPIC=<optional topic ID>
+ ```
+3. **Verify health:**
+ ```bash
+ gbrain integrations doctor restart-sweep
+ ```
+4. **Wire cron** following the recipe body's wrapper-script pattern (cron doesn't inherit your shell env — the recipe's troubleshooting section walks you through PATH + `.env` loading).
+
+If you've been running an earlier copy of `restart-sweep.mjs` from the directory-shaped recipe (`recipes/restart-sweep/`), the directory is gone in v0.28.3. The script content lives inlined inside `recipes/restart-sweep.md` now. Re-copy the script into your host repo from the new location.
+
+### Itemized changes
+
+#### Added
+- `recipes/restart-sweep.md` — opt-in recipe in the `reflex` category. Frontmatter declares two required env_exists checks plus an `openclaw sessions --json` command check. Body is agent-facing setup instructions: prerequisites, secret collection, host-repo install path, dry-run, cron wiring with absolute paths, verification, tuning, troubleshooting.
+- `test/restart-sweep.test.ts` — 27 bun:test cases covering constructor mode resolution, session filtering, dropped-message detection, log timestamp parsing, idempotency (load/save/prune/atomic-write), cooldown gating, AGGRESSIVE env handling, alert formatting, execFile shell-injection defense, GBRAIN_HOME path overrides, and a sentinel-shape guard.
+
+#### Changed (vs the original PR)
+- Reshaped from `recipes/restart-sweep/` directory (3 files: README + .mjs + .test.ts) into a single self-contained `recipes/restart-sweep.md` with the script inlined as a fenced code block. The recipe loader at `src/commands/integrations.ts:445-485` only discovers `*.md` — the directory shape was invisible.
+- Test extractor anchors on `<!-- restart-sweep:script -->` sentinel comment, salts the tmp filename per call to bypass the ESM import cache. Future doc edits adding example blocks above the script can't accidentally redirect what's tested.
+
+#### Fixed
+- Newline double-escape in alert text — `'\\n'` literals at 8 sites printed as `\n` characters, not real newlines.
+- Shell injection in `sendTelegramAlert` — replaced `exec()` of an interpolated string with `execFile` taking an argv array. Shell metachars in `OPENCLAW_TELEGRAM_GROUP` no longer reach `/bin/sh`.
+- Idempotency state file location — moved from `/tmp/restart-sweep.log` to `~/.gbrain/integrations/restart-sweep/` (honors `GBRAIN_HOME`).
+- Atomic state write via tmp+rename — prevents file corruption from concurrent cron runs (file corruption only; duplicate-send race under overlapping cron is documented as accepted).
+- Corrupt-JSON recovery in `loadAlerted` — invalid `alerted.json` warns to stderr and falls back to empty Map instead of crashing every cron run.
+- Idempotency key collapse with synthesized restart time — added a `(sessionKey, lastAlertedAt)` cooldown layer with 6h re-alert threshold. Cooldown wins when the bootstrap log is missing and `restartTime` is unstable.
+- Constructor-time env reads — moved `OWNER_IDS`, `TELEGRAM_GROUP_ID`, `ALERT_TOPIC` from module top-level to `MessageSweepDetector` constructor. Tests can mutate `process.env` between constructions.
+- Aggressive heuristic gating — the timing-based "active before, silent after" detection is now opt-in via `OPENCLAW_RESTART_SWEEP_AGGRESSIVE=1`. Default OFF because it false-positives during normal quiet periods.
+- Cron environment guidance — recipe body now includes a wrapper-script pattern (`set -a; source .env; set +a; exec /usr/local/bin/node ...`) and explicit `PATH=` line for the cron entry. Closes 80% of cron-day-one failures (env doesn't load, `node` not on stripped PATH).
+
+#### Removed
+- `recipes/restart-sweep/README.md`, `recipes/restart-sweep/restart-sweep.mjs`, `recipes/restart-sweep/test/restart-sweep.test.ts` — superseded by the inlined recipe.
+
+#### For contributors
+- Plan + reviews for this work live at `~/.claude/plans/figure-out-if-we-eager-coral.md`. Three review passes ran (CEO/HOLD, ENG/PLAN, codex outside-voice). Codex caught two silent-correctness bugs the eng review missed: idempotency key collapse (C1) and import-time env snapshot (C2). Both folded in before merge. The plan documents the recipe-vs-plugin-handler decision (held recipe path for v1; plugin handler is the v2 shape per `docs/guides/plugin-handlers.md`).
+
## [0.28.1] - 2026-05-06
## **Long-running deployments stop drowning in zombie processes. /health stops racing the orchestrator. Pool slots free immediately on shutdown.**
diff --git a/CLAUDE.md b/CLAUDE.md
index e8447f94fd..6b28959f61 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -497,7 +497,8 @@ parity), `test/cli.test.ts` (CLI structure), `test/config.test.ts` (config redac
`test/skillify-scaffold.test.ts` (v0.19 `gbrain skillify scaffold` stubs: SKILL.md, script, tests, routing-eval fixtures),
`test/skillpack-install.test.ts` (v0.19 `gbrain skillpack install` managed-block install / update / no-clobber semantics),
`test/skillpack-sync-guard.test.ts` (v0.19 sync-guard: bundled skills stay byte-identical to `skills/` source),
-`test/http-transport.test.ts` (v0.22.7 HTTP transport: 23 unit cases covering bearer auth + missing/no-Bearer/unknown/revoked + `/health` bypass, F1+F2 round-trip via dispatch.ts, F3 invalid_params, application/json response shape (not SSE), CORS default-deny + allowlist, body cap on Content-Length AND chunked, two-bucket rate limit (refill, exhaust+Retry-After, LRU eviction, TTL prune, pre-auth IP fires before DB), and `mcp_request_log` audit on success + auth_failed).
+`test/http-transport.test.ts` (v0.22.7 HTTP transport: 23 unit cases covering bearer auth + missing/no-Bearer/unknown/revoked + `/health` bypass, F1+F2 round-trip via dispatch.ts, F3 invalid_params, application/json response shape (not SSE), CORS default-deny + allowlist, body cap on Content-Length AND chunked, two-bucket rate limit (refill, exhaust+Retry-After, LRU eviction, TTL prune, pre-auth IP fires before DB), and `mcp_request_log` audit on success + auth_failed),
+`test/restart-sweep.test.ts` (v0.28.3 — 27 bun:test cases for the `recipes/restart-sweep.md` inlined script: sentinel-anchored fenced-block extraction with salted tmp filenames to bypass ESM cache; constructor-time env reads (proves no module-load snapshot); idempotency layer load/save/atomic-tmp-rename/corrupt-JSON-recovery/30-day-prune; `(sessionKey, lastAlertedAt)` cooldown gate with 6h threshold (the C1 fix that survives synthesized restartTime); AGGRESSIVE-gate two-state tests; execFile argv shape proving shell metachars in `OPENCLAW_TELEGRAM_GROUP` cannot reach `/bin/sh`; real-`\n`-not-literal alert formatting; `GBRAIN_HOME` state path override).
E2E tests (`test/e2e/`): Run against real Postgres+pgvector. Require `DATABASE_URL`.
- `bun run test:e2e` runs Tier 1 (mechanical, all operations, no API keys). Includes 9 dedicated cases for the postgres-engine `addLinksBatch` / `addTimelineEntriesBatch` bind path — postgres-js's `unnest()` binding is structurally different from PGLite's and gets its own coverage.
diff --git a/README.md b/README.md
index cb4de62aa3..a2a6a46cbb 100644
--- a/README.md
+++ b/README.md
@@ -439,6 +439,7 @@ GBrain ships integration recipes that your agent sets up for you. Each recipe te
| [X-to-Brain](recipes/x-to-brain.md) | — | Twitter timeline + mentions + deletions |
| [Calendar-to-Brain](recipes/calendar-to-brain.md) | credential-gateway | Google Calendar to searchable daily pages |
| [Meeting Sync](recipes/meeting-sync.md) | — | Circleback transcripts to brain pages with attendees |
+| [Restart Sweep](recipes/restart-sweep.md) | OpenClaw + Telegram | Detect dropped Telegram messages after OpenClaw gateway restarts |
**Data research recipes** extract structured data from email into tracked brain pages. Built-in recipes for investor updates (MRR, ARR, runway, headcount), expense tracking, and company metrics. Create your own with `gbrain research init`.
diff --git a/VERSION b/VERSION
index 48f7a71df4..b79f04f44d 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.28.1
+0.28.3
diff --git a/llms-full.txt b/llms-full.txt
index 8eb2d93751..7ac15a6e0b 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -142,7 +142,7 @@ strict behavior when unset.
- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`)
- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all 40 BrainEngine methods. `addLinksBatch` / `addTimelineEntriesBatch` use multi-row `unnest()` with manual `$N` placeholders. As of v0.13.1, `connect()` wraps `PGlite.create()` in a try/catch that emits an actionable error naming the macOS 26.3 WASM bug (#223) and pointing at `gbrain doctor`; the lock is released on failure so the next process can retry cleanly. v0.22.0: `searchKeyword` and `searchKeywordChunks` multiply `ts_rank` by the source-factor CASE expression at the chunk-grain level; `searchVector` becomes a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`. Inner LIMIT scales with offset to preserve pagination contract. As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL — probes for the specific forward-referenced state the embedded schema blob needs (`pages.source_id`, `links.link_source`, `links.origin_page_id`, `content_chunks.symbol_name`, `content_chunks.language`, `sources` FK target table) and adds only what's missing. Closes the upgrade-wedge bug class that bit users 10+ times across 6 schema versions over 2 years (#239/#243/#266/#357/#366/#374/#375/#378/#395/#396). No-op on fresh installs and modern brains.
- `src/core/pglite-schema.ts` — PGLite-specific DDL (pgvector, pg_trgm, triggers)
-- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch` / `addTimelineEntriesBatch` use `INSERT ... SELECT FROM unnest($1::text[], ...) JOIN pages ON CONFLICT DO NOTHING RETURNING 1` — 4-5 array params regardless of batch size, sidesteps the 65535-parameter cap. As of v0.12.3, `searchKeyword` / `searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection (contributed by @garagon). `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. v0.22.0: `searchKeyword`, `searchKeywordChunks`, and `searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude clause from `src/core/search/sql-ranking.ts`. `searchVector` switches to a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in the outer SELECT) and carries `p.source_id` through inner→outer for v0.18 multi-source callers. v0.22.1 (#406): `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures). `executeRaw` is a single-statement passthrough — no per-call retry (D3 dropped that as unsound for non-idempotent statements; recovery is supervisor-driven). v0.22.1 (#363, contributed by @orendi84): `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. v0.22.1 (#409, contributed by @atrevino47): `countStaleChunks()` + `listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale`, eliminating ~76 MB/call client-side pull on a fully-embedded brain; `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding (consistency). As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL on the same forward-reference probe set as the PGLite engine, so old Postgres brains pinned at v0.13/v0.18/v0.19 walk forward cleanly instead of wedging on `column "..." does not exist`.
+- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch` / `addTimelineEntriesBatch` use `INSERT ... SELECT FROM unnest($1::text[], ...) JOIN pages ON CONFLICT DO NOTHING RETURNING 1` — 4-5 array params regardless of batch size, sidesteps the 65535-parameter cap. As of v0.12.3, `searchKeyword` / `searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection (contributed by @garagon). `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. v0.22.0: `searchKeyword`, `searchKeywordChunks`, and `searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude clause from `src/core/search/sql-ranking.ts`. `searchVector` switches to a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in the outer SELECT) and carries `p.source_id` through inner→outer for v0.18 multi-source callers. v0.22.1 (#406): `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures). `executeRaw` is a single-statement passthrough — no per-call retry (D3 dropped that as unsound for non-idempotent statements; recovery is supervisor-driven). v0.22.1 (#363, contributed by @orendi84): `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. v0.22.1 (#409, contributed by @atrevino47): `countStaleChunks()` + `listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale`, eliminating ~76 MB/call client-side pull on a fully-embedded brain; `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding (consistency). As of v0.22.6.1, `initSchema()` calls `applyForwardReferenceBootstrap()` BEFORE replaying SCHEMA_SQL on the same forward-reference probe set as the PGLite engine, so old Postgres brains pinned at v0.13/v0.18/v0.19 walk forward cleanly instead of wedging on `column "..." does not exist`. **v0.28.1:** `disconnect()` is now idempotent. New `_connectionStyle` instance field tracks whether the engine owns its pool (worker engines) or shares the module-level singleton; second call on an instance-pool engine is a no-op rather than falling through to `db.disconnect()` and clobbering the singleton. Pinned by `test/e2e/postgres-engine-disconnect-idempotency.test.ts` (2 cases). Closes the bug class where any test sharing an engine across multiple `worker.start()` / `worker.stop()` cycles silently broke its own DB connectivity.
- `src/core/utils.ts` — Shared SQL utilities extracted from postgres-engine.ts. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and as of v0.12.3 `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). **v0.26.9 (D14):** adds `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated. Replaces bare `catch {}` blocks in `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback path. Reusable from any future code that needs the same column-existence probe semantics.
- `src/core/db.ts` — Connection management, schema initialization. v0.22.1 (#363, contributed by @orendi84): `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults: 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT` / `GBRAIN_IDLE_TX_TIMEOUT` / `GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (unlike the prior `setSessionDefaults` post-pool SET, kept as a back-compat no-op shim).
- `src/commands/migrate-engine.ts` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`)
@@ -198,10 +198,12 @@ strict behavior when unset.
- `src/commands/extract.ts` — `gbrain extract links|timeline|all [--source fs|db]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use this for live brains with no local checkout). As of v0.12.1 there is no in-memory dedup pre-load — candidates are buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, and the `created` counter returns real rows inserted (truthful on re-runs). v0.22.1 (#417): `ExtractOpts.slugs?: string[]` enables incremental extract — when set, `extractForSlugs()` reads ONLY those slugs' files (single combined links+timeline pass) instead of the full directory walk. CLI `gbrain extract` keeps full-walk behavior; the cycle path threads sync's `pagesAffected` through. `walkMarkdownFiles(brainDir)` still runs at line 455 to build `allSlugs` for link resolution — see `TODOS.md` for replacing it with `engine.getAllSlugs()`.
- `src/commands/graph-query.ts` — `gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both]`: typed-edge relationship traversal (renders indented tree)
- `src/core/link-extraction.ts` — shared library for the v0.12.0 graph layer. extractEntityRefs (canonical, replaces backlinks.ts duplicate) matches both `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks as of v0.12.3. extractPageLinks, inferLinkType heuristics (attended/works_at/invested_in/founded/advises/source/mentions), parseTimelineEntries, isAutoLinkEnabled config helper. `DIR_PATTERN` covers `people`, `companies`, `deals`, `topics`, `concepts`, `projects`, `entities`, `tech`, `finance`, `personal`, `openclaw`. Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts.
+- `src/core/zombie-reap.ts` (v0.28.1) — idempotent `installSigchldHandler()` so JS-spawned children get reaped via Bun's internal `waitpid()`. Bun (like Node) only auto-reaps when a SIGCHLD listener is registered; without it, every child the worker spawns (shell jobs, embed batches, sub-agents) becomes a zombie on exit and holds connection slots. Called once at module load from `src/cli.ts` (with Windows platform guard — SIGCHLD doesn't exist on Windows). Cross-file leak guard via `_uninstallSigchldHandlerForTests()` for tests. Layer 1 of the three-layer zombie defense; Layer 2 is tini-as-PID-1 wrapping the worker subtree (via `src/core/minions/spawn-helpers.ts`); Layer 3 is the container's own tini for hard Bun crashes.
- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, stagger, handlers/shell).
- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). v0.14.1 #219: `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. v0.19.0: `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). v0.19.1: `maxWaiting` coalesce path now uses `pg_advisory_xact_lock` keyed on `(name, queue)` to serialize concurrent submits for the same key, and filters on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other.
-- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). v0.14.0 abort-path fix: aborted jobs now call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`) instead of returning silently. `shutdownAbort` (instance field) fires on process SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` — shell handler listens to it; non-shell handlers don't. v0.22.1 (#403): per-job timeout fires `abort.abort(new Error('timeout'))` then a 30-second grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead in DB if the handler ignores the abort signal — frees the slot even when a handler wedges (the 98-waiting-0-active prod incident driver).
-- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, restarts on crash with exponential backoff, periodic health check. v0.22.1 (#406): `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets the counter. Worker exit classifier emits `likely_cause` field on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`.
+- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). v0.14.0 abort-path fix: aborted jobs now call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`) instead of returning silently. `shutdownAbort` (instance field) fires on process SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` — shell handler listens to it; non-shell handlers don't. v0.22.1 (#403): per-job timeout fires `abort.abort(new Error('timeout'))` then a 30-second grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead in DB if the handler ignores the abort signal — frees the slot even when a handler wedges (the 98-waiting-0-active prod incident driver). **v0.28.1 engine-ownership invariant:** `start()` no longer calls `engine.disconnect()` on shutdown — that was a leaky abstraction (the worker disconnected an engine it didn't own). The CLI handler in `src/commands/jobs.ts case 'work'` now owns engine lifecycle via try/finally with loud error logging on disconnect failure. Pinned by `test/worker-shutdown-disconnect.test.ts` asserting the inverse (`disconnectSpy).not.toHaveBeenCalled()`).
+- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, restarts on crash with exponential backoff, periodic health check. v0.22.1 (#406): `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets the counter. Worker exit classifier emits `likely_cause` field on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`. **v0.28.1:** consumes `detectTini()` + `buildSpawnInvocation()` from `src/core/minions/spawn-helpers.ts` to wrap the worker subtree in tini-as-PID-1 when tini is on `PATH` (handles native-addon zombie reaping that the in-process SIGCHLD reaper can't reach). Exposes `isTiniDetected` read-only accessor for tests.
+- `src/core/minions/spawn-helpers.ts` (v0.28.1) — pure `detectTini()` + `buildSpawnInvocation()` helpers consumed by both `supervisor.ts` and `autopilot.ts`. Resolves the DRY violation between the two spawn sites and makes the tini wrapping testable without `mock.module()` (rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations (the env-snapshot bug fix). `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with tini prepended when present, or the bare invocation otherwise. Pinned by `test/spawn-helpers.test.ts` (5 cases) and `test/supervisor-tini.test.ts` (4 cases).
- `src/core/minions/types.ts` — `MinionJobInput` + `MinionJobStatus` + handler context types. `MinionJobInput.max_stalled` (new in v0.14.1) is optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to `[1, 100]`.
- `src/core/minions/protected-names.ts` — side-effect-free constant module exporting `PROTECTED_JOB_NAMES` + `isProtectedJobName()`. Kept pure so queue core can import without loading handler modules.
- `src/core/minions/handlers/shell.ts` — `shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist: `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Requires `GBRAIN_ALLOW_SHELL_JOBS=1` on worker (gated by `registerBuiltinHandlers`).
@@ -219,13 +221,13 @@ strict behavior when unset.
- `src/core/minions/attachments.ts` — Attachment validation (path traversal, null byte, oversize, base64, duplicate detection)
- `src/commands/agent.ts` (v0.16) — `gbrain agent run <prompt> [flags]` CLI. Submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`. Single-entry `--fanout-manifest` short-circuits. Children get `on_child_fail: 'continue'` + `max_stalled: 3`. `--follow` is the default on TTY; streams logs + polls `waitForCompletion` in parallel. Ctrl-C detaches, does not cancel.
- `src/commands/agent-logs.ts` (v0.16) — `gbrain agent logs <job> [--follow] [--since]`. Merges JSONL heartbeat audit + `subagent_messages` into a chronological timeline. `parseSince` accepts ISO-8601 or relative (`5m`, `1h`, `2d`). Transcript tail renders only for terminal jobs.
-- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. v0.13.1 surfaces the full `MinionJobInput` retry/backoff/timeout/idempotency surface as first-class CLI flags on `jobs submit`: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`. `jobs smoke --sigkill-rescue` is the opt-in regression guard for #219. v0.16 wires `registerBuiltinHandlers` to always register `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the natural cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at worker startup with a loud startup-line per plugin. `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface, separate concern). v0.22.10 (#521): the `autopilot-cycle` handler now forwards `job.data.phases` to `runCycle` (was previously discarded — caller-supplied phase selection silently became a full cycle). Phases are validated against `ALL_PHASES` from `src/core/cycle.ts`; invalid names are filtered out and an empty/missing array falls back to the default 6-phase cycle. v0.22.13 (PR #490 CODEX-1+CODEX-4): `sync` handler now resolves `sourceId` at entry by looking up `sources.local_path` (mirrors `cycle.ts:480`'s autopilot fix from PR #475) so multi-source brains read the per-source `last_commit` anchor instead of the global config key. Concurrency routed through the shared `autoConcurrency()` policy in `src/core/sync-concurrency.ts` instead of the prior hardcoded `4`; PGLite stays serial. `noEmbed` default is `true` (embed is a separate job — submit `gbrain embed --stale` after sync, or rely on the autopilot cycle's embed phase).
+- `src/commands/jobs.ts` — `gbrain jobs` CLI subcommands + `gbrain jobs work` daemon. **v0.28.1:** `case 'work'` now wraps `worker.start()` in try/finally and owns engine lifecycle — calls `engine.disconnect()` on shutdown with loud error logging on failure. Replaces the prior call inside `MinionWorker.start()` (which violated engine ownership: the worker disconnected an engine it didn't own, and clobbered the module-level singleton on PostgresEngine via the now-fixed idempotency bug). Pool slots now free immediately on shutdown instead of waiting for TCP keepalive (~minutes). v0.13.1 surfaces the full `MinionJobInput` retry/backoff/timeout/idempotency surface as first-class CLI flags on `jobs submit`: `--max-stalled`, `--backoff-type fixed|exponential`, `--backoff-delay`, `--backoff-jitter`, `--timeout-ms`, `--idempotency-key`. `jobs smoke --sigkill-rescue` is the opt-in regression guard for #219. v0.16 wires `registerBuiltinHandlers` to always register `subagent` + `subagent_aggregator` (no env flag — `ANTHROPIC_API_KEY` is the natural cost gate, trust is via `PROTECTED_JOB_NAMES`) and loads `GBRAIN_PLUGIN_PATH` plugins at worker startup with a loud startup-line per plugin. `shell` handler still gated by `GBRAIN_ALLOW_SHELL_JOBS=1` (RCE surface, separate concern). v0.22.10 (#521): the `autopilot-cycle` handler now forwards `job.data.phases` to `runCycle` (was previously discarded — caller-supplied phase selection silently became a full cycle). Phases are validated against `ALL_PHASES` from `src/core/cycle.ts`; invalid names are filtered out and an empty/missing array falls back to the default 6-phase cycle. v0.22.13 (PR #490 CODEX-1+CODEX-4): `sync` handler now resolves `sourceId` at entry by looking up `sources.local_path` (mirrors `cycle.ts:480`'s autopilot fix from PR #475) so multi-source brains read the per-source `last_commit` anchor instead of the global config key. Concurrency routed through the shared `autoConcurrency()` policy in `src/core/sync-concurrency.ts` instead of the prior hardcoded `4`; PGLite stays serial. `noEmbed` default is `true` (embed is a separate job — submit `gbrain embed --stale` after sync, or rely on the autopilot cycle's embed phase).
- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman
-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed)
+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). **v0.28.1:** consumes `detectTini()` from `src/core/minions/spawn-helpers.ts` and resolves it once at startup instead of per worker respawn (was paying an `execFileSync` cost on every restart).
- `src/mcp/server.ts` — MCP stdio server (generated from operations). v0.22.7: tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path.
- `src/mcp/dispatch.ts` (v0.22.7) — Shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and `validateParams(op, params)`. Single source of truth for `(ctx, params)` handler arg order and the 5-field `OperationContext` shape (engine + config + logger + dryRun + remote). Defaults to `remote: true` (untrusted); local CLI callers pass `remote: false`. Closed F1/F2/F3 drift bugs in the original v0.22.5 HTTP transport. **v0.26.9 (F8):** adds `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed. Returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved as a sorted array for debug visibility; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes via repeated probes. Operators on a personal laptop who want raw payload visibility opt back in with `gbrain serve --http --log-full-params` (loud stderr warning at startup). Canonical helper — new logging code paths route through it rather than `JSON.stringify(params)`.
- `src/mcp/rate-limit.ts` (v0.22.7) — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is actually capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth.
-- `src/commands/serve-http.ts` (v0.26.0) — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--log-full-params]`. Supersedes the v0.22.7 `src/mcp/http-transport.ts` simple bearer-auth path. Combines MCP SDK's `mcpAuthRouter` (authorize / token / register / revoke endpoints), a custom `client_credentials` handler (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; the custom handler runs BEFORE the router and falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement before op dispatch, `localOnly` rejection, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE endpoint broadcasts every MCP request to connected admin browsers. `cookie-parser` middleware wired (Express 5 has no built-in). Startup logging prints port, engine, configured issuer URL (honors `--public-url`), registered-client count, DCR status, and admin bootstrap token. **v0.26.9 hardening pass:** F7 sets `remote: true` explicitly on the `/mcp` request handler's OperationContext literal (closes the HTTP shell-job RCE — without this, `submit_job`'s protected-name guard at `operations.ts:1391` saw a falsy undefined and skipped, letting a `read+write`-scoped OAuth token submit `shell` jobs). F8 wires `summarizeMcpParams` from `src/mcp/dispatch.ts` into both `mcp_request_log` writes and the admin SSE feed by default (raw payloads opt-in via `--log-full-params` with stderr warning). F9 sets cookie `Secure` flag when behind HTTPS or a public-URL proxy. F10 caps the magic-link nonce store with an LRU bound. F12 routes DCR disable through the `GBrainOAuthProvider` constructor's `dcrDisabled` option instead of the prior monkey-patch on the express router. F14 wraps `transport.handleRequest` in try/catch so SDK throws return a JSON-RPC 500 envelope instead of express's default HTML error page. F15 unifies OperationError + unexpected exceptions through `buildError` / `serializeError` so `/mcp` always returns the same envelope shape.
+- `src/commands/serve-http.ts` (v0.26.0) — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--log-full-params]`. Supersedes the v0.22.7 `src/mcp/http-transport.ts` simple bearer-auth path. Combines MCP SDK's `mcpAuthRouter` (authorize / token / register / revoke endpoints), a custom `client_credentials` handler (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; the custom handler runs BEFORE the router and falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement before op dispatch, `localOnly` rejection, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE endpoint broadcasts every MCP request to connected admin browsers. `cookie-parser` middleware wired (Express 5 has no built-in). Startup logging prints port, engine, configured issuer URL (honors `--public-url`), registered-client count, DCR status, and admin bootstrap token. **v0.26.9 hardening pass:** F7 sets `remote: true` explicitly on the `/mcp` request handler's OperationContext literal (closes the HTTP shell-job RCE — without this, `submit_job`'s protected-name guard at `operations.ts:1391` saw a falsy undefined and skipped, letting a `read+write`-scoped OAuth token submit `shell` jobs). F8 wires `summarizeMcpParams` from `src/mcp/dispatch.ts` into both `mcp_request_log` writes and the admin SSE feed by default (raw payloads opt-in via `--log-full-params` with stderr warning). F9 sets cookie `Secure` flag when behind HTTPS or a public-URL proxy. F10 caps the magic-link nonce store with an LRU bound. F12 routes DCR disable through the `GBrainOAuthProvider` constructor's `dcrDisabled` option instead of the prior monkey-patch on the express router. F14 wraps `transport.handleRequest` in try/catch so SDK throws return a JSON-RPC 500 envelope instead of express's default HTML error page. F15 unifies OperationError + unexpected exceptions through `buildError` / `serializeError` so `/mcp` always returns the same envelope shape. **v0.28.1:** `/health` endpoint extracted into pure `probeHealth(engine)` async function with `HEALTH_TIMEOUT_MS = 3000` exported constant — drops the timeout from 5s to 3s so Fly.io's 5s health-check deadline gets 2s of headroom for TCP, response framing, and clock skew. Races `engine.getStats()` against the timeout via `Promise.race`; saturated pool returns 503 with `Health check timed out (database pool may be saturated)` instead of hanging. `clearTimeout` in finally block prevents pending-timer pile-up under high probe rates (race-leak fix from adversarial review).
- `src/core/oauth-provider.ts` (v0.26.0) — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore` interfaces. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1 spec: `authorize` + `exchangeAuthorizationCode` with PKCE (for ChatGPT), `client_credentials` (for Perplexity / Claude), `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR path validates redirect_uri must be `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Auth codes single-use with 10-minute TTL via atomic `DELETE...RETURNING` (closes RFC 6749 §10.5 TOCTOU race). Refresh rotation also `DELETE...RETURNING` (closes §10.4 stolen-token detection bypass). `pgArray()` escapes commas/quotes/braces in elements so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` grandfathers pre-v0.26 bearer tokens as `read+write+admin`. `sweepExpiredTokens()` runs on startup wrapped in try/catch. **v0.26.9 RFC 6749/7009 hardening pass:** F1+F2 fold `client_id` atomically into the `DELETE WHERE` clauses for both auth-code exchange and refresh rotation — pre-fix the post-hoc client compare burned the row on wrong-client paths so the legitimate client couldn't retry. F3 enforces refresh-scope-subset against the original grant on the row (RFC 6749 §6), not the client's currently-allowed scopes — fixes the case where revoking a scope from a client wouldn't shrink the agent's existing refresh tokens. F4 binds `client_id` on `revokeToken` so a client can only revoke its own tokens (RFC 7009 §2.1). F7c validates the `/token` request's `redirect_uri` against the value stored at `/authorize` (RFC 6749 §4.1.3) — empty-string treated as missing rather than wildcard match (adversarial-review fix). F5 swaps bare `catch {}` blocks in `verifyAccessToken` and `getClient` for `isUndefinedColumnError` from `src/core/utils.ts` — only SQLSTATE 42703 falls through to legacy fallback; lock timeouts and network blips throw and surface. F6 makes `sweepExpiredTokens()` actually return the count via `RETURNING 1` + array length, not a fire-and-forget zero. F12 adds `dcrDisabled` constructor option so `serve-http.ts` can disable the `/register` endpoint without monkey-patching the router. **v0.26.2:** module-private `coerceTimestamp()` boundary helper at the top of the file normalizes postgres-driver-as-string BIGINT columns to JS numbers at every read site (5 call sites: `getClient` L112+L113 for DCR `/register` RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` L274 + `verifyAccessToken` L296+L303 for the SDK's `typeof === 'number'` bearerAuth check). Throws on non-finite input (NaN/Infinity) so corrupt rows fail loud at the boundary instead of riding through as `expiresAt: NaN`; returns undefined for SQL NULL so callers decide NULL semantics explicitly (refresh + access token paths treat NULL as expired). Helper intentionally NOT promoted to `src/core/utils.ts` — codex review flagged repo-wide BIGINT precision-loss risk for a generic helper.
- `admin/` (v0.26.0) — React 19 + Vite + TypeScript admin SPA embedded in the binary via `admin/dist/` served by `serve-http.ts`. 7 screens: Login (bootstrap token → session cookie), Dashboard (metrics + SSE feed + token health), Agents (sortable table + sparklines + Register button), Register (modal with scope checkboxes + grant type selector), Credentials reveal (full-screen modal with Copy + Download JSON + yellow one-time-only warning), Request Log (filterable paginated), Agent Detail drawer (Details / Activity / Config Export tabs + Revoke). Design tokens: `#0a0a0f` bg, Inter for UI, JetBrains Mono for data, 4-32px spacing scale, rounded pill badges. HTTP-only SameSite=Strict cookie auth. 65KB gzip. Build: `cd admin && bun install && bun run build`; output at `admin/dist/` is committed for self-contained binaries.
- `src/commands/auth.ts` — Token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (v0.22.7 wired as a first-class CLI subcommand) plus `gbrain auth register-client` (v0.26.0) and `gbrain auth revoke-client <client_id>` (v0.26.2) for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + authorization code in a single transaction. `process.exit(1)` on no-such-client (idempotent — re-running on the same id produces the same exit-1 message). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`. As of v0.26.0, legacy tokens grandfather to `read+write+admin` scopes on the OAuth HTTP server, so pre-v0.26 deployments keep working with no migration.
@@ -592,7 +594,8 @@ parity), `test/cli.test.ts` (CLI structure), `test/config.test.ts` (config redac
`test/skillify-scaffold.test.ts` (v0.19 `gbrain skillify scaffold` stubs: SKILL.md, script, tests, routing-eval fixtures),
`test/skillpack-install.test.ts` (v0.19 `gbrain skillpack install` managed-block install / update / no-clobber semantics),
`test/skillpack-sync-guard.test.ts` (v0.19 sync-guard: bundled skills stay byte-identical to `skills/` source),
-`test/http-transport.test.ts` (v0.22.7 HTTP transport: 23 unit cases covering bearer auth + missing/no-Bearer/unknown/revoked + `/health` bypass, F1+F2 round-trip via dispatch.ts, F3 invalid_params, application/json response shape (not SSE), CORS default-deny + allowlist, body cap on Content-Length AND chunked, two-bucket rate limit (refill, exhaust+Retry-After, LRU eviction, TTL prune, pre-auth IP fires before DB), and `mcp_request_log` audit on success + auth_failed).
+`test/http-transport.test.ts` (v0.22.7 HTTP transport: 23 unit cases covering bearer auth + missing/no-Bearer/unknown/revoked + `/health` bypass, F1+F2 round-trip via dispatch.ts, F3 invalid_params, application/json response shape (not SSE), CORS default-deny + allowlist, body cap on Content-Length AND chunked, two-bucket rate limit (refill, exhaust+Retry-After, LRU eviction, TTL prune, pre-auth IP fires before DB), and `mcp_request_log` audit on success + auth_failed),
+`test/restart-sweep.test.ts` (v0.28.3 — 27 bun:test cases for the `recipes/restart-sweep.md` inlined script: sentinel-anchored fenced-block extraction with salted tmp filenames to bypass ESM cache; constructor-time env reads (proves no module-load snapshot); idempotency layer load/save/atomic-tmp-rename/corrupt-JSON-recovery/30-day-prune; `(sessionKey, lastAlertedAt)` cooldown gate with 6h threshold (the C1 fix that survives synthesized restartTime); AGGRESSIVE-gate two-state tests; execFile argv shape proving shell metachars in `OPENCLAW_TELEGRAM_GROUP` cannot reach `/bin/sh`; real-`\n`-not-literal alert formatting; `GBRAIN_HOME` state path override).
E2E tests (`test/e2e/`): Run against real Postgres+pgvector. Require `DATABASE_URL`.
- `bun run test:e2e` runs Tier 1 (mechanical, all operations, no API keys). Includes 9 dedicated cases for the postgres-engine `addLinksBatch` / `addTimelineEntriesBatch` bind path — postgres-js's `unnest()` binding is structurally different from PGLite's and gets its own coverage.
@@ -2042,6 +2045,7 @@ GBrain ships integration recipes that your agent sets up for you. Each recipe te
| [X-to-Brain](recipes/x-to-brain.md) | — | Twitter timeline + mentions + deletions |
| [Calendar-to-Brain](recipes/calendar-to-brain.md) | credential-gateway | Google Calendar to searchable daily pages |
| [Meeting Sync](recipes/meeting-sync.md) | — | Circleback transcripts to brain pages with attendees |
+| [Restart Sweep](recipes/restart-sweep.md) | OpenClaw + Telegram | Detect dropped Telegram messages after OpenClaw gateway restarts |
**Data research recipes** extract structured data from email into tracked brain pages. Built-in recipes for investor updates (MRR, ARR, runway, headcount), expense tracking, and company metrics. Create your own with `gbrain research init`.
diff --git a/package.json b/package.json
index e3458cb67e..7e79752890 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.28.1",
+ "version": "0.28.3",
"description": "Postgres-native personal knowledge brain with hybrid RAG search",
"type": "module",
"main": "src/core/index.ts",
diff --git a/recipes/restart-sweep.md b/recipes/restart-sweep.md
new file mode 100644
index 0000000000..95efe59ca5
--- /dev/null
+++ b/recipes/restart-sweep.md
@@ -0,0 +1,654 @@
+---
+id: restart-sweep
+name: Restart Sweep
+version: 0.1.0
+description: Detect Telegram messages dropped during OpenClaw gateway restarts. Reads OpenClaw session state, alerts on aborted-mid-run sessions and (opt-in) suspicious silence gaps. Cooldown-gated so repeat detections don't spam.
+category: reflex
+requires: []
+secrets:
+ - name: OPENCLAW_OWNER_IDS
+ description: Comma-separated user IDs that own this brain instance
+ where: openclaw config — your own user IDs from the platforms you connect
+ - name: OPENCLAW_TELEGRAM_GROUP
+ description: Target Telegram group ID for restart alerts (negative number for groups)
+ where: forward a message from the group to @userinfobot, copy the chat.id
+health_checks:
+ - type: env_exists
+ name: OPENCLAW_OWNER_IDS
+ label: Owner IDs configured
+ - type: env_exists
+ name: OPENCLAW_TELEGRAM_GROUP
+ label: Telegram group configured
+ - type: command
+ argv: [openclaw, sessions, --json]
+ label: OpenClaw CLI reachable
+setup_time: 10 min
+cost_estimate: "$0 (no per-call cost; runs locally on cron)"
+---
+
+# Restart Sweep: Detect Dropped Messages After Gateway Restarts
+
+When the OpenClaw gateway restarts, webhook-delivered Telegram messages
+that haven't been processed yet get dropped permanently. Long-poll bots
+can replay missed updates via `getUpdates`. Webhook bots cannot. This
+recipe detects the gap by reading OpenClaw's session state and alerting
+when a session was active just before a restart but silent afterward.
+
+## IMPORTANT: Instructions for the Agent
+
+**You are the installer.** This recipe is written for YOU (the AI agent)
+to execute on behalf of the user. Follow these steps precisely.
+
+**Stop points (MUST pause and verify before continuing):**
+- After Step 1: prerequisites pass? If not, fix before proceeding.
+- After Step 4: dry run produces sensible output? If not, debug before
+ wiring cron.
+- After Step 5: cron entry created and visible in `crontab -l`? If not,
+ cron isn't installed.
+
+**When something fails:** Tell the user EXACTLY what failed, what it
+means, and what to try. Never say "something went wrong."
+
+## What this does
+
+1. Reads `/tmp/bootstrap-services.log` (or `$OPENCLAW_BOOTSTRAP_LOG`)
+ to find when the gateway last restarted. Falls back to `now() - 30
+ minutes` if the log isn't readable.
+2. Runs `openclaw sessions --json` to enumerate all live sessions.
+3. Filters to Telegram group sessions matching `$OPENCLAW_TELEGRAM_GROUP`.
+4. Flags sessions with `abortedLastRun: true` (strong signal of a
+ dropped message). Optionally flags sessions that were active in the
+ 5 minutes before restart but silent in the 10 minutes after — gated
+ behind `OPENCLAW_RESTART_SWEEP_AGGRESSIVE=1` because the timing
+ heuristic produces false positives during quiet periods.
+5. Cooldown layer: each sessionKey alerted gets stamped with a
+ `lastAlertedAt` timestamp. Re-alerting on the same sessionKey is
+ suppressed for 6 hours regardless of whether the synthesized restart
+ time matches. This prevents the "missing bootstrap log →
+ re-alert-every-5-minutes-forever" failure mode.
+6. Sends one alert per cycle to Telegram (or stdout if no Telegram
+ config), then records the alert in
+ `~/.gbrain/integrations/restart-sweep/alerted.json`.
+
+## Prerequisites
+
+- OpenClaw running with Telegram in webhook mode (long-poll mode
+ doesn't need this — `getUpdates` recovers missed messages on restart)
+- The `openclaw` CLI on PATH (or you'll provide an absolute path in
+ Step 5)
+- Telegram bot token already configured in OpenClaw, group ID and
+ optional topic ID known
+- Cron available on the host (this recipe schedules a 5-minute job;
+ systemd timers, launchd, or any other scheduler also work — adapt
+ Step 5 accordingly)
+
+## Step 1: Verify prerequisites
+
+```bash
+openclaw sessions --json | head -40
+```
+
+Should print JSON with a `sessions` array. If it errors, fix
+`openclaw` reachability before continuing.
+
+Decide a host-repo install path. The recipe assumes
+`~/openclaw/scripts/restart-sweep.mjs` and the user's `.env` lives at
+`~/openclaw/.env`. Adapt to your repo layout.
+
+## Step 2: Collect the secrets
+
+Confirm with the user:
+
+- `OPENCLAW_OWNER_IDS` — comma-separated user IDs (e.g. `123456789,987654321`)
+- `OPENCLAW_TELEGRAM_GROUP` — the target group ID (negative number for
+ group chats, e.g. `-1001234567890`). Forward a message from the
+ group to `@userinfobot` to get it.
+- `OPENCLAW_ALERT_TOPIC` — optional, the topic/thread ID for forum
+ groups. Open the topic in Telegram, the URL ends with the thread ID.
+
+Add these three lines to the host's `.env` (or wherever the host loads
+env from):
+
+```bash
+OPENCLAW_OWNER_IDS=...
+OPENCLAW_TELEGRAM_GROUP=...
+OPENCLAW_ALERT_TOPIC=...
+```
+
+Optional tuning:
+
+```bash
+# Set to 1 to enable the timing-based heuristic (active before restart,
+# silent after). Off by default because it false-positives during quiet
+# periods.
+OPENCLAW_RESTART_SWEEP_AGGRESSIVE=1
+
+# Override the bootstrap log path (default /tmp/bootstrap-services.log)
+OPENCLAW_BOOTSTRAP_LOG=/var/log/openclaw/bootstrap.log
+```
+
+## Step 3: Write the script to the host repo
+
+Write the script content from the next section to
+`~/openclaw/scripts/restart-sweep.mjs` (or wherever the user picks).
+The script is self-contained — no npm install needed, just Node 18+
+or Bun.
+
+<!-- restart-sweep:script -->
+```javascript
+#!/usr/bin/env node
+
+/**
+ * Restart Message Sweep Script
+ *
+ * Detects Telegram messages dropped during OpenClaw gateway restarts.
+ * Webhook-delivered messages can't be replayed via getUpdates, so we
+ * read OpenClaw's session state and look for sessions that show signs
+ * of dropped processing.
+ *
+ * Runs under Node 18+ or Bun. Copy this file into your host repo and
+ * wire it to a 5-minute cron.
+ */
+
+import fs from 'node:fs';
+import fsp from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import { exec, execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+
+const execP = promisify(exec);
+
+// Module-level constants (no env reads here — env is read at construct time)
+const RESTART_THRESHOLD_MINUTES = 30; // Fallback restart-time window when bootstrap log is missing
+const COOLDOWN_HOURS = 6; // Re-alert suppression per sessionKey
+const STALE_DAYS = 30; // Prune alerted.json entries older than this
+const PRE_RESTART_WINDOW_MS = 5 * 60 * 1000;
+const POST_RESTART_WINDOW_MS = 10 * 60 * 1000;
+
+class MessageSweepDetector {
+ /**
+ * @param {{ execFile?: typeof execFile, runOpenclawSessions?: () => Promise<any[]> }} [deps]
+ * Optional dependency injection for tests. Production: leave undefined.
+ */
+ constructor(deps = {}) {
+ // Constructor-time env reads (C2): tests can mutate process.env per construction
+ const ownerEnv = process.env.OPENCLAW_OWNER_IDS ?? '';
+ this.OWNER_IDS = ownerEnv.split(',').map(s => s.trim()).filter(Boolean);
+ this.TELEGRAM_GROUP_ID = process.env.OPENCLAW_TELEGRAM_GROUP ?? '';
+ this.ALERT_TOPIC = process.env.OPENCLAW_ALERT_TOPIC ?? '';
+ this.AGGRESSIVE = process.env.OPENCLAW_RESTART_SWEEP_AGGRESSIVE === '1';
+
+ const gbrainHome = process.env.GBRAIN_HOME ?? path.join(os.homedir(), '.gbrain');
+ this.STATE_DIR = path.join(gbrainHome, 'integrations', 'restart-sweep');
+ this.LOG_PATH = path.join(this.STATE_DIR, 'sweep.log.jsonl');
+ this.ALERTED_PATH = path.join(this.STATE_DIR, 'alerted.json');
+ this.BOOTSTRAP_LOG = process.env.OPENCLAW_BOOTSTRAP_LOG ?? '/tmp/bootstrap-services.log';
+
+ // DI hooks (default to real implementations)
+ this._execFile = deps.execFile ?? execFile;
+ this._runOpenclawSessions = deps.runOpenclawSessions ?? null;
+
+ this.sessions = null;
+ this.restartTime = null;
+ this.alertMode = this.determineAlertMode();
+ this.alerted = new Map(); // populated in run() / loadAlerted()
+ }
+
+ determineAlertMode() {
+ if (this.TELEGRAM_GROUP_ID && this.ALERT_TOPIC) return 'telegram';
+ if (this.TELEGRAM_GROUP_ID) return 'telegram_stdout';
+ return 'stdout';
+ }
+
+ async run() {
+ try {
+ console.log('🔍 Starting restart message sweep detection...');
+
+ if (this.OWNER_IDS.length === 0) {
+ console.warn('⚠️ No OPENCLAW_OWNER_IDS configured. Set this environment variable.');
+ }
+ if (!this.TELEGRAM_GROUP_ID) {
+ console.warn('⚠️ No OPENCLAW_TELEGRAM_GROUP configured. Alerts will only go to stdout.');
+ }
+
+ fs.mkdirSync(this.STATE_DIR, { recursive: true });
+ this.alerted = await this.loadAlerted();
+
+ this.restartTime = await this.getLastRestartTime();
+ console.log(`📅 Last restart detected at: ${new Date(this.restartTime).toISOString()}`);
+
+ this.sessions = await this.getSessionState();
+ console.log(`📊 Found ${this.sessions.length} total sessions`);
+
+ const telegramSessions = this.filterTelegramSessions(this.sessions);
+ console.log(`📱 Found ${telegramSessions.length} Telegram sessions`);
+
+ const droppedMessages = await this.detectDroppedMessages(telegramSessions);
+ const newDrops = droppedMessages.filter(m => !this.isInCooldown(m.sessionKey));
+ const suppressedCount = droppedMessages.length - newDrops.length;
+
+ if (newDrops.length > 0) {
+ const tail = suppressedCount > 0 ? ` (${suppressedCount} suppressed by cooldown)` : '';
+ console.log(`⚠️ Found ${newDrops.length} potentially dropped message(s)${tail}`);
+ await this.recordAndAlert(newDrops);
+ } else if (suppressedCount > 0) {
+ console.log(`✅ All ${suppressedCount} candidate(s) suppressed by cooldown`);
+ } else {
+ console.log('✅ No dropped messages detected');
+ }
+
+ await this.logResults(droppedMessages);
+
+ } catch (error) {
+ console.error('❌ Error in message sweep:', error);
+ await this.logError(error);
+ }
+ }
+
+ async getLastRestartTime() {
+ try {
+ const logContent = await fsp.readFile(this.BOOTSTRAP_LOG, 'utf8');
+ const gatewayLines = logContent.split('\n')
+ .filter(line => line.includes('Gateway token synced') || line.includes('✅ OpenClaw gateway'))
+ .reverse();
+ if (gatewayLines.length > 0) {
+ const match = gatewayLines[0].match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/);
+ if (match) {
+ return new Date(match[1] + ' UTC').getTime();
+ }
+ }
+ return Date.now() - (RESTART_THRESHOLD_MINUTES * 60 * 1000);
+ } catch (error) {
+ console.warn('⚠️ Could not determine restart time from logs, using fallback');
+ return Date.now() - (RESTART_THRESHOLD_MINUTES * 60 * 1000);
+ }
+ }
+
+ async getSessionState() {
+ if (this._runOpenclawSessions) {
+ return await this._runOpenclawSessions();
+ }
+ try {
+ const { stdout } = await execP('openclaw sessions --json');
+ const sessionData = JSON.parse(stdout);
+ return sessionData.sessions || [];
+ } catch (error) {
+ console.error('❌ Failed to get session state:', error);
+ throw error;
+ }
+ }
+
+ filterTelegramSessions(sessions) {
+ if (!this.TELEGRAM_GROUP_ID) return [];
+ return sessions.filter(session => {
+ return session.key &&
+ session.key.includes('telegram:group:' + this.TELEGRAM_GROUP_ID) &&
+ session.kind === 'group';
+ });
+ }
+
+ async detectDroppedMessages(telegramSessions) {
+ const droppedMessages = [];
+ const recentRestartWindow = this.restartTime - PRE_RESTART_WINDOW_MS;
+ const afterRestartWindow = this.restartTime + POST_RESTART_WINDOW_MS;
+
+ for (const session of telegramSessions) {
+ try {
+ const sessionUpdated = session.updatedAt;
+
+ // Primary: aborted last run is the strong signal
+ if (session.abortedLastRun) {
+ const topic = this._extractTopic(session.key);
+ droppedMessages.push({
+ sessionKey: session.key,
+ topic,
+ lastUpdate: new Date(sessionUpdated).toISOString(),
+ sessionId: session.sessionId,
+ abortedLastRun: true,
+ reason: 'Session aborted on last run',
+ });
+ continue;
+ }
+
+ // Secondary: timing-based gap detection — opt-in only (false-positive prone)
+ if (!this.AGGRESSIVE) continue;
+
+ if (sessionUpdated >= recentRestartWindow &&
+ sessionUpdated < this.restartTime &&
+ Date.now() > afterRestartWindow) {
+ const topic = this._extractTopic(session.key);
+ droppedMessages.push({
+ sessionKey: session.key,
+ topic,
+ lastUpdate: new Date(sessionUpdated).toISOString(),
+ timeSinceUpdate: Math.floor((Date.now() - sessionUpdated) / 1000 / 60),
+ sessionId: session.sessionId,
+ suspiciousGap: true,
+ reason: 'Active before restart, silent after',
+ });
+ }
+ } catch (error) {
+ console.warn(`⚠️ Error analyzing session ${session.key}:`, error);
+ }
+ }
+ return droppedMessages;
+ }
+
+ _extractTopic(sessionKey) {
+ const m = sessionKey?.match(/:topic:(\d+)/);
+ return m ? m[1] : 'unknown';
+ }
+
+ /**
+ * Cooldown layer (C1): suppresses re-alerts on the same sessionKey
+ * for COOLDOWN_HOURS, regardless of whether the synthesized
+ * restartTime matches. Cooldown wins when the bootstrap log is
+ * missing and restartTime is unstable.
+ */
+ isInCooldown(sessionKey) {
+ const entry = this.alerted.get(sessionKey);
+ if (!entry || !entry.lastAlertedAt) return false;
+ const ageMs = Date.now() - new Date(entry.lastAlertedAt).getTime();
+ return ageMs < COOLDOWN_HOURS * 60 * 60 * 1000;
+ }
+
+ async loadAlerted() {
+ try {
+ const content = await fsp.readFile(this.ALERTED_PATH, 'utf8');
+ const parsed = JSON.parse(content);
+ const map = new Map();
+ const cutoffMs = Date.now() - STALE_DAYS * 24 * 60 * 60 * 1000;
+ for (const [key, entry] of Object.entries(parsed || {})) {
+ if (entry && entry.lastAlertedAt) {
+ const ts = new Date(entry.lastAlertedAt).getTime();
+ if (Number.isFinite(ts) && ts >= cutoffMs) {
+ map.set(key, entry);
+ }
+ }
+ }
+ return map;
+ } catch (err) {
+ if (err && err.code === 'ENOENT') return new Map();
+ console.warn(`⚠️ Failed to load ${this.ALERTED_PATH}: ${err && err.message}; starting with empty state`);
+ return new Map();
+ }
+ }
+
+ async saveAlerted() {
+ const obj = Object.fromEntries(this.alerted);
+ const json = JSON.stringify(obj, null, 2);
+ const tmp = this.ALERTED_PATH + '.tmp';
+ // Atomic on POSIX: write tmp, then rename. Note: this prevents
+ // file corruption only — concurrent cron runs can still both
+ // read old state, both decide to alert, both rename. Given
+ // 5-min cadence and 2-5s runtime, overlap is rare and a
+ // duplicate alert is preferable to a missed one.
+ await fsp.writeFile(tmp, json);
+ await fsp.rename(tmp, this.ALERTED_PATH);
+ }
+
+ async recordAndAlert(droppedMessages) {
+ let alertSent = false;
+ try {
+ await this.alertOnDroppedMessages(droppedMessages);
+ alertSent = true;
+ } catch (err) {
+ console.error('❌ Failed to send alert (will retry next cycle):', err && err.message);
+ }
+ if (!alertSent) return;
+
+ const nowIso = new Date().toISOString();
+ const restartIso = new Date(this.restartTime).toISOString();
+ for (const msg of droppedMessages) {
+ this.alerted.set(msg.sessionKey, {
+ lastAlertedAt: nowIso,
+ restartTime: restartIso,
+ });
+ }
+ try {
+ await this.saveAlerted();
+ } catch (err) {
+ console.warn('⚠️ Failed to save alerted state:', err && err.message);
+ }
+ }
+
+ async alertOnDroppedMessages(droppedMessages) {
+ let alertText = `⚠️ Found ${droppedMessages.length} unprocessed message(s) after restart:\n\n`;
+ for (const msg of droppedMessages.slice(0, 10)) {
+ alertText += `• Topic ${msg.topic}: ${msg.reason} (last update: ${msg.lastUpdate})\n`;
+ if (msg.timeSinceUpdate) {
+ alertText += ` ${msg.timeSinceUpdate} minutes ago\n`;
+ }
+ }
+ if (droppedMessages.length > 10) {
+ alertText += `\n... and ${droppedMessages.length - 10} more`;
+ }
+
+ switch (this.alertMode) {
+ case 'telegram':
+ await this.sendTelegramAlert(alertText);
+ break;
+ case 'telegram_stdout':
+ console.log('📢 Would send Telegram alert, but no topic configured:');
+ console.log(alertText);
+ break;
+ default:
+ console.log('📢 Alert:');
+ console.log(alertText);
+ }
+ }
+
+ async sendTelegramAlert(alertText) {
+ // execFile (not exec): argv array, no shell interpretation,
+ // shell metachars in env vars cannot inject commands.
+ const argv = [
+ 'message', 'send',
+ '--channel', 'telegram',
+ '--target', this.TELEGRAM_GROUP_ID,
+ '--thread-id', this.ALERT_TOPIC,
+ '--message', alertText,
+ ];
+ await new Promise((resolve, reject) => {
+ this._execFile('openclaw', argv, (err, _stdout, stderr) => {
+ if (err) {
+ err.stderr = stderr;
+ reject(err);
+ } else {
+ resolve();
+ }
+ });
+ });
+ console.log('📢 Alert sent to Telegram');
+ }
+
+ async logResults(droppedMessages) {
+ const logEntry = {
+ timestamp: new Date().toISOString(),
+ restartTime: new Date(this.restartTime).toISOString(),
+ droppedMessageCount: droppedMessages.length,
+ droppedMessages,
+ };
+ try {
+ await fsp.appendFile(this.LOG_PATH, JSON.stringify(logEntry) + '\n');
+ } catch (error) {
+ console.warn('⚠️ Failed to write log file:', error && error.message);
+ }
+ }
+
+ async logError(error) {
+ const errorEntry = {
+ timestamp: new Date().toISOString(),
+ error: error && error.message,
+ stack: error && error.stack,
+ };
+ try {
+ await fsp.appendFile(this.LOG_PATH, 'ERROR: ' + JSON.stringify(errorEntry) + '\n');
+ } catch (logError) {
+ console.error('Failed to log error:', logError && logError.message);
+ }
+ }
+}
+
+// Run if executed directly
+if (import.meta.url === `file://${process.argv[1]}`) {
+ const detector = new MessageSweepDetector();
+ detector.run().catch(console.error);
+}
+
+export default MessageSweepDetector;
+```
+
+## Step 4: Dry-run
+
+Run the script once manually with the env loaded, before wiring cron:
+
+```bash
+set -a; source ~/openclaw/.env; set +a
+node ~/openclaw/scripts/restart-sweep.mjs
+```
+
+Expected output (no drops):
+
+```
+🔍 Starting restart message sweep detection...
+📅 Last restart detected at: 2026-05-06T12:53:45.000Z
+📊 Found 48 total sessions
+📱 Found 39 Telegram sessions
+✅ No dropped messages detected
+```
+
+If you want to see the alert path, manually edit a session in OpenClaw
+to set `abortedLastRun: true` and re-run. After the alert fires, check
+`~/.gbrain/integrations/restart-sweep/alerted.json` — the sessionKey
+should be there with a `lastAlertedAt` timestamp. Re-running within 6
+hours suppresses the alert.
+
+## Step 5: Wire 5-minute cron
+
+Cron does NOT inherit your shell environment. `openclaw` and `node` may
+not be on cron's stripped PATH. `.env` files don't auto-load. Use the
+wrapper-script pattern below to handle both.
+
+Create `~/openclaw/scripts/restart-sweep-wrapper.sh`:
+
+```bash
+#!/usr/bin/env bash
+set -euo pipefail
+set -a
+source ~/openclaw/.env
+set +a
+exec /usr/local/bin/node ~/openclaw/scripts/restart-sweep.mjs
+```
+
+```bash
+chmod +x ~/openclaw/scripts/restart-sweep-wrapper.sh
+```
+
+Adjust `/usr/local/bin/node` to wherever your `node` actually lives
+(`which node` to find it). Same for `openclaw` if the wrapper needs to
+add it to PATH explicitly:
+
+```bash
+export PATH=/usr/local/bin:/usr/bin:/bin:$PATH
+```
+
+Add to crontab via `crontab -e`:
+
+```cron
+PATH=/usr/local/bin:/usr/bin:/bin
+*/5 * * * * /bin/bash ~/openclaw/scripts/restart-sweep-wrapper.sh >> ~/.gbrain/integrations/restart-sweep/cron.log 2>&1
+```
+
+Verify with `crontab -l`. Wait 5 minutes, then check the cron log to
+confirm it ran:
+
+```bash
+tail -20 ~/.gbrain/integrations/restart-sweep/cron.log
+```
+
+## Step 6: Verification
+
+1. `gbrain integrations doctor restart-sweep` — should pass all three
+ health checks
+2. `~/.gbrain/integrations/restart-sweep/sweep.log.jsonl` exists and
+ gets a new entry every 5 minutes
+3. `~/.gbrain/integrations/restart-sweep/cron.log` shows successful
+ invocations (no PATH errors, no `command not found`)
+4. After a real OpenClaw restart with a stuck session, the Telegram
+ alert fires once, then the cooldown layer suppresses repeats for 6h
+
+## Tuning
+
+`OPENCLAW_RESTART_SWEEP_AGGRESSIVE=1` — enables the secondary
+"active-before-restart, silent-after" heuristic. Off by default because
+during normal quiet periods (overnight, weekends) it false-positives.
+Enable if you want maximum sensitivity AND you've established that your
+group is consistently active.
+
+The cooldown threshold (6 hours) is a constant in the script. Edit
+`COOLDOWN_HOURS` if you need different behavior — e.g. 24 hours if your
+group's normal cadence is daily.
+
+## Troubleshooting
+
+### Alerts firing repeatedly on the same session
+
+Check `~/.gbrain/integrations/restart-sweep/alerted.json`. If the
+sessionKey is missing or `lastAlertedAt` is recent, the cooldown should
+suppress. If it's not suppressing:
+
+- The state file may not be writable. Check `ls -ld
+ ~/.gbrain/integrations/restart-sweep/`.
+- `GBRAIN_HOME` may be set to a different path under cron than under
+ your shell. Check the wrapper script's env loading.
+- The script's `STATE_DIR` resolution prints in stderr if mkdir fails.
+ Check the cron log.
+
+### Telegram alert fails silently
+
+The script logs `❌ Failed to send alert (will retry next cycle)` to
+stderr when `openclaw message send` returns non-zero. Common causes:
+
+- `openclaw` not on cron's PATH (use absolute path in the wrapper)
+- Telegram bot token expired or rate-limited
+- Wrong group/topic ID (try `openclaw message send --channel telegram
+ --target $OPENCLAW_TELEGRAM_GROUP --message test` manually)
+
+When the send fails, state is NOT updated, so next cycle retries.
+
+### Bootstrap log missing
+
+If `/tmp/bootstrap-services.log` (or `$OPENCLAW_BOOTSTRAP_LOG`) doesn't
+exist, the script falls back to `now() - 30 minutes` for restartTime.
+The cooldown layer keeps this from spamming. If you want a stable
+restart anchor, point `OPENCLAW_BOOTSTRAP_LOG` at OpenClaw's actual
+startup log (whatever your deployment uses).
+
+### Cron environment
+
+The wrapper script in Step 5 handles 80% of cron-day-one failures, but
+two more knobs:
+
+- **Locale:** if your script ever interpolates user-provided text into
+ log lines, set `LANG=en_US.UTF-8` in the cron entry to avoid mojibake.
+- **Working directory:** cron starts in `$HOME` by default. The script
+ uses absolute paths everywhere, so this shouldn't matter, but if you
+ ever add a relative-path dependency, `cd ~/openclaw` in the wrapper.
+
+## Future upgrade path
+
+This recipe is the v1 shape: a script copied into the host repo and
+wired to cron. The v2 shape is a plugin Minion handler registered in
+the OpenClaw repo against `gbrain/minions` (see
+`docs/guides/plugin-handlers.md`). Plugin-handler advantages:
+
+- Built-in queue idempotency (no cooldown layer needed)
+- Submit via `gbrain jobs submit restart-sweep` from any cron / agent /
+ manual trigger
+- Centralized retry / backoff / lock management
+- One less host script to maintain
+
+When this becomes the right tradeoff (multiple deployments, multiple
+cron schedules, or just enough complexity to justify the move), promote
+to the plugin-handler shape and deprecate this recipe.
diff --git a/test/restart-sweep.test.ts b/test/restart-sweep.test.ts
new file mode 100644
index 0000000000..73c46412f4
--- /dev/null
+++ b/test/restart-sweep.test.ts
@@ -0,0 +1,611 @@
+/**
+ * Tests for the restart-sweep recipe's inlined script.
+ *
+ * The script lives inside `recipes/restart-sweep.md` as a fenced
+ * `javascript` block, anchored on a sentinel HTML comment
+ * (`<!-- restart-sweep:script -->`). loadDetector() extracts the
+ * block, salts the tmp filename to bypass the ESM import cache, and
+ * dynamic-imports for fresh construction per call.
+ *
+ * Test isolation: every env mutation routes through `withEnv` from
+ * `test/helpers/with-env.ts` per the project's R1 lint rule. State-
+ * file tests scope `GBRAIN_HOME` to a per-test tmpdir so they don't
+ * touch the developer's real `~/.gbrain/`.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { mkdtempSync, readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { withEnv } from './helpers/with-env.ts';
+
+const RECIPE_PATH = join(import.meta.dir, '../recipes/restart-sweep.md');
+
+/**
+ * Sentinel-anchored extractor (C6). Future doc edits adding example
+ * blocks above the script can't redirect what's tested.
+ */
+async function loadDetector(): Promise<any> {
+ const md = readFileSync(RECIPE_PATH, 'utf8');
+ const m = md.match(
+ /<!--\s*restart-sweep:script\s*-->\s*\n```javascript\s*\n([\s\S]+?)\n```/,
+ );
+ if (!m) {
+ throw new Error(
+ 'Sentinel <!-- restart-sweep:script --> + fenced javascript block not found in recipe. ' +
+ 'Did you remove the sentinel from recipes/restart-sweep.md?',
+ );
+ }
+ const dir = mkdtempSync(join(tmpdir(), 'restart-sweep-test-'));
+ // Salt filename per call so ESM cache returns fresh module — required for
+ // the constructor-time env tests where each construction needs to see the
+ // env mutation we just made.
+ const filename = `restart-sweep-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`;
+ const path = join(dir, filename);
+ writeFileSync(path, m[1]);
+ const mod = await import(path);
+ return mod.default;
+}
+
+function makeStateDir(): string {
+ return mkdtempSync(join(tmpdir(), 'restart-sweep-state-'));
+}
+
+// ─── Sentinel + recipe-shape guards ───────────────────────────────────
+
+test('recipe contains the C6 sentinel before the fenced javascript block', () => {
+ const md = readFileSync(RECIPE_PATH, 'utf8');
+ expect(md).toContain('<!-- restart-sweep:script -->');
+ // Sentinel must precede the fenced block, not follow it
+ const sentinelIdx = md.indexOf('<!-- restart-sweep:script -->');
+ const fenceIdx = md.indexOf('```javascript', sentinelIdx);
+ expect(fenceIdx).toBeGreaterThan(sentinelIdx);
+ // ...and within ~50 chars (a single line of slack)
+ expect(fenceIdx - sentinelIdx).toBeLessThan(50);
+});
+
+// ─── 1-3: Constructor mode resolution (ported, but C2-strengthened) ────
+
+describe('determineAlertMode', () => {
+ test('returns "telegram" when both group and topic are configured', async () => {
+ await withEnv(
+ {
+ OPENCLAW_OWNER_IDS: '1,2',
+ OPENCLAW_TELEGRAM_GROUP: '-100',
+ OPENCLAW_ALERT_TOPIC: '5',
+ },
+ async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ expect(d.alertMode).toBe('telegram');
+ },
+ );
+ });
+
+ test('returns "telegram_stdout" when only group is configured', async () => {
+ await withEnv(
+ {
+ OPENCLAW_OWNER_IDS: '1',
+ OPENCLAW_TELEGRAM_GROUP: '-100',
+ OPENCLAW_ALERT_TOPIC: undefined,
+ },
+ async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ expect(d.alertMode).toBe('telegram_stdout');
+ },
+ );
+ });
+
+ test('returns "stdout" when neither group nor topic is configured', async () => {
+ await withEnv(
+ {
+ OPENCLAW_OWNER_IDS: undefined,
+ OPENCLAW_TELEGRAM_GROUP: undefined,
+ OPENCLAW_ALERT_TOPIC: undefined,
+ },
+ async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ expect(d.alertMode).toBe('stdout');
+ },
+ );
+ });
+});
+
+// ─── 4-6: filterTelegramSessions (ported) ──────────────────────────────
+
+describe('filterTelegramSessions', () => {
+ test('filters Telegram group sessions for the configured group', async () => {
+ await withEnv(
+ {
+ OPENCLAW_TELEGRAM_GROUP: '-1001234567890',
+ OPENCLAW_ALERT_TOPIC: '12345',
+ },
+ async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const sessions = [
+ { key: 'agent:main:telegram:group:-1001234567890:topic:12345', kind: 'group', sessionId: 'a' },
+ { key: 'agent:main:discord:channel:123456', kind: 'channel', sessionId: 'b' },
+ { key: 'agent:main:telegram:group:-1001234567890:topic:67890', kind: 'group', sessionId: 'c' },
+ { key: 'agent:main:telegram:group:-9999999999:topic:99999', kind: 'group', sessionId: 'd' },
+ ];
+ const filtered = d.filterTelegramSessions(sessions);
+ expect(filtered).toHaveLength(2);
+ expect(filtered.every((s: any) => s.key.includes('telegram:group:-1001234567890'))).toBe(true);
+ },
+ );
+ });
+
+ test('returns empty array when TELEGRAM_GROUP_ID is not configured', async () => {
+ await withEnv({ OPENCLAW_TELEGRAM_GROUP: undefined }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const sessions = [
+ { key: 'agent:main:telegram:group:-100:topic:1', kind: 'group', sessionId: 'a' },
+ ];
+ expect(d.filterTelegramSessions(sessions)).toHaveLength(0);
+ });
+ });
+
+ test('returns empty array when no sessions match the configured group', async () => {
+ await withEnv({ OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const sessions = [{ key: 'agent:main:discord:channel:1', kind: 'channel', sessionId: 'a' }];
+ expect(d.filterTelegramSessions(sessions)).toHaveLength(0);
+ });
+ });
+});
+
+// ─── 7-10: detectDroppedMessages (ported + AGGRESSIVE-aware) ───────────
+
+describe('detectDroppedMessages', () => {
+ test('detects sessions with abortedLastRun set', async () => {
+ await withEnv({ OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ d.restartTime = new Date('2026-05-06T12:53:45Z').getTime();
+ const sessions = [
+ {
+ key: 'agent:main:telegram:group:-100:topic:12345',
+ sessionId: 'abc123',
+ updatedAt: new Date('2026-05-06T12:55:00Z').getTime(),
+ abortedLastRun: true,
+ },
+ ];
+ const dropped = await d.detectDroppedMessages(sessions);
+ expect(dropped).toHaveLength(1);
+ expect(dropped[0]).toMatchObject({
+ sessionKey: 'agent:main:telegram:group:-100:topic:12345',
+ topic: '12345',
+ sessionId: 'abc123',
+ abortedLastRun: true,
+ reason: 'Session aborted on last run',
+ });
+ });
+ });
+
+ test('extracts topic ID from the session key', async () => {
+ await withEnv({ OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ d.restartTime = Date.now();
+ const sessions = [
+ {
+ key: 'agent:main:telegram:group:-100:topic:99888',
+ sessionId: 'xyz',
+ updatedAt: Date.now(),
+ abortedLastRun: true,
+ },
+ ];
+ const dropped = await d.detectDroppedMessages(sessions);
+ expect(dropped[0].topic).toBe('99888');
+ });
+ });
+
+ test('handles malformed session keys gracefully (topic="unknown")', async () => {
+ await withEnv({ OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ d.restartTime = Date.now();
+ const sessions = [
+ {
+ key: 'malformed:session:key',
+ sessionId: 'bad',
+ updatedAt: Date.now(),
+ abortedLastRun: true,
+ },
+ ];
+ const dropped = await d.detectDroppedMessages(sessions);
+ expect(dropped[0].topic).toBe('unknown');
+ });
+ });
+
+ test('does NOT fire suspicious-gap heuristic when AGGRESSIVE is unset (C-default-off)', async () => {
+ await withEnv(
+ {
+ OPENCLAW_TELEGRAM_GROUP: '-100',
+ OPENCLAW_RESTART_SWEEP_AGGRESSIVE: undefined,
+ },
+ async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const restartTime = new Date('2026-05-06T12:53:45Z').getTime();
+ d.restartTime = restartTime;
+ // Session active 2 min before restart, no abortedLastRun.
+ const sessions = [
+ {
+ key: 'agent:main:telegram:group:-100:topic:67890',
+ sessionId: 'def',
+ updatedAt: restartTime - 2 * 60 * 1000,
+ abortedLastRun: false,
+ },
+ ];
+ // Mock "now" to be 15 min past restart so the post-window condition is true
+ const realNow = Date.now;
+ Date.now = () => restartTime + 15 * 60 * 1000;
+ try {
+ const dropped = await d.detectDroppedMessages(sessions);
+ // AGGRESSIVE off → secondary heuristic silent
+ expect(dropped).toHaveLength(0);
+ } finally {
+ Date.now = realNow;
+ }
+ },
+ );
+ });
+
+ test('fires suspicious-gap heuristic when AGGRESSIVE=1 (C-opt-in)', async () => {
+ await withEnv(
+ {
+ OPENCLAW_TELEGRAM_GROUP: '-100',
+ OPENCLAW_RESTART_SWEEP_AGGRESSIVE: '1',
+ },
+ async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const restartTime = new Date('2026-05-06T12:53:45Z').getTime();
+ d.restartTime = restartTime;
+ const sessions = [
+ {
+ key: 'agent:main:telegram:group:-100:topic:67890',
+ sessionId: 'def',
+ updatedAt: restartTime - 2 * 60 * 1000, // 2 min before restart
+ abortedLastRun: false,
+ },
+ ];
+ const realNow = Date.now;
+ Date.now = () => restartTime + 15 * 60 * 1000;
+ try {
+ const dropped = await d.detectDroppedMessages(sessions);
+ expect(dropped).toHaveLength(1);
+ expect(dropped[0]).toMatchObject({
+ suspiciousGap: true,
+ reason: 'Active before restart, silent after',
+ });
+ } finally {
+ Date.now = realNow;
+ }
+ },
+ );
+ });
+});
+
+// ─── Timing window correctness (NEW) ──────────────────────────────────
+
+test('AGGRESSIVE: timing window — outside the 5-min-before window does NOT fire', async () => {
+ await withEnv(
+ {
+ OPENCLAW_TELEGRAM_GROUP: '-100',
+ OPENCLAW_RESTART_SWEEP_AGGRESSIVE: '1',
+ },
+ async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const restartTime = new Date('2026-05-06T12:53:45Z').getTime();
+ d.restartTime = restartTime;
+ const sessions = [
+ {
+ key: 'agent:main:telegram:group:-100:topic:1',
+ sessionId: 'old',
+ updatedAt: restartTime - 30 * 60 * 1000, // 30 min before — OUTSIDE 5-min window
+ abortedLastRun: false,
+ },
+ ];
+ const realNow = Date.now;
+ Date.now = () => restartTime + 15 * 60 * 1000;
+ try {
+ const dropped = await d.detectDroppedMessages(sessions);
+ expect(dropped).toHaveLength(0);
+ } finally {
+ Date.now = realNow;
+ }
+ },
+ );
+});
+
+// ─── 11-12: log parsing regex (ported) ────────────────────────────────
+
+describe('bootstrap log timestamp regex', () => {
+ test('extracts timestamp from "Gateway token synced" line', () => {
+ const logLine = '2026-05-06 12:53:45 Gateway token synced to .env';
+ const match = logLine.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/);
+ expect(match).toBeTruthy();
+ expect(match![1]).toBe('2026-05-06 12:53:45');
+ });
+
+ test('extracts timestamp from "OpenClaw gateway" line', () => {
+ const logLine = '2026-05-06 12:53:45 ✅ OpenClaw gateway started';
+ const match = logLine.match(/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/);
+ expect(match).toBeTruthy();
+ expect(match![1]).toBe('2026-05-06 12:53:45');
+ });
+});
+
+// ─── Idempotency: loadAlerted (NEW, D4 + 30-day prune) ─────────────────
+
+describe('loadAlerted', () => {
+ test('returns empty Map when alerted.json does not exist', async () => {
+ const stateRoot = makeStateDir();
+ await withEnv({ GBRAIN_HOME: stateRoot, OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const map = await d.loadAlerted();
+ expect(map.size).toBe(0);
+ });
+ });
+
+ test('returns empty Map + warns on corrupt JSON (D4)', async () => {
+ const stateRoot = makeStateDir();
+ const stateDir = join(stateRoot, 'integrations', 'restart-sweep');
+ mkdirSync(stateDir, { recursive: true });
+ writeFileSync(join(stateDir, 'alerted.json'), '{ this is not valid json');
+ await withEnv({ GBRAIN_HOME: stateRoot, OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ // Capture stderr warning
+ const warnings: string[] = [];
+ const origWarn = console.warn;
+ console.warn = (...args: any[]) => warnings.push(args.join(' '));
+ try {
+ const map = await d.loadAlerted();
+ expect(map.size).toBe(0);
+ expect(warnings.some(w => w.includes('Failed to load') || w.includes('alerted.json'))).toBe(true);
+ } finally {
+ console.warn = origWarn;
+ }
+ });
+ });
+
+ test('prunes entries older than 30 days', async () => {
+ const stateRoot = makeStateDir();
+ const stateDir = join(stateRoot, 'integrations', 'restart-sweep');
+ mkdirSync(stateDir, { recursive: true });
+ const now = Date.now();
+ const fortyDaysAgo = new Date(now - 40 * 24 * 60 * 60 * 1000).toISOString();
+ const oneDayAgo = new Date(now - 1 * 24 * 60 * 60 * 1000).toISOString();
+ writeFileSync(
+ join(stateDir, 'alerted.json'),
+ JSON.stringify({
+ 'old-session': { lastAlertedAt: fortyDaysAgo, restartTime: fortyDaysAgo },
+ 'fresh-session': { lastAlertedAt: oneDayAgo, restartTime: oneDayAgo },
+ }),
+ );
+ await withEnv({ GBRAIN_HOME: stateRoot, OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const map = await d.loadAlerted();
+ expect(map.size).toBe(1);
+ expect(map.has('fresh-session')).toBe(true);
+ expect(map.has('old-session')).toBe(false);
+ });
+ });
+});
+
+// ─── Idempotency: saveAlerted atomic write (NEW, D3) ──────────────────
+
+test('saveAlerted writes via tmp+rename (atomic, no leftover .tmp)', async () => {
+ const stateRoot = makeStateDir();
+ await withEnv({ GBRAIN_HOME: stateRoot, OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const stateDir = join(stateRoot, 'integrations', 'restart-sweep');
+ mkdirSync(stateDir, { recursive: true });
+ d.alerted = new Map([
+ ['session-1', { lastAlertedAt: new Date().toISOString(), restartTime: new Date().toISOString() }],
+ ]);
+ await d.saveAlerted();
+ // alerted.json exists, no leftover .tmp file
+ const files = readdirSync(stateDir);
+ expect(files).toContain('alerted.json');
+ expect(files).not.toContain('alerted.json.tmp');
+ // Round-trip: load returns the same data
+ const map = await d.loadAlerted();
+ expect(map.size).toBe(1);
+ expect(map.get('session-1').lastAlertedAt).toBeDefined();
+ });
+});
+
+// ─── Cooldown layer (NEW, C1) ──────────────────────────────────────────
+
+describe('cooldown layer (C1)', () => {
+ test('isInCooldown returns false when sessionKey is not in alerted map', async () => {
+ await withEnv({ OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ d.alerted = new Map();
+ expect(d.isInCooldown('agent:main:telegram:group:-100:topic:1')).toBe(false);
+ });
+ });
+
+ test('cooldown suppresses re-alert within 6h even when restartTime is unstable (the C1 bug)', async () => {
+ const stateRoot = makeStateDir();
+ await withEnv({ GBRAIN_HOME: stateRoot, OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const sessionKey = 'agent:main:telegram:group:-100:topic:42';
+ const oneHourAgo = new Date(Date.now() - 1 * 60 * 60 * 1000).toISOString();
+ // Simulate: a prior cycle alerted this session 1h ago with synthesized restartTime A.
+ d.alerted = new Map([
+ [sessionKey, { lastAlertedAt: oneHourAgo, restartTime: 'restart-A' }],
+ ]);
+ // Current cycle: restartTime is now "restart-B" (synthesized fresh, different).
+ // Without cooldown the original key-only logic would treat this as new
+ // and re-alert. Cooldown short-circuits.
+ expect(d.isInCooldown(sessionKey)).toBe(true);
+ });
+ });
+
+ test('cooldown expires — entry older than 6h fires again', async () => {
+ await withEnv({ OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ const sessionKey = 'agent:main:telegram:group:-100:topic:99';
+ const sevenHoursAgo = new Date(Date.now() - 7 * 60 * 60 * 1000).toISOString();
+ d.alerted = new Map([
+ [sessionKey, { lastAlertedAt: sevenHoursAgo, restartTime: sevenHoursAgo }],
+ ]);
+ expect(d.isInCooldown(sessionKey)).toBe(false);
+ });
+ });
+});
+
+// ─── Cooldown round-trip across two invocations (NEW) ─────────────────
+
+test('round-trip: second invocation skips already-alerted session within cooldown', async () => {
+ const stateRoot = makeStateDir();
+ await withEnv({ GBRAIN_HOME: stateRoot, OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+
+ // First "invocation": alert + record state
+ const d1 = new Detector();
+ const stateDir = join(stateRoot, 'integrations', 'restart-sweep');
+ mkdirSync(stateDir, { recursive: true });
+ d1.restartTime = Date.now();
+ d1.alerted = new Map();
+ d1.alerted.set('agent:main:telegram:group:-100:topic:7', {
+ lastAlertedAt: new Date().toISOString(),
+ restartTime: new Date(d1.restartTime).toISOString(),
+ });
+ await d1.saveAlerted();
+
+ // Second "invocation": fresh detector, loads state, cooldown blocks
+ const d2 = new Detector();
+ d2.alerted = await d2.loadAlerted();
+ expect(d2.isInCooldown('agent:main:telegram:group:-100:topic:7')).toBe(true);
+ expect(d2.isInCooldown('agent:main:telegram:group:-100:topic:other')).toBe(false);
+ });
+});
+
+// ─── Alert formatting: real \n, not literal (NEW) ──────────────────────
+
+test('alert text contains real newlines (not literal \\n)', async () => {
+ await withEnv({ OPENCLAW_TELEGRAM_GROUP: '-100', OPENCLAW_ALERT_TOPIC: '5' }, async () => {
+ const Detector = await loadDetector();
+ let captured = '';
+ const mockExecFile = (_cmd: string, argv: string[], cb: any) => {
+ captured = argv[argv.indexOf('--message') + 1];
+ cb(null, '', '');
+ };
+ const d = new Detector({ execFile: mockExecFile });
+ await d.alertOnDroppedMessages([
+ { sessionKey: 'k1', topic: '5', reason: 'Session aborted on last run', lastUpdate: '2026-05-06T12:00:00Z' },
+ ]);
+ // Real newlines, not the literal two-char sequence backslash-n
+ expect(captured).toContain('\n');
+ expect(captured).not.toContain('\\n');
+ });
+});
+
+// ─── execFile shape + shell-injection defense (NEW) ────────────────────
+
+test('sendTelegramAlert calls execFile with argv array (no shell, no metachar interpretation)', async () => {
+ // Defense in depth: even if env contains shell metachars, execFile (not exec)
+ // means they end up as literal string args, not interpreted by /bin/sh.
+ await withEnv(
+ {
+ OPENCLAW_TELEGRAM_GROUP: '-100; rm -rf /',
+ OPENCLAW_ALERT_TOPIC: '$(reboot)',
+ },
+ async () => {
+ const Detector = await loadDetector();
+ const calls: any[] = [];
+ const mockExecFile = (cmd: string, argv: string[], cb: any) => {
+ calls.push({ cmd, argv });
+ cb(null, '', '');
+ };
+ const d = new Detector({ execFile: mockExecFile });
+ await d.sendTelegramAlert('test message');
+ expect(calls).toHaveLength(1);
+ expect(calls[0].cmd).toBe('openclaw');
+ expect(calls[0].argv).toEqual([
+ 'message', 'send',
+ '--channel', 'telegram',
+ '--target', '-100; rm -rf /',
+ '--thread-id', '$(reboot)',
+ '--message', 'test message',
+ ]);
+ // The dangerous strings are passed as literal argv elements — no shell can interpret them
+ expect(calls[0].argv).toContain('-100; rm -rf /');
+ expect(calls[0].argv).toContain('$(reboot)');
+ },
+ );
+});
+
+// ─── GBRAIN_HOME state path override (NEW, D2 verification) ────────────
+
+test('GBRAIN_HOME env override redirects state file to env-pointed dir', async () => {
+ const customRoot = makeStateDir();
+ await withEnv({ GBRAIN_HOME: customRoot, OPENCLAW_TELEGRAM_GROUP: '-100' }, async () => {
+ const Detector = await loadDetector();
+ const d = new Detector();
+ expect(d.STATE_DIR).toBe(join(customRoot, 'integrations', 'restart-sweep'));
+ expect(d.ALERTED_PATH).toBe(join(customRoot, 'integrations', 'restart-sweep', 'alerted.json'));
+ expect(d.LOG_PATH).toBe(join(customRoot, 'integrations', 'restart-sweep', 'sweep.log.jsonl'));
+ });
+});
+
+// ─── Constructor-time env reads (NEW, C2 contract) ─────────────────────
+
+test('env reads happen at construct time, not module load (C2)', async () => {
+ // Verifies the C2 fix: the original script snapshotted env at module load,
+ // making constructor-mode tests semantically bogus. We move env reads to
+ // the constructor; mutating env between constructions changes the result.
+ const Detector = await loadDetector();
+
+ await withEnv(
+ {
+ OPENCLAW_TELEGRAM_GROUP: '-100',
+ OPENCLAW_ALERT_TOPIC: '5',
+ },
+ async () => {
+ const d1 = new Detector();
+ expect(d1.alertMode).toBe('telegram');
+ },
+ );
+
+ await withEnv(
+ {
+ OPENCLAW_TELEGRAM_GROUP: '-100',
+ OPENCLAW_ALERT_TOPIC: undefined,
+ },
+ async () => {
+ // Same module instance, new construction → reflects mutated env
+ const d2 = new Detector();
+ expect(d2.alertMode).toBe('telegram_stdout');
+ },
+ );
+
+ await withEnv(
+ {
+ OPENCLAW_TELEGRAM_GROUP: undefined,
+ OPENCLAW_ALERT_TOPIC: undefined,
+ },
+ async () => {
+ const d3 = new Detector();
+ expect(d3.alertMode).toBe('stdout');
+ },
+ );
+});