Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ai): an expired claude-cli OAuth login is an auth failure, so dream --drain exits 1 (#6817)
time-attack97129ccef0d4
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.tsindex 7ee8792eed..22016a1c37 100644--- a/src/core/ai/errors.ts+++ b/src/core/ai/errors.ts@@ -267,7 +267,7 @@ const PER_ITEM_HTTP_STATUSES = new Set([400, 408, 413, 422]);export const BILLING_MESSAGE_RE =/insufficient_quota|quota exceeded|exceeded your (?:current )?quota|credit balance is too low|spend limit|billing_not_active|billing hard limit|payment required/i;const AUTH_MESSAGE_RE =- /authentication_error|permission_error|invalid (?:x-)?api[-_ ]?key|api key (?:is )?(?:invalid|expired|missing)|unauthorized/i;+ /authentication_error|permission_error|invalid (?:x-)?api[-_ ]?key|api key (?:is )?(?:invalid|expired|missing)|unauthorized|failed to authenticate|oauth session expired/i;export const RATE_MESSAGE_RE = /rate[-_ ]?limit(?:ed|_error)?\b|too many requests/i;// Provider phrasings for an unknown or inaccessible model: OpenAI// `model_not_found` / "does not exist or you do not have access" (404),diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f3b0e87c87..6108afa36b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -926,6 +926,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.312.0', text: 'A same-day `dream` synthesize rerun that writes no pages now keeps that day\'s existing `dream-cycle-summaries/<date>` page (database row and file) on every brain, as managed brains already did, instead of replacing it with an empty summary. The first run of a day still writes its summary even when it wrote nothing.' },{ since: '0.60.312.0', text: 'Hermes transcript import now unwraps message content Hermes stores as `json:` followed by a block array, as it already did for a bare array: text blocks are kept and each image block becomes an `[image]` placeholder, so a pasted screenshot no longer imports as kilobytes of base64 text. Sessions already imported keep their old text until they are imported again.' },{ since: '0.60.312.0', text: '`gbrain dream --drain` no longer exits 11 for every incomplete stop. A stop running again cannot clear now exits 1 with a `Fix:` line instead of a rerun hint: a provider failure on every item caused by auth, billing, an unknown model or a content block (`atom_drain_provider_failure`), and `no_progress` over a counted backlog (`atom_drain_no_progress`). A rate limit, a transient provider failure, the window, budget, batch cap, deadline, lock and an unknown backlog count still exit 11 with the rerun command. `--json` of an incomplete stop now reports `status` `incomplete` or `provider_failure` (never `ok`) with `retryable`, `code` and `reason`, and the help no longer says exit 3. The `extract-atoms-drain` job dead-letters an auth, billing, unknown-model or content-block failure at once instead of retrying it.' },+ { since: '0.60.312.0', text: 'A claude-cli error that reports `Failed to authenticate` or `OAuth session expired` (an expired Claude Code login) is now an auth failure: cycle phases halt on the first one instead of failing every item, and `gbrain dream --drain` exits 1 with `atom_drain_provider_failure` reason `auth` instead of 11. Log in to Claude Code again, then rerun the drain.' },{ since: '0.60.312.0', text: '`gbrain transcripts ingest --format <f>` now refuses a symlink or an unreadable path before parsing, as auto-detection already did, instead of handing the path to the adapter. A refused file is reported per file with its cause and next step (an unreadable path carries its `errno`, for example ENOENT or EACCES); the rest of the run still imports.' },{ since: '0.60.312.0', text: 'A Claude Code session that ended with no conversation (only session bookkeeping and local slash commands such as `/rename`) is now reported by the session-end hook as `empty_session` instead of `parser_drift`, so the next session no longer shows a transcript-ingestion alert for it. A record that carries a message but yields no turn, or a file of only unknown records, still reports `parser_drift`.' },{ since: '0.60.312.0', text: 'Autopilot\'s automatic atom drain (`extract-atoms-drain` jobs) now gets a job deadline that covers its window plus one final item (two chat timeouts and a minute), instead of the shorter interval-derived deadline that stopped and dead-lettered drains mid-call. `autopilot.auto_drain.window_seconds` is clamped so the deadline stays within 30 minutes (a window of up to 1140 s at the default chat timeout).' },diff --git a/test/claude-cli-oauth-expired-6817.test.ts b/test/claude-cli-oauth-expired-6817.test.tsnew file mode 100644index 0000000000..a05353bff9--- /dev/null+++ b/test/claude-cli-oauth-expired-6817.test.ts@@ -0,0 +1,76 @@+/**+ * #6817: an expired claude-cli login reports `Failed to authenticate: OAuth session expired and could not be+ * refreshed` in an error envelope with no API status. The classifier read it as an unknown (transient) failure,+ * so `gbrain dream --drain` exited 11 and a retry loop restarted it until the login was fixed. It is an auth+ * failure: the drain must exit 1 and name the blocker.+ *+ * A POSIX shell stub at GBRAIN_CLAUDE_CLI_BIN plays the CLI, and the drain runs through the real gateway `chat()`+ * with the claude-cli recipe, the real extract_atoms phase and the real drain-to-exit mapping.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { LanguageModelV2CallOptions } from '@ai-sdk/provider';+import { ClaudeCliLanguageModel } from '../src/core/ai/providers/claude-cli-language-model.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { classifyGlobalLlmError, normalizeAIError } from '../src/core/ai/errors.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { EXTRACT_ATOMS_MODEL_KEY } from '../src/core/cycle/extract-atoms.ts';+import { runExtractAtomsDrainForSource } from '../src/core/cycle/extract-atoms-drain.ts';+import { drainOutcome } from '../src/core/cycle/extract-atoms-drain-outcome.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++const OAUTH_EXPIRED = 'Failed to authenticate: OAuth session expired and could not be refreshed';+const envelope = { type: 'result', subtype: 'success', is_error: true, stop_reason: null, result: OAUTH_EXPIRED,+ session_id: 'synthetic-session', num_turns: 1, usage: { input_tokens: 10, output_tokens: 0 } };++async function withCli<T>(run: () => Promise<T>): Promise<T> {+ const dir = mkdtempSync(join(tmpdir(), 'claude-oauth-'));+ const response = join(dir, 'response.json');+ writeFileSync(response, JSON.stringify(envelope));+ const bin = join(dir, 'claude');+ writeFileSync(bin, `#!/bin/sh\ncat > /dev/null\ncat "${response}"\nexit 1\n`);+ chmodSync(bin, 0o755);+ try { return await withEnv({ GBRAIN_CLAUDE_CLI_BIN: bin, CLAUDE_CODE_MAX_OUTPUT_TOKENS: undefined }, run); }+ finally { rmSync(dir, { recursive: true, force: true }); }+}++describe('claude-cli expired OAuth login (#6817)', () => {+ test('classifies as auth, raw and normalized', async () => {+ const error = await withCli(async () => {+ try {+ await new ClaudeCliLanguageModel('claude-sonnet-4-6').doGenerate({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Synthetic page' }] }] } as LanguageModelV2CallOptions);+ } catch (e) { return e; }+ throw new Error('expected the CLI call to reject');+ });+ expect(classifyGlobalLlmError(error)).toBe('auth');+ expect(classifyGlobalLlmError(normalizeAIError(error, 'chat(claude-cli:claude-sonnet-4-6)'))).toBe('auth');+ });++ test('the same words inside raw model output stay unclassified', () => {+ expect(classifyGlobalLlmError(new Error(`claude-cli exited 1\n--- raw ---\n${OAUTH_EXPIRED}`))).toBeNull();+ });++ describe('dream --drain end to end', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);+ afterAll(async () => { await engine.disconnect(); });+ beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig(EXTRACT_ATOMS_MODEL_KEY, 'claude-cli:claude-sonnet-4-6');+ resetGateway();+ configureGateway({ chat_model: 'claude-cli:claude-sonnet-4-6', env: {} });+ });+ afterEach(resetGateway);++ test('the drain stops on an auth provider failure and exits 1 naming the blocker', async () => {+ await engine.putPage('note/alice-example', { title: 'alice-example', type: 'note', compiled_truth: 'meeting notes about acme-example '.repeat(40) } as never, { sourceId: 'default' });+ const result = await withCli(() => runExtractAtomsDrainForSource(engine, { sourceId: undefined, windowSeconds: 60, maxBatches: 2 }));+ expect(result).toMatchObject({ status: 'provider_failure', stopped: 'provider_failure', provider_failure_class: 'auth' });+ expect(JSON.stringify(result)).toContain('OAuth session expired');+ expect(drainOutcome(result)).toMatchObject({ exit: 1, retryable: false, code: 'atom_drain_provider_failure', reason: 'auth' });+ }, 60_000);+ });+});