Skip to content

Update Driver Check - #3

Merged
kovtcharov merged 1 commit into
mainfrom
kalin/driver-check
Feb 25, 2025
Merged

kovtcharov merged 1 commit into
mainfrom
kalin/driver-check

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor
  • Adjust driver check to be equal or greater than a specific minimum version (NPU_DRIVER_VERSION)
  • Update content of popup warning messages
  • Modify messages to allow user to exit installation if needed during driver check

@kovtcharov
kovtcharov requested a review from vgodsoe February 3, 2025 20:25
@kovtcharov kovtcharov self-assigned this Feb 3, 2025
@kovtcharov kovtcharov added the installer Installer changes label Feb 3, 2025
@kovtcharov
kovtcharov merged commit b7cbd8a into main Feb 25, 2025
@kovtcharov
kovtcharov deleted the kalin/driver-check branch February 25, 2025 09:57
itomek pushed a commit that referenced this pull request Apr 30, 2025
itomek pushed a commit that referenced this pull request Mar 12, 2026
- [x] Adjust driver check to be equal or greater than a specific minimum
version (`NPU_DRIVER_VERSION`)
- [x] Update content of popup warning messages
- [x] Modify messages to allow user to exit installation if needed
during driver check
kovtcharov added a commit that referenced this pull request Apr 20, 2026
…steps 7-8)

Opens a **draft** self-fix PR against the coder integration branch via
`gh pr create` (shells out — GitHubToolsMixin is Phase-10 work). Hard
rules enforced at the module boundary:

* regression_test_path must be non-empty; §7.4 step 5 forbids opening a
  self-fix PR without a regression test. Raises ValueError.
* plan.feedback_id must match the feedback_id argument; a mismatched
  binding would defeat Pass 7 (feedback-binding) before it even runs.
* base branch defaults to 'coder' — never main (§5.6).

compose_pr_body() cites feedback_id explicitly and block-quotes the
EM's feedback verbatim (§15.8 P7 requirements #3). The review-pass
table is templated from an optional ReviewGateResult; when the Phase-4
gate isn't wired yet we emit a "(review gate not available)" stub.

notify_em() routes to `gh pr comment` or `gh issue comment` based on
the feedback context_url; missing/unrecognised URLs log a WARN and
return a deferred marker so the loop driver can retry.
kovtcharov added a commit that referenced this pull request Apr 20, 2026
…steps 7-8)

Opens a **draft** self-fix PR against the coder integration branch via
`gh pr create` (shells out — GitHubToolsMixin is Phase-10 work). Hard
rules enforced at the module boundary:

* regression_test_path must be non-empty; §7.4 step 5 forbids opening a
  self-fix PR without a regression test. Raises ValueError.
* plan.feedback_id must match the feedback_id argument; a mismatched
  binding would defeat Pass 7 (feedback-binding) before it even runs.
* base branch defaults to 'coder' — never main (§5.6).

compose_pr_body() cites feedback_id explicitly and block-quotes the
EM's feedback verbatim (§15.8 P7 requirements #3). The review-pass
table is templated from an optional ReviewGateResult; when the Phase-4
gate isn't wired yet we emit a "(review gate not available)" stub.

notify_em() routes to `gh pr comment` or `gh issue comment` based on
the feedback context_url; missing/unrecognised URLs log a WARN and
return a deferred marker so the loop driver can retry.
kovtcharov added a commit that referenced this pull request Apr 20, 2026
…steps 7-8)

Opens a **draft** self-fix PR against the coder integration branch via
`gh pr create` (shells out — GitHubToolsMixin is Phase-10 work). Hard
rules enforced at the module boundary:

* regression_test_path must be non-empty; §7.4 step 5 forbids opening a
  self-fix PR without a regression test. Raises ValueError.
* plan.feedback_id must match the feedback_id argument; a mismatched
  binding would defeat Pass 7 (feedback-binding) before it even runs.
* base branch defaults to 'coder' — never main (§5.6).

compose_pr_body() cites feedback_id explicitly and block-quotes the
EM's feedback verbatim (§15.8 P7 requirements #3). The review-pass
table is templated from an optional ReviewGateResult; when the Phase-4
gate isn't wired yet we emit a "(review gate not available)" stub.

notify_em() routes to `gh pr comment` or `gh issue comment` based on
the feedback context_url; missing/unrecognised URLs log a WARN and
return a deferred marker so the loop driver can retry.
itomek pushed a commit that referenced this pull request Apr 29, 2026
…loor, walk __context__

- Delete tunnel-friendly-error.png — debug screenshot that slipped in via
  upstream commit f0844d0; no references in code/docs (#3 from Apr-29 review).
- Restore uv.lock requires-python ">=3.13" to match origin/main (was silently
  narrowed to ">=3.12" in the same upstream commit). setup.py's python_requires
  stays >=3.10; the lock now no longer drifts from main (#4 from Apr-29 review).
- Restore src/gaia/apps/webui/package-lock.json to origin/main (revert my
  drive-by 0.17.3 -> 0.17.4 bump). Main itself has the package.json=0.17.4 vs
  lockfile=0.17.3 drift; the auto-correction triggered the heavy Build
  Installers workflow on this PR, which then timed out at the workflow's
  hardcoded 90s state-ready poll while still downloading the ~3 GB
  Gemma-4-E4B-it-GGUF. Reverting eliminates the unrelated CI noise; the
  lockfile/package.json drift is its own tech debt.
- _classify_chat_exception now walks __context__ as well as __cause__ so
  implicit exception chains (raise ... inside an except block, no `from`)
  preserve typed-class metadata like LemonadeContextOverflowError.retryable
  (#5 from Apr-29 review).
itomek pushed a commit that referenced this pull request Apr 29, 2026
…loor, walk __context__

- Delete tunnel-friendly-error.png — debug screenshot that slipped in via
  upstream commit f0844d0; no references in code/docs (#3 from Apr-29 review).
- Restore uv.lock requires-python ">=3.13" to match origin/main (was silently
  narrowed to ">=3.12" in the same upstream commit). setup.py's python_requires
  stays >=3.10; the lock now no longer drifts from main (#4 from Apr-29 review).
- Restore src/gaia/apps/webui/package-lock.json to origin/main (revert my
  drive-by 0.17.3 -> 0.17.4 bump). Main itself has the package.json=0.17.4 vs
  lockfile=0.17.3 drift; the auto-correction triggered the heavy Build
  Installers workflow on this PR, which then timed out at the workflow's
  hardcoded 90s state-ready poll while still downloading the ~3 GB
  Gemma-4-E4B-it-GGUF. Reverting eliminates the unrelated CI noise; the
  lockfile/package.json drift is its own tech debt.
- _classify_chat_exception now walks __context__ as well as __cause__ so
  implicit exception chains (raise ... inside an except block, no `from`)
  preserve typed-class metadata like LemonadeContextOverflowError.retryable
  (#5 from Apr-29 review).
@klkr1 klkr1 mentioned this pull request May 11, 2026
2 of 3 tasks
alexey-tyurin added a commit to alexey-tyurin/gaia that referenced this pull request Jun 23, 2026
… (amd#1828)

## Summary

Procedural memory now keeps **one** proven recipe per goal even when the
distiller renames it between synthesis passes — recipes are matched by
meaning, not by an exact name string.

## Why

The procedural-memory tier (amd#887) promises "learn a task once, keep one
proven recipe, replace it when a better version appears." Supersession
is the *replace* half. But `reconcile_and_store` decided "same recipe?"
by exact-string match on `name` — and the distiller LLM authors a fresh
kebab name each pass (`DISTILL_TEMPERATURE = 0.1`, kebab-validated only,
never canonicalized). So a recurring goal that drifts from
`summarize-unread-emails` one pass to `summarize-my-unread-emails` the
next slipped past the name lookup: **before**, a drifted name produced a
*second* ADD and the supersede branch silently never fired — duplicates
accumulated, `recall_skill(top_k=2)` could surface two near-identical
copies into the planner prompt, and a genuinely better recipe coexisted
with the stale one instead of replacing it. **After**, reconcile matches
the nearest enabled, non-superseded procedure by `when_to_use` embedding
cosine `>= SIMILARITY_TAU` (0.82), so a drifted name still resolves to
the same recipe and supersession fires as designed. Go-forward only —
cleaning up rows already duplicated by prior drift is out of scope (the
feature is new and off-by-default).

## Linked issue

Closes amd#1818

## Changes

- **Match key is meaning, not name.** `reconcile_and_store` now finds
the prior recipe via a new pure helper `_nearest_enabled_procedure`
(cosine `>= similarity_tau` over `when_to_use` vectors), reusing the
embedding the call site already computes and passes as `embedding=` —
previously persisted but never used for matching. The
supersede-by-`success_count` dominance check, the
insert-new-then-`superseded_by` lineage, the ADD/UPDATE/NOOP shape, and
"never DELETE" are all unchanged; only the match source moved.
- **Live SQLite cosine pass, not the FAISS index** (per maintainer steer
in [issue amd#1818 comment
4772627749](amd#1818 (comment))).
The scan goes over `search_skills(..., with_embedding=True)`, which sees
rows written earlier in the *same* `max_clusters_per_pass` loop
(`put_skill` commits immediately) — the FAISS index isn't refreshed
until after reconcile returns, so reusing it could let a same-pass
double-ADD through. This also keeps `reconcile_and_store` a pure
function (`store`-only) that unit-tests without a live backend.
- **Fail-loud, no silent cap.** The scan is bounded by
`_RECONCILE_SCAN_LIMIT = 500`; saturating it logs a `warning` rather
than silently dropping rows. Degraded inputs
(missing/zero-norm/wrong-dim embeddings) are skipped with intent, not
swallowed.
- **No import-cycle regression.** Embedding BLOBs are decoded locally
with `np.frombuffer` so `skill_synthesis` imports no `memory` symbol,
preserving the `memory → procedural_memory → skill_synthesis` one-way
direction.

## Test plan

- [x] `python -m pytest tests/unit/test_skill_synthesis.py
tests/unit/test_memory_mixin.py tests/unit/test_memory_store.py -q` —
all green (578 passed locally), including the 4 new pure-fn tests, the
e2e two-pass drift test, and the 3 updated pure-fn tests.
- [x] `python util/lint.py --all` — black/isort/pylint/flake8 clean
(remaining MyPy/Bandit warnings are pre-existing and not in the touched
files).
- [x] **Regression check (optional but recommended):** revert the one
match line in `reconcile_and_store` to the old
`search_skills(name=candidate.name, …)` lookup and re-run the four
meaning tests — they must FAIL on the old code and PASS on the fix,
proving they exercise the changed branch (not vacuous).

> No `gaia eval agent` run is included — this is persistence-only (no
prompt, tool schema, recall path, model, or error-classification
change), and a cold eval runs from empty memory so it cannot reach the
multi-pass name-drift branch the fix targets. The deterministic unit +
e2e tests above exercise that branch directly.

## Deviations from the approved sketch

| Sketch / comment said | Code reality | Resolution |
|---|---|---|
| "search the procedures **FAISS index** (or a `search_skills` cosine
pass)" | `_proc_faiss_index` lives on the mixin and is refreshed only
*after* `reconcile_and_store` returns; the function is pure and takes
only `store`. | Took the offered **`search_skills` cosine pass** — keeps
the function pure/unit-testable and catches same-pass ADDs the index
wouldn't. No behavior gap vs the sketch. |
| Comment cites the call-site vector at `procedural_memory.py:86` |
After the amd#1794 extraction, the vector is computed at
[`procedural_memory.py:463`](src/gaia/agents/base/procedural_memory.py#L463)
and passed as `embedding=`. | Line-drift only; the vector exists and is
reused as the match input. |
| (none — net-new) | The existing pure-fn tests
`test_noop_when_existing_dominates` and
`test_update_supersedes_lower_success_count` seeded rows with **no
embedding** and relied on name equality. | Updated to seed matching
embeddings (the new match key) — they would otherwise ADD instead of
supersede. In-scope test churn. |

## Checklist

- [x] I have linked a GitHub issue above (`Closes amd#1818`).
- [x] I have described **why** this change is being made, not just what
changed.
- [x] I have run linting and tests locally (`python util/lint.py --all`,
`pytest tests/unit/`).
- [x] No user-visible/CLI/API surface changed — internal reconcile logic
only, so no docs update is required.

---

## Acceptance-criteria proof — amd#1818

The match key in `reconcile_and_store` moved from exact `name` to
`when_to_use` embedding cosine `>= SIMILARITY_TAU` (0.82) via a new
live-SQLite cosine pass `_nearest_enabled_procedure`
([skill_synthesis.py:580](src/gaia/agents/base/skill_synthesis.py#L580));
dominance, lineage, and never-DELETE are unchanged.

Every AC is proven by a **deterministic** test that exercises the
changed branch — and each is shown to **fail on the old name-match code
and pass on the fix** (regression proof below), which is what makes the
green meaningful.

### AC → proof map

| Acceptance criterion | Proving test(s) | Key assertions |
|---|---|---|
| **AC amd#1** — match by `when_to_use` cosine `>= SIMILARITY_TAU`, not
`name`; recurring goal → one enabled row under name drift |
`test_matches_by_meaning_supersedes_under_name_drift`
([:542](tests/unit/test_skill_synthesis.py#L542)),
`test_distinct_meaning_adds_even_with_same_name`
([:578](tests/unit/test_skill_synthesis.py#L578)) | drifted name +
cosine-1.0 vector → **1** enabled row; identical `name` + orthogonal
vector (cosine 0 < τ) → **2** rows (ADD). Proves the key is meaning, not
name. |
| **AC amd#2** — supersession fires under drift: higher-`success_count`
candidate supersedes (insert-new + `superseded_by`, never DELETE);
dominance unchanged |
`test_matches_by_meaning_supersedes_under_name_drift`
([:542](tests/unit/test_skill_synthesis.py#L542)),
`test_lower_success_same_meaning_noops`
([:597](tests/unit/test_skill_synthesis.py#L597)),
`test_update_supersedes_lower_success_count`
([:513](tests/unit/test_skill_synthesis.py#L513)),
`test_noop_when_existing_dominates`
([:494](tests/unit/test_skill_synthesis.py#L494)) | `action=="update"`,
`superseded_id==old_id`, old row kept with `superseded_by` set (never
deleted); weaker cluster under a drifted name → `noop` (dominance logic
intact under the new key). |
| **AC amd#3** — same cluster distilled twice with differing names →
exactly one surviving enabled, non-superseded row, second supersedes
first | `test_name_drift_across_passes_supersedes`
([test_memory_mixin.py:3331](tests/unit/test_memory_mixin.py#L3331)) —
two real `_synthesize_skills` passes | pass 1 ADDs
`summarize-unread-emails`; pass 2 (drifted `summarize-my-unread-emails`,
higher `success_count`) → `stored==1` (UPDATE); `search_skills()`
returns **1** row; pass-1 id `superseded_by` the pass-2 id. |

### Comment
[#4772627749](amd#1818 (comment))
refinements — both addressed

**1. "Live SQLite + cosine pass, not `_proc_faiss_search`"** (avoids a
stale-index same-pass double-ADD). `_nearest_enabled_procedure` scans
`store.search_skills(enabled_only=True, include_superseded=False,
with_embedding=True)` — the live table, never the FAISS index. Pinned by
a contract-shape spy:

> `test_reconcile_queries_store_by_embedding_not_name`
([:619](tests/unit/test_skill_synthesis.py#L619)) — asserts every
`search_skills` call passes `with_embedding=True, enabled_only=True,
include_superseded=False` and **`name` is always `None`**, so a silent
revert to name-matching (or to the index) is caught.

**2. "Assert the surviving row carries the *second* candidate's
name/body, not just count==1"** (catches a wrong-direction supersede).
Both the pure-fn and e2e AC tests assert name **and** body of the
survivor:
- pure-fn: `visible[0]["name"] == "summarize-my-unread-emails"` **and**
`visible[0]["markdown_body"] == "# New\n1. better step"`.
- e2e: `visible[0]["name"] == "summarize-my-unread-emails"` **and**
`"digest" in visible[0]["markdown_body"]`, plus `old[0]["superseded_by"]
== visible[0]["id"]`.

### Verbatim results

**All AC tests pass on the fix:**

test_matches_by_meaning_supersedes_under_name_drift PASSED
test_distinct_meaning_adds_even_with_same_name      PASSED
test_lower_success_same_meaning_noops               PASSED
test_reconcile_queries_store_by_embedding_not_name  PASSED
test_update_supersedes_lower_success_count          PASSED
test_noop_when_existing_dominates                   PASSED
test_name_drift_across_passes_supersedes PASSED (e2e, 2 synthesis
passes)
test_rerun_is_noop_and_never_deletes PASSED (never-DELETE)
8 passed in 1.28s



**Regression proof — the tests catch the bug** (temporarily revert the
match line to the old `search_skills(name=…)` lookup):

=== AC tests against OLD exact-name code — MUST FAIL ===
FAILED test_matches_by_meaning_supersedes_under_name_drift
FAILED test_distinct_meaning_adds_even_with_same_name
FAILED test_lower_success_same_meaning_noops
FAILED test_name_drift_across_passes_supersedes
4 failed in 1.05s

=== same 4 against the fix — MUST PASS ===
4 passed in 0.78s

Full suite for the touched modules: **578 passed**; `python util/lint.py
--all` → **ALL QUALITY CHECKS PASSED**.

Co-authored-by: Alexey Tyurin <>
theonlychant pushed a commit to theonlychant/gaia that referenced this pull request Jun 25, 2026
…ion (amd#1844)

<!--
PR title: test(tool-loader): pin amd#800 doc-profile data-vs-recall
disambiguation
Branch:    test/800-tool-collision-regression
-->

## Summary

Before this PR, amd#800's scratchpad/memory tool collision was resolved in
*code* (by the amd#688 dynamic tool loader, landed via amd#1449/amd#1450/amd#1451)
but **nothing pinned it** — no test asserted that the structured-data
tool and memory `recall` can't crowd each other out of the prompt, so
the fix could silently regress. This adds a deterministic regression
test, a live eval scenario, and an in-repo note that together lock the
resolution and let amd#800 close with evidence. No runtime code changes —
this is a closeout + regression, not a feature.

## Why

amd#800 is a coordination tracker: it exists to *prove* the collision is
fixed, not leave it as a known gap. The decisive finding (verified on
`main`) is that the literal pair in the title — `scratchpad.query_data`
vs `memory.recall` — **cannot occur in the loaded profile**: scratchpad
tools are registered only for the ChatAgent `data`/`full` profiles,
never `doc`, which is the only profile the loader is wired to. The real
doc-profile arbitration is `analyze_data_file` (structured-data,
**conditional**) vs `recall` (**CORE, always-on**). That asymmetry *is*
the resolution — and until now no test encoded it.

## Linked issue

Closes amd#800

## Changes

- **Deterministic regression that pins the resolution** — asserts
`recall ∈ CORE` (always present) while `analyze_data_file` loads only
when the turn's query clears the semantic threshold, using the real
`DOC_CORE_TOOLS`/`DOC_BUNDLES` config and production τ/cap (not
hand-picked literals), with a fresh loader per case so it tests the
cold/empty-memory new-user state.
- **Live eval scenario** exercising the same routing end-to-end on the
committed `sales_data_2025.csv` corpus, so the disambiguation is checked
against a real model, not just unit logic.
- **In-repo closeout note** in the tool-loader plan doc explaining how
amd#800 is resolved (design asymmetry), cross-linked to the test and
scenario.

## Deviations from the approved sketch (amd#800's body)

Flagged per CLAUDE.md — the landed design diverges from the original
sketch in several places:

| amd#800 sketch said | Reality on `main` | Resolution in this PR |
|---|---|---|
| Collision is `scratchpad.query_data` vs `memory.recall` | Scratchpad
tools aren't in the `doc` profile; loader is `doc`-only | Test the doc
analog: `analyze_data_file` (conditional) vs `recall` (CORE) |
| The two not both in prompt unless justified | `recall` is **CORE →
always present**; the *conditional* side is `analyze_data_file` |
Regression asserts the conditional side; `recall` is intentionally
always-on |
| Prompt drops ~12K → ~3-4K tokens | 12K premise is the wrong cost
model; gate is **TTFT / native-token reduction** (~50–60%) | AC #1
reframed onto the token-budget proxy already on `main` |
| Decisions logged to memory's SQL `tool_history` | Logged as structured
`TOOL_LOADER {json}` INFO lines; `gaia.eval.tool_recall` consumes them |
AC amd#4 satisfied via log signal (deliberate: no UI-DB migration) |
| Bundle table = core/rag/filesystem/scratchpad/browser/memory/mcp |
Landed bundles are finer & doc-scoped; no `scratchpad`/`browser` in
`doc` | Landed taxonomy supersedes the sketch |
| AC amd#7 pivot example "file browsing → web research" | Browser tools
aren't in the `doc` profile | Mid-conversation re-eval proven for
**in-profile** pivots |
| *(new)* Refresh committed Gemma-4-E4B baseline | Local run timed out
`smart_discovery` (hardware artifact); fixture is also independently
stale | **Baseline refresh deferred** to a clean run on target hardware;
committed fixture left untouched |
| *(new)* Eval scenario passes | Records **FAIL 6.58** — but for reasons
unrelated to amd#800 (see AC amd#6) | Kept as honest corroboration; the unit
test is the binding gate |

## Test plan

- [x] `python -m pytest tests/unit/test_tool_loader_disambiguation.py
-v` → 4 passed (the AC amd#5 gate)
- [x] `python -m pytest tests/unit/test_tool_loader_selection.py
tests/unit/test_chat_tool_bundles.py
tests/unit/test_chat_dynamic_tools.py -q` → 67 passed (no loader
regression; confirms the new test's registry/embedder assumptions match
shipped config)
- [x] `python -m pytest tests/test_eval.py -k scenarios -q` → 27 passed
(validates the new scenario YAML: required fields, sequential turns,
existing corpus path)
- [x] `python util/lint.py --all` → clean
- [x] *(optional, needs a running Lemonade backend + UI server)* `gaia
eval agent --category tool_selection --agent-type doc` → the 4
pre-existing scenarios match the amd#1451 Part-3 proof (no selection
regression)

## Checklist

- [x] I have linked a GitHub issue above (`Closes amd#800`).
- [x] I have described **why** this change is being made, not just what
changed.
- [x] I have run linting and tests locally (`python util/lint.py --all`,
`pytest tests/unit/`).
- [x] I have updated documentation if user-visible behavior changed
(in-repo closeout note; no user-facing behavior changed).

---

## amd#800 Acceptance Criteria — Proof

**Verdict:** all 7 ACs satisfied on `main` + this PR. The collision is
resolved structurally by the amd#688 dynamic tool loader (landed via
amd#1449/amd#1450/amd#1451); this PR pins it. Three ACs are satisfied **with the
documented reframing** above.

> **Structural finding:** the literal `scratchpad.query_data` vs
`memory.recall` pair cannot occur in the `doc` profile (scratchpad isn't
registered there). The proofs test the real pair: `analyze_data_file`
(conditional) vs `recall` (CORE, always-on).

| # | Acceptance criterion | Status |
|---|---|---|
| 1 | Tool prompt drops ~12K → ~3-4K tokens | ✅ *reframed to TTFT/token
reduction* |
| 2 | `query_data` & `recall` not both unless justified | ✅ *via doc
analog* |
| 3 | Core tools always available despite heuristic failure | ✅ |
| 4 | Selection decisions logged for eval/tune | ✅ *log signal, not SQL
sink* |
| 5 | E2E regression test (data-query vs recall) | ✅ **new in this PR**
|
| 6 | Eval suite passes, no selection regression | ✅ |
| 7 | Mid-conversation re-evaluation works | ✅ *in-profile* |

### AC #1 — Tool-prompt token reduction
Reframed: the ~12K figure assumed the text path; the real cost (and
gate) is the **native tool-schema path / TTFT**. The 38-tool doc profile
is capped to **14** (`DEFAULT_MAX_TOOLS`).
```
$ pytest tests/unit/test_tool_loader_token_budget.py -q     →  10 passed
```
`test_core_only_is_the_reduction_best_case` pins the always-on CORE
floor at **≤45% of the native baseline** (~50–60% reduction).

### AC #2 — `query_data` and `recall` not both unless justified
`recall ∈ DOC_CORE_TOOLS`; `analyze_data_file ∈` the conditional `data`
bundle (`tool_bundles.py`). The conditional tool loads only when the
query clears τ:
```
$ pytest tests/unit/test_tool_loader_disambiguation.py -v
test_data_tool_is_conditional_and_recall_is_core                 PASSED
test_structured_data_query_loads_data_tool_with_recall_present   PASSED
test_recall_query_keeps_recall_and_omits_data_tool               PASSED   ← recall present, data tool ABSENT when unjustified
test_pivot_loads_data_bundle_mid_conversation                    PASSED
```

### AC amd#3 — Core tools always available despite heuristic failure
CORE is admitted unconditionally and is cap-/eviction-exempt; on
embedder failure the loader disables for the session and falls back to
the full registry, **logging loudly** (`tool_loader.py`).
```
test_core_always_admitted_even_without_match     PASSED
test_embedder_failure_session_disables_loudly    PASSED
```

### AC amd#4 — Decisions logged for eval/tune
Satisfied with a deliberate deviation: decisions are emitted as
structured `TOOL_LOADER {json}` INFO lines (not the SQL `tool_history`
table — avoids a UI-DB migration). Consumed by
`src/gaia/eval/tool_recall.py` (`_TOOL_LOADER_RE` / `_SESSION_RE` /
`_ESCAPE_HATCH_RE`) → per-turn loaded sets + escape-hatch rate for
τ-tuning.

### AC amd#5 — End-to-end regression test (data-query vs recall) — new in
this PR
- Deterministic gate: `tests/unit/test_tool_loader_disambiguation.py` (4
tests; real config, fresh loader per case = cold/empty-memory state;
asserts loaded-**set membership**, not "select was called").
- Live scenario:
`eval/scenarios/tool_selection/data_vs_recall_disambiguation.yaml`
(validates + discovered: `find_scenarios(category='tool_selection')` → 5
scenarios incl. the new one).

### AC amd#6 — Eval suite passes, no selection regression
Live serial run on Gemma-4-E4B corroborates the amd#1451 Part-3
success-criteria proof — no regression:

| scenario | amd#1451 Part-3 proof | this run |
|---|---|---|
| `known_path_read` | PASS 9.45 | PASS 9.38 |
| `no_tools_needed` | PASS 9.97 | PASS 9.87 |
| `multi_step_plan` | FAIL 7.62 | FAIL 8.47 (both FAIL — borderline,
pre-existing) |
| `smart_discovery` | PASS 9.95 | TIMEOUT* |

\* hardware artifact of the local Apple-Silicon box (Metal llama.cpp
~14–19 tok/s), not a behavior change. The new scenario records FAIL 6.58
**for reasons unrelated to amd#800**: the disambiguation works (agent
routed both aggregates to `analyze_data_file`, never misused `recall`;
Turn 2 returned the exact answer), but Turn 1's correctness failed on
`analyze_data_file`'s date-filter handling of the monthly-summary CSV
plus an agent hallucination — flagged as a separate follow-up. Committed
baseline refresh deferred to a clean run on target hardware.

### AC amd#7 — Mid-conversation re-evaluation works
Proven for **in-profile** pivots (the sketch's "file→web" example is out
of the doc profile — browser tools aren't registered there):
```
test_pivot_loads_data_bundle_mid_conversation   PASSED   ← turn 1 omits data tool; turn 2 adds it
test_monotonic_growth_no_pruning_on_score_drop  PASSED
test_lru_evicts_oldest_last_call                PASSED
test_evicted_tool_can_be_readmitted             PASSED
```

Co-authored-by: Alexey Tyurin <>
kovtcharov-amd pushed a commit to TravisHaa/gaia that referenced this pull request Jun 29, 2026
amd#1875)

The email-triage eval corpus was scored against the wrong vocabulary.
The agent emits the schema-2.0 five-bucket taxonomy (`URGENT /
NEEDS_RESPONSE / FYI / PROMOTIONAL / PERSONAL`), but the committed
`ground_truth.json` still carried the retired 4-way labels (`urgent /
actionable / informational / low priority`). Since `category_accuracy`
is a case-insensitive exact match and the two vocabularies overlap only
on `urgent`, almost every prediction scored wrong — the email scorecard
read `category_accuracy = 0.04` purely as a labeling artifact, not real
quality. After this change the corpus carries the same five buckets the
agent predicts, so a correct triage prediction is scored correct.

The corpus generator already maps to the schema-2.0 strings; the fixture
was simply never regenerated after that mapping landed. Regenerating is
deterministic — the `.mbox` bytes and Gmail-id keys are byte-identical,
so existing throughput/perf and FakeGmailBackend hashing baselines stay
comparable (only the `category` labels and `_meta.taxonomy` change).

Closes amd#1874

## Test plan

- [ ] `PYTHONPATH=...:src:hub/agents/python/email python -m pytest
tests/unit/test_synthetic_mbox.py tests/unit/email/ tests/unit/eval/ -x`
passes (ran here: 372 passed)
- [ ] `python util/lint.py --all` passes
- [ ] `python tests/fixtures/email/generate_mbox.py --verify` prints
`VERIFY OK` (committed fixtures match deterministic output, mbox hash
unchanged)
- [ ] **Manual (needs AMD hardware + Lemonade):** run `gaia eval
benchmark --mbox-path tests/fixtures/email/synthetic_inbox.mbox
--ground-truth tests/fixtures/email/ground_truth.json --limit 25
--output-dir <dir>` and confirm `category_accuracy` moves from ~0.04 to
a representative value with predicted categories now drawn from the same
vocabulary as the labels.
- [ ] **Follow-up (AC amd#3, needs hardware):** regenerate the real-run
baselines (`tests/fixtures/email/baseline_accuracy*.json` via
`score_baseline.py`) and the email scorecard at the next eligible
version — these still hold stale-taxonomy numbers and are out of scope
for an offline change.

> ⚠️ **Needs manual validation** — the automated checks here confirm no
Python
> regression and that the relabel is deterministic/byte-stable, but
can't exercise
> the live benchmark. A maintainer should run the `gaia eval benchmark`
step above
> on AMD hardware (Lemonade running) before relying on the new scorecard
number.

<details>
<summary>🔍 Technical details</summary>

**Root cause.** `tests/fixtures/email/generate_mbox.py:70-75`
(`_BUCKET_TO_CATEGORY`) maps the generator's internal buckets to the
production `triage_heuristics.ALL_CATEGORIES` strings, and line 365
routes every label through it. The committed `ground_truth.json`
predates that mapping, so it held the old 4-way labels while the
generator (and the agent) had moved to the 5-bucket set.
`src/gaia/eval/quality_metrics.py:126` `category_accuracy` does a
lower-cased exact match, so the vocab mismatch floored the score.

**Changes:**
- `tests/fixtures/email/ground_truth.json` — regenerated via the
deterministic generator (`SEED=23023`). Verified the `.mbox` sha256
(`a4243f72…`) and the full id set are unchanged; only `category` values
and `_meta.taxonomy` differ. New realized counts: URGENT 47,
NEEDS_RESPONSE 56, FYI 80, PROMOTIONAL 37 (PERSONAL not yet populated in
the synthetic corpus — pre-existing, tracked by amd#1438).
- `src/gaia/eval/quality_metrics.py:53` — `NEEDS_ATTENTION_CATEGORIES`
`{"urgent", "actionable"}` → `{"urgent", "needs_response"}` (plus the
two docstring references). Without this the FP/FN needs-attention axis
would silently drop the old `actionable` cohort after the relabel;
`needs_response` is the schema-2.0 successor. Compared lower-cased,
matching the scorer.
- `tests/unit/test_synthetic_mbox.py` — updated
`test_category_coverage_and_counts` and `test_meta_block_present` to the
5-bucket strings, and added `test_corpus_vocab_matches_scorer_taxonomy`
(AC amd#4) asserting the committed corpus vocabulary and the scorer's
attention axis both stay a subset of `ALL_CATEGORIES` — a drift guard so
a future taxonomy change can't silently re-break scoring.

**Verification run here:** 372 email+eval unit tests pass;
`generate_mbox.py --verify` self-checks clean; black + isort clean. The
inline-GT unit tests in `test_quality_metrics.py` / `test_benchmark.py`
use synthetic labels to exercise the taxonomy-agnostic scorer mechanics
and are intentionally left unchanged.
</details>

Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
Co-authored-by: Tomasz Iniewicz <[email protected]>
ljluestc pushed a commit to ljluestc/gaia that referenced this pull request Sep 24, 2026
Closes amd#4086

Asking the agent "what needs me today?" makes it read several emails in
one go. Each single message was already capped at 12,000 characters, but
nothing capped the pile — read four or five long quoted threads and the
model quietly ran out of room, losing the earlier half of its own
conversation and answering from a partial view with no error anywhere.
Mail reading now has a per-turn character budget sized from the
machine's real context window, and once a turn has spent it the next
read is refused with a result that tells the model to stop, answer from
what it already read, and say so. The budget resets on the next turn.

The bound sits in the shared mixin, above both mailbox backends, so
Gmail and Outlook behave identically; neither backend file is touched.

<details>
<summary>🔍 Technical details</summary>

**No new tuning constant.** The turn budget is
`Agent._truncation_budget()[0]` — the same per-tool-result character cap
already applied to any other large tool output, derived from the device
profile via `budget_for_ctx`. Policy in one sentence: all the mail
bodies a turn pulls in together may occupy what one large tool result is
allowed to. It is therefore profile-derived by construction, and already
correct for a `-FLM` NPU model, a cloud/gateway session, and Claude's
200K window.

| profile | ctx | turn budget | measured spend at refusal | % of window
at the issue's worst ratio (3.02) |
|---|---|---|---|---|
| NPU | 32,768 | 30,000 chars | 36,000 chars after 3 reads | 36% |
| GPU/CPU | 65,536 | 60,000 chars | 60,000 chars after 5 reads | 30% |

**Admission rule.** A read is admitted while `used < budget`, so at most
one message crosses the line and that one is itself capped at
`_MAX_BODY_CHARS` — a turn can never admit an unbounded pile. Refusing
earlier (when `budget - used < _MAX_BODY_CHARS`) would make the bound
strictly ≤ budget but costs a whole read whenever bodies are small: two
reads on NPU, too stingy for the triage case the issue is about.

**Turn detection.** `Agent` gains a monotonic `_turn_seq`, incremented
in `_process_query_impl` — the single path every entry point (CLI, UI,
API server, sidecar, hub servers) goes through. The mixin reads it with
`getattr` and resets its ledger when it moves. `_on_task_start` was not
usable: `EmailToolsMixin` is listed after `ChatAgent` in `GaiaAgent`'s
bases, so `Agent`'s no-op would win the MRO — the exact trap
`ProjectMapMixin.__init_subclass__` exists to catch — and reordering
would put a tool mixin ahead of the base agent, which the comment at
`gaia_agent/agent.py:236` warns against.

**Replaced rather than adapted** the retired sidecar's
`context_budget.py`. The flagship wheel cannot import it (hub package,
not a dependency) and its numbers are pinned to that sidecar's 16K eval
target. What carried over is the method: derive from the device profile,
and be pessimistic about chars per token.

**Out of scope, stated:** `list_inbox` / `search_email` return previews
bounded by `limit <= 100` and are not charged; `_MAX_BODY_CHARS`
(amd#4085's constant) is unchanged; neither message-id guard was touched —
they differ deliberately between the two backends.

</details>

## Test plan

- [x] `pytest tests/unit/agents/` — **1234 passed, 50 skipped**
- [x] `python util/lint.py --black --isort` — both PASS
- [x] **Mutation check: the guard was disabled (`if used >= budget` →
`if False`) and 5 of the 6 new tests failed**; reverted to a
byte-identical tree (`git status` clean). The sixth is the
profile-derivation test, which correctly does not depend on the guard.
- [x] **The budget observed firing**, driving 14,000-char bodies through
one turn on each profile:

```
=== NPU profile: ctx 32768 tokens, turn budget 30000 chars ===
  read amd#1: OK  body 12000 chars (truncated=True), turn total 12000/30000
  read amd#2: OK  body 12000 chars (truncated=True), turn total 24000/30000
  read amd#3: OK  body 12000 chars (truncated=True), turn total 36000/30000
  read amd#4: REFUSED  {"action": "read_email", "success": false, "turn_budget_exhausted": true,
                     "messages_read_this_turn": 3, "budget_chars": 30000, "budget_used_chars": 36000}
    error -> This turn has already read 3 message body(ies), filling this turn's mail-reading
             budget (36000 of 30000 chars) — further reads are refused so the conversation does
             not silently overflow the context window. Answer from the messages already read,
             tell the user reading stopped here, and ask them to narrow the request or continue
             in a new turn. See https://amd-gaia.ai/docs/guides/email
  turn charged 36000 chars = ~11921 tokens at the worst measured ratio = 36% of the window
  invariant: charged (36000) <= budget + per-message cap (42000) -> True
  new turn (_turn_seq 1 -> 2): reading resumes

=== GPU/CPU profile: ctx 65536 tokens, turn budget 60000 chars ===
  read amd#1..amd#5: OK, turn total 60000/60000
  read amd#6: REFUSED  budget_chars 60000, budget_used_chars 60000, messages_read_this_turn 5
  turn charged 60000 chars = ~19868 tokens at the worst measured ratio = 30% of the window
  new turn (_turn_seq 1 -> 2): reading resumes
```

- [ ] Not run: `gaia eval` — the judge credential is failing
intermittently in CI and would not produce an attributable signal.
kovtcharov-amd pushed a commit to Hashim1999164/gaia that referenced this pull request Sep 29, 2026
…pick (amd#4414)

Picking a Fireworks model in the TUI showed a rank and a three-word
label — "best overall, cheapest" — with nothing to say what that was
measured on or what a run costs. Focusing a ranked model now shows the
measurement behind its label: tasks solved, judged quality, and the
dollar cost of one pass. Every figure on that line is the model's own
row in the benchmark table published in amd#4335, and a test fails if the
two ever drift apart.

This replaces amd#4385 (@kovtcharov's
`feat/tui-benchmarked-fireworks-models`). All three of its commits are
ancestors here, authorship intact; the difference is that the TheRock
half of each line is gone. Neither TheRock quality score — 3.69/5 for
GLM, 4.44/5 for DeepSeek — is published anywhere a reader can reach, and
amd#4335 says so itself: "TheRock tier results will be added once its
reruns complete." A line labelled `Measured:` that a user cannot trace
is the thing this repo's evidence rule exists to prevent, so the
untraceable half was removed rather than sourced. The everyday-suite
figures stay, because they match amd#4335's table cell for cell.

## Test plan

- [x] `go build ./...` and `go vet` clean on the whole `tui` module (Go
1.26.3, Strix Halo)
- [x] `go test ./...` — 21 of 23 packages pass; the two that don't are
`internal/ui/chat` and `internal/ui/preflight`, which fail identically
on plain `main` (a headless clipboard read and a Lemonade autostart,
both hanging until the timeout, neither touched by this change)
- [x] Drift guard proven by breaking it: changing `4.89` to `4.95` fails
`TestEvidenceIsTranscribed` with the published cell named
- [x] Rendered panel captured: rank 1 and 2 show their `Measured:` line,
rank 3 (no published figures) and an unranked model show none
- [x] `python util/check_doc_links.py --internal-only` — 1042 links, 0
broken
- [ ] With a Fireworks key: `/provider` → Fireworks AI → focus
`glm-5p3-flash` against a live account

<details>
<summary>🔍 Provenance check: which figures have a source</summary>

Every figure in amd#4385 was searched for across the whole tree, every PR
body in the repo's last 120 PRs, and every issue comment on the last 60.

| Figure | Model | Source | |
|---|---|---|---|
| 14/14, 4.89, $0.09, 7:04 | GLM-5.3 Flash, everyday | amd#4335 merged
body, GAIA row | traceable |
| 14/14, 4.92, $0.10, 5:39 | DeepSeek V4.1 Flash, everyday | amd#4335
merged body, GAIA row | traceable |
| 4/4, 3.69, $0.42 | GLM-5.3 Flash, TheRock | only amd#4397, still open |
not citable |
| 4/4, 4.44, $0.47 | DeepSeek V4.1 Flash, TheRock | cost only —
`docs/plans/nightly-benchmarks.mdx` puts DeepSeek's `therock` pass at
`~$0.47`; the 4.44 quality score nowhere | not citable |

`14/14` and `4/4` denominators are independently checkable:
`eval/tasks/tasks.json` defines `everyday` as 14 tasks and `therock` as
4.

```
$ rg -n --fixed-strings 4.89 .
./tui/internal/lemonade/cloud.go:39:  Evidence: "14/14 tasks · quality 4.89/5 · $0.09 per 14-task run · TheRock 4/4, 3.69/5, $0.42",
./docs/guides/ai-providers.mdx:55:| GLM-5.3 Flash | `fireworks.glm-5p3-flash` | 14/14 solved, quality 4.89/5, $0.09 per run, 7:04 | 4/4, quality 3.69/5, $0.42 |

$ gh pr list -R amd/gaia --state all --limit 120 --json number,title,body | python -c "<scan for 3.69 / 4.44 / \$0.42 / \$0.47>"
scanned 120 PRs
4397 feat(agent): evict stale tool results from the sent context, ['3.69', '$0.42']
4385 feat(tui): show the measurement behind each ranked Fireworks   ['3.69', '$0.42']

$ <same scan over issue comments on the 60 most recent PRs>
no comment on the last 60 PRs contains 4.44 / $0.47 / 3.69 / $0.42
```

Corrected after review: an earlier version of this table said `$0.47`
was sourced nowhere. It is in `docs/plans/nightly-benchmarks.mdx` on
`main` (line 37 and the `therock` row), attributed to DeepSeek V4.1
Flash under a column headed "Cost per pass (measured)". That is a
planning estimate for the suite rather than a published per-model cell,
and the `4.44/5` quality score in the same trailer still has no source,
so the trailer still cannot ship — but the claim as written was wrong.
`$0.42` does have zero occurrences anywhere.

amd#4397 is open, and carries the GLM row only, as an aside: "the earlier
GLM TheRock row without eviction: 3.69, $0.42". The DeepSeek TheRock
figures have no public source at all.

</details>

<details>
<summary>🔍 Ancestry, build, tests, and the rendered panel</summary>

Every commit of amd#4385 is an ancestor of this branch:

```
$ git merge-base --is-ancestor e472abc HEAD; echo $?
0
$ git merge-base --is-ancestor 56eadd4 HEAD; echo $?
0
$ git merge-base --is-ancestor bfa1070 HEAD; echo $?
0
```

Build and vet, on Strix Halo (no Go toolchain on the authoring machine):

```
$ go version
go version go1.26.3 linux/amd64
$ gofmt -l internal/lemonade internal/ui/providers
$ go build ./... ; echo BUILD_EXIT=$?
BUILD_EXIT=0
$ go vet ./internal/lemonade/... ./internal/ui/providers/...
VET_OK
```

Full module, this branch:

```
$ go test -timeout 150s ./...
ok   github.com/amd/gaia/tui/internal/catalog          0.004s
ok   github.com/amd/gaia/tui/internal/cli              0.012s
ok   github.com/amd/gaia/tui/internal/client           9.834s
ok   github.com/amd/gaia/tui/internal/control          0.859s
ok   github.com/amd/gaia/tui/internal/daemon           0.325s
ok   github.com/amd/gaia/tui/internal/event            0.011s
ok   github.com/amd/gaia/tui/internal/gaiainit         0.007s
ok   github.com/amd/gaia/tui/internal/gaiaslack        0.018s
ok   github.com/amd/gaia/tui/internal/lemonade         0.014s
ok   github.com/amd/gaia/tui/internal/ui               0.169s
ok   github.com/amd/gaia/tui/internal/ui/agents        0.009s
ok   github.com/amd/gaia/tui/internal/ui/brand         0.010s
ok   github.com/amd/gaia/tui/internal/ui/cards         0.040s
FAIL github.com/amd/gaia/tui/internal/ui/chat        150.015s
ok   github.com/amd/gaia/tui/internal/ui/components    1.096s
ok   github.com/amd/gaia/tui/internal/ui/gateway       0.005s
FAIL github.com/amd/gaia/tui/internal/ui/preflight   150.007s
ok   github.com/amd/gaia/tui/internal/ui/providers     0.003s
ok   github.com/amd/gaia/tui/internal/ui/root          0.015s
ok   github.com/amd/gaia/tui/internal/ui/status        0.001s
ok   github.com/amd/gaia/tui/internal/ui/theme         0.104s
ok   github.com/amd/gaia/tui/test                    112.666s
ok   github.com/amd/gaia/tui/test/mockagent            0.001s
```

Same two packages, same two tests, on plain `origin/main` — pre-existing
and environmental, not from this change:

```
this branch:                          origin/main:
  running tests:                        running tests:
    TestCtrlVReadsTheClipboard (2m30s)    TestCtrlVReadsTheClipboard (2m30s)
  running tests:                        running tests:
    TestADownLemonadeOffersTheOneKeySetup   TestADownLemonadeOffersTheOneKeySetup
FAIL .../internal/ui/chat      150.015s  FAIL .../internal/ui/chat      150.016s
FAIL .../internal/ui/preflight 150.007s  FAIL .../internal/ui/preflight 150.008s
```

The drift guard, proven by breaking it:

```
$ sed -i 's|quality 4.89/5|quality 4.95/5|' internal/lemonade/cloud.go
$ go test -run TestEvidenceIsTranscribed ./internal/lemonade/...
--- FAIL: TestEvidenceIsTranscribed (0.00s)
    cloud_test.go:210: fireworks.glm-5p3-flash: evidence "14/14 tasks · quality 4.95/5 · $0.09 per 14-task run" dropped published cell "4.89"
FAIL
$ <restore>
ok   github.com/amd/gaia/tui/internal/lemonade  0.002s
```

The panel as rendered, walking focus down the list:

```
  › glm-5p3-flash · amd#1 best overall, cheapest
    deepseek-v4p1-flash · amd#2 fastest
    deepseek-v4-pro-0813 · amd#3 most truthful
    plain-model
  1 of 4
  Measured: 14/14 tasks · quality 4.89/5 · $0.09 per 14-task run

    glm-5p3-flash · amd#1 best overall, cheapest
  › deepseek-v4p1-flash · amd#2 fastest
    deepseek-v4-pro-0813 · amd#3 most truthful
    plain-model
  2 of 4
  Measured: 14/14 tasks · quality 4.92/5 · $0.10 per 14-task run

    glm-5p3-flash · amd#1 best overall, cheapest
    deepseek-v4p1-flash · amd#2 fastest
  › deepseek-v4-pro-0813 · amd#3 most truthful
    plain-model
  3 of 4
                              ← no published figures, so no line
```

</details>

<details>
<summary>🔍 Merge-order note for amd#4176 and amd#4265</summary>

Both rewrite `RecommendedModels` into a registry-populated slice whose
populating line copies only two fields
(`tui/internal/lemonade/recommended.go:70` — `Recommendation{ID: r.ID,
Note: r.Note}`) and drop `Evidence` from the struct entirely. Landing
this first does **not** silently drop the evidence: it produces a hard
conflict a human has to resolve.

```
$ git merge-tree --write-tree itomek/tui-measured-evidence pr4176
CONFLICT (content): Merge conflict in tui/internal/lemonade/cloud.go
CONFLICT (content): Merge conflict in tui/internal/ui/providers/model.go

$ git merge-tree --write-tree itomek/tui-measured-evidence pr4265
CONFLICT (content): Merge conflict in tui/internal/lemonade/cloud.go
CONFLICT (content): Merge conflict in tui/internal/ui/providers/model.go
CONFLICT (content): Merge conflict in tui/internal/ui/providers/model_test.go
```

Stages 1, 2 and 3 are all present, so it is an ordinary content conflict
with a shared base, not an add/add. Whoever resolves it needs to carry
`Evidence` and `EvidenceSource` into the registry shape, or
`TestEvidenceIsTranscribed` and the `Measured:` line go with it. Both
PRs already conflict with `main` on `hub/agents/gaia/npm/CHANGELOG.md`
independently of this.

</details>

Replaces amd#4385 — leave that one open for @kovtcharov to close or keep.

---------

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

Labels

installer Installer changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants