Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs: segmented agent-session-facts repair and Claude CLI tool-markup retry

garrytan2f4eed72eca7
diff --git a/docs/architecture/key-files/core-ai-continued.md b/docs/architecture/key-files/core-ai-continued.md
index 0f3d5a5c62..13b19e82f2 100644
--- a/docs/architecture/key-files/core-ai-continued.md
+++ b/docs/architecture/key-files/core-ai-continued.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
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-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. A reply with no parsable `<use_tools>` block that still carries the model's native tool-call markup outside code spans and blocks, on a call that offered tools, throws a transient error instead of returning prose, so the job's attempt limit bounds the retries (#9085, `test/claude-cli-stop-reason.test.ts`). 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`; 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`.
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 7af0e3fb09..1ef809f5fe 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -2701,7 +2701,10 @@ page's takes fence when the page holds it, otherwise made inactive in the
database. The preview lists those as `take_to_retire`. A fact or take that
changed since the preview reports `changed_since_preview` and is kept; a fact
that already reads as the agent's with its speaker note (a resumed apply whose
-accepted request committed meanwhile) reports `reattributed`.
+accepted request committed meanwhile) reports `reattributed`. A page stored in
+segments is read back whole, up to 24 MiB, and written back bound to that
+revision; a larger page reports `page_body_segmented` and its facts and takes
+are kept.
<a id="redacted-facts"></a>
### Redacted facts