Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wakeshift: key never re-enters the environment, claim rechecks backoff and attempts, per-brain emit id, NULL finish wakes, header-less 429 backs off, disable reports a failed update, stdin key saved after consent, capped addition
garrytan71ce4c3a85d4
diff --git a/docs/guides/wakeshift.md b/docs/guides/wakeshift.mdindex 3b642ff9e7..fb7a53f231 100644--- a/docs/guides/wakeshift.md+++ b/docs/guides/wakeshift.md@@ -20,7 +20,7 @@ The watch tools (`watch_job`, `list_watches`, `unwatch`) appear on the next `tooA Wakeshift key is an Ed25519 private key: `wst_` followed by 50 base58 characters, the last four bytes a checksum, so a mistyped key is caught before anything is sent. Older `test_…`/`live_…` keys are refused; make a new one in the console.-- gbrain reads `WAKESHIFT_API_KEY` once and then removes it from its own environment, so child processes don't inherit it. Otherwise it reads `~/.gbrain/wakeshift.key`, which must be readable by its owner only (a looser file is ignored, and `gbrain doctor` says so).+- gbrain moves `WAKESHIFT_API_KEY` out of its own environment as soon as it loads its config (including a value in `~/.gbrain/.env`), so child processes and jobs don't inherit it. `gbrain wakeshift enable --key-stdin` saves a key only after the checks and your consent pass. Otherwise it reads `~/.gbrain/wakeshift.key`, which must be readable by its owner only (a looser file is ignored, and `gbrain doctor` says so).- The key never leaves the brain host. Each request carries a fresh signed assertion that expires in two minutes.- The key is never stored in the database or printed. `status`, `test` and `doctor` show only its kid, a 22-character fingerprint.diff --git a/src/commands/wakeshift.ts b/src/commands/wakeshift.tsindex 6b18f3c60f..a975f2967b 100644--- a/src/commands/wakeshift.ts+++ b/src/commands/wakeshift.ts@@ -8,7 +8,7 @@* watches; `status` and `test` show the key's kid fingerprint, never the key.* Guide: docs/guides/wakeshift.md.*/-import { chmodSync, readFileSync, writeFileSync } from 'node:fs';+import { readFileSync, renameSync, writeFileSync } from 'node:fs';import type { BrainEngine } from '../core/engine.ts';import { loadConfigFileOnly, saveConfig, type GBrainConfig } from '../core/config.ts';import { opError } from '../core/ops/contract.ts';@@ -109,14 +109,14 @@ async function status(engine: BrainEngine, json: boolean): Promise<void> {}async function enable(engine: BrainEngine, args: string[]): Promise<void> {- if (args.includes('--key-stdin')) {- const raw = readFileSync(0, 'utf8').trim();- try { parseWakeshiftKey(raw); } catch (e) { if (e instanceof WakeshiftKeyError) throw keyError(e.reason, e.message, KEY_HINT); throw e; }- writeFileSync(wakeshiftKeyFile(), raw + '\n', { mode: 0o600 });- chmodSync(wakeshiftKeyFile(), 0o600);- console.error(`[wakeshift] saved the key to ${wakeshiftKeyFile()} (0600).`);+ const stdinKey = args.includes('--key-stdin') ? readFileSync(0, 'utf8').trim() : null;+ let loaded: { key: WakeshiftKey; source: 'env' | 'file' | 'stdin' };+ if (stdinKey !== null) {+ try { loaded = { key: parseWakeshiftKey(stdinKey), source: 'stdin' }; } catch (e) { if (e instanceof WakeshiftKeyError) throw keyError(e.reason, e.message, KEY_HINT); throw e; }+ } else {+ loaded = loadKey();}- const { key, source } = loadKey();+ const { key, source } = loaded;const members = await liveAccessMembers(engine);if (members > 0) {throw opError('wakeshift_shared_brain', `This brain has ${members} live access member(s); this release reports back only on a brain that serves its owner alone. Nothing was turned on.`,@@ -141,6 +141,12 @@ async function enable(engine: BrainEngine, args: string[]): Promise<void> {`Wakeshift did not accept the key or the manifest: ${describeWakeshiftError(e)}. Nothing was turned on.`,'Check the key belongs to your Wakeshift app (gbrain wakeshift test) and retry.', { reason: e instanceof WakeshiftError ? e.code : 'error' });}+ if (stdinKey !== null) {+ const tmp = `${wakeshiftKeyFile()}.${process.pid}.tmp`;+ writeFileSync(tmp, stdinKey + '\n', { mode: 0o600, flag: 'wx' });+ renameSync(tmp, wakeshiftKeyFile());+ console.error(`[wakeshift] saved the key to ${wakeshiftKeyFile()} (0600).`);+ }wakeshiftSecret();writeFilePlane(w => {const next: { enabled?: boolean; url?: string } = { ...w, enabled: true, url };@@ -158,7 +164,7 @@ async function disable(engine: BrainEngine, json: boolean): Promise<void> {writeFilePlane(w => ({ ...w, enabled: false }));const rows = await engine.executeRaw<{ id: number; wake_user: string; ws_subscription_id: string }>(`UPDATE wake_subscriptions SET state = 'ended', last_error = 'disabled', lease_until = NULL, updated_at = now() WHERE state = 'open'- RETURNING id, wake_user, ws_subscription_id`).catch(() => []);+ RETURNING id, wake_user, ws_subscription_id`);let told = 0;if (rows.length > 0) {try {diff --git a/src/core/gbrain-env-file.ts b/src/core/gbrain-env-file.tsindex 9a42a6ce1e..b7530f3711 100644--- a/src/core/gbrain-env-file.ts+++ b/src/core/gbrain-env-file.ts@@ -13,6 +13,7 @@import { existsSync, readFileSync } from 'fs';import { join } from 'path';import { splitDotenvLines } from './env-trust.ts';+import { takeWakeshiftEnvKey } from './wakeshift/env-key.ts';// KEY=VALUE with a POSIX-shaped name. `export KEY=...` is deliberately not// accepted: this is an env FILE, not a shell script (same stance as Bun's@@ -58,4 +59,5 @@ export function loadGbrainEnvFile(resolveDir: () => string): void {// The file is optional — missing, unreadable, or an invalid home dir// must not break config loading.}+ takeWakeshiftEnvKey();}diff --git a/src/core/wakeshift/client.ts b/src/core/wakeshift/client.tsindex 4e4ff9c0a9..5e2348c3ba 100644--- a/src/core/wakeshift/client.ts+++ b/src/core/wakeshift/client.ts@@ -142,7 +142,8 @@ export function wakeshiftClient(key: WakeshiftKey, opts: { url?: string; fetch?:try { json = text ? JSON.parse(text) : null; } catch { /* non-JSON body */ }if (!res.ok) {const err = (json as { error?: { code?: unknown; message?: unknown } } | null)?.error;- const retryAfter = Number(res.headers.get('retry-after'));+ const retryHeader = res.headers.get('retry-after')?.trim();+ const retryAfter = retryHeader ? Number(retryHeader) : NaN;throw new WakeshiftError(res.status, typeof err?.code === 'string' ? err.code.slice(0, 64) : `http_${res.status}`,typeof err?.message === 'string' ? err.message.slice(0, 300) : `Wakeshift answered HTTP ${res.status}.`,Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter : undefined);diff --git a/src/core/wakeshift/config.ts b/src/core/wakeshift/config.tsindex 3979f0c156..80c13c8a2e 100644--- a/src/core/wakeshift/config.ts+++ b/src/core/wakeshift/config.ts@@ -4,8 +4,8 @@** - `wakeshift.enabled` / `wakeshift.url` in the file plane (~/.gbrain/config.json), written only by the* trusted local `gbrain wakeshift enable|disable`, so a remote caller can never turn reporting back on;- * - the key: WAKESHIFT_API_KEY (read once, then removed from this process's environment so child processes do- * not inherit it), else ~/.gbrain/wakeshift.key, which must be 0600 (a looser file is ignored and doctor says so);+ * - the key: WAKESHIFT_API_KEY (moved out of this process's environment whenever config loads, env-key.ts, so+ * child processes do not inherit it), else ~/.gbrain/wakeshift.key, which must be 0600 (a looser file is ignored and doctor says so);* - the HMAC secret ~/.gbrain/wakeshift.secret (0600, random): the Wakeshift `user` is the first 32 hex of* HMAC-SHA256 over (brain, principal), never an email, name or token.*@@ -15,8 +15,9 @@ import { createHash, createHmac, randomBytes } from 'node:crypto';import { readFileSync, statSync, writeFileSync } from 'node:fs';import { gbrainPath, loadConfig, type GBrainConfig } from '../config.ts';import { normalizeWakeshiftUrl, parseWakeshiftKey, wakeshiftClient, type WakeshiftApi, type WakeshiftKey } from './client.ts';+import { WAKESHIFT_KEY_ENV, takeWakeshiftEnvKey } from './env-key.ts';-export const WAKESHIFT_KEY_ENV = 'WAKESHIFT_API_KEY';+export { WAKESHIFT_KEY_ENV, resetWakeshiftEnvKeyForTests } from './env-key.ts';export const wakeshiftKeyFile = () => gbrainPath('wakeshift.key');export const wakeshiftSecretFile = () => gbrainPath('wakeshift.secret');@@ -26,15 +27,15 @@ export type KeyRead =| { source: 'none' }| { source: 'file_too_open'; mode: string };-let envKey: string | null = null;--/** Where the key comes from, without parsing it. The env value moves into this module the first time it is seen. */+/** Where the key comes from, without parsing it. The process's env value moves out of process.env when first seen (env-key.ts). */export function readWakeshiftKey(env: NodeJS.ProcessEnv = process.env): KeyRead {- const fromEnv = env[WAKESHIFT_KEY_ENV]?.trim();- if (fromEnv) {- if (env === process.env) { envKey = fromEnv; delete env[WAKESHIFT_KEY_ENV]; } else return { source: 'env', raw: fromEnv };+ if (env === process.env) {+ const taken = takeWakeshiftEnvKey();+ if (taken) return { source: 'env', raw: taken };+ } else {+ const fromEnv = env[WAKESHIFT_KEY_ENV]?.trim();+ if (fromEnv) return { source: 'env', raw: fromEnv };}- if (env === process.env && envKey) return { source: 'env', raw: envKey };const file = wakeshiftKeyFile();let mode: number;try { mode = statSync(file).mode; } catch { return { source: 'none' }; }@@ -47,8 +48,6 @@ export function readWakeshiftKey(env: NodeJS.ProcessEnv = process.env): KeyRead}}-/** Test seam: forget a key taken from the environment. */-export function resetWakeshiftEnvKeyForTests(): void { envKey = null; }export interface WakeshiftFileConfig { enabled?: boolean; url?: string }diff --git a/src/core/wakeshift/drain.ts b/src/core/wakeshift/drain.tsindex 1428ae761d..a3ae2fc23c 100644--- a/src/core/wakeshift/drain.ts+++ b/src/core/wakeshift/drain.ts@@ -15,6 +15,7 @@* told. Off or keyless: the tick returns before touching the database. A brain* with live access members sends nothing (watch_job refuses there too).*/+import { createHash } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import { memberIdentityFor } from '../access/caller.ts';import { WakeshiftError, type WakeshiftApi } from './client.ts';@@ -38,6 +39,7 @@ export interface WakeRow {wake_user: string;ws_subscription_id: string;attempts: number;+ created_us: string;job_id: number | null;job_name: string | null;job_status: string | null;@@ -50,6 +52,7 @@ export interface DrainReport { delivered: number; retried: number; dead: number;const CANDIDATES_SQL = (byId: boolean) => `SELECT w.id, w.event, w.target, w.principal_kind, w.principal_id, w.member_id, w.wake_user, w.ws_subscription_id, w.attempts,+ (floor(extract(epoch FROM w.created_at) * 1000000))::bigint::text AS created_us,j.id AS job_id, j.name AS job_name, j.status AS job_status, j.started_at, j.finished_at,(floor(extract(epoch FROM j.finished_at) * 1000000))::bigint::text AS finished_usFROM wake_subscriptions w@@ -57,17 +60,21 @@ SELECT w.id, w.event, w.target, w.principal_kind, w.principal_id, w.member_id, wWHERE w.state = 'open' AND w.next_attempt_at <= now() AND (w.lease_until IS NULL OR w.lease_until < now())AND (j.id IS NULL OR j.status IN ${TERMINAL})AND w.delivered_marker IS DISTINCT FROM CASE WHEN j.id IS NULL THEN 'gone' ELSE- (floor(extract(epoch FROM j.finished_at) * 1000000))::bigint::text || ':' || j.status END+ COALESCE((floor(extract(epoch FROM j.finished_at) * 1000000))::bigint::text, '0') || ':' || j.status END${byId ? 'AND w.id = ANY($1::bigint[])' : ''}ORDER BY w.next_attempt_at, w.idLIMIT ${WAKE_DRAIN_BATCH}`;-/** Lease one open row; the lease's timestamp in epoch microseconds (text, so no driver rounds it) is the token settle() must match. */-async function claim(engine: BrainEngine, id: number): Promise<string | null> {- const rows = await engine.executeRaw<{ lease: string }>(+/**+ * Lease one open, due row. Returns the lease's timestamp in epoch microseconds (text, so no driver rounds it), the+ * token settle() must match, and the row's current attempts: the candidate snapshot may be stale by now.+ */+async function claim(engine: BrainEngine, id: number): Promise<{ lease: string; attempts: number } | null> {+ const rows = await engine.executeRaw<{ lease: string; attempts: number }>(`UPDATE wake_subscriptions SET lease_until = now() + interval '${LEASE_S} seconds', updated_at = now()- WHERE id = $1 AND state = 'open' AND (lease_until IS NULL OR lease_until < now()) RETURNING (floor(extract(epoch FROM lease_until) * 1000000))::bigint::text AS lease`, [id]);- return rows[0]?.lease ?? null;+ WHERE id = $1 AND state = 'open' AND next_attempt_at <= now() AND (lease_until IS NULL OR lease_until < now())+ RETURNING (floor(extract(epoch FROM lease_until) * 1000000))::bigint::text AS lease, attempts`, [id]);+ return rows[0] ? { lease: rows[0].lease, attempts: Number(rows[0].attempts) } : null;}/** Settle a leased row; false when it was ended (unwatch, disable, expiry) or re-leased meanwhile, which then wins. */@@ -118,9 +125,10 @@ function jobOf(row: WakeRow): JobSnapshot | null {}async function deliver(engine: BrainEngine, api: WakeshiftApi, row: WakeRow, report: DrainReport): Promise<void> {- const lease = await claim(engine, row.id);- if (!lease) return;- const attempts = row.attempts + 1;+ const claimed = await claim(engine, row.id);+ if (!claimed) return;+ const { lease } = claimed;+ const attempts = claimed.attempts + 1;try {if (!(await principalLive(engine, row))) {await endAtWakeshift(api, row);@@ -134,7 +142,7 @@ async function deliver(engine: BrainEngine, api: WakeshiftApi, row: WakeRow, reptry {sent = await api.emit({name: row.event, arguments: { job: Number(row.target) }, payload, text,- id: wakeEmitId(row.event, row.target, marker, row.id),+ id: wakeEmitId(row.event, row.target, marker, row.id, createHash('sha256').update(`${row.wake_user}:${row.created_us}`).digest('hex').slice(0, 12)),to: [{ user: row.wake_user, subscription: row.ws_subscription_id }],});} catch (e) {diff --git a/src/core/wakeshift/env-key.ts b/src/core/wakeshift/env-key.tsnew file mode 100644index 0000000000..17a1f2a7e1--- /dev/null+++ b/src/core/wakeshift/env-key.ts@@ -0,0 +1,19 @@+/**+ * WAKESHIFT_API_KEY leaves process.env as soon as gbrain sees it (the shell's export or ~/.gbrain/.env, which+ * loadGbrainEnvFile fills on every config load), so jobs and other child processes never inherit the app's+ * signing key. The value lives on only in this module. No imports: gbrain-env-file.ts calls it.+ */+export const WAKESHIFT_KEY_ENV = 'WAKESHIFT_API_KEY';++let envKey: string | null = null;++/** Move the key out of process.env into this module; a later value (a reloaded .env) replaces the cached one. */+export function takeWakeshiftEnvKey(): string | null {+ const value = process.env[WAKESHIFT_KEY_ENV]?.trim();+ if (value) envKey = value;+ delete process.env[WAKESHIFT_KEY_ENV];+ return envKey;+}++/** Test seam: forget a key taken from the environment. */+export function resetWakeshiftEnvKeyForTests(): void { envKey = null; }diff --git a/src/core/wakeshift/events.ts b/src/core/wakeshift/events.tsindex b15bfd5839..ad496b0fde 100644--- a/src/core/wakeshift/events.ts+++ b/src/core/wakeshift/events.ts@@ -72,9 +72,12 @@ export function jobMarker(job: JobSnapshot | null): string {return job?.status ? `${job.finished_us ?? '0'}:${job.status}` : 'gone';}-/** Emit id: `<event>:<target>:<marker>:<watch row id>`, so two watchers and a re-run job never collide. */-export function wakeEmitId(event: string, target: string, marker: string, rowId: number | string): string {- return `${event}:${target}:${marker}:${rowId}`;+/**+ * Emit id: `<event>:<target>:<marker>:<watch row id>:<namespace>`, so two watchers and a re-run job never collide,+ * and neither do two brains (or a re-initialized one) on one Wakeshift key, whose job and row ids restart at 1.+ */+export function wakeEmitId(event: string, target: string, marker: string, rowId: number | string, namespace: string): string {+ return `${event}:${target}:${marker}:${rowId}:${namespace}`;}/** Payload and the line the agent reads first, for a watched job (or its removed row). */diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 6b64222203..6484e94da3 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -812,10 +812,13 @@ function attachResponseMeta(out: ToolResult, responseMeta: Record<string, unknowtype ToolTail = Parameters<NonNullable<OperationContext['emitToolTail']>>[0];-/** Wakeshift's addition: its text as the LAST text block, its meta merged into `_meta` (a conversation credential: never logged). */+/**+ * Wakeshift's addition: its text (at most 2,000 characters) as the LAST text block, its meta merged into `_meta`+ * under gbrain's own keys, which it never replaces (a conversation credential: never logged).+ */function appendToolTail(out: ToolResult, tail: ToolTail): void {- if (tail.text) out.content.push({ type: 'text', text: tail.text });- if (tail.meta && typeof tail.meta === 'object') out._meta = { ...(out._meta ?? {}), ...tail.meta };+ if (tail.text) out.content.push({ type: 'text', text: tail.text.slice(0, 2000) });+ if (tail.meta && typeof tail.meta === 'object') out._meta = { ...tail.meta, ...(out._meta ?? {}) };}/** The one error result path: toAgentError → exactly one content block. */diff --git a/test/wakeshift-client.test.ts b/test/wakeshift-client.test.tsindex f283e01c69..a47a14eecf 100644--- a/test/wakeshift-client.test.ts+++ b/test/wakeshift-client.test.ts@@ -91,7 +91,8 @@ describe('wakeshift events', () => {expect(jobMarker(j)).toBe('100:failed');expect(jobMarker({ ...j, finished_us: '200' })).not.toBe(jobMarker(j));expect(jobMarker(null)).toBe('gone');- expect(wakeEmitId(JOB_FINISHED, '1', '100:failed', 1)).not.toBe(wakeEmitId(JOB_FINISHED, '1', '100:failed', 2));+ expect(wakeEmitId(JOB_FINISHED, '1', '100:failed', 1, 'brain-a')).not.toBe(wakeEmitId(JOB_FINISHED, '1', '100:failed', 2, 'brain-a'));+ expect(wakeEmitId(JOB_FINISHED, '1', 'gone', 1, 'brain-a')).not.toBe(wakeEmitId(JOB_FINISHED, '1', 'gone', 1, 'brain-b'));expect(formatDuration(59_000)).toBe('59s');expect(formatDuration(3_725_000)).toBe('1h02m');});diff --git a/test/wakeshift.serial.test.ts b/test/wakeshift.serial.test.tsindex 2d4f58ee47..3841ff427f 100644--- a/test/wakeshift.serial.test.ts+++ b/test/wakeshift.serial.test.ts@@ -15,7 +15,8 @@ import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { disabledOpsForPublishGates } from '../src/mcp/publish-gates.ts';import { encodeWakeshiftKey } from '../src/core/wakeshift/client.ts';import { drainWakes, WAKE_MAX_ATTEMPTS } from '../src/core/wakeshift/drain.ts';-import { resetWakeshiftEnvKeyForTests } from '../src/core/wakeshift/config.ts';+import { readWakeshiftKey, resetWakeshiftEnvKeyForTests } from '../src/core/wakeshift/config.ts';+import { loadConfig } from '../src/core/config.ts';import { startFakeWakeshift, type FakeWakeshift } from './helpers/fake-wakeshift.ts';import { runWakeshift } from '../src/commands/wakeshift.ts';import { readFileSync } from 'node:fs';@@ -102,7 +103,7 @@ describe('watch_job → completion → one pointer emit', () => {expect(e.body.name).toBe('gbrain.job.finished');expect(e.body.to).toEqual([{ user: sub.body.call.user, subscription: 'sub_1' }]);expect(e.body.text).toMatch(new RegExp(`^gbrain: job ${id} \\(sync\\) finished ok in 3m0[0-9]s\\. Call get_job ${id} for the result\\.$`));- expect(e.body.id).toMatch(new RegExp(`^gbrain\\.job\\.finished:${id}:\\d+:completed:\\d+$`));+ expect(e.body.id).toMatch(new RegExp(`^gbrain\\.job\\.finished:${id}:\\d+:completed:\\d+:[0-9a-f]{12}$`));const raw = JSON.stringify(e.body);expect(raw).not.toContain('alice-example');expect(raw).not.toContain('canary');@@ -305,6 +306,46 @@ describe('failure schedule', () => {}});+ test('a 429 without Retry-After backs off on the schedule', async () => {+ const id = await seedJob('active');+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);+ await finish(id);+ fake.respond.set('/events/emit', () => ({ status: 429, body: { error: { code: 'rate_limited', message: 'slow' } } }));+ await drainWakes(engine);+ const [row] = await engine.executeRaw<{ delay: number; attempts: number }>('SELECT attempts, round(extract(epoch FROM next_attempt_at - now()))::int AS delay FROM wake_subscriptions');+ expect(row).toMatchObject({ attempts: 1, delay: 30 });+ });++ test('a drainer holding a stale snapshot never skips the backoff another drainer just set', async () => {+ const id = await seedJob('active');+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);+ await finish(id);+ const stale = new Proxy(engine, {+ get(t, k, r) {+ if (k !== 'executeRaw') return Reflect.get(t, k, r);+ return async (sql: string, params?: unknown[]) => {+ const out = await t.executeRaw(sql, params);+ if (sql.includes('FROM wake_subscriptions w')) {+ await t.executeRaw("UPDATE wake_subscriptions SET attempts = 2, next_attempt_at = now() + interval '2 minutes', lease_until = NULL");+ }+ return out;+ };+ },+ });+ expect(await drainWakes(stale)).toMatchObject({ delivered: 0, retried: 0 });+ expect(emits()).toHaveLength(0);+ const [row] = await engine.executeRaw<{ attempts: number }>('SELECT attempts FROM wake_subscriptions');+ expect(row!.attempts).toBe(2);+ });++ test('a terminal job with no finished_at still wakes its watcher', async () => {+ const id = await seedJob('active');+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);+ await engine.executeRaw("UPDATE minion_jobs SET status = 'cancelled', finished_at = NULL WHERE id = $1", [id]);+ expect(await drainWakes(engine)).toMatchObject({ delivered: 1 });+ expect(emits()).toHaveLength(1);+ });+test('Wakeshift down during watch_job: a clear error with the wait_job fix and no row', async () => {const id = await seedJob('active');fake.respond.set('/event-subscriptions', () => ({ status: 503, body: { error: { code: 'unavailable', message: 'down' } } }));@@ -394,6 +435,37 @@ describe('gbrain wakeshift', () => {}});+ test('disable reports a failed watch-ending update instead of claiming it ended none', async () => {+ const failing = new Proxy(engine, {+ get(t, k, r) {+ if (k !== 'executeRaw') return Reflect.get(t, k, r);+ return (sql: string, params?: unknown[]) => sql.includes("last_error = 'disabled'") ? Promise.reject(new Error('db down')) : t.executeRaw(sql, params);+ },+ });+ const orig = console.log;+ console.log = () => {};+ try {+ await expect(runWakeshift(failing, ['disable', '--json'])).rejects.toThrow('db down');+ } finally { console.log = orig; }+ expect(JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8')).wakeshift.enabled).toBe(false);+ });++ test('a key in ~/.gbrain/.env is taken out of process.env when config loads, so children never inherit it', async () => {+ const envFile = join(home, '.gbrain', '.env');+ writeFileSync(envFile, `WAKESHIFT_API_KEY=${KEY}\n`, { mode: 0o600 });+ try {+ loadConfig();+ expect(process.env.WAKESHIFT_API_KEY).toBeUndefined();+ expect(readWakeshiftKey()).toEqual({ source: 'env', raw: KEY });+ loadConfig();+ expect(process.env.WAKESHIFT_API_KEY).toBeUndefined();+ } finally {+ rmSync(envFile, { force: true });+ delete process.env.WAKESHIFT_API_KEY;+ resetWakeshiftEnvKeyForTests();+ }+ });+test('enable with the default URL drops a custom URL saved earlier', async () => {writeConfig({ enabled: true, url: 'http://127.0.0.1:9' });const realFetch = globalThis.fetch;