Skip to content

feat(agent): test the harness on Claude, and fix what that exposed - #2964

Merged
kovtcharov-amd merged 119 commits into
amd:feat/gaia-flagship-agent-2804from
kovtcharov:feat/gaia-flagship-agent-2804
Aug 17, 2026
Merged

kovtcharov-amd merged 119 commits into
amd:feat/gaia-flagship-agent-2804from
kovtcharov:feat/gaia-flagship-agent-2804

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

When the flagship agent gave a bad answer, there was no way to tell whether the harness was broken or the local model was simply small — every failure looked the same. --use-claude runs the agent on Anthropic's API instead of Lemonade, so a bad answer on a known-good model is unambiguously the harness's fault. Pointing it at the harness immediately exposed a run of bugs that had been invisible behind "the model is small", and most of this PR is those fixes. The agent now completes real GitHub triage, keeps conversation history across turns, and stops confidently reporting work it never did.

The threads

Testing the harness against a known-good model. --use-claude (with --claude-model, default claude-sonnet-5) points any subprocess agent at Claude; /model switches models mid-session without losing history or loaded skills. The chat header names the live model and marks it remote, because this is the one thing GAIA otherwise never does — sends your conversation off the machine. Paths that cannot honour the flag refuse loudly rather than ignoring it.

What that immediately caught. Shell commands inherited the agent's stdin and hung for the full 180s timeout, leaving orphaned processes, while the agent blamed "a networking bottleneck" — the same command took 0.07s in a shell. Shell output was silently discarded whenever one byte failed to decode under the Windows locale codec, returning rc=0 with empty stdout. Tool results were truncated to the local NPU's budget even on Claude, gutting structured output. Memory recalled stale errors and unmasked credentials into every prompt. The TUI agent had no conversation history at all.

Making the terminal app usable. A discoverable slash-command palette, /help, /memory, and /setup; paste and text selection that work; Enter that always sends however fast it arrives; follow-ups typed mid-turn no longer dropped; wrapped-line and background rendering fixes.

Measuring it. A code benchmark scored by actually running the generated code rather than judging prose, and a session-replay eval that scores the agent against real recorded sessions.

Test plan

  • python -m pytest tests/unit/test_claude_provider.py tests/unit/test_shell_output_encoding.py tests/unit/test_shell_guardrails.py tests/unit/test_skill_binary_grants.py
  • cd tui && go build ./... && go vet ./... && go test ./...
  • Harness on Claude, with a planted fact the model cannot know:
    echo "passphrase HALIBUT-4417-ZULU" > /tmp/probe.txt, then
    gaia-tui run gaia --query "read /tmp/probe.txt and tell me the passphrase" --use-claude.
    It must call the file tool and return the phrase — a fluent answer without a tool call is a failure.
  • With github-triage installed, ask the TUI for the 3 most recently opened issues in amd/gaia and diff against gh issue list --repo amd/gaia --limit 3 --json number,title
  • Confirm no gh.exe survives a triage run: Get-CimInstance Win32_Process -Filter "Name='gh.exe'"
  • --use-claude requires ANTHROPIC_API_KEY; without it the launch must fail with an actionable message, not fall back to Lemonade

Notes

Only the chat model moves under --use-claude — retrieval still embeds locally through Lemonade, so document questions need Lemonade either way.

gaia prompt --use-claude and gaia llm --use-claude still parse the flag and then answer from Lemonade, because cli.py hardcodes the provider and strips the parameter. Not fixed here; the flag is honoured on the TUI and stdio paths this PR covers.

Ovtcharov added 11 commits August 13, 2026 15:17
Running the TUI with --dev printed `[control] …` lines directly onto the
chat frame — one per control-API request — so the screen a developer turned
--dev on to read was the screen the logging destroyed. Driving a --dev
session over the API repainted it faster than the TUI could redraw.

The control plane runs for the whole session, alongside a Bubble Tea program
holding the alt screen, so stderr is not its to write to between p.Run() and
its return. Diagnostics now append to ~/.gaia/logs/gaia-tui.log (or
GAIA_TUI_HOME when set) — the same on-screen-pointer / in-file-record split
internal/ui/chat/devlog.go already draws for the agent work log.

A log that cannot be opened drops the line rather than falling back to
stderr: a lost diagnostic costs less than a corrupted session.

The one pre-Run() write that stays on stderr is the discovery-file takeover
warning, which now also mirrors to the log — the alt screen was wiping the
one message that explains why a driver is talking to the wrong TUI.
The flagship harness could only be exercised against the local Lemonade
backend, so harness bugs and model bugs were indistinguishable. --use-claude
(with --claude-model, default claude-sonnet-5) appends the literal flags to
the spawned agent's argv, letting the harness be validated on a known-good
model before local Gemma-4 testing.

Because this sends the conversation to Anthropic instead of keeping it on
the machine, the mode is visible end to end: the help text says where the
data goes, the chat header carries a persistent claude chip driven by the
child's actual argv (ClaudeAtLaunch), and a launch status line states it.
Paths that cannot honour the flags refuse loudly instead of dropping them:
the daemon transport, chat --subprocess, and --claude-model without
--use-claude.
Two fixtures assumed a Unix filesystem: TestASubprocessAgentIsNotGated used
/bin/echo as the agent binary and TestHubCatalogLoadSurvivesTheChatView
looked for the built mock without its .exe suffix, so both launches never
left the hub on Windows. The third, the smoke test for a direct chat
launch, still asserted the pre-amd#2932 contract that an idle Esc quits; it
now pins the current one — Esc neither quits nor dispatches ReturnToHubMsg,
and Ctrl+C remains the way out.
… side

Every agent appended to one ~/.gaia/logs/gaia-agent.log with no pid on the
line, so two sessions running at once produced a single interleaved file.
That is worse than no log: a tool timeout logged by a neighbouring agent
reads as a failure of the one being watched, and a test harness driving one
TUI cannot tell whose record it is looking at. It cost a real debugging hour
here — a 180s run_shell_command timeout was nearly filed as a shell bug
before the log turned out to belong to another process.

Two changes, both additive:

- GAIA_AGENT_LOG overrides the log path, so a harness can give its session a
  private file. Unset (or blank) keeps the shared default exactly as before.
- Every line now carries its pid, so the shared default stays attributable
  when no override is set.
GitHub triage reported on a backlog it had never read. `gh issue list` came
back with returncode 0 and an EMPTY stdout, so the model saw no issues and
answered from nothing — no error anywhere to say the output had been lost.

The executor passed bare `text=True`, which decodes with the OS locale codec
(cp1252 on a default Windows box). subprocess does that decode inside its pipe
reader thread, so one unmappable byte raises UnicodeDecodeError there, the
thread dies, and subprocess.run still returns success with empty output. The
trigger was ordinary: issue amd#2962's title contains "⚠️".

Decoding is now explicitly utf-8 with errors="replace", so a stray undecodable
byte costs one character instead of the entire output. Any tool that emits
UTF-8 — git, gh, npm, docker — was on this path.

Reproduced end to end before and after: the same `gh issue list` returns 0
chars under text=True and the full 311-char JSON under utf-8.

Five sibling call sites (agents/base/discovery.py, agents/base/system_context.py)
still pass bare text=True and have the same latent defect; left for a separate
change rather than edited untested here.
--use-claude previously died on first contact with the Anthropic API: the
SDK sent the local Gemma model id (404), a null tools array (400), a
role=system message in the messages array (400), and llama.cpp sampling
kwargs Claude rejects. Even when a request got through, tools were never
sent (the tool-calling gate keyed on Lemonade model ids) and tool_use
responses had no parser. The harness could not be validated against a
strong model before testing the local one.

ClaudeProvider now speaks the full loop: hoists system prompts to the
top-level param, translates OpenAI tool schemas to Anthropic shape,
whitelists request kwargs, floors max_tokens at 8K (thinking shares the
cap on claude-sonnet-5), and re-encodes tool_use blocks — streaming
input_json_delta reassembly included — into the exact Lemonade sentinel
envelope, so the agent loop's parser runs unchanged on either backend.
AgentSDK routes the claude model id whenever use_claude is set and only
forwards tools when present; the base agent counts the claude path as
tool-calling so schemas are sent and the legacy JSON-envelope template
stays out of the system prompt. The stdio transport (what the TUI
spawns) gains --use-claude / --claude-model, and its Lemonade-specific
error copy no longer fires for Anthropic outages. Stale
claude-sonnet-4-20250514 defaults become claude-sonnet-5.

Verified end-to-end against the live API: gaia chat retrieved a planted
fact through a real tool call, and the stdio JSONL stream carried
tool_call -> tool_result -> token -> final for a directory-listing query.
Lemonade-path behavior is unchanged (all new logic is gated on
use_claude); embeddings stay on Lemonade — Anthropic has no embeddings
API.
…ing forever

GitHub triage could not run a single `gh` command. Every attempt hung for the
full 180s tool timeout, left an orphaned gh.exe behind, and the agent then told
the user it was a network problem — while the identical command took 0.07s from
a shell.

capture_output redirects stdout and stderr but leaves stdin alone, so each
command inherited this process's stdin: the transport pipe the TUI holds open
and never writes to. A child that reads it — directly, or by probing whether it
is interactive — waits on input that cannot arrive, because there is no human
on that pipe.

subprocess.run's own timeout does not rescue it. On expiry it kills the cmd.exe
it launched, then calls communicate() a second time with NO timeout, which
blocks on pipe handles the surviving grandchild still holds. That is why a 30s
inner timeout produced a 180s outer one, and why the orphans accumulated one
per attempt.

stdin is now DEVNULL, which is the honest answer: an agent's shell command is
non-interactive by construction, so an immediate EOF is what it should read.

Verified end to end. `List the 3 most recently opened issues in amd/gaia` now
returns in 24.6s and matches `gh issue list` exactly, including the "⚠️" in
amd#2962's title that the sibling encoding fix recovered. Zero orphaned processes
after the run, against two per attempt before.
Six things cost real time here and none were written down. A harness meant to
run unattended has to survive them without a human re-deriving each one.

- A private agent log (GAIA_AGENT_LOG). Agents share one file, so a neighbour's
  tool timeout reads as yours — this nearly produced a false bug report.
- The TUI spawns `gaia-agent` from PATH, which a source checkout does not have.
  Install the hub packages with --no-deps, or pip pulls amd-gaia from PyPI and
  the agent runs that instead of the worktree.
- The flagship ships with NO skills, so L5-L7 cannot pass on a clean checkout.
  Says how to install one, and why to copy rather than `gaia skill import`
  (import re-stamps the tier experimental).
- `gh` is refused until the granting skill is loaded. The refusal reads like a
  missing-tool bug and is not one.
- Restarting Lemonade is LemonadeServer.exe, not `lemonade-server serve`; and
  pre-warm the model or turn 1 pays ~240s and gets reported as agent latency.
- A whole section on diagnosing the 180s shell hang, ordered by what to check.

Also flags that gofmt -l is meaningless on a Windows checkout (CRLF, not drift).
@github-actions github-actions Bot added chat Chat SDK changes llm LLM backend changes tests Test changes performance Performance-critical changes agents tui Go terminal UI (gaia-tui) labels Aug 13, 2026
Ovtcharov added 6 commits August 13, 2026 16:41
"Load the github-triage skill" failed on a tree that visibly contains
github-triage. SKILL_DIRS named only gaia_agent/skills/, which packaging stages
but a checkout leaves holding a lone .gitkeep — so the agent discovered zero
bundled skills and every one of the nine starter-pack skills was unreachable
without hand-copying it into ~/.gaia/skills first.

Worse than failing: asked for a skill it could not find, the agent loaded a
different, similarly-named one (github-issue-response) and reported success.
The user got a skill they never asked for and was never told the requested one
did not exist.

SKILL_DIRS now resolves the packaged directory first and falls back to
hub/skills, mirroring the _MANIFEST_CANDIDATES idiom directly above it. Both
are listed when both exist, so a staged copy shadows the checkout instead of
the two disagreeing silently, and a missing root is skipped rather than handed
to SkillManager as a place to scan.

This is discovery, NOT auto-loading. The prompt-budget trade this agent has
deliberately not taken is default_skill_set, which loads skill bodies into every
prompt; that stays commented out and a test now fails if it is quietly enabled.
The out-of-the-box prompt is unchanged — a skill asked for by name is simply
there to load.

Verified from a clean checkout with ~/.gaia/skills emptied: all nine starter
skills discovered, github-triage and daily-brief both load, and triage of
amd/gaia returns in 24.6s matching `gh issue list` exactly.
The confirmation modal for `run_shell_command command="pwd"` read "This is a
destructive action and may not be reversible." That is false, and it is the
expensive kind of false: a warning someone has learned is wrong on the safe
calls is the warning they dismiss without reading on the dangerous one.

Two different claims were sharing one tier. permanent_delete IS destructive, by
name. run_shell_command is not — it is *unbounded*, `pwd` on one call and
`rm -rf` on the next, which is why it is tiered cautiously in the first place.
The badge was already right for that reason; only the sentence overreached.

The unbounded case now says the true thing and points at what actually settles
it — the command, already on screen one line above. The badge stays
DESTRUCTIVE, and genuinely irreversible actions keep the original wording.
Five subprocess calls decoded child output with bare text=True, which uses the
locale codec. A console tool writes in the OEM codepage and hardware and
credential names carry user-supplied text, so a byte that codec cannot map is
an ordinary occurrence, not an exotic one.

The consequences differed and both were silent:

- discovery.py's `cmdkey /list` catches SubprocessError, FileNotFoundError and
  OSError. UnicodeDecodeError is none of those, so it escaped the handler and
  took the whole credential-discovery pass down over one accented character.
- system_context.py's three GPU probes are each wrapped in a bare
  `except Exception: pass`, so the raise never surfaced — the reading was just
  quietly missing.

errors="replace" everywhere, so a stray byte costs one character instead of the
result. The codec is deliberately left alone: unlike the shell tool (which runs
modern UTF-8 CLIs and now decodes utf-8), these are OS tools whose output really
is in the platform encoding, and forcing utf-8 would corrupt them.

Same root cause as 530d514/e72c2a01, which is why an AST sweep now backs the
claim: no `text=True` without `errors=` remains in agents/base or agents/tools.
… there

`search_web` failed with "[WinError 2] The system cannot find the file
specified" on every call. The agent, given only that, told the user it had "a
consistent environmental problem preventing external network requests" and
abandoned the task — a fabricated diagnosis built on an errno.

Node ships npx on Windows as npx.cmd. Spawning the literal string "npx" without
a shell hands CreateProcess a name that does not exist. This file already knew
that — Context7Service.is_available() probes with shutil.which("npx") — the
spawn just never used the result. argv[0] now resolves through shutil.which,
which applies PATHEXT.

The errors were as bad as the bug:

- A genuinely missing program now names itself and points at Node, instead of
  surfacing an errno that mentions neither npx nor the network.
- Perplexity without PERPLEXITY_API_KEY now refuses up front with the variable's
  name, rather than starting npx and failing somewhere that never mentions the
  key. The model relays this text verbatim, so it decides whether the user reads
  "set PERPLEXITY_API_KEY" or an invented outage story.

Both subprocess calls also decode utf-8 rather than bare text=True: JSON-RPC is
UTF-8 by specification and was being read through the Windows locale codec.
…t opt out of

The agent kept producing confident, wrong answers. Asked to load github-triage
when it was not installed, it loaded github-issue-response instead and replied
"Got it! github-issue-response is now active" — the user got a skill they never
asked for and was never told their request had failed. After three tool
timeouts it announced "a significant networking bottleneck between this agent
and GitHub", a cause it invented; the real fault was inside the tool. It also
narrated its own machinery at users ("1683 prompt tokens", "the response was
truncated") and refused work it had never attempted ("`ls` isn't supported here,
it's a Linux utility" — the tool maps it).

gaia-voice is a new bundled skill, declared in `skills:` so it loads on every
launch. Every rule in it is written against one of those observed failures, and
the first section is the floor: do not claim work you did not do, do not present
empty output as a result, do not substitute a near-miss and report success.

Always-on rather than opt-in because those failures corrupt an answer whichever
task is running — a task recipe can be loaded when its task comes up, an honesty
rule cannot. It is ~900 measured tokens and declares no tools, so the concern
that keeps `default_skill_set` commented out (loading several large skill bodies
into every prompt) does not apply; that stays off.

Verified in the TUI: asked to load a skill that does not exist, the agent now
answers "That skill doesn't exist in any of my directories" and offers the ones
that do, instead of quietly activating a near-match.

The library tests asserted "nothing loads by default"; that invariant is now
"no TASK skill loads by default", pinned by a companion test asserting the
always-on set is exactly {gaia-voice} — the one skill list that has to be
argued for rather than added to. The shared fixture also stopped unloading the
always-on skill between tests, which would have left every later test running
against a prompt the real agent never has.
@github-actions github-actions Bot added the mcp MCP integration changes label Aug 14, 2026
Ovtcharov added 6 commits August 13, 2026 17:08
Killing the agent mid-turn put "agent process exited with code 4294967295" on
screen. That number is 0xFFFFFFFF — the status Windows reports for a
force-terminated process, not a code the agent chose — and to a reader it looks
like memory corruption rather than "it was stopped".

Both branches now also say what happens next. The transport respawns the child
on the following Send, so recovery needs no action at all, and nothing else on
screen tells the user that: they are looking at a red error box with no idea
whether the session is dead.

Found by killing gaia-agent mid-turn from the robustness sweep. The TUI itself
survived correctly and the next message did restart the agent — only the message
was wrong.
…rors"

Tool errors are auto-stored as knowledge and retrieved into every later system
prompt under "Known errors to avoid". Nothing expired them and nothing lowered
their confidence, so one bad moment became permanent doctrine.

The prompt was still carrying this after the hang was fixed:

    - run_shell_command: Tool 'run_shell_command' did not return within 180s
      and was abandoned...

so the model was being told, on every turn, that shell access was broken —
which is exactly the story it kept telling users while running those same
commands successfully. It is also the likeliest cause of the intermittent
"there isn't a skill called github-triage available": a session that recorded
that error before the skill was discoverable carried the belief forward.

Two rules:

- A transient failure is never persisted. Timeouts, dropped connections, rate
  limits and cancellations describe a moment, not a rule this agent must obey.
  A durable constraint still is — "Command 'cmd' is not in the allowed list" is
  a fact about this agent and worth carrying forward.
- A tool that succeeds retires the errors stored against it. A call that just
  worked is direct evidence the tool is not broken, and it is the only signal
  available that a fix has landed. Scoped by the stored "tool: " prefix so one
  tool's recovery never clears another's, and failure-safe: the cleanup runs on
  the success path and must never turn a good call into a bad one.

The self-healing half also repairs databases already poisoned by the old
behaviour — the first successful call clears them.
The flag shipped undocumented, so the one thing a user most needs to know
about it -- that it sends the conversation to Anthropic, unlike everything
else GAIA does -- was only visible in --help.
One turn after triaging amd/gaia, "cool, can you print issue 2975?" got "I need
to know which repository it belongs to". It was not being difficult — it was
never told. Every turn over this transport reached the model as exactly two
messages: the system prompt and the current question.

Agent composes each request as [system, *conversation_history, user], and
nothing in the base class ever appends to conversation_history. The HTTP surface
fills it in per request (gaia/ui/agent_loop.py, gaia/ui/_chat_helpers.py); this
transport never did. So the flagship was amnesiac in the TUI: no pronoun, no
"that repo", no "print issue 2975" could resolve, on any turn.

Each turn's question and final answer are now recorded, capped at 12 pairs and
trimmed in whole turns so the window never opens on an answer whose question was
dropped. Only the question and the answer: tool calls belong to the turn that
made them, and replaying them would re-feed stale tool output into every later
prompt. A turn ending in an error is not recorded — replaying a failure as if it
were an answer teaches the model that the failure is what it said.

The recording sits on the path a normal turn actually takes. The first attempt
put it after the fallback that reconstructs an answer from the return value,
which a streaming turn never reaches: the translator emits the terminal event
and the function returns above it. The answer is now captured from the `final`
event as it goes out on the wire.

Verified in the TUI: "My favourite fruit is mango" then "What fruit did I just
mention?" answers "Mango." (previously "No fruit has been mentioned yet in our
conversation"), and the original amd/gaia follow-up now prints issue amd#2975.
A green ladder hid a total loss of conversation history for a day. Every rung is
a self-contained prompt that names its own repo and subject, so none of them
could ever need a previous turn — and the bug surfaced the moment a user typed
"cool, can you print issue 2975?".

Records the two-turn canary that catches it in ~20s with no tools or network,
and why three separate green signals were misleading: L3 proves the memory
store rather than history, the stdio "survives between turns" test asserts
object state which really does survive, and the HTTP surface populates history
so only the TUI's transport was affected.
Ovtcharov added 22 commits August 16, 2026 22:30
Ran the Go setup-gate tests and the npm client's vitest suite instead
of just describing them — both fully green (7/7 Go, 101/101 npm) — and
wrote the real numbers into the verification section instead of a
vaguer "it has tests" claim. Also spells out why a live PyInstaller
freeze wasn't attempted locally: accelerate pulls torch in transitively
even though the frozen binary excludes it, so reproducing that build
here would mean downloading several GB just to re-derive a number CI
already produces for free.
…verification

gaia-tui --version exited 1 with "unknown flag" because cobra never had
rootCmd.Version set -- only the `version` subcommand worked. Both now print
the same line, sourced from the same build-time-injected version string
build_tui.yml already stamps. Covered by three new tests alongside the
existing binary-name tests in root_test.go.

Also folds in the Python side of this session's own verification into the
flagship installer plan (a full editable install + its 146-test suite
passing) and adds the missing cross-reference from `gaia init`'s docs to
where the flagship agent and its terminal UI actually come from.
Ran the PyInstaller freeze this plan's own verification section said it
had skipped: a real --onefile build produced a 48.9 MB gaia-agent.exe
(smaller than the ~90-120 MB estimate), and packaging/smoke_test.py
passed against that exact binary. Replaces the estimate with a measured,
Windows-confirmed number and moves the freeze from "not verified" to
"verified" in the audit section.

Also sharpens the signing gap: AMD already has a working, free SignPath
OSS policy (.signpath/policies/gaia.policy), but it's scoped to NSIS
installers only and would reject a bare .exe from either binary here --
so closing the Windows half is wiring against existing infrastructure,
not a new procurement, unlike the macOS half which genuinely needs an
Apple Developer ID. Cross-checked against an earlier design doc
(docs/superpowers/specs/2026-07-25-tui-packaging-design.md) that reached
the same SignPath finding independently and had already measured (and
rejected, for architectural reasons) a separately-frozen "engine" binary
alternative -- folded that citation into the rejected-options table.
The slash palette and a mid-run question could only be driven from the
keyboard even though the mouse is now free for text selection between
overlays. Clicking a row did nothing, and pasting a screenshot silently
dropped it since Ctrl+V only ever read clipboard text.

Capture is now scoped to exactly the frames an overlay is open: opening
the palette or a question grabs the mouse (in All-Motion mode, for
hover), closing it releases the mouse back to the terminal. A user's own
Ctrl+T wheel mode is tracked separately and survives an overlay opening
and closing around it, since the two reasons to hold the mouse are
independent and reconciled together on every update.

Hovering a palette row or a question's option selects it; clicking the
row that is already selected runs or answers it, the same as Enter.
Clicking outside the palette closes it, same as Esc — none of it ever
posts the command as a literal chat message.

Ctrl+V now checks the clipboard for an image first (a Win+Shift+S
screenshot, Snip & Sketch, a browser's "copy image") and, if present,
decodes the raw DIB Windows hands back (24-bit and 32-bit, with a guard
against the well-known all-zero-alpha quirk some apps leave behind),
writes it to a temp PNG, and inserts its path — quoted if the path has
a space, matching how Windows Terminal already quotes a dropped file.
macOS and Linux get their own clipboard-image readers (AppleScript and
xclip/wl-paste respectively); text paste is unchanged on every platform.

Verified live against the real Windows clipboard: a synthetic bitmap
round-tripped through Ctrl+V to a correct PNG on disk, and dragging a
path with a space, a folder, and multiple files all landed in the
composer unmangled.
…stion panels

The clickable-overlays work was written against the old bordered panels, so
its hit-tests subtracted a top border row the borderless redesign no longer
draws. A palette click missed entirely at some heights, and a click on a
question option's label row acted on the line above it — reachable only
through its wrapped description lines, which is why the reachability tests
stayed green.

Also moves the Commands block above the copy/paste section in the chat help
panel, so /model and friends are visible without scrolling on a 30-row
terminal. A new component test pins the exact label-row mapping so a
constant off-by-one can never pass as 'reachable' again.
…flagship branch

The coding starter skill's honesty guards were checking its declared tools
against a mixin list that predates the flagship agent: search_file_content,
search_code_index and execute_python_file are all real tools GaiaAgent
registers (via FileSearchToolsMixin, CodeIndexToolsMixin and ChatAgent's
inline registration), but the fixture never instantiated those registrars,
so the guard called the skill a liar. The fixture now runs both mixins and
verifies ChatAgent's inline tool names against the agent's source, so a
rename still fails loudly.

test_manifest_error_names_the_file hardcoded POSIX separators; the loader
renders the source path through Path(), which uses backslashes on Windows.
The test now matches the normalized form.

The coding skill also declared read_file without ever naming it in the
procedure — the section describing it now uses the tool's real name.
…sses

CI's golangci-lint failed the branch on the two literal bidi characters in
devlog_test.go — the nolint directives on those lines did not suppress a
character-level bidichk finding. Escape sequences produce the identical test
data with nothing in the source for the linter (or an editor) to trip on.
golangci-lint flags appending to a slice made with non-zero length; build
the DIB byte stream with slices.Concat instead.
The page landed with the code-index hardening but was never referenced in
docs.json, so it built as an orphan.
Code index: a file that lost even one chunk to a failed embedding still had
its content hash recorded, so every later index skipped it as unchanged and
the missing chunks stayed unsearchable until the cache was wiped. Such files
are now left un-hashed (retried next index), the drop is a WARNING instead
of a DEBUG line, and IndexResult carries a chunks_dropped count.

Code index: an oversized chunk split into parts gave every part the same
(file, start_line), and the embedding-reuse match keyed on exactly that pair
— on re-index, parts 2..N inherited part 1's vector. The match now includes
content and consumes each cache row once; any mismatch re-embeds the lot
rather than silently pairing fewer embeddings than chunks.

TUI: the palette's fits-check still budgeted 4 border rows the borderless
redesign removed, so a window of exactly 14 rows drew nothing while 13 rows
drew fine; budget is now zero, with a height-sweep regression test. Question
hover only re-renders when the cursor actually moves (All-Motion tracking
fires per cell). Renamed a variable shadowing image/png.

Tests: the starter-skill honesty fixture now registers into an emptied
registry so leftovers from earlier tests can't vouch for a typo; the live
code-index test honors LEMONADE_BASE_URL. Dynamic skill selection logs when
memory-off silently reverts it to full-body prompts.
The lazy skill loading landed with no doc updates, so four surfaces still
described a loaded body as permanently resident in the prompt — including the
npm package's SPEC/SKILL/CHANGELOG, which would have shipped a lifecycle its
runtime no longer has. Each now states the flagship agent's per-turn
selection, the collapse-to-menu behavior, the GAIA_DYNAMIC_SKILLS /
GAIA_DYNAMIC_SKILLS_TAU overrides, and the render-everything fallback on an
embedder outage. Base-agent behavior is unchanged and documented as such.
…e header wrap

Every Ctrl+V wrote a PNG straight into the OS temp directory and nothing
ever deleted it. Pastes now land in a gaia-paste/ subdirectory that is swept
of week-old files on each use — old pastes go, files the sweep does not own
stay.

The chat header is budgeted as exactly one row by every mouse hit-test
below it, but a long agent name plus the model and Lemonade chips could
wrap on a narrow terminal and shift them all; it now truncates instead.
…ment

The custom-agent MCP harness has been red on this branch since the mcp
requirement was widened to <3.0: pip resolves mcp 2.0.0, which removed
mcp.server.fastmcp, so the dummy MCP server dies at import and
MCPClient.connect() returns False — exactly the breakage the cap's comment
already documented. The requirement now matches the comment again; lifting
it belongs to a change that actually ports the client to 2.x.

The harness's happy-path test also predates the MCP tool confirmation gate
and ran headless, so the tool call came back 'denied'. It now grants the
documented unattended-run opt-in through the pre-dotenv snapshot the gate
reads (amd#2210), leaving the deny path to the gate's own tests. Harness is
4/4 locally on mcp 1.29.
…s' shadowed the module import

The eval code/sessions branches inside main() each did a function-local
'import os', which makes os a local variable for the WHOLE function — so
'gaia chat --ui --max-indexed-files N' (the exact command the packaged
AppImage backend runs) died at startup with UnboundLocalError before the
server could bind, and /api/health never answered. Both AppImage smoke jobs
have been red on this branch because of it. The module-level import already
covers both branches; the local ones are gone, and the fix is proven by
driving the real CLI path to a booted UI server.

The userns smoke job also now dumps the app's stdout/stderr when the health
check fails — it only dumped on the ready-state failure, which is why this
took a traceback from the distro-matrix job to see.
TESTING_STATUS.md is a session log naming local paths — the same class of
file this branch already evicted and gitignored; it was missed because its
name matched no pattern. Now it does.
lint.yml only fires on PRs whose base is main, so black violations
accumulated invisibly on this feature branch — PR amd#2964 stayed green while
the identical tree would fail PR amd#2932's lint the moment it advanced. Black
26.5.1 (what CI resolves) reformatted; no semantic change.

util/lint.py --fix also crashed on Windows before reporting: bare text=True
decodes subprocess output with cp1252, and black's summary emoji killed the
reader thread, handing back None. It now decodes UTF-8 with replacement.
The agent's 170+ tests ran only inside release_agent_gaia.yml, so a PR that
broke the flagship agent stayed green until the release gate. The new
workflow runs the package suite plus the skill-framework suites it leans on
(skill loader, lazy activation, starter-pack guards, skill sets) on every
PR touching the agent or those surfaces, with the same dependency shape the
release job tests against.
…ix the sidecar's code-index root

SkillLibraryToolsMixin imported nothing gaia-agent-specific — it is general
'let the model manage its own skill library' capability, and its four trust
refusals are framework decisions a second agent would have re-derived. It
now lives in gaia.agents.tools.skill_library_tools, is composable by name
(KNOWN_TOOLS['skills']), and the old import path re-exports it.

GaiaAgent's code index was rooted at os.getcwd() — the same wrong cwd its
allowed_paths field documents rejecting (the daemon launches the sidecar
with cwd = the package directory), so code search was sandboxed to the
agent's own source tree and indexed it by default. It now shares
allowed_paths' scope. The base class also moves first in the MRO, matching
every other hub agent so a future mixin method can't silently win over
ChatAgent's.

setup.py's mcp comment is aligned with the block main merged in amd#2941, so
the branches no longer conflict on that hunk.
…p implementation

components.HelpState was extracted so help works without a root wrapper,
but RootModel kept its own three fields and re-implemented the key handling
inline — two copies of open/scroll/dismiss that could drift. Root now holds
the same state machine the chat view uses.

Also records the review's deliberately-deferred design findings in
docs/plans/flagship-review-followups.md so the debt is visible instead of
folklore: history ownership, the dual readiness gates, ChatModel
decomposition, focus ownership, the diff render contract, binary-policy
shapes, loader dedup, session-registry extraction, and the control-API
transcript endpoint.
…and an explicit skill ask survives follow-ups

Three confirmed review findings on the lazy skill selection:

A transient embedding failure set a permanent session-disabled flag, and
nothing in any host ever resets a skill loader — so one warm-up hiccup on
turn 1 reverted every remaining turn to full-body prompts, silently
reinstating the bloat the loader exists to fix. The disable is now a
5-turn cooldown that retries on its own.

A warming-up embedder can answer 200 with fewer vectors than texts; the
bare zip in both loaders silently dropped entries and surfaced later as a
KeyError misreported as 'service unreachable'. Both now fail loudly at the
mismatch.

Explicitly re-activating a skill (load_skill on an already-loaded one)
survived less than one exchange: the next turn's fresh selection wiped it,
so a follow-up like 'yes, continue' collapsed the recipe mid-execution.
Explicit asks are now pinned active for 3 turns before pure semantic
selection resumes.
… bigger than what gets embedded

One stale metadata row used to discard embedding reuse for every unchanged
chunk in the repo — thousands of re-embed calls to recover vectors that
matched the cache perfectly. Matching is now per-chunk (misses re-embed
alone) and keyed through a map instead of an O(reused x existing) scan.

The oversized-chunk guard split at 20,000 chars while only the first 1,200
are ever embedded, so ~94% of every split part stayed unsearchable — the
exact failure the guard's own comment cites as its reason to exist. The
split size is now derived from the embed window, which itself was
copy-pasted three times inside the SDK and now has one home.

gaia-code 'index search' was the one CLI action with no error wrapper, so
a search during embedder warm-up died with a raw traceback instead of the
message its sibling actions print.
Ctrl+V preferred a clipboard image over text, so copying cells from Excel
or Word — which put BOTH a text and a bitmap rendering on the clipboard —
pasted a PNG path of a picture of them. Text now wins; screenshot tools
put nothing in the text slot, so screenshots still paste as images.

Pasted screenshots landed in the OS temp dir, which on Linux and macOS is
outside the agent's home-directory sandbox — the agent refused the very
path the paste inserted. They now land under ~/.gaia/paste (still swept).

Clicking a question's free-text row when it was already the cursor row
synthesized Enter and submitted whatever half-typed answer it held; a
click there now only focuses. Long option labels used to wrap while the
row map counted them as one line, shifting every hit-test below by a row —
labels now truncate, like the header.

Stepping mouse capture down from All-Motion to Cell-Motion emitted only
?1002h; terminals tracking the two flags independently kept streaming
every pointer movement. The step-down now drops all tracking first.
@github-actions github-actions Bot added the agent::code Code agent changes label Aug 17, 2026
Ovtcharov added 3 commits August 17, 2026 10:28
…ll layers

The stdio pipe could desync permanently: a per-tool policy alert maps to a
terminal 'error' while the agent keeps running, the reader stops at the
first terminal event, and the run's real 'final' sat unread in the pipe —
every later turn then showed the previous turn's answer. The writer now
stops at the first terminal event, like the HTTP transport always did.

From the other end of the same pipe: a child that died between turns (the
ordinary cold-start Lemonade failure) left the client pointing at the
corpse, so the retry the error message asked for could never work — and a
scanner error (a >1MB line) left a permanently-errored reader re-reporting
itself forever. Both paths now reset the client so the next message
respawns.

The embedder-failure cooldown from round one never expired in the real
agent — the host skips select() while disabled, and select() was the only
place the turn counter advanced. It is now wall-clock. The sticky skill
pin also skipped the explicit-ask-while-already-active case, collapsing the
recipe one follow-up later.

Also: a bare index_codebase() no longer walks the user's entire home
directory (the flagship's sandbox root); the code-index cache version is
bumped so pre-split 20K chunks are re-indexed instead of staying 94%
unsearchable, and split parts now carry real per-part line ranges; the hub
agent's dependency floor rises to 0.23.0 (it imports a module 0.22.0 does
not ship); Ctrl+V prefers the image again when the text beside it is just
the image's URL; the session registry's capacity refusal is a typed 503
instead of a bug-shaped 500, and its eviction warning can no longer be
swallowed by a racing creator; empty answers are no longer recorded into
history.
The break-on-first-terminal fix traded one bug for another: exiting the
drain early let the strictly-sequential stdio loop start a second
process_query() on the same agent while the old worker was still mutating
it. The drain now runs to worker completion and only stops WRITING after
the first terminal event. The streamed and fallback paths also now agree
that an empty answer is never recorded.

Ctrl+V no longer silently pastes a caption URL when the image it captions
failed to decode — the decode error surfaces, per the platform readers'
contract — and the caption heuristic gained the test coverage it shipped
without.

The home-directory indexing refusal suggested a '~/...' path the pipeline
then failed to expand; repo_path now goes through expanduser. The walk
itself is bounded too: enumerating a huge non-repo root (a whole drive, a
cloud-synced home) now stops with an actionable error instead of burning
the tool timeout listing entries. The split-part line scan is O(n) instead
of O(n-squared) on the giant files it exists for.

The manifest's dependencies list caught up with the 0.23.0 floor bumped
everywhere else in the same commit; the new at-capacity 503 is documented
in SPEC §5.2 and the CHANGELOG; the dead-child reset triple in the
subprocess client is one helper instead of two hand-copied variants.
… the source

The round-three drain fix traded the pipe desync for a deadlock: once a
mid-run terminal error went out, the drain suppressed every later event —
including a permission prompt whose stdio wait is unbounded — so the worker
parked forever and the process never served another turn. Terminal now
cancels the run (the handler's cancelled event breaks both the confirm and
input waits), and the invariant itself moved into CanonicalTranslator:
nothing is emitted after the first terminal event, making every consumer
loop — stdio, HTTP, email — correct by construction, with tests.

The walk bound became a cap instead of a crash: a legitimate repo with a
giant assets/ subtree now indexes what was found (loudly), instead of a
RuntimeError advising the user to do what they had already done. The budget
counts entries after pruning, lives in CodeIndexConfig with the other
limits, and has tests. expanduser now applies to the STORED index root too,
so a '~'-style allowed_paths config can't produce a root that rejects the
very paths the refusal message recommends.

Ctrl+V: a transiently busy Windows clipboard no longer fails a paste whose
caption text was already in hand (a typed busy sentinel distinguishes it
from a real decode failure), and a Linux box with neither wl-paste nor
xclip finally says so instead of a silent no-op. Turns whose final carried
an empty answer keep the user's question in history. SKILL.md now
distinguishes the /query capacity 503 from the init 503 it previously
taught was the only kind. The cancel path uses the shared dead-child reset
helper instead of hand-rolling two-thirds of it.
@kovtcharov
kovtcharov marked this pull request as ready for review August 17, 2026 23:22
@kovtcharov-amd
kovtcharov-amd merged commit a3a4bce into amd:feat/gaia-flagship-agent-2804 Aug 17, 2026
57 of 58 checks passed
kovtcharov-amd pushed a commit that referenced this pull request Aug 18, 2026
…2964)

When the flagship agent gave a bad answer, there was no way to tell
whether the harness was broken or the local model was simply small —
every failure looked the same. `--use-claude` runs the agent on
Anthropic's API instead of Lemonade, so a bad answer on a known-good
model is unambiguously the harness's fault. Pointing it at the harness
immediately exposed a run of bugs that had been invisible behind "the
model is small", and most of this PR is those fixes. The agent now
completes real GitHub triage, keeps conversation history across turns,
and stops confidently reporting work it never did.

**Testing the harness against a known-good model.** `--use-claude` (with
`--claude-model`, default `claude-sonnet-5`) points any subprocess agent
at Claude; `/model` switches models mid-session without losing history
or loaded skills. The chat header names the live model and marks it
remote, because this is the one thing GAIA otherwise never does — sends
your conversation off the machine. Paths that cannot honour the flag
refuse loudly rather than ignoring it.

**What that immediately caught.** Shell commands inherited the agent's
stdin and hung for the full 180s timeout, leaving orphaned processes,
while the agent blamed "a networking bottleneck" — the same command took
0.07s in a shell. Shell output was silently discarded whenever one byte
failed to decode under the Windows locale codec, returning rc=0 with
empty stdout. Tool results were truncated to the local NPU's budget even
on Claude, gutting structured output. Memory recalled stale errors and
unmasked credentials into every prompt. The TUI agent had no
conversation history at all.

**Making the terminal app usable.** A discoverable slash-command
palette, `/help`, `/memory`, and `/setup`; paste and text selection that
work; Enter that always sends however fast it arrives; follow-ups typed
mid-turn no longer dropped; wrapped-line and background rendering fixes.

**Measuring it.** A code benchmark scored by actually running the
generated code rather than judging prose, and a session-replay eval that
scores the agent against real recorded sessions.

- [ ] `python -m pytest tests/unit/test_claude_provider.py
tests/unit/test_shell_output_encoding.py
tests/unit/test_shell_guardrails.py
tests/unit/test_skill_binary_grants.py`
- [ ] `cd tui && go build ./... && go vet ./... && go test ./...`
- [ ] Harness on Claude, with a planted fact the model cannot know:
      `echo "passphrase HALIBUT-4417-ZULU" > /tmp/probe.txt`, then
`gaia-tui run gaia --query "read /tmp/probe.txt and tell me the
passphrase" --use-claude`.
It must call the file tool and return the phrase — a fluent answer
without a tool call is a failure.
- [ ] With `github-triage` installed, ask the TUI for the 3 most
recently opened issues in `amd/gaia` and diff against `gh issue list
--repo amd/gaia --limit 3 --json number,title`
- [ ] Confirm no `gh.exe` survives a triage run: `Get-CimInstance
Win32_Process -Filter "Name='gh.exe'"`
- [ ] `--use-claude` requires `ANTHROPIC_API_KEY`; without it the launch
must fail with an actionable message, not fall back to Lemonade

Only the chat model moves under `--use-claude` — retrieval still embeds
locally through Lemonade, so document questions need Lemonade either
way.

`gaia prompt --use-claude` and `gaia llm --use-claude` still parse the
flag and then answer from Lemonade, because `cli.py` hardcodes the
provider and strips the parameter. Not fixed here; the flag is honoured
on the TUI and stdio paths this PR covers.

---------

Co-authored-by: Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent::code Code agent changes agents chat Chat SDK changes cli CLI changes dependencies Dependency updates devops DevOps/infrastructure changes documentation Documentation changes eval Evaluation framework changes llm LLM backend changes mcp MCP integration changes performance Performance-critical changes tests Test changes tui Go terminal UI (gaia-tui) website GAIA website (amd-gaia.ai)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants