> ## Documentation Index
> Fetch the complete documentation index at: https://amd-gaia.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Goal Mode

> /goal: keep working across turns until a stated condition is checked and holds, then stop and say so

# Goal mode: work until it's actually done

> **Status:** Proposed. Nothing below is built unless marked *exists today*.
>
> **Priority:** P1. Long jobs that stop early or claim false completion are the largest
> correction cluster measured in [Agent-loop gaps](https://github.com/amd/gaia/blob/main/docs/plans/agent-loop-gaps-from-session-mining.md).
>
> **Extends:** #3959 (TUI `/goal` as a standing directive). This plan adds the part
> \#3959 left open: a check that refuses to end the run until the goal holds.
>
> **Related:** #3381 (verification state for one turn), #7995 (background goals retry
> forever), #8100 (plan cap ends long turns early), #8099 (claimed verification that
> never ran), #5402 (undo missing outside the Agent UI chat path),
> [Adaptive Recovery](https://amd-gaia.ai/docs/plans/adaptive-recovery.md), [Autonomy Engine](https://amd-gaia.ai/docs/plans/autonomy-engine.md)

***

## 1. The problem

**GAIA ends a job when the model says it's done, not when the job is done.** A long
task stops at the first confident answer. The user then finds the half-finished work,
types "continue", or asks "did you actually check?".

* The agent loop has two real exits: an answer that passes the regex guards, or the
  step cap. Nothing between "the model wrote an answer" and "the turn ends" asks
  whether the requested outcome exists.
* Long turns end before their step budget does. #8100: the plan-iteration cap stops a
  300-file job at \~530 steps of 1000.
* Answers claim checks that never ran (#8099).
* The background goals in Memory › Goals (*exist today*, `GoalStore` +
  `ui/agent_loop.py`) have the opposite failure. Nothing judges a tick's result, so a
  goal that can't be done is retried every 60 s indefinitely and never shows as failed
  (#7995).

Claude Code's `/goal` handles this by storing a completion condition. Every time the
agent tries to stop, a separate evaluator reads the transcript. If the condition
doesn't hold, the stop is refused with a reason and the agent keeps going. The goal
clears itself once the condition is met. GAIA should offer the same contract, built
for a 4B local model that grades its own work too generously.

## 2. What the user gets

```
/goal all 300 CSVs in data/raw are converted to parquet in data/clean, and check_counts.py passes
```

GAIA starts working. Each time it would normally stop, it checks the goal instead:

* **Met:** the run ends with *"Goal met"* and the evidence: the command that passed and
  the files it saw.
* **Not met:** it names what's still missing (*"212 of 300 converted; check\_counts.py
  fails on 2024-03.csv"*) and starts the next round with that list.
* **Blocked:** when only the user can unblock it (a missing file, a sign-in, a denied
  permission), it stops and asks a precise question instead of retrying.
* **Out of budget or stalled:** it stops, and the result says plainly that it is *not*
  done and what's left. This must never read like success.

| Command | Effect |
| - | - |
| `/goal <condition>` | Set the goal and start working on it now |
| `/goal` | Show the goal, the current round, and what's left |
| `/goal clear` | Drop the goal; the running round stops at its next step |
| Stop / Esc | Pause the goal |
| `/goal resume` | Continue a paused goal from its ledger |

Text typed *during* a round is folded into that round as a follow-up, like any running
turn today (`queue_followup`). Text typed *between* rounds, or while the goal is paused,
runs as a normal turn and doesn't consume a round. A paused goal stays paused until
`/goal resume`.

## 3. Design

### 3.1 Shared policy in base, rounds driven by each host

`process_query` runs one turn. It does not save history: each host does that itself.
stdio uses `_record_turn`, the sidecar re-pushes `turns` from the Agent UI database, and
`-p` keeps only process memory. Each host also has its own turn contract. For example,
stdio emits exactly one terminal event per query and cancels the run when it does. So a
loop inside `agents/base/` can't drive rounds for every surface.

The split:

* **`src/gaia/agents/base/goal_run.py` holds the policy, with no I/O.** `GoalSpec`,
  `GoalLedger`, `GoalVerdict`, and `next_action(verdict, ledger, budget)` decide one of
  continue, met, needs\_user, stalled, budget, paused or cleared. It also builds each
  round's prompt and the goal system-prompt fragment.
* **`src/gaia/agents/base/goal_check.py` holds the checker** (§3.3).
* **Each host owns a `run_round(prompt) -> RoundResult` and the loop around it.** The
  host records history the way it already does for a turn, and calls the checker
  between rounds.

```
while True:
    result  = host.run_round(policy.round_prompt(ledger))   # host saves history
    verdict = checker.check(goal, ledger, result.evidence)
    ledger.record(verdict, result)
    host.emit(goal_verdict)                                 # non-terminal event
    action  = policy.next_action(verdict, ledger, host.budget())
    if action != "continue": host.finish(action); break     # one terminal event
```

Every path that runs a flagship turn today has to be covered. The evals must name which
path they exercise:

| Surface | Path (*exists today*) | Who loops |
| - | - | - |
| TUI, subprocess transport | flagship over stdio, `gaia_agent/stdio.py` | stdio host: one stdin query = one goal; per-round `goal_round` / `goal_verdict` events, then one terminal event |
| TUI, daemon transport | relay through the daemon (`tui/internal/client/factory.go` picks by install state) | the sidecar, as for the Agent UI |
| Agent UI, binary install | sidecar `POST /v1/gaia/query` | Agent UI backend: one relay per round |
| Agent UI, wheel/dev install | in-process `GaiaAgent` (`ui/_chat_helpers.py`), the path `gaia eval agent` uses | Agent UI backend: one `process_query` per round |
| Headless, wheel | `gaia -p` in-process (`print_mode.py`) | `print_mode`, which appends each round to history itself |
| Headless, relayed | `gaia -p` one-shot relay, no `session_id` | not supported in v1: refused with an actionable error, because rounds would share no history |

`/goal clear` and Stop can't wait for the turn to end: the TUI holds slash commands
until the running turn finishes (`followup.go`). On stdio they travel as a
`gaia_control` message, like `full_access`. On the sidecar they use a cancel-style
endpoint next to `/query/{run_id}/cancel`.

### 3.2 The contract lives outside the conversation

The goal text, its checks, and a **ledger** (what's done and what's left, per round)
are kept beside the history, never inside `messages`. History fitting
(`fit_history_to_turn` / `SessionHistory.prepare`) drops older turns as the session
grows, so a goal kept only in the chat is lost on a long run. Each round sees the goal
through a `get_goal_system_prompt()` fragment. `_get_mixin_prompts` already
auto-discovers that kind of method. The fragment must be listed in
`VOLATILE_PROMPT_FRAGMENTS` (base and the flagship's union), or the ledger changing
every round rewrites the system prompt and loses the cached prefix.

There's no single session store, so each surface keeps the goal where it keeps the
session:

| Surface | Goal + ledger stored in | Survives restart |
| - | - | - |
| Agent UI (both paths) | `ui/database.py`, a column on the session | yes, restored **paused** |
| TUI stdio | the `SessionHistory` file at `--history-file` | yes, restored **paused** |
| Sidecar | not stored; pushed per request, following the server's "pushed context, never pulled" rule | n/a |
| `-p` | process memory | no |

The sidecar gains an optional `goal` object on `QueryRequest`. That model forbids extra
fields, so this needs an `API_VERSION` bump (currently 2.28) and a capability flag the
host checks, the way `session_id_supported` is gated. A goal never restarts work on its
own after a restart.

### 3.3 The check: execution first, then evidence, never the model's own claim

A small model asked "is this done?" says yes. So the checker runs in three tiers and
stops at the first that decides:

1. **Executable checks (deterministic).** A goal can name commands, either explicitly
   (`/goal … --check "pytest tests/unit"`) or proposed from the condition text (*"and
   check\_counts.py passes"*). Between rounds there's no channel for a permission prompt:
   stdio and the sidecar have already closed the turn, and `-p` denies gated tools. So
   the user confirms the exact command once, when the goal is set. It is stored as a
   session grant scoped to that command string, and the host runs it through the shell
   tool's guard. A non-zero exit means **not met**, whatever any model thinks.
2. **Goal-level evidence.** `CompletionEvidence` (`completion.py`) is per-turn: it's
   rebuilt every turn and its obligations come from that turn's text. A round prompt of
   "Still missing… Continue" names no outputs, and a file written in round 1 is unknown
   to round 3. So the ledger accumulates each round's `written_files()` and
   `completion_gaps`. Tier 2 checks the goal's own `save_obligations(goal_text)` against
   the filesystem, and round prompts carry the goal's named outputs. A named output
   that doesn't exist means **not met**.
3. **Evaluator call.** A fresh-context side call to the **already-loaded model** at
   temperature 0 with JSON-schema output: `{met, missing[], evidence[], blocked,
   question}`. It goes through the agent's own client, the way the memory-extraction
   side call does (`tools=[]` + `response_format`), so it inherits the loaded context
   size. A fresh client could reload the model at the default window (the #1030
   failure). Its input is the condition, the ledger, and a bounded digest of the
   round's **tool calls and results**. The agent's final answer is included but
   labelled *claims, not evidence*. A `met` must cite a tool result. An uncited `met`
   is downgraded to not-met and the missing citation is named. This is the guard
   against #8099. Its tokens are added to spend explicitly, because side-call usage is
   kept out of a turn's stats.

Prose goals with no runnable check are legitimate (tier 3 only). The final message then
says the outcome was judged from evidence, not proven by a test.

**Sharing the model between rounds.** Memory extraction starts about 3 s after
`process_query` returns, so it competes with the evaluator for the model. It also stores
each turn's input as user text. Round prompts are system-written, so they're marked
`mark_external_content()`, and extraction waits until the goal ends.

### 3.4 Stopping is bounded and always says why

The goal is an explicit user opt-in, so continuing is the requested behaviour and not a
hidden retry. It still needs hard bounds, each with a distinct end state:

| End state | Trigger | What the user sees |
| - | - | - |
| `met` | check passes | "Goal met" + evidence |
| `needs_user` | evaluator `blocked`, or the same blocker two rounds running | the precise question, as in [Adaptive Recovery](https://amd-gaia.ai/docs/plans/adaptive-recovery.md) |
| `stalled` | 3 rounds with an unchanged ledger and no new successful tool result | "Not done: stopped making progress" + what's left |
| `budget` | max rounds (default 20), wall-clock (default 2 h), or the cloud spend limit | "Not done: budget reached" + what's left + a one-click "keep going" |
| `paused` / `cleared` | Stop, Esc, `/goal clear` | the goal state, unchanged |

Defaults are settings (`goal_max_rounds`, `goal_max_minutes`), not hidden constants.
`goal_run.py` takes a host-supplied budget callback and never imports the UI's spend
module, since the TUI and `-p` have no UI database. The Agent UI's callback checks
`spending.limit_refusal` once per round, as it already does per turn.

### 3.5 What each round looks like

Round *n+1*'s prompt is short and system-authored: *"Goal not met yet. Still missing: …
Outputs: … Continue."* It is never re-sent as the user's text. Each round gets the
agent's normal step budget. In the Agent UI, rounds are stored under a new visible
`goal_round` message role. The `autonomous` role is hidden and left out of
`message_count`, so it doesn't fit. That needs a CHECK-constraint migration like
`_migrate_autonomous_role`. History then shows the user's request once, followed by
numbered rounds.

### 3.6 Background goals reuse the same checker

`AgentLoop._execute_tick` (*exists today*) trusts `set_loop_state`, or falls back to
"more goals remain → continue". Phase 3 reuses the checker, which takes three changes:

* **Ticks become per-goal.** A tick prompt carries up to three goals today, so one
  verdict can't be mapped to one goal.
* **The sidecar tick path returns evidence.** It currently returns only the answer
  text, which leaves tiers 2 and 3 nothing to read.
* **`GoalStore` gains a `blocked` status.** Mapping `needs_user` to `failed` would lose
  the difference between "ask me" and "gave up".

Then `met` → `completed`, `needs_user` → `blocked`, and `stalled`/`budget` → `failed`
with the reason in `progress_notes`. This closes #7995 without a second goal system.

The foreground `/goal` stays session-scoped and doesn't create a `GoalStore` row.
Memory › Goals stays the place for approved background work.

## 4. What it doesn't do

* **No context compaction.** It follows the standing decision: long runs rely on the
  ledger, memory, and the existing history fitting. If a round still overflows, the
  goal stops as `budget` with what's left. It does not summarise history behind the
  user's back.
* **No permission escalation.** Gated tools prompt as usual inside a round. The one
  standing grant is the confirmed check command (§3.3).
* **No second judge model.** A separate evaluator model (as Claude Code uses) is only
  offered once evals prove it beats self-checking on GAIA hardware.
* **No goals the agent sets for itself.** That is the autonomy engine's observation
  cycle, a separate plan.

## 5. Proof before it ships

Under [Offer users only what GAIA has proven](https://github.com/amd/gaia/blob/main/CLAUDE.md),
`/goal` appears in the palette, the help, and the Agent UI only on models whose goal
evals pass.

* **New eval category `gaia_goal`** with its own `ci_lanes.json` lane, scored on the
  flagship baseline models (Gemma-4-E4B and Qwen3.6-35B-A3B). The scenario runner
  learns to set a goal and read the end state. Scenarios:
  * a job that needs more than one turn (step budget forced low);
  * a planted premature claim (a test that fails until a second fix lands);
  * an impossible goal that must end `needs_user` within two rounds, not loop
    (the #7995 shape);
  * a fabricated-verification answer, where the evaluator must refuse `met` (the
    \#8099 shape);
  * a stall, where the agent repeats a failing call and the goal must end `stalled`.
* **Path coverage:** the scenario eval drives the in-process Agent UI path. A smoke run
  through the packaged sidecar and the TUI stdio host covers the paths users install.
* **The headline metric is the false-`met` rate.** A goal that claims success when the
  work isn't done is worse than no goal mode. Completion rate, rounds used, and time
  come second.
* **Head-to-head with Claude Code's `/goal`** on the same tasks: `gaia eval tasks` gains
  a goal option for both `--harness gaia` and `--harness claude-code`, so the comparison
  isolates the harness.
* **Tier gate:** if the compact tier's evaluator can't hold the false-`met` bar, an entry
  in `model_features.py` limits `/goal` to the `full` tier until it can, or allows it on
  compact only with an executable `--check`.
* **Context and prefill cost** of the goal fragment, the evaluator digest, and the
  evaluator call's prompt-cache miss (each round may re-prefill) are measured at 32K and
  64K before merge, per #3381.

## 6. Build order

| Phase | Ships | Depends on |
| - | - | - |
| 0 | Fix #8100 (plan cap ends long turns early) so a single round can use its whole budget | — |
| 1 | `goal_run.py` (policy) + `goal_check.py` (tiers 1–3); volatile prompt fragment; extraction hold during goals; in-process hosts: `gaia -p --goal` and the Agent UI wheel path; unit tests asserting the evaluator call's shape, plus one `require_lemonade` integration test | 0 |
| 2 | Wire contract: `goal_round` / `goal_verdict` events in `ui/sse_translation.py`, the TUI's `canonical.go`, and `tests/fixtures/stdio/gaia_stdio_wire.json`; sidecar `goal` field + `API_VERSION` bump + capability flag; `gaia_control` clear/pause on stdio | 1 |
| 3 | TUI `/goal` (stdio host loop, palette, `/help`, status line); Agent UI goal chip, `goal_round` role migration, "keep going" on `budget`; `gaia_goal` evals + lane; `model_features.py` gate; goal option in `gaia eval tasks` | 2 |
| 4 | Background goals judged by the checker: per-goal ticks, evidence from the sidecar tick path, `blocked` status (#7995); file snapshots for goal rounds so undo covers them (#5402) | 1 |
| 5 | #3381 reuses `goal_check` for single-turn verification, which retires the ad-hoc answer guards it already owns | 1 |

Each phase updates the docs it touches: `docs/reference/cli.mdx` for `--goal`, and
`docs/guides/agent-ui.mdx` and `docs/guides/tui.mdx` for `/goal`.

## 7. Open questions

1. **Inferring checks from prose.** Should the agent propose an executable check when
   the condition implies one ("tests pass"), with the user confirming it once? This is
   recommended; the cost is one confirmation when the goal is set.
2. **Concurrent goals.** One goal per session (Claude Code's model) is proposed. Several
   goals belong in Memory › Goals as background work.
3. **Where rounds run in the Agent UI.** In the user's own chat (visible, holds the
   session lock) or in a background chat like ticks? The user's chat is proposed: a
   foreground goal is something the user is watching.
4. **Who loops on the TUI's subprocess path.** This plan keeps the loop in the stdio host
   (one query = one goal, non-terminal round events). The alternative is the Go side
   re-issuing each round as its own query. That's simpler on the wire but splits the
   policy across two languages.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.