Skip to content

fix(agents): verify completion and preserve exhaustive inventories - #4145

Closed
kovtcharov wants to merge 26 commits into
amd:mainfrom
kovtcharov:fix/3983-evidence-completion
Closed

kovtcharov wants to merge 26 commits into
amd:mainfrom
kovtcharov:fix/3983-evidence-completion

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

GAIA could claim it saved a file it never wrote this turn, or turn a long workshop transcript into a condensed list presented as complete. Now a save counts only when that exact file was written and read back, and a long document is extracted page by page into a full inventory in which every item keeps a verbatim quote from the source. The result is kept in memory, and anything unfinished is reported as incomplete. Ordinary questions ("What time does the store close?") behave exactly as on main.

Fixes #3983 and #4141; related to #4009.

Test plan

  • python -m pytest tests/unit/agents/ tests/unit/test_memory*.py -n 8: 2,671 pass locally.
  • python scripts/dev/validate_document_extraction.py <MODEL> <new-dir> and the same with --unlined: 40/40 extracted, saved and recalled from memory on Fireworks (deepseek-v4p1-flash).
  • Real YouTube auto-captions (13K, 21K and a combined 74K characters, with no newlines or punctuation): on Fireworks all pages complete in 40–140 s, and the full agent turn on the 74K file saves and verifies 111 items. Local Gemma-4-E4B completes the 13K file (63 items, 17 min on a Mac).
  • Reporter check: Patrick reruns the original workshop transcript before Enumerating a long document returns a fraction of the items, with no sign anything was dropped #4141 is closed.
  • Judged gaia eval agent run: deferred by maintainer; the completion gate changes final answers, so decide before merge.
🔍 Technical details

What a reviewer should know

  • Saves
    • A request that names a file, folder or disk is a hard obligation: the file must be written and read back this turn.
    • A save claim is checked hard when a save was requested, a disk tool ran, or the answer says "I" or "we" saved something. Any other claim gets one correction and then stands, as on main.
    • A file written through the shell counts only when a successful call modified it. The agent's scratch folder never counts as the user's save.
  • Extraction
    • Pages are 4K characters with 600 characters of overlap, snapped to a line, sentence or word boundary. Each page gets two passes, a retry on an unusable reply, and a 16K-token output budget.
    • Cloud models are asked for no reasoning: a reasoning model spent 50–100 s per page and ran past the 30-minute limit on a 74K file.
    • Quote matching ignores case and spacing, but only on whole words. The stored quote is always the source text at its exact offsets.
    • An item is placed by the span of its name when the name is copied from the quote, otherwise by its quote.
    • Merging never fails a run and never drops an item. Differing descriptions are both kept, and uncertain cases keep both entries, marked "(may repeat item N)".
  • Exports
    • JSON records give each field its own key and CSV gives each field its own column. The framework reads the saved file back in full and requires an exact match, and hand edits to it are refused.

Adversarial coverage

  • A planted-item oracle (about 20,000 items, repeated names, paraphrased labels, repeats across pages and passes) finds no lost, absorbed or wrongly merged items.
  • In 60,000 hostile replies, no exception escaped the tool, and every quote matched the source at its offsets.

Audit of the 51 commits that landed on main meanwhile

Known limits

  • Full page coverage does not prove recall on unseen prose: two cloud runs on one file gave 46 and 56 items.
  • A slow local model can exceed the 30-minute budget on long files.
  • The Claude provider ignores the JSON schema, so each page there relies on the prompt.

@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Sep 23, 2026
@kovtcharov kovtcharov changed the title fix(agents): require evidence before reporting completion fix(agents): verify completion and preserve exhaustive inventories Sep 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions — strong test coverage and the right architecture, but one correctness regression must be fixed before the extraction gap check ships.


🔴 Code-symbol queries falsely trigger extraction mode and return status: incomplete

A query like "List all functions in app.py" or "Find every class in models.py" enables ExtractionLedger (exhaustive_request matches "list all" and \.[a-zA-Z]{1,5}\b matches the extension). destination_paths has no destination preposition (to/into/at/as) to anchor on, so it scans the whole query and picks up "app.py" as a path token, placing it in self.requested. At turn end gaps() finds the path unprocessed and emits "Incomplete extraction of app.py: use extract_document_items…", which collapses the answer to incomplete_answer(...) and sets status: "incomplete". Any agent that handles this query with code-index or read-file tools rather than extract_document_items will silently regress. The test at test_active_skill_enables_extraction_but_general_knowledge_does_not confirms exhaustive_request("Enumerate every function in code.py") = True but never asserts what status the agent loop returns for that query.

Fix: when computing self.requested, only include paths that follow a destination preposition or appear after the exhaustive verb without an intervening preposition-free noun phrase. Alternatively, seed self.requested only when destination_paths found a destination anchor — the fallback "scan the whole clause" path is what picks up source-file names in code queries.


🟡 validate_sources and validate_outputs use broad except Exception on new code

Both methods in extraction.py (lines ~418 and ~432) catch every exception and record it as a gap string, but CLAUDE.md requires newly written code to catch specific exceptions and re-raise or translate with context — broad handlers that absorb unexpected errors are listed as prohibited in new files, not just legacy tech debt. (OSError, ValueError) would cover the realistic failure cases here.


🟢 ExtractionLedger.key() constructs a throw-away CompletionEvidence("", self.root) on every call just to use its key() method. Extract key() (or the path-normalisation logic) into a module-level helper used by both classes.

🟢 completion.py:delivered() computes start, end, total from raw twice — once before the early-return branches and identically again afterwards (lines ~1496-1498 and ~1510-1512). Remove the first triple and compute once after the returns.

🟢 validate_document_extraction.py reuses the variable name label (line 397 inner-loop target) after assigning it to "validation" for the session ID. No bug (session ID is bound before the inner loop), but a silent collision — rename the inner loop target to result_type or similar.

🔍 Technical details

🔴 Extraction activation for code queries

ExtractionLedger.__init__ (extraction.py:336-358):

self.enabled = exhaustive_request(query) and bool(
    re.search(r"\b...\b|\.[a-zA-Z]{1,5}\b", query, re.I)
)
...
self.requested = {
    self.key(p)
    for p in destination_paths(source_clause)
    ...
}

destination_paths (completion.py:251-269) falls back to scanning the entire clause when _DESTINATION (to|into|at|as) finds nothing. For "List all functions in app.py" there is no preposition, so the fallback path tokenises "app.py" and returns it. That lands in self.requested, and gaps() then requires extract_document_items("app.py") to have succeeded before the turn can return status: "success".

Minimal fix: only populate self.requested when _DESTINATION found a preposition, or add a second guard in destination_paths that returns [] when the scan starts at position 0 (no preposition anchor). Alternatively add a source-specific helper that excludes the fallback scan.

The test that would catch this: add a case to test_advice_negation_and_directory_requests_are_not_extraction for "List all functions in app.py" asserting not state.enabled — or, if the author intentionally wants code queries to activate extraction for GaiaAgent, assert that an agent successfully finishing a code query with code_index tools returns status: "success", not "incomplete".

🟡 Broad exception handlers in new files

extraction.py:validate_sources (~line 418):

except Exception as error:          # should be (OSError, ValueError, UnicodeDecodeError)
    self.results.pop(path, None)
    self.errors[path] = str(error)

extraction.py:validate_outputs (~line 432): same pattern. The realistic failure set is file-system errors (OSError), encoding errors (UnicodeDecodeError), and value/format errors (ValueError). A MemoryError or SystemExit leaking through silently as a gap string would be very hard to debug.

🟢 Duplicate computation in delivered()

completion.py:1496-1498 and 1510-1512 are identical:

start = raw.get("offset", 0)
end = start + len(content)
total = None if raw.get("next_offset") is not None else end

The first set is unreachable for the item.page(start, end, total) call because an early return intervenes. Remove lines 1496-1498.

🟢 label collision in dev script

scripts/dev/validate_document_extraction.py:397:

for label, records in (
    ("extracted", [e.text for e in items]),
    ("saved", ...),
):

Shadows label = "validation" from line 297. Non-breaking but confusing. Rename to result_type.

@amd-pworfolk

Copy link
Copy Markdown
Collaborator

Tested on the original #4141 workshop, on Strix Halo with local Gemma-4-26B. The design is right and I can close your open validation item — local Gemma gets 40/40 on your fixture. But the same build fails on the real transcript that motivated the issue, and I think I have the root cause: your fixture has line breaks and GAIA's own transcripts have none.

Your open item: local Gemma passes the synthetic benchmark

validate_document_extraction.py with Gemma-4-26B-A4B-it-GGUF: 40/40 extracted, 40/40 saved, all names correct, ~17 min against the 30-min budget.

One qualification — the script still reports "passed": false, but not for extraction. The memory follow-up runs with max_steps=5 (validate_document_extraction.py:162) while the main extraction gets 10; Gemma spent all five searching and never answered. That looks like a harness budget rather than a product defect, but it does mean the script cannot currently report a pass on a local model.

The real transcript still fails

Same build, same model, the actual 77,361-char workshop:

Extraction failed on page 2: Extractor did not confirm that the page was finished

The agent fell back to reading manually and wrote 17 of ~40 — up from 15 before the PR, so roughly 43% recall, still far from exhaustive.

The completion guard worked exactly as designed here, and it is the best part of this result: the turn refused to claim success, said the task was incomplete, and told the user to verify before relying on the output. That is the #3983 behaviour, and it held.

Root cause: the fixture has line structure that real transcripts do not

chars newlines avg line
your synthetic fixture 79,378 679 116
my real transcript 77,361 0 77,361

extract_pages snaps page boundaries to whole lines inside the overlap. With zero newlines that never fires, so page 2 opens mid-sentence — "it of a hard seat. Okay. And the last thing…" — on a stretch of pure logistics filler containing no exercise at all. The extractor will not set complete: true for a page with nothing to extract and a truncated opening, and parse_page treats that as fatal rather than as an empty page.

This is not an unusual input. Every transcribe_media output on this machine is a single unbroken line — that is just what the tool emits, so any GAIA-transcribed source hits this path, and the benchmark never exercises it.

Two things worth considering, both cheap:

  • Treat a genuinely empty page as valid. A page of filler should yield items: [], not a hard failure. Right now one barren page aborts a 20-page extraction.
  • Fall back to sentence boundaries when no newline exists in the overlap. Prose transcripts have . even when they have no \n.

Adding an unlined variant of the fixture would catch both, and would have caught this before merge.

Windows: three of the PR's own tests fail

On Windows tests/unit/agents/ gives 3 failed / 138 passed, all in new tests, none a logic bug:

  • test_non_directory_parent_does_not_crash_snapshot and test_combined_source_and_save_request_keeps_all_sources — the code lowercases paths, the assertions compare against original case.
  • test_snapshot_without_validator_does_not_follow_external_symlink — OSError: [WinError 1314] A required privilege is not held; needs a skip marker when symlink privileges are absent.

Flagging because Strix Halo is largely a Windows target, so this suite will be red for the people most likely to run it.

On my #3983 feedback

transcribe_media moving out of the blanket write set into SIDE_EFFECT_PATHS with its specific output path is exactly the claimed-path-vs-any-write distinction, and gaps() now checks each required path individually. That closes the suppression I reported.

Verdict

The architecture answers #4141 — per-page extraction with verbatim-quote grounding and offset-keyed dedup is the right shape, and the quote-must-appear-in-page check is a real structural defence against fabrication. I would not merge on the synthetic result alone, though: the one real-world document I have still fails, and the failure is in a code path the fixture cannot reach. The empty-page fix looks small.

🔍 Technical details

Environment. main + PR 4145 at 7ec91a65, Gemma-4-26B-A4B-it-GGUF via Lemonade (GPU, ctx 131072), Ryzen AI MAX+ PRO 395, 128 GB, Windows.

Real-transcript run. 17 steps, 15 tools, 1,489 s, 22,585 tokens. Tool sequence: extract_document_items (failed) → read_file → 20× read_tool_output → write_file. Routing to the new skill worked; the fallback path is what produced the 17 items.

Page 2 span. [3400:8600], 5,200 chars, 0 newlines. left snapping looks for \n in [3400, 4000) and finds none, so the page begins mid-word-group.

Synthetic run. 40/40 extracted and saved; memory_recalled_inventory: false, memory_followup_status: "failed" with "Reached maximum steps limit (5 steps)".

Cost note for local models. 20 pages × 2 passes = 40 calls minimum, up to 80 with retries. At Gemma-4-26B's ~24 tok/s the synthetic run took ~17 min of the 1,800 s budget; a slower model or a longer document would exhaust it. Worth stating the practical ceiling in the guide.

kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 23, 2026
…g extraction

Three real issues from review, one from a field report (amd-pworfolk,
PR amd#4145):

- A query like "list all functions in app.py" has no destination
  preposition for destination_paths to anchor on, so its no-anchor
  fallback scanned the whole clause and picked up the source file
  itself as an extraction destination that never resolves -- every such
  code query reported status: incomplete. Excludes common code
  extensions from ExtractionLedger.requested; a real destination is
  never source code, and code-index/read-file tools already own that
  file.
- validate_sources/validate_outputs caught bare Exception on newly
  written code; narrowed to ValueError (read_snapshot's own signal) and
  OSError (the file operations it does not pre-validate).
- extract_pages only snapped page boundaries to newlines, but
  transcribe_media's own output is a single unbroken line -- every
  GAIA-transcribed source opened pages mid-word, and a page landing on
  pure filler with a truncated opening made the extractor unable to
  confirm completion, aborting the whole extraction. Falls back to
  sentence-ending punctuation when no newline exists in the overlap
  window.

Also fixes two Windows-only test failures the same field report
flagged: two assertions compared normalized (Windows-lowercased) keys
against raw mixed-case tmp_path strings, and a third symlink-based test
needs elevated privilege Windows CI runners don't reliably have --
added a skip marker rather than leaving it permanently red.
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 23, 2026
A slower local model spent all 5 steps searching and never answered,
reporting the script's own tight budget as a failed follow-up rather
than a real one (amd-pworfolk field report, PR amd#4145).
@github-actions

Copy link
Copy Markdown
Contributor

🔴 The code-symbol query regression is not fully fixed — status: incomplete still fires

The previous review flagged that "List all functions in app.py" returns status: incomplete because app.py ends up in ExtractionLedger.requested and never gets extracted. This push fixes that specific symptom: .py (and other code extensions) are now excluded from self.requested. But enabled is still True for these queries (.py still matches \.[a-zA-Z]{1,5}\b in the enabled-check regex), and gaps() checks self.sources | self.requested. With both empty — no read_file call adds to sources, no code file lands in requested — gaps() returns "Exhaustive extraction has no verified source.", which drives the same status: incomplete outcome via the same correction-and-fallback path.

The new test (test_code_symbol_queries_do_not_demand_the_source_file_as_a_destination) asserts app.py not in state.requested but never asserts state.gaps() == [], so it cannot catch this.

Fix: either gate enabled on the second condition not matching a code-only extension (os.path.splitext on every file token before setting it True), or make gaps() return [] when not (self.sources | self.requested) and the query contains only code-extension tokens with no explicit destination preposition.

🔍 Technical details

extraction.py ExtractionLedger.__init__ (line ~398):

self.enabled = exhaustive_request(query) and bool(
    re.search(
        r"\b(?:document|file|...)|\.[a-zA-Z]{1,5}\b",
        query, re.I,
    )
)

For "List all functions in app.py": exhaustive_request returns True (matches list...all), and .py matches \.[a-zA-Z]{1,5}\b → enabled = True.

self.requested is now correctly empty because .py ∈ _CODE_EXTENSIONS. But gaps() (line ~463):

sources = self.sources | self.requested   # {} | {} = {}
if not sources:
    return ["Exhaustive extraction has no verified source..."]

Still returns a non-empty list → completion_gaps non-empty → incomplete_answer(...) → status: "incomplete".

Minimal fix — add to the enabled guard:

from gaia.agents.base.extraction import _CODE_EXTENSIONS
self.enabled = exhaustive_request(query) and bool(
    re.search(
        r"\b(?:document|file|...)|\.[a-zA-Z]{1,5}\b",
        query, re.I,
    )
) and not all(
    os.path.splitext(p)[1].lower() in _CODE_EXTENSIONS
    for p in destination_paths(source_clause)
    if os.path.splitext(p)[1]
)

Or, simpler: in gaps(), guard the "no verified source" branch on self.requested being non-empty (i.e., only fire it when the query named an explicit non-code destination that was never extracted).

The test to add: assert ExtractionLedger("List all functions in app.py", str(tmp_path)).gaps() == [].

@kovtcharov

Copy link
Copy Markdown
Contributor Author

A code query like "list all functions in app.py" no longer ends the turn as incomplete, and the four smaller review items are in. One of @amd-pworfolk's two suggestions is deliberately not taken.

Fixed

  • The extraction ledger now stays off for a query whose only file names are source code. The previous push kept those files out of the requested set but left the ledger on, so the turn still failed with "no verified source". The test asserted the wrong thing — gaps() == [] passes whether the ledger is off or on-with-nothing-outstanding — so it now pins enabled directly, and a companion test pins that a real document still activates when the save target happens to be a code file.
  • path_key replaces the throw-away evidence object the ledger built just to normalize a path; delivered() no longer recomputes an unchanged offset triple; the validation script no longer shadows its session label. The broad except Exception in validate_sources/validate_outputs was already narrowed to (ValueError, OSError) in an earlier push.

Not taken: treating an incomplete page as empty

A page the extractor declines to finish and a page with nothing in it are the same JSON, so accepting complete: false would turn a model that gave up into a silently-dropped page — the failure this PR exists to prevent. The real cause of your page-2 failure was the mid-sentence opening, and that is fixed: pages now fall back to sentence boundaries when the overlap contains no newline, with a zero-newline fixture covering it. If a well-formed barren page still comes back complete: false on a local model, that is worth a separate look at the page prompt rather than a relaxed guard.

Your Windows findings and the max_steps=5 follow-up budget are also fixed. Thank you for running the real transcript — the newline difference is not something the synthetic fixture could have surfaced.

@amd-pworfolk

Copy link
Copy Markdown
Collaborator

Reran the original workshop on 0b3eafb0. The unbroken-transcript fix works — page 2 now opens on a clean sentence instead of mid-word, and the Windows test failures are gone (1348 passed, 0 failed). But the extraction still aborts, one page later, on a different rule.

Result

Extraction failed on page 3: Conflicting fields for an overlapping occurrence.
Recheck both source spans; do not discard stated values:
name: slow down your march; target area: not stated; cue: start picking your feet up higher.

The agent fell back to manual reading and saved 8 of ~40 — down from 17 on the previous head, because the fallback started later. 1,181 s, 29,320 tokens.

The completion guard held again and is still the best part of this: "I couldn't verify completion… The task is incomplete." Nothing was claimed that did not happen.

Root cause: overlapping-but-not-contained spans cannot reconcile

The phrase sits at offset 7574, inside the region where pages 2 and 3 both cover the source (page 2 [3419:8600], page 3 [7414:12600]). The model extracted the same sentence on both pages, choosing slightly different quote boundaries each time.

reconcile_occurrence only merges when one span contains the other. Two extractions of the same sentence that merely overlap — page 2 quoting from a few characters earlier, page 3 from a few later — fall through to None, and extract_pages raises. I reproduced it directly against the shipped function:

spans overlap: True | one contains the other: False
same_occurrence_fields: True
reconcile_occurrence(...) -> None     # then ValueError, whole run aborts

Two things make this expensive rather than merely wrong:

  • One disagreement discards nineteen good pages. The ledger holds everything extracted so far; a single unreconcilable overlap throws all of it away rather than recording the conflict and continuing.
  • The overlap region is where it is most likely. OVERLAP = 600 exists precisely so an item spanning a boundary is seen twice — so every boundary is an opportunity for two differently-worded quotes of one sentence.

Worth considering: treat an unreconcilable overlap as one item with the earlier-page fields retained (the error text already says "do not discard stated values"), or record the conflict and continue, rather than failing the run. Either keeps a boundary disagreement proportionate to its cost.

Why the fixture still does not catch it

The new 86K zero-newline fixture fixed the line-structure gap, and that fix is confirmed working here. But its items are distinct planted markers, so two pages quoting the same item pick the same distinctive string and land on identical spans — the contained case, which reconciles. Real prose has no such anchor: "slow down your march and start picking your feet up higher" can be quoted from several plausible starting points, and two of them overlap without containment.

A fixture item whose natural quote boundary is genuinely ambiguous — a long sentence with no unique marker, placed deliberately at a page boundary — would exercise the path that is failing here.

Still open from my last review

The max_steps mismatch in the validation harness is fixed (862a5df5), thanks.

Verdict

The two fixes I reported are real and verified. I cannot yet confirm #4141 is resolved: the one real-world document I have gets 8/40, and the abort is in reconciliation rather than in page splitting. The synthetic path is green and the prose path is not, which is the same shape as last time at one layer deeper.

🔍 Technical details

Environment. PR 4145 at 0b3eafb0, Gemma-4-26B-A4B-it-GGUF via Lemonade (GPU, ctx 131072), Ryzen AI MAX+ PRO 395, 128 GB, Windows.

Sentence-boundary fix verified. _snap_forward moves page 2 from 3400 (mid-word, "it of a hard seat") to 3419, opening "Okay. And the last thing and one of the most important things is padding." Confirmed directly against my 0-newline transcript.

Windows suite. tests/unit/agents/ — 1348 passed, 51 skipped, 0 failed. The three failures I reported (two path-casing, one symlink privilege) are resolved. The 2 remaining errors are the pre-existing test_large_tool_result_truncation.py collection issue, unrelated to this PR and present on main.

Conflict site. Source context: "...Go back to that march. Okay. As long as the march is feeling good, I want you to slow down your march and start picking your feet up higher, which is going to be a little bit of a balance exercise..." — one sentence, no unique marker, sitting at the page 2/3 overlap.

Reconciliation boundary. reconcile_occurrence requires containment (first.start <= second.start and first.end >= second.end, or the reverse). The identical-span case reconciles correctly when one side has not stated — I verified that too. It is specifically the partial-overlap case that returns None.

Run shape. Tools: extract_document_items (error) → read_file ×4 → run_python ×2 → save. 6 steps, 4 tools.

Kalin Ovtcharov and others added 17 commits September 24, 2026 13:28
- extraction.py: render() unpacked a per-path (entries, pages, digest)
  tuple but never used digest -- unused-variable.
- agent.py: _tool_overrides, _extraction_ledger, _completion_evidence
  were all first assigned outside __init__ (lazily, via hasattr guards
  or directly in process_query) -- attribute-defined-outside-init.
  Declared upfront: _tool_overrides as the empty dict every call site
  already assumed, the other two as Optional (they're only ever built
  fresh per turn).
…g extraction

Three real issues from review, one from a field report (amd-pworfolk,
PR amd#4145):

- A query like "list all functions in app.py" has no destination
  preposition for destination_paths to anchor on, so its no-anchor
  fallback scanned the whole clause and picked up the source file
  itself as an extraction destination that never resolves -- every such
  code query reported status: incomplete. Excludes common code
  extensions from ExtractionLedger.requested; a real destination is
  never source code, and code-index/read-file tools already own that
  file.
- validate_sources/validate_outputs caught bare Exception on newly
  written code; narrowed to ValueError (read_snapshot's own signal) and
  OSError (the file operations it does not pre-validate).
- extract_pages only snapped page boundaries to newlines, but
  transcribe_media's own output is a single unbroken line -- every
  GAIA-transcribed source opened pages mid-word, and a page landing on
  pure filler with a truncated opening made the extractor unable to
  confirm completion, aborting the whole extraction. Falls back to
  sentence-ending punctuation when no newline exists in the overlap
  window.

Also fixes two Windows-only test failures the same field report
flagged: two assertions compared normalized (Windows-lowercased) keys
against raw mixed-case tmp_path strings, and a third symlink-based test
needs elevated privilege Windows CI runners don't reliably have --
added a skip marker rather than leaving it permanently red.
A slower local model spent all 5 steps searching and never answered,
reporting the script's own tight budget as a failed follow-up rather
than a real one (amd-pworfolk field report, PR amd#4145).
"List all functions in app.py" excluded app.py from the requested-
destinations set but left the ledger enabled, so gaps() still
demanded a verified source that code-index/read-file tools never
produce, collapsing the turn to status: incomplete. Gate enabled on
the query naming a real (non-code) destination or no destination
token at all.

Also folds duplicate offset/end/total computation out of
completion.py's delivered(), shares one path-normalization helper
between CompletionEvidence and ExtractionLedger instead of each
constructing its own evidence object, and renames a shadowed loop
variable in the extraction validation script.
gaps() == [] holds for two different reasons -- the ledger being off, and
the ledger being on with nothing outstanding -- so the existing assertion
passes even if activation regresses. Also pins that a document source still
activates when the save target happens to be a code file.
…wo pages

A real unbroken workshop transcript aborted on page 3 because pages 2 and 3
quoted the same sentence from slightly different start points. Their spans
overlapped without either containing the other, so reconciliation treated
identical fields as a conflict and discarded every page extracted so far.

Field values are verbatim in their quotes, so partially overlapping quotes now
merge when every value both sides state sits once, at the same source offset,
in each quote. Repeated items that share context still stay separate, because
their names sit at different offsets. Free-text entries keep the containment
rule, since their text cannot be grounded.
"What time does the store close?" or "List every U.S. state capital" came back
as "I couldn't verify completion" because the save detector counted any
"store/save/export" word and the extraction ledger demanded a source that no
one asked for. Save requests now need the verb as an instruction, and a turn
that never read a document leaves no extraction gap.

- Correct saves no longer read as missing through a symlinked directory, a
  named folder, or a relative path inside a repo subdirectory; paths resolve
  against the working directory, as the file tools do.
- A Lemonade connection error keeps its message and failed status; unverified
  work is listed beneath it rather than replacing it.
- Explaining deletion ("deleted files go to the bin") is not a cleanup claim.
- Extraction never merges two non-overlapping quotes into one entry, so a
  broad quote can no longer absorb a repeated item. Ambiguous replies are
  re-asked, and values repeated inside one quote still match their occurrence.
- An over-long extraction answer stores neither turn instead of an unanswered
  question; loading document-extract keeps code-symbol queries off.
- Docs: tool signature, merge rule, memory limit, gaia-voice token count,
  CHANGELOG entry; inline comments trimmed.
A second review round found ordinary requests still ending as incomplete
("Save me some time", "Store this in memory", "Write a guide to Node.js") and
extraction still able to lose or abort on realistic quotes.

- A save request now counts only when it names a file or disk; a pathless
  "save it" is checked through the answer's own save claim. A destination path
  must follow its preposition directly, so "to clean logs/app.log" is a topic.
- "Write X to Y" is a save only for "it", "this" or "the summary", not "a
  guide to Node.js". Every save verb in a sentence is read, and a trailing ?
  or ! no longer hides the path.
- The answer check reads only a claim's main clause, so "a function that
  saves to x" and "Once saved, the file is at x" are not claims. A deletion
  claim about a path that is absent and untouched is not flagged.
- Two overlapping extractions whose values sit at one source location, one
  inside the other, merge into one entry spanning both quotes with the fuller
  value of each field, so a value cut short at a page boundary no longer aborts.
- Two items from one reply never merge, and a candidate must reconcile with
  every quote already merged, so a broad quote cannot chain two items into one.
  Conflicts are re-asked with the conflicting quote named.
- Free-text entries with equal text merge when their quotes share most of
  their text; repeats sharing only context stay separate.
…lysis

A third review round found the nested-value merge could let an omission-pass
"march in place" swallow an earlier "march", and several ordinary requests
still ending as incomplete.

- Identity fields (name, id, title) must match exactly; only descriptive
  values may be cut short across a page boundary.
- Sources are the files a request reads from: "from meeting.txt into
  actions.json" now extracts meeting.txt and lets the inventory be saved to
  actions.json. Parenthesized paths and multiple sources are found.
- Extraction stays off for agents without a file permission validator, for
  PDFs and other binary documents, and for analysis of code ("find all bugs in
  main.py"); listing content such as TODOs still extracts from code.
- The inventory is appended to the model's answer instead of replacing it, so
  requested analysis ("which one is hardest") survives.
- Save claims keep their relative clauses ("the summary that you asked for");
  only code descriptions ("a function that saves to x") are ignored. A save
  from an earlier session is not a claim about this turn.
- Only requested or claimed outputs need readback; fixing a typo does not.
- Removing a file from an index or list is not a deletion claim.
…cord

A fourth review round found wording-only checks still misfiring: "Downloads
are saved to ~/Downloads" ended incomplete, "Write a Node.js server" demanded a
file named Node.js, and "List all the features of Node.js" required extracting
a document that does not exist. The checks now lean on what actually happened.

- An answer's save claims are checked only when the user asked for a save or
  a disk-writing tool ran this turn; a reused transcript still counts.
- A document source must exist on disk; data files (CSV, JSON, logs, YAML,
  XML) are left to code tools.
- Without a field named for a name, id or title (exercise_name, ExerciseName
  included), the first requested field identifies the item, so an omission
  pass reporting "march in place" can no longer absorb "march".
- "extract/put/copy ... into x.json" names an output, "not to x" drops x, a
  folder is a save target, and a bare name that modifies a noun ("a Three.js
  scene") or sits past a dash is not a path.
- Malformed tool paths (NUL bytes, non-strings) end as normal results.
A fifth review round found the previous commit let "I saved it to notes.md"
pass after "Create notes.md", dropped "Save it to x.txt thanks" as a request,
and aborted extraction when two copies of an item both left the first field
"not stated".

- A first-person save claim is always checked; only impersonal statements
  ("downloads are saved to ~/Downloads") need a save instruction or a write.
- The modifier rule ("a Three.js scene") applies only when no destination
  preposition names the path.
- With no identity value stated in both, any equal field identifies the item.
- A file a successful shell or Python run modified this turn counts as
  written once it is read back, so "ls > listing.txt" can complete.
…ntories

A sixth review round found the previous commit treated any "I" in a sentence
as a save claim, so "I think downloads are saved to ~/Downloads" ended
incomplete, and accepted files touched by a failed or unrelated shell run as
the saved output. A live run also showed a turn that ran out of steps dropping
its 40 extracted items from the answer and from memory.

- A first-person claim needs I/we as the subject of the save verb.
- A shell-written file counts only when its modification time falls inside a
  successful executor call and no failed one, and it never satisfies a
  pathless "saved it to a file" claim.
- "Create/make/generate notes.md" names an output; "a Node.js app" does not.
- A turn that ends without a final answer still shows the extracted inventory.
… speaker

A seventh review round found "create a summary of the errors in app.log"
treating the user's source as the save target, and "I've successfully saved
it to notes.md" slipping past the first-person check.

- Create/make/generate name an output only through their direct object
  ("create notes.md"), never through "in X", and a tech name before a noun
  ("a Next.js landing page") is not a file.
- A first-person claim is I/we followed within a few words by a save verb,
  with no be-verb or clause break between, so adverbs no longer hide it and
  "I think downloads are saved to x" is still information.
- A turn that stops at the step limit shows the finished inventory under the
  step-limit message.
Kalin Ovtcharov added 5 commits September 24, 2026 13:28
…verdict

An eighth review round showed that narrowing which save claims count had
dropped main's safety net: "The summary has been saved to notes.md" with no
save requested passed with no challenge at all, while checking every claim
hard had turned informational answers into incomplete turns.

- A save claim still makes the turn incomplete when a save was requested, a
  file-writing tool ran, or I/we did the saving. Any other claim now gets one
  correction (write it, or say it was not saved now) and then stands, as the
  fabricated-save guard on main did.
- "Create/make/generate ... in notes.md" names an output when notes.md does
  not exist yet; an existing file there is the source.
- A file name followed by a participle and an article ("report.md summarizing
  the project") is the output, while "a Next.js landing page" is not.
A ninth review round found the previous commit treating "create a summary of
the action items in meeting.md" as a save to meeting.md whenever the source
sat outside the working directory, ending correct answers as incomplete.
Only a create verb's direct object names an output now; a claim about a file
after "in" still gets the one-correction check.
Testing against real YouTube workout captions (no newlines, no punctuation,
non-breaking spaces) and an audit of main since this branch showed the
pipeline failing on the input it exists for.

- A cloud reasoning model spent its whole 8K budget thinking about one dense
  caption page and returned no JSON. Page calls now ask cloud models for low
  reasoning effort, allow 16K output tokens, and report a spent budget by
  name; the old finish_reason check never fired because the SDK drops it.
- Quotes match captions despite non-breaking and doubled spaces; the stored
  quote is still the source's own text at its exact offsets.
- Pages snap to a word boundary when a transcript has no punctuation.
- A model that reshaped the saved JSON by hand made correct runs incomplete.
  Exports now give each requested field its own key, and hand edits to a file
  save_extracted_items wrote this turn are refused.
- Local page calls drop the anti-repetition penalties, which fight verbatim
  copying; a save into the agent's scratch folder, deleted on close, no longer
  satisfies "save it"; save_extracted_items gets path grants like write_file.
Adversarial fuzzing and live runs on real YouTube workout captions found the
extractor failing honest models and occasionally losing items.

- An item is located by the source span of its identity value, not its whole
  quote. Neighbouring items' quotes may now overlap, which aborted about a
  quarter of real-caption runs; an omission-pass repeat whose quote names the
  item twice takes the unclaimed occurrence instead of vanishing into the
  first. Free text that repeats inside one quote is never merged.
- Matching ignores case and spacing but only on whole words ("arm" is not in
  "farm"); stored quotes stay the source's own text.
- A cloud page that exhausts its budget reasoning is retried once with
  reasoning off; malformed or truncated replies are retryable errors.
- The fields list stops before a save clause, an all-"not stated" item is
  rejected, CSV keeps colliding field names and escapes formulas, large
  exports validate right after saving, the prompt cap fits the query cap, a
  field-schema mismatch names the fields to resend, and the hand-edit guard
  matches case-insensitive filesystems.
…ripts

Live runs on real YouTube workout captions showed honest models failing whole
documents: instructors repeat names inside one quote, cloud reasoning models
exhaust their budget on dense pages, and models compose exercise names
("Big circles (arms)") rather than copying them.

- Merging no longer raises. Extractions are one item only at the same place
  (same name span, or quotes sharing half their text) with matching or nested
  names; different names stay separate items, differing descriptions are both
  kept, and anything too ambiguous keeps both entries marked
  "(may repeat item N)".
- A name copied from the quote locates the item; a composed label leaves the
  quote to locate it, and one sharing no words with its quote is kept but
  marked "(label not in quote)". Only the item's quote must be verbatim.
- A quote naming its item twice parses; an omission pass takes the unclaimed
  occurrence, so a missed repeat is never folded into the first.
- Errors name the offending field and value so a retry can fix it.
@kovtcharov
kovtcharov force-pushed the fix/3983-evidence-completion branch from 0b3eafb to 279800d Compare September 24, 2026 22:45
…ports

A 74K-character real caption file (the size of the original workshop) timed
out at 30 minutes because a cloud reasoning model spent 50-100 s per page
thinking, and a finished extraction then ran out of steps while the model
paged through a 60K-character export to "verify" it.

- Page calls ask cloud models for no reasoning; copying quotes needs none.
  The same file now finishes in about two minutes with comparable recall.
- The framework reads every exported inventory back in full and compares it
  exactly, so that counts as the readback; the model no longer pages through
  it, and a tampered file is still caught.
- An entry that states no field is ignored instead of failing its page.
Kalin Ovtcharov added 2 commits September 24, 2026 16:35
A final planted-item fuzz found no lost items but a rare wrong merge: when a
quote named its item twice, the extraction was pinned to an occurrence already
found and its values landed on a different item of the same name.

- A quote naming its item twice takes an unclaimed occurrence and is never
  merged; a true re-report shows as a flagged possible repeat.
- A name with a trailing period still locates itself, a one-sided located
  name must sit inside the other quote, and free-text items at different
  name positions stay apart.
- The repeat flag also catches label drift ("march" vs "Seated marching").
- Free text normalises carriage returns, invalid Unicode is a retryable
  reply error, and the output-size error no longer calls the file a source.
@kovtcharov
kovtcharov force-pushed the fix/3983-evidence-completion branch from 1c27205 to 31f937c Compare September 24, 2026 23:37
@kovtcharov

Copy link
Copy Markdown
Contributor Author

The overlap abort you hit is fixed, and so is the class of failure behind it. I tested against real YouTube workout captions: one unbroken line, no punctuation at all, non-breaking spaces. A 74K-character class, the size of your workshop, now extracts end to end on Fireworks in about two minutes. Could you rerun your original transcript on the new head?

Your report

  • Two pages quoting the same sentence from different start and end points now merge into one item. Your exact case is a regression test.
  • On your other point: one disagreement no longer throws away the other pages. Merging never fails a run now. When two extractions can't be shown to be the same item, both are kept and the inventory marks the second one "(may repeat item N)" so you can check it. Keeping the earlier page's values and dropping the later ones would have lost stated information, so I didn't take that option.

What real captions surfaced beyond your case

  • Instructors repeat names, and models compose labels ("Big circles (arms)"), so an item is now located by the span of its name when the name is copied from the source, and by its quote otherwise. Matching ignores case and spacing, but only on whole words.
  • A cloud reasoning model spent its whole output budget thinking about one dense page and returned no JSON; with reasoning on, a 74K file ran past the 30-minute limit. Page calls now ask cloud models for no reasoning, and a 16K budget exhaustion is reported by name.
  • A model that "fixed" the saved JSON by hand made correct runs incomplete. Exports now carry each requested field as its own key, hand edits to the saved inventory are refused, and the framework verifies the file itself.

Limits worth knowing

  • On a local model, speed decides long documents: Gemma-4-E4B on a Mac took 17 minutes for a 13K file, so 74K would exceed the 30-minute budget there. Your Strix Halo run should be much faster.
  • Recall on unseen prose still isn't guaranteed. Two cloud runs on the same file gave 46 and 56 items.
🔍 Technical details

Live runs (Fireworks deepseek-v4p1-flash, head 31f937c02)

  • Three real auto-caption files of 13K, 21K and 74K characters. All pages completed, and every quote equals the source text at its offsets.
  • The 74K end-to-end agent run: 111 items, saved and verified in 122 s with 5 tool calls.
  • The lined and unlined 40-item fixtures still pass 40/40, including save and memory recall.

Local run

  • Gemma-4-E4B on the 13K file: 63 items, success.

Adversarial coverage

  • A stub-model fuzzer found the old merge rules aborting honest models on about a quarter of real-caption runs, and able to drop a repeat in one case. Both are fixed under the new design.
  • The same fuzzer's honest-model run now completes 48/48 and recovers 39/39 planted items with fields.

Architecture audit of the 51 commits on main since this branched

Skills now load when the model calls load_skill rather than being guessed
before the turn, so that call is the main way extraction switches on.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Replicated as #4374 — fork push access (kovtcharov/gaia) was revoked mid-review, so this PR could no longer be refreshed against main (59 commits behind and growing). Same content, conflicts re-resolved against current main. Closing in favor of the replacement.

pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Sep 27, 2026
…md#4374)

Replicates amd#4145 (`kovtcharov/gaia` fork, push access blocked) onto a
branch this session can push to. No content changes beyond conflict
resolution against current `main`.

GAIA could claim it saved a file it never wrote this turn, or turn a
long workshop transcript into a condensed list presented as complete.
Now a save counts only when that exact file was written and read back,
and a long document is extracted page by page into a full inventory in
which every item keeps a verbatim quote from the source. The result is
kept in memory, and anything unfinished is reported as incomplete.
Ordinary questions ("What time does the store close?") behave exactly as
on `main`.

Fixes amd#3983 and amd#4141; related to amd#4009. Closes amd#4145.

## Test plan

- [x] `python -m pytest tests/unit/agents/ -q`: 1,663 pass, 51 skip. The
one failure (`test_symlinked_directory_is_the_same_output`) is this
Windows box lacking the symlink privilege, not the code.
- [x] `python -m pytest tests/unit/ -k "memory" -q`: 1,136 pass. The one
failure (`test_memory_discovery.py::TestCredentialManagerContractShape`)
reproduces on pristine `main`.
- [x] `python -m pytest tests/unit/ -k "inventory or transcript or
overlap or youtube or extract" -q`: 547 pass; remaining failures are a
local `mcp` package version mismatch and a live-Lemonade ASR test.
- [x] `black --check` / `isort --check-only` clean on every touched
file.
- [ ] Reporter check: Patrick reruns the original workshop transcript.
- [ ] Judged `gaia eval agent` run: deferred by maintainer; the
completion gate changes final answers, so decide before merge.

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

**What a reviewer should know**

- **Saves**
- A request that names a file, folder or disk is a hard obligation: the
file must be written and read back this turn.
- A save claim is checked hard when a save was requested, a disk tool
ran, or the answer says "I" or "we" saved something. Any other claim
gets one correction and then stands, as on `main`.
- A file written through the shell counts only when a successful call
modified it. The agent's scratch folder never counts as the user's save.
- **Extraction**
- Pages are 4K characters with 600 characters of overlap, snapped to a
line, sentence or word boundary. Each page gets two passes, a retry on
an unusable reply, and a 16K-token output budget.
- Cloud models are asked for no reasoning: a reasoning model spent
50–100 s per page and ran past the 30-minute limit on a 74K file.
- Quote matching ignores case and spacing, but only on whole words. The
stored quote is always the source text at its exact offsets.
- An item is placed by the span of its name when the name is copied from
the quote, otherwise by its quote.
- Merging never fails a run and never drops an item. Differing
descriptions are both kept, and uncertain cases keep both entries,
marked "(may repeat item N)".
- **Exports**
- JSON records give each field its own key and CSV gives each field its
own column. The framework reads the saved file back in full and requires
an exact match, and hand edits to it are refused.

**Adversarial coverage (from amd#4145)**

- A planted-item oracle (about 20,000 items, repeated names, paraphrased
labels, repeats across pages and passes) finds no lost, absorbed or
wrongly merged items.
- In 60,000 hostile replies, no exception escaped the tool, and every
quote matched the source at its offsets.
- Live runs on Fireworks `deepseek-v4p1-flash` against real YouTube
auto-captions of 13K, 21K and 74K characters; the 74K end-to-end agent
run saved and verified 111 items in 122 s. Local Gemma-4-E4B completed
the 13K file (63 items).

**Conflicts resolved against current `main`**

Two, both in `src/gaia/agents/base/agent.py`, plus an additive one in
the flagship `CHANGELOG.md`:

1. **Turn-sealing order vs. amd#3707 (mid-turn followups).** `main` added a
`_drain_followups` check that re-enters the loop rather than sealing the
answer; amd#4145 replaced the same lines with `finalize_answer` + the
completion-evidence gate. Kept both, drain first: a late user message
still gets folded into the running turn, and the completion gate then
runs on the answer that actually seals.
2. **Duplicated `_refresh_active_skill_filter` vs. amd#4369 (a loaded skill
brings its tools).** amd#4369 hoisted that call to *before*
`_refresh_active_tool_filter`; amd#4145 still carried it in its old
position below, so a naive merge called it twice per turn. Dropped the
duplicate and kept `main`'s hoisted call — the extraction block that
follows reads `_active_skill_filter`, so running it earlier is strictly
correct.

**Verification of the resolution**

- Per-file diff of (merge-base → amd#4145 head) against (current `main` →
this branch): byte-identical on every file except the one blank line the
de-duplication above removes. That rules out the silent near-identical
duplication a large auto-merge can introduce.
- `compile()` (not just `ast.parse`, which does not reject repeated
keyword arguments) over every `.py` in `src/`, `tests/`, `hub/` and
`scripts/`: clean. Repo-wide sweep for stray conflict markers: none.
</details>

---------

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

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(agent): a run can report success for work it never did

3 participants