Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ai): claude-cli continuation_unproven reasons are the stdout-only ones it emits, each notice naming its remedy (#6791)

garrytan9bcc4ab1620e
diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.md
index 1776f464dc..e38420f134 100644
--- a/docs/ai-providers/claude-cli.md
+++ b/docs/ai-providers/claude-cli.md
@@ -208,6 +208,6 @@ check, removal and hosted brains. Two points are specific to `claude-cli`:
| `claude-cli exited <code>` + `--- raw ---` blob | Non-zero exit from the `claude` subprocess where stdout carried no parseable result envelope; the CLI's stderr/stdout follows the `--- raw ---` marker (kept behind the marker so error classifiers never phrase-match model-derived text) | Run `claude` interactively with the same model to see the underlying CLI error directly (e.g. not logged in, model unavailable) | user (log in, pick an available model) | `credentials` when logging in | `gbrain models doctor --json` (one tiny call per model) |
| `claude-cli output not JSON: ...` | `JSON.parse(stdout)` threw (stdout wasn't valid JSON at all) | Confirm the installed `claude` CLI version still supports `--print --output-format json`; this adapter's JSON handling was verified against CLI 2.1.145 | agent | none | `claude --version` |
| `claude-cli JSON event array had no "result" event` | stdout parsed as the `--verbose` event array but none of the events had `type: "result"` (the run ended before reporting) | Run `claude --print --output-format json --verbose` by hand with the same model to see where it stops | agent | none | `gbrain models doctor --json` (one tiny call per model) |
-| `[claude-cli] continuation_unproven (<reason>)` on stderr; the call finishes `length` with no text | The answer hit its output cap and Claude Code continued it, but the adapter could not prove the full text from the event array (`segments_unmatched`), or stdout carried only the bare envelope (`events_missing`) | Nothing to repair: callers treat it as a capped answer and retry or escalate. A caller that keeps hitting it needs a larger output cap | agent | none | rerun the call; a raised cap finishes `stop` |
+| `[claude-cli] continuation_unproven (<reason>)` on stderr (once per reason per process); the call finishes `length` with no text | The answer hit its output cap and Claude Code continued it, and stdout could not prove the full text: the bare envelope without the event array (`events_missing`), an event array with no assistant message (`no_assistant_events`), or assistant segments that do not provably make up this answer (`segments_unmatched`) | Callers treat it as a capped answer and retry or escalate. `events_missing` and `no_assistant_events`: upgrade the claude CLI so `--output-format json --verbose` prints the session's assistant events. `segments_unmatched`: raise the caller's output cap (the setting its truncation warning names) | agent | none | rerun the call; a raised cap or an upgraded CLI finishes `stop` |
| `gbrain models doctor` reports `chat` as `status: unknown` for a `claude-cli:` model | The probe allows 30s for the subprocess (see "Doctor probe timeout" above); a persistent `unknown` means the call genuinely failed or outran even that window — `classifyError` falls through to `unknown` for the adapter's abort message | Investigate directly: run the same model via `gbrain models doctor --json` or call `claude` by hand (e.g. not logged in, model unavailable) | agent | none | `gbrain models doctor --json` (one tiny call per model) |
| A call bills through the Anthropic API or a cloud backend instead of the local session | The adapter deletes `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN` / `ANTHROPIC_BASE_URL` and every `CLAUDE_CODE_USE_*` backend-switch flag from the subprocess env — this covers gbrain's own env leaking into the call. It does not inspect billing switches the installed `claude` CLI carries in its own config files | If billing looks wrong, check the `claude` CLI's own auth/billing configuration on this machine, not just gbrain's env. For intentional cloud routing, use the `anthropic` recipe instead | user | none | the `claude` CLI's own auth status on this machine |
diff --git a/docs/architecture/key-files/core-ai-continued.md b/docs/architecture/key-files/core-ai-continued.md
index cf648cc8d5..d3c88b1fe2 100644
--- a/docs/architecture/key-files/core-ai-continued.md
+++ b/docs/architecture/key-files/core-ai-continued.md
@@ -6,7 +6,7 @@ Provider adapters, recipes and the Voyage width plumbing.
- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter over the local `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt JSON: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt asks for no id and a stray `id` is ignored (nothing round-trips it; the loop pairs results in memory within one turn). Every child gets `--settings '{"disableAllHooks":true}'` (#5820: user/project hooks never run, so gbrain's own Stop hook cannot bank the call; login is untouched; managed-policy hooks still run on 2.1.287). A CLI that rejects any flag (`unknown option`) fails with `claude CLI 2.0.60 or newer required (found <version>)` (`MIN_CLAUDE_CLI_VERSION`, probed: 2.0.59 rejects `--disable-slash-commands`). No doStream: gateway.toolLoop uses doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`. `claudeCliFinishReason` maps the CLI's `stop_reason` to the finish reason (`max_tokens` → `length`, `refusal` → `content-filter`, parsed tool calls → `tool-calls`, anything else → `stop`), so callers can refuse clipped answers (`test/claude-cli-stop-reason.test.ts`). `renderPrompt` replays an earlier tool call with its input as JSON (`[tool_use name({...})]`). #6424: a positive integer `maxOutputTokens` reaches the child as `CLAUDE_CODE_MAX_OUTPUT_TOKENS` (env, `--settings` env). #6523: the CLI reports a response that hit that cap (or its own default) as an `is_error` envelope whose `result` starts `API Error: Claude's response exceeded the N output token maximum`; `isOutputCapEnvelope` (anchored prefix, `is_error: true`, no `api_error_status`, string `result`, any cap, any exit code) resolves it as a success with empty text and `stop_reason: 'max_tokens'`, so callers see `length` and their escalation ladders run (loops_extract 2048 → 8192, facts/extract 1× → 2×); every other error envelope stays `ClaudeCliProcessError` (`test/claude-cli-output-cap.test.ts`). #6791: every child also gets `--verbose`, so the json stdout is the session's event array; `doGenerate` takes its text from `resolveClaudeCliAnswer` (`claude-cli-continuation.ts`) and, when that refuses a continued answer, returns empty text, no tool calls, finish `length` and `providerMetadata['claude-cli'] = { code: 'continuation_unproven', reason }` before any `<use_tools>` block is parsed.
-- `src/core/ai/providers/claude-cli-continuation.ts` — what text a claude-cli print-mode run answered. Claude Code continues a response that hit its output cap on its own (meta "Resume directly" nudge, second request), and the envelope's `result` / `stop_reason` are then only the continuation's. `resolveClaudeCliAnswer(run, requestedCap)` keeps the envelope `result` when there was no continuation (or the envelope already says `max_tokens`); otherwise it rebuilds the answer from the call's own events (consecutive assistant events sharing a `message.id` are one segment; `<synthetic>` error messages are skipped), joining the segments' text in order. A rebuild needs the last segment's final text block to equal `result`, no `tombstone` event, every earlier text-bearing segment to report `max_tokens` or no stop reason, and every user event between segments to be a "Resume directly" nudge; anything else is `continuation_unproven` with reason `segments_unmatched`. Without events (a bare envelope) a continuation is inferred from `num_turns > 1` or output tokens above the cap (the forwarded positive-integer `maxOutputTokens`, else `CLAUDE_CLI_DEFAULT_OUTPUT_CAP` = 32000) and refused as `events_missing`; one segment with output above a requested cap is `segments_unmatched`. Nothing is read from disk, so a hermetic `CLAUDE_CONFIG_DIR` changes nothing. The first refusal in a process writes one `[claude-cli] continuation_unproven (<reason>)` line to stderr; `continuationUnprovenMetadata` builds the provider metadata. Pinned by `test/claude-cli-continuation-6791.test.ts`.
+- `src/core/ai/providers/claude-cli-continuation.ts` — what text a claude-cli print-mode run answered. Claude Code continues a response that hit its output cap on its own (meta "Resume directly" nudge, second request), and the envelope's `result` / `stop_reason` are then only the continuation's. `resolveClaudeCliAnswer(run, requestedCap)` keeps the envelope `result` when there was no continuation (or the envelope already says `max_tokens`); otherwise it rebuilds the answer from the call's own events (consecutive assistant events sharing a `message.id` are one segment; `<synthetic>` error messages are skipped), joining the segments' text in order. A rebuild needs the last segment's final text block to equal `result`, no `tombstone` event, every earlier text-bearing segment to report `max_tokens` or no stop reason, and every user event between segments to be a "Resume directly" nudge; anything else is `continuation_unproven` with reason `segments_unmatched`. Without events (a bare envelope) a continuation is inferred from `num_turns > 1` or output tokens above the cap (the forwarded positive-integer `maxOutputTokens`, else `CLAUDE_CLI_DEFAULT_OUTPUT_CAP` = 32000) and refused as `events_missing`; an event array with no assistant message under those signals is `no_assistant_events`; one segment with output above a requested cap is `segments_unmatched`. Each reason's first refusal in a process writes one notice naming its remedy (`CONTINUATION_UNPROVEN_REMEDY`: upgrade the CLI for the first two, raise the caller's output cap for the third). Nothing is read from disk, so a hermetic `CLAUDE_CONFIG_DIR` changes nothing. The notice is one `[claude-cli] continuation_unproven (<reason>)` stderr line; `continuationUnprovenMetadata` builds the provider metadata. Pinned by `test/claude-cli-continuation-6791.test.ts`.
- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. `claudeCliSelfSessionIds(projectsRoot = claudeProjectsDir())` lists the session ids of those harness transcripts; `isClaudeCliSelfSessionId(id, projectDirs = claudeCliSelfProjectDirs())` is the single-session classifier (#5820) shared by the serve-side writeback harvest, the sweep and doctor `self_capture`: one listing of the projects root, then an existence check per prefix-matched scratch project (path-shaped ids are refused); the session-end hook named each corpus file `<session id>.txt`, so dream discovery and the sweep's corpus pass use the set to skip self-captures written before the hook refused them (best-effort: a pruned harness transcript leaves its capture unclassifiable). Pinned by `test/transcripts-self-exclusion.test.ts`.
diff --git a/src/core/ai/providers/claude-cli-continuation.ts b/src/core/ai/providers/claude-cli-continuation.ts
index 8fa42f6c1d..3996075e5e 100644
--- a/src/core/ai/providers/claude-cli-continuation.ts
+++ b/src/core/ai/providers/claude-cli-continuation.ts
@@ -25,7 +25,20 @@
/** CLAUDE_CODE_MAX_OUTPUT_TOKENS' default when the CLI's model table names none (Claude Code 2.1.x). */
export const CLAUDE_CLI_DEFAULT_OUTPUT_CAP = 32_000;
-export type ContinuationUnprovenReason = 'events_missing' | 'segments_unmatched';
+/**
+ * Why a continued answer could not be proven, read from stdout only (no transcript is read):
+ * `events_missing`: stdout was the bare result envelope, so the CLI ignored `--verbose`;
+ * `no_assistant_events`: the event array carried no assistant message to rebuild from;
+ * `segments_unmatched`: the assistant segments do not provably make up this answer.
+ */
+export type ContinuationUnprovenReason = 'events_missing' | 'no_assistant_events' | 'segments_unmatched';
+
+/** The remedy each reason's stderr notice names. */
+export const CONTINUATION_UNPROVEN_REMEDY: Record<ContinuationUnprovenReason, string> = {
+ events_missing: 'upgrade the claude CLI: this one printed only the result envelope under --output-format json --verbose, without the session event array',
+ no_assistant_events: 'upgrade the claude CLI: its --verbose event array carried no assistant messages to rebuild the answer from',
+ segments_unmatched: "raise that caller's output cap (the setting its truncation warning names) so the answer fits without a continuation",
+};
export type ClaudeCliAnswer =
| { kind: 'answer'; text: string }
@@ -130,17 +143,18 @@ export function resolveClaudeCliAnswer(run: ClaudeCliRunView, requestedCap: numb
}
const segments = readSegments(run.events);
if (segments === null) return unproven('segments_unmatched');
+ if (segments.length === 0) return overCap || (run.num_turns ?? 1) > 1 ? unproven('no_assistant_events') : answer;
if (segments.length <= 1) return overCap && forwardedCap !== undefined ? unproven('segments_unmatched') : answer;
const text = rebuild(segments, run.result);
return text === null ? unproven('segments_unmatched') : { kind: 'answer', text };
}
-let noticed = false;
+const noticed = new Set<ContinuationUnprovenReason>();
function unproven(reason: ContinuationUnprovenReason): ClaudeCliAnswer {
- if (!noticed) {
- noticed = true;
- process.stderr.write(`[claude-cli] continuation_unproven (${reason}): Claude Code continued an answer past its output cap and gbrain could not prove the full text, so the call finished as length with no text and no tool calls; the caller retries or escalates as for any capped answer. Remedy: raise that caller's output cap (the setting its truncation warning names) so the answer fits without a continuation; details: gbrain errors continuation_unproven.\n`);
+ if (!noticed.has(reason)) {
+ noticed.add(reason);
+ process.stderr.write(`[claude-cli] continuation_unproven (${reason}): Claude Code continued an answer past its output cap and gbrain could not prove the full text, so the call finished as length with no text and no tool calls; the caller retries or escalates as for any capped answer. Remedy: ${CONTINUATION_UNPROVEN_REMEDY[reason]}. Details: gbrain errors continuation_unproven.\n`);
}
return { kind: 'unproven', reason };
}
diff --git a/test/claude-cli-continuation-6791.test.ts b/test/claude-cli-continuation-6791.test.ts
index 7c7b75e9ef..8ace929419 100644
--- a/test/claude-cli-continuation-6791.test.ts
+++ b/test/claude-cli-continuation-6791.test.ts
@@ -222,6 +222,8 @@ describe('an unprovable continuation is a length outcome with no text and no too
['a segment was retracted',
[init, assistant('a', [{ type: 'text', text: PREFIX }]), { type: 'tombstone', message: { uuid: 'uuid-a-1' } }, assistant('b', [{ type: 'text', text: CONTINUATION }]), envelope(CONTINUATION)],
undefined, 'segments_unmatched'],
+ ['the event array carries no assistant message while usage exceeds the requested cap',
+ [init, envelope(CONTINUATION)], undefined, 'no_assistant_events'],
['one segment but usage exceeds the requested cap',
[init, assistant('a', [{ type: 'text', text: CONTINUATION }], 'end_turn'), envelope(CONTINUATION)],
undefined, 'segments_unmatched'],
@@ -279,6 +281,28 @@ describe('an unprovable continuation is a length outcome with no text and no too
const notices = stderr.split('\n').filter(line => line.includes('continuation_unproven'));
expect(notices).toHaveLength(1);
expect(notices[0]).toContain('events_missing');
+ expect(notices[0]).toContain('Remedy: upgrade the claude CLI');
+ expect(notices[0]).toContain('gbrain errors continuation_unproven');
+ });
+ }, 30_000);
+
+ test('one stderr notice per reason per process, naming that reason\'s remedy (segments_unmatched)', async () => {
+ const modulePath = join(import.meta.dir, '..', 'src', 'core', 'ai', 'providers', 'claude-cli-language-model.ts');
+ const script = [
+ `const { ClaudeCliLanguageModel } = await import(${JSON.stringify(modulePath)});`,
+ 'const opts = { prompt: [{ role: "user", content: [{ type: "text", text: "x" }] }], maxOutputTokens: 4000 };',
+ 'for (let i = 0; i < 2; i++) {',
+ ' const out = await new ClaudeCliLanguageModel("claude-sonnet-5").doGenerate(opts);',
+ ' if (out.finishReason !== "length") throw new Error("expected length");',
+ '}',
+ ].join('\n');
+ await withCli({ verbose: [init, assistant('a', [{ type: 'text', text: PREFIX }], 'max_tokens'), assistant('b', [{ type: 'text', text: 'other text' }], 'end_turn'), envelope(CONTINUATION)], bare: envelope(CONTINUATION) }, async () => {
+ const child = Bun.spawnSync([process.execPath, '-e', script], { env: { ...process.env }, stderr: 'pipe', stdout: 'pipe' });
+ const stderr = child.stderr.toString();
+ expect(child.exitCode, stderr).toBe(0);
+ const notices = stderr.split('\n').filter(line => line.includes('continuation_unproven'));
+ expect(notices).toHaveLength(1);
+ expect(notices[0]).toContain('segments_unmatched');
expect(notices[0]).toContain('Remedy: raise that caller\'s output cap');
expect(notices[0]).toContain('gbrain errors continuation_unproven');
});