Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wakeshift: take the env key even with no ~/.gbrain/.env, first value wins (shell over .env), --key-stdin refuses while an env key overrides it, key-files entry current

garrytan09eefb54d928
diff --git a/docs/architecture/key-files/wakeshift.md b/docs/architecture/key-files/wakeshift.md
index da0e7725e5..d2cfdc8651 100644
--- a/docs/architecture/key-files/wakeshift.md
+++ b/docs/architecture/key-files/wakeshift.md
@@ -3,4 +3,4 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/ops/wakeshift.ts` + `src/core/wakeshift/{client,config,events,drain}.ts` + `src/commands/wakeshift.ts` + `src/commands/doctor/checks/wakeshift.ts` — report back to agent conversations through Wakeshift (docs/guides/wakeshift.md), off by default. `client.ts` is the in-repo HTTP client (no SDK): key parsing (`wst_` + 50 base58 with a CRC32; legacy formats refused), a fresh EdDSA `app+jwt` assertion per request, one `fetch` with a 10 s timeout and no retry, loopback-only http. `config.ts` holds the host-only state: `wakeshift.enabled`/`url` in the file plane, the key (WAKESHIFT_API_KEY moved out of the environment on first read, else a 0600 `~/.gbrain/wakeshift.key`), the 0600 HMAC secret and the opaque Wakeshift user (HMAC over brain and principal); `wakeshiftPublished` is publish gate `mcp.publish_wakeshift`, which `mcp/publish-gates.ts` resolves from the file plane and key presence only (never the DB plane; not in `PUBLISH_GATE_KEYS`). `watch_job` runs the get_job owner fence (exported from `ops/jobs.ts`), subscribes the conversation (`once`, 7 d), stores a `wake_subscriptions` row (migration v290), rolls the subscription back when the insert fails, and hands Wakeshift's addition to dispatch through `ctx.emitToolTail` (the result's last text block plus `_meta` keys); `ctx.mcpCaller` (client name, User-Agent, request `_meta`) is set by the stdio and both HTTP transports. `drain.ts` is pull reconciliation: `gbrain serve` and `MinionWorker.start` run a 5 s unref'd timer, `gbrain jobs work` (PGLite) a final pass; at most 20 leased rows a tick, the emit id `<event>:<target>:<finished_us>:<status>:<row>`, the principal re-checked before each emit, 5 attempts on 30 s/2 m/8 m/30 m (429 honours Retry-After, other 4xx final), dead/revoked/expired rows ended at Wakeshift once. The payload (`events.ts`) is a pointer: job id, kind, status, times, next call; never page text. The CLI (`enable` with consent, the owner-only member check, GET /app and the manifest merge; `disable`, `status`, `test`) is the only writer of the enabled flag. Tests: `test/wakeshift-client.test.ts`, `test/wakeshift.serial.test.ts` (repo-less PGLite against `test/helpers/fake-wakeshift.ts`), `test/e2e/wakeshift-postgres.test.ts`.
+- `src/core/ops/wakeshift.ts` + `src/core/wakeshift/{client,config,env-key,events,drain}.ts` + `src/commands/wakeshift.ts` + `src/commands/doctor/checks/wakeshift.ts` — report back to agent conversations through Wakeshift (docs/guides/wakeshift.md), off by default. `client.ts` is the in-repo HTTP client (no SDK): key parsing (`wst_` + 50 base58 with a CRC32; legacy formats refused), a fresh EdDSA `app+jwt` assertion per request, one `fetch` with a 10 s timeout and no retry, loopback-only http. `config.ts` holds the host-only state: `wakeshift.enabled`/`url` in the file plane, the key (WAKESHIFT_API_KEY, which `env-key.ts` moves out of the environment on every config load so children never inherit it, the first value seen winning; else a 0600 `~/.gbrain/wakeshift.key`), the 0600 HMAC secret and the opaque Wakeshift user (HMAC over brain and principal); `wakeshiftPublished` is publish gate `mcp.publish_wakeshift`, which `mcp/publish-gates.ts` resolves from the file plane and key presence only (never the DB plane; not in `PUBLISH_GATE_KEYS`). `watch_job` runs the get_job owner fence (exported from `ops/jobs.ts`), subscribes the conversation (`once`, 7 d), stores a `wake_subscriptions` row (migration v290), rolls the subscription back when the insert fails, and hands Wakeshift's addition to dispatch through `ctx.emitToolTail` (the result's last text block plus `_meta` keys); `ctx.mcpCaller` (client name, User-Agent, request `_meta`) is set by the stdio and both HTTP transports. `drain.ts` is pull reconciliation: `gbrain serve` and `MinionWorker.start` run a 5 s unref'd timer, `gbrain jobs work` (PGLite) a final pass; at most 20 leased rows a tick, the emit id `<event>:<target>:<finished_us>:<status>:<row>:<namespace>` (12 hex of the watch's user and creation time, so brains on one key never collide), the claim re-checking backoff and attempts, a settle only under the claim's lease, the principal re-checked before each emit, 5 attempts on 30 s/2 m/8 m/30 m (429 honours Retry-After, other 4xx final), dead/revoked/expired rows ended at Wakeshift once. The payload (`events.ts`) is a pointer: job id, kind, status, times, next call; never page text. The CLI (`enable` with consent, the owner-only member check, GET /app and the manifest merge; `disable`, `status`, `test`) is the only writer of the enabled flag. Tests: `test/wakeshift-client.test.ts`, `test/wakeshift.serial.test.ts` (repo-less PGLite against `test/helpers/fake-wakeshift.ts`), `test/e2e/wakeshift-postgres.test.ts`.
diff --git a/src/commands/wakeshift.ts b/src/commands/wakeshift.ts
index a975f2967b..00cedb394b 100644
--- a/src/commands/wakeshift.ts
+++ b/src/commands/wakeshift.ts
@@ -112,6 +112,10 @@ async function enable(engine: BrainEngine, args: string[]): Promise<void> {
const stdinKey = args.includes('--key-stdin') ? readFileSync(0, 'utf8').trim() : null;
let loaded: { key: WakeshiftKey; source: 'env' | 'file' | 'stdin' };
if (stdinKey !== null) {
+ if (readWakeshiftKey().source === 'env') {
+ throw keyError('env_overrides', 'WAKESHIFT_API_KEY is set (in the environment or ~/.gbrain/.env) and takes precedence over a saved key, so --key-stdin would save a key gbrain never uses. Nothing was saved.',
+ 'Remove WAKESHIFT_API_KEY, then run gbrain wakeshift enable --key-stdin again; or run gbrain wakeshift enable without --key-stdin to use it.');
+ }
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();
diff --git a/src/core/gbrain-env-file.ts b/src/core/gbrain-env-file.ts
index b7530f3711..3ed0a779f8 100644
--- a/src/core/gbrain-env-file.ts
+++ b/src/core/gbrain-env-file.ts
@@ -58,6 +58,7 @@ export function loadGbrainEnvFile(resolveDir: () => string): void {
} catch {
// The file is optional — missing, unreadable, or an invalid home dir
// must not break config loading.
+ } finally {
+ takeWakeshiftEnvKey();
}
- takeWakeshiftEnvKey();
}
diff --git a/src/core/wakeshift/env-key.ts b/src/core/wakeshift/env-key.ts
index 17a1f2a7e1..2ae16b9199 100644
--- a/src/core/wakeshift/env-key.ts
+++ b/src/core/wakeshift/env-key.ts
@@ -7,10 +7,13 @@ 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. */
+/**
+ * Move the key out of process.env into this module. The first value seen wins, so a shell export (taken at the
+ * first config load) keeps precedence over a ~/.gbrain/.env value a later load fills; a changed key needs a restart.
+ */
export function takeWakeshiftEnvKey(): string | null {
const value = process.env[WAKESHIFT_KEY_ENV]?.trim();
- if (value) envKey = value;
+ if (value && envKey === null) envKey = value;
delete process.env[WAKESHIFT_KEY_ENV];
return envKey;
}
diff --git a/test/wakeshift.serial.test.ts b/test/wakeshift.serial.test.ts
index 3841ff427f..10327e3152 100644
--- a/test/wakeshift.serial.test.ts
+++ b/test/wakeshift.serial.test.ts
@@ -466,6 +466,24 @@ describe('gbrain wakeshift', () => {
}
});
+ test('a shell-exported key leaves process.env on config load with no .env, and keeps precedence over a .env key', async () => {
+ const other = encodeWakeshiftKey(Buffer.alloc(32, 7));
+ const envFile = join(home, '.gbrain', '.env');
+ process.env.WAKESHIFT_API_KEY = KEY;
+ try {
+ loadConfig();
+ expect(process.env.WAKESHIFT_API_KEY).toBeUndefined();
+ writeFileSync(envFile, `WAKESHIFT_API_KEY=${other}\n`, { mode: 0o600 });
+ loadConfig();
+ expect(process.env.WAKESHIFT_API_KEY).toBeUndefined();
+ expect(readWakeshiftKey()).toEqual({ source: 'env', raw: KEY });
+ } 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;