Skip to content

feat(delivery)!: bound default results by an agent result budget - #14252

Merged
morluto merged 38 commits into
mainfrom
feat/agent-result-budget
Nov 25, 2026
Merged

morluto merged 38 commits into
mainfrom
feat/agent-result-budget

Conversation

@morluto

@morluto morluto commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Phase 1 of #14187: one agent-sized delivery budget decides whether an omitted detail returns complete Evidence or its retained summary. The budget is separate from the stdio frame limit. Over-budget results are never refused or silently truncated.

One owner for the size decision

main gained a second mechanism while this PR was open. 59a7999 added size-aware detail for list_names, list_procedures, list_strings, search_procedures, search_strings, trace_feature and batch_decompile, with a fixed 32 KiB bound. 89919c8 limited it to sessions that advertise inspect_analysis_view. #14368 (67a1e2c) extended it to inspect_web_page and added the web-page section views. This PR now merges both into one:

  • One threshold. delivery.agent_result_budget_bytes is the only size that chooses the shape. SIZE_AWARE_INLINE_EVIDENCE_BYTES, analysisDetailSizeAwareSchema and declaresSizeAwareDetail are removed, and every contract uses analysisDetailSchema.
  • One decision function. budgetedSummaryBytes in src/domain/agentResultBudget.ts decides, and both MCP tool-result delivery and CLI publication call it. Main's deliversRetainedSummary and the size branches in the Evidence, analysis and provider-operation handlers are removed. retainedSummaryDelivery now handles only an explicit detail: "summary".
  • Main's paging rule is kept. Only a session that can page a summary gets one. The request context records whether the session advertises inspect_analysis_view, next to the caller's detail, at canonical validation. A session scoped without the application family, or a server that retains no Evidence, still gets complete Evidence. Main's MCP test for the scoped session still passes.
  • Applies to every budgeted tool. The 45 tools with a delivery detail, which now include inspect_web_page, use the same decision. A test checks the list against the contracts' input JSON Schemas.
  • Both view families kept. The web-page section views from feat(browser)!: size inspect_web_page delivery and page captures by section #14368 and the native-inventory and batch-decompile views remain the producers' summaries and pages. evidence-json remains the generic exact-bytes cursor. Neither is duplicated: the over-budget summary is the producer's own summary view.
  • Main's boundary tests are kept. Its 32,768/32,769 tests, with escaped and multibyte text, now pin the setting's boundary, for the default and for an override. They run against budgetedSummaryBytes.

Default: 32 KiB, not 48 KiB

Claude Code moves MCP results above 25,000 tokens out of context and warns above 10,000. Main's evidence for its bound (59a7999) was a 120-row inventory page of 73K characters that crossed the 25,000-token cap. That is at most about 2.9 bytes per token for dense JSON such as addresses, digests and identifiers, well below the usual 4.

Budget Est. tokens at 2.9 B/token Est. tokens at 4 B/token
32,768 bytes ~11,300 ~8,200
49,152 bytes ~16,900 ~12,300

At 48 KiB, a dense result just under budget is about two thirds of the cap before any other output in the turn. At 32 KiB it is under half, with room for the delivery facts. It may cross the 10,000-token warning for the densest rows; that is only a warning. The default is therefore 32,768 bytes, the same as main's bound, so main's tools keep their observed behavior. These are estimates, not tokenizer measurements. Token labels in the delivery facts now use 3 bytes per token, and the evidence-json default page (24,576 escaped bytes) is derived from the default budget.

Behavior

  • Setting. delivery.agent_result_budget_bytes, default 32,768 compact JSON bytes, range 4,096 to 10,485,760.
    • Changes at runtime through update_analysis_settings.
    • Its launch seed is REA_AGENT_RESULT_BUDGET_BYTES, read from the environment the server captured. It also covers one-shot CLI runs.
    • An invalid seed leaves delivery unbudgeted, and settings inspection reports it.
    • REA_MCP_MAX_RESPONSE_BYTES stays the transport safety net.
  • Over budget. The result is delivered as the producer's summary view: exactly the record detail: "summary" returns, retained the same way.
    • Delivery facts travel beside the summary, in a second MCP text block {"delivery": …} and in _meta["rea/agent-budget-delivery"]. They carry budget_bytes, budget_source, the range, complete_bytes, estimated_complete_tokens, evidence_id, retained, next (the exact inspect_analysis_view call) and a note. The frame check reserves their bytes.
    • MCP retains the complete Evidence in the session.
    • CLI with --evidence_output prints {summary, evidence_bundle, delivery}.
    • CLI without it prints {summary, delivery} and writes nothing. The rerun arrays list only the arguments to add (--evidence_output <new-bundle-path> or --detail complete) and never echo argv.
    • --filter-output keeps complete delivery, because a summary would drop the selected paths.
  • Cursor. inspect_analysis_view view {kind: "evidence-json", offset, limit} pages the exact JSON text of retained, inline or file Evidence in UTF-16 code units.
    • Pages never split a surrogate pair, and joining them in offset order reproduces the record exactly.
    • With limit omitted, a page holds at most 24,576 escaped UTF-8 bytes, so with its view Evidence it fits the default budget. An explicit limit counts code units, up to 1,048,576.
  • Per call. detail: "complete" (--detail complete) always delivers everything inline. detail: "summary" is unchanged.
  • Unchanged. Admission limits and refusals, selected views, operations without a summary view and partial-failure Evidence.
  • [Bug] inspect-managed-members: 772k tokens for a 129 KB assembly, and --type leaves member_refs assembly-wide #14172. type_names (--type) narrows member_refs to the MemberRef rows that the selected method bodies use, directly or through a MethodSpec, and narrows exported_types to the selected names.
  • [Feature] inspect-byte-entropy: return runs by default and page blocks (2 GiB window costs ~164k tokens) #14156 (part). inspect-byte-entropy gains --detail and --evidence_output.

The overflow path is a successful delivery event and adds no error classification or remediation (#14239).

Test and verifier harnesses.

  • The shared MCP and CLI test transports request complete Evidence by default (completeEvidenceByDefault). Tests about delivery itself opt out with delivery: "budgeted" or testDelivery: "budgeted"; main's size tests now do this.
  • Verifiers wrap their clients and CLI argv through scripts/lib/complete-evidence.mjs, which reads the compiled budget list and CLI registry. That covers inspect_web_page and the new Cortex-M verifier.
  • The explicit detail: "complete" that feat(browser)!: size inspect_web_page delivery and page captures by section #14368 added to four browser verifiers is now redundant and was removed.

Size before and after

CLI --json output on public artifacts, which were downloaded and never executed. Tokens are estimates at 3 bytes per token. Before is main at the original base; after is this branch run from source. The after column was measured with the earlier 48 KiB default. Every summary is under 32 KiB, so the shape is the same at the new default; only the budget digits in the delivery facts differ.

Call Before bytes (est. tokens) After bytes (est. tokens)
inspect-managed-members BepInEx 5.4.23.6 BepInEx.dll (129 KB) 4,141,539 (~1.38M) 8,672 (~2.9k)
same, --type BepInEx.Paths 523,618 (~175k) 10,053 (~3.4k)
same, --type BepInEx.Paths --detail complete 523,618 (~175k) 93,176 (~31k)
inspect-managed-members OpenCiv3 v0.3-dutch-2 C7Engine.dll (531 KB) 20,795,315 (~6.9M) 8,690 (~2.9k)
inspect-byte-entropy OpenCiv3 Windows zip (172 MB), --block-size 8192 1,079,991 (~360k) 4,532 (~1.5k)
inspect-desktop-application OpenCiv3 Windows release folder 683,314 (~228k) 6,925 (~2.3k)

Wall time, CPU and memory were not measured; this change targets delivery size. A fitting result stops measuring at the budget, and the complete size is measured once, only when the result is over budget.

Merged from main

Phase 2 (not in this PR)

Validation

  • src/domain/agentResultBudget.test.ts:
    • Exact boundary at the default and at an override (main's escaped and multibyte cases).
    • Each condition of the decision: retained, pageable, budget present, and omitted versus explicit detail.
    • Setting precedence and invalid seeds.
  • tests/boundary/mcp/nativeInventoryViewsMcp.test.ts: main's omitted-detail inventory cases, including the scoped session without inspect_analysis_view.
  • tests/boundary/mcp/webPageViewMcp.test.ts: main's omitted-detail capture cases.
  • tests/boundary/mcp/agentResultBudgetMcp.test.ts:
    • The summary with delivery facts and a cursor.
    • evidence-json pages that reproduce the record and each fit the default budget.
    • The override, the runtime setting and admission refusals.
    • CLI parity with and without --evidence_output.
  • src/server/ToolResultDelivery.agentBudget.test.ts (frame reservation and the captured seed) and src/contracts/analysisDetail.test.ts (the 45-tool list derived from contracts).
  • batchDecompileViewsMcp, ghidraInventoryMcp, analysisViewMcp, webNetworkCaptureMcp, browserCli, completeEvidenceByDefault and the other delivery consumer suites, run locally with targeted vitest.
  • oxfmt per changed file, oxlint (no errors) and a scoped typecheck of the touched files. The only typecheck errors were two in Frida files from the stale local node_modules.
  • Not run locally, because they need a full build: verify:advertised-schemas (summaries are recorded from CI), productCatalog, and the entropy MCP/CLI parity case, which spawns the built CLI. No real-client verification was done in Claude Code or any other client.

BREAKING CHANGE: An omitted detail no longer always returns complete Evidence inline. On MCP and the CLI, it returns complete Evidence only when that fits delivery.agent_result_budget_bytes (default 32,768 bytes) and the session can page a summary, and the retained summary otherwise. Affected tools: analyze_javascript_application, analyze_web_bundle, batch_decompile, capture_browser_scenario, decode_interface_builder, frida_session_status, gdb_console, get_call_graph, inspect_android_class, inspect_android_method, inspect_android_package, inspect_artifact, inspect_binary_layout, inspect_byte_entropy, inspect_dart_aot, inspect_devicetree, inspect_elf_dependencies, inspect_erlang_beam, inspect_evm_interface, inspect_go_binary, inspect_macho, inspect_managed_artifact, inspect_managed_members, inspect_native_exports, inspect_native_load_image, inspect_pcap_capture, inspect_python_pyc, inspect_rust_binary, inspect_wasm_artifact, inspect_web_network_capture, inspect_web_page, inspect_with_objdump, list_names, list_procedures, list_strings, procedure_address, procedure_callees, procedure_callers, procedure_pseudo_code, procedure_references, resolve_containing_procedure, search_procedures, search_strings, trace_feature and trace_web_source_location. The size-aware bound of 32 KiB from main is now this setting, so it follows runtime overrides and the launch seed. The analysisDetailSizeAwareSchema contract export is removed. Pass detail: "complete" (--detail complete) to restore complete inline delivery. inspect_managed_members type_names now also narrows member_refs and exported_types.

Fixes #14172
Fixes #14180
Part of #14187
Part of #14156

Omitted detail now returns complete Evidence only when it fits the new
delivery.agent_result_budget_bytes runtime setting (default 49152 compact
JSON bytes, about 12k tokens at an estimated 4 bytes per token). Larger
results are retained and delivered as the producer's summary with a
limitation naming the budget and the recovery call; nothing is refused or
truncated. inspect_analysis_view gains an evidence-json view that pages the
exact JSON text of retained Evidence. The CLI applies the same budget and
publishes the complete bundle with --evidence_output.

inspect_managed_members type_names now also narrows member_refs and
exported_types, and inspect-byte-entropy gains CLI evidence delivery.

BREAKING CHANGE: An omitted detail no longer always returns complete
Evidence inline on MCP or the CLI for tools with a detail selector
(including inspect_managed_members, inspect_managed_artifact,
inspect_byte_entropy, inspect_artifact, analyze_javascript_application,
list_procedures, list_strings and the other operations listed in
src/domain/agentBudgetOperations.ts). Over the budget they return the
retained summary; pass detail complete (--detail complete) for complete
inline delivery. inspect_managed_members type_names narrows member_refs
and exported_types.

Fixes #14172
Fixes #14180
Part of #14187
Part of #14156
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-24T02:11:42.347905Z
We couldn’t complete this review. Comment @codex review to try again.
f6fcf4a PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@greptile-apps

greptile-apps Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5 · Not ready to merge: large JSON Lines exports fail, and paging still keeps full serialized copies without counting them toward the memory limit.RetriggerView in GreptileConfidence Score: 3/5 Tier: plus

[High impact] The new delivery rule reaches many analysis tools and both MCP and CLI callers.

Not ready to merge: large JSON Lines exports fail, and paging still keeps full serialized copies without counting them toward the memory limit.

FindingsFix All in CodexFindings

  1. P1 Large JSON Lines exports fail ▶
  2. P2 Paging keeps uncounted full copies ▶
  3. P2 Delivery guidance has duplicate owners ▶
Fix with agent prompt
### Issue 1
src/cli/analysisEvidenceDelivery.ts:187-195
`list-procedures <target> --format jsonl` now fails when its Evidence exceeds the budget. This branch replaces the Evidence with `{summary, delivery}`, but `prepareJsonLines` only accepts arrays at the result, `page`, or `normalized_result`. It rejects the wrapper with `invalid_request`, so the caller receives neither rows nor the delivery advice. Without `--evidence_output`, nothing was saved either.

Preserve complete delivery for JSON Lines, as for `--filter-output`, or let the JSON Lines writer emit the summary and delivery facts as a successful result.

### Issue 2
src/domain/analysisView/evidenceJsonView.ts:66-77
`evidence-json` caches the entire escaped record even when the caller requests one code unit. The retained-record path checks neither live memory nor the ledger allowance before allocating these chunks. The cache then keeps them while the parent remains retained, so paging large records can exhaust server memory despite successful retention admission.

Bound this cache or charge its escaped size before allocation. The repository requires retained state and serialization growth to stay bounded.

### Issue 3
docs/reference/rea-limit-inventory.md:65-67
This paragraph repeats the delivery and recovery contract owned by `limits-and-recovery.md#agent-result-budget`. The documentation rule requires one canonical owner and links instead of copied claims. Keeping both explanations means future changes can leave readers with conflicting recovery advice.

Replace this paragraph with a link to the shared section. This repository requirement must be satisfied before merging.

```suggestion
See [Agent result budget](limits-and-recovery.md#agent-result-budget) for
`delivery.agent_result_budget_bytes` delivery and recovery behavior.
```

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

This PR shares one result-budget decision between MCP and CLI delivery. It adds exact-JSON paging and narrows selected managed-member results.

  • Large MCP results arrive as summaries with a way to reach the full record.
  • Callers can page the exact JSON text of a complete Evidence record.
  • CLI commands use the shared budget to choose between complete Evidence and a summary.
  • Selecting managed types narrows related references and exported types.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Completed Evidence] --> B{Explicit detail?}
  B -->|Complete| C[Deliver complete Evidence]
  B -->|Summary| D[Existing summary delivery]
  B -->|Omitted| E{Fits budget or cannot summarize?}
  E -->|Yes| C
  E -->|No| F[Producer summary and delivery facts]
  F --> G[MCP: retain parent and summary]
  F --> H[CLI: save bundle only when requested]
  H --> I{Output format}
  I -->|Document| J[Write summary and recovery facts]
  I -->|JSON Lines| K[Wrapper rejected: no row array]
Loading

Reviews (26) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

Comment thread src/server/EvidenceMcpServerCore.ts Resolved
Comment thread src/server/ToolResultDelivery.ts Resolved
Comment thread src/contracts/analysisDetail.ts Resolved
Comment thread src/server/ToolResultDelivery.ts Resolved
Comment thread src/domain/agentResultBudget.ts Resolved
…acts beside them

Review fixes for the agent result budget:

- Deliver the producer's own summary record, identical to detail summary,
  so its identity holds in summary consumers such as compare_artifacts.
  The budget, sizes, retention and the exact paging call travel as
  delivery facts: a second MCP text block and _meta, or a delivery field
  in CLI output.
- Capture the caller's detail for application-validated tools too, so
  inspect_binary_layout and similar tools are budgeted.
- Keep recovery facts when a budgeted summary itself exceeds the frame.
- Size an omitted evidence-json limit by escaped UTF-8 bytes and never
  split a surrogate pair, even in a one-unit page.
- Add the REA_AGENT_RESULT_BUDGET_BYTES launch seed; the shared test
  environment raises it for semantic tests, and budget tests clear it.
- Align tool descriptions and verifiers that read complete Evidence.
Comment thread src/domain/agentResultBudget.ts Resolved
Comment thread src/server/ToolResultDelivery.ts Resolved
… count delivery facts in the frame

- The agent result budget seed is read from the environment the server or
  CLI invocation captured: ToolResultDelivery takes it at construction,
  and a CLI invocation binds it in its publication context. The ambient
  process environment is no longer read.
- The frame check reserves the bytes of the delivery block and _meta that
  are added after encoding, so a budgeted response cannot exceed the frame.
- Conformance workflows that resend complete Evidence raise the budget
  through the shared inline-Evidence environment, as do the artifact and
  binary layout verifiers.
…CLI overflow

- Shared test and verifier environments no longer raise the agent result
  budget. Every test and verifier workflow that reads complete Evidence
  from a budgeted tool now requests it with detail complete or --detail
  complete, including the real-provider verifiers outside PR CI (Ghidra,
  Hopper, IDA, Kuna and client verifiers). Default delivery is exercised
  as shipped.
- Budgeting applies only to tools with a detail selector, so every
  budgeted call has a complete opt-out.
- CLI overflow without --evidence_output writes nothing; its delivery
  facts carry exact rerun argv for --detail complete and
  --evidence_output, omitted when the command declares sensitive values.
Comment thread src/cli/runCliCommand.ts Resolved
- Add tests/support/completeDetail.ts with COMPLETE_DETAIL and
  completeArguments so tests that read complete Evidence request it in one
  place, keeping functions within max-lines-per-function without raising
  the limit.
- Restore provider-client tests (GhidraClient, Hopper health): their
  callTool("name", ...) calls are bridge requests, not MCP tools, and take
  no detail.
- Update the game-scale type inventory test for member_refs narrowing.
Resolves managedMemberComparisonCli.test.ts by keeping main's pruning.

Also, from review:
- CLI overflow rerun advice names only the arguments to add
  (--detail complete, --evidence_output <new-bundle-path>); the caller's
  arguments are no longer echoed, since they can carry access credentials
  such as a browser socket ID.
- Calls that select a view keep no complete-detail override, which the
  schema rejects (rust, erlang, python and route view tests).
Comment thread src/dotnet/ManagedMemberInspector.ts Resolved
Comment thread src/dotnet/ManagedMemberInspector.ts Resolved
The shared MCP client helpers (createTestMcp, connectLocalToolsMcp and
the CLI fixture's shared MCP session) and the CLI runners (the cli
fixture and the shared CLI session) now apply one named default,
completeEvidenceByDefault. A budgeted tool called with neither detail nor
view gets detail complete; the CLI does the same with --detail complete,
chosen by the command's tool contract. A budgeted operation that resolves
to no contract fails loudly at load. Tests whose subject is delivery opt
out with delivery "budgeted". This is a test-harness choice; production
delivery is unchanged and the budget tests prove the default path.

Per-call complete-detail edits are reverted in the 204 test files whose
transports all apply the default. Explicit requests remain where a test
drives its own SDK client, server, CLI instance or process, and where
the detail choice is the test's subject.
Comment thread src/cli/analysisEvidenceDelivery.ts Resolved
The Real Apple and browser verifiers read complete Evidence through
artifactCliEvidence, which ran the compiled CLI without a detail choice
and got the budgeted {summary, delivery} output. The helper now requests
complete Evidence for commands that take --detail, read from the compiled
CLI's own registry (scripts/lib/complete-evidence-cli.mjs).

The test harness default had a sibling bug: it treated every cli-flagged
budgeted contract as taking --detail, but only Evidence-delivery commands
do (inspect-binary-layout does not). It now reads the source CLI registry
too, and covers every command the CLI budgets.
…ent and CLI argv

The real-browser failure was the same missing normalized_result as the
Apple one: browser-capture-metadata-budget-e2e reads analyze-web-bundle
through artifactCliEvidence, fixed in the previous commit.

The shared verifier module, scripts/lib/complete-evidence.mjs, now owns
both transports:
- completeEvidenceClient wraps each verifier's SDK Client once, so every
  callTool to a budgeted tool with neither detail nor view requests
  complete Evidence, whatever local call helper a verifier uses (86
  clients, including the Ghidra, Hopper, IDA and Kuna verifiers'
  argument-less list_procedures and inspect_native_load_image calls).
- completeEvidenceCliArguments covers the remaining verifier CLI argv
  that chose no detail, such as function, decompile, analyze and the
  Android and Apple commands.
Commands and tools that are not budgeted are sent as written.
Comment thread scripts/lib/complete-evidence.mjs Resolved
…/main

- Page evidence-json via cached jsonParts chunks and reject surrogate-splitting start offsets
- Preserve --filter-output selections on over-budget CLI Evidence
- Update managed-member selected scope guidance and CLI regression coverage
- Make completeEvidenceCliArguments respect --detail enums and analyze route selection
- Fix verifier array wrapping in real-ghidra-namespace-annotations and verify-real-ghidra-riscv
- Record preparationRequest unchanged in javascript/module-references verifier
- Unify origin/main size-aware delivery under the agent result budget and preserve view-tool advertisement checks
About 90 tests spawn scripts/rea.mjs or a server directly, outside the
harness default that asks for complete Evidence, and read analysis facts
from the result. Over the default budget they received a summary instead;
javascriptChildHandleOwnership failed this way.

The Vitest environment now seeds REA_AGENT_RESULT_BUDGET_BYTES with the
largest accepted value, so a spawned CLI or server delivers complete
Evidence, as the in-process default does. Delivery tests keep their own
budget: agentResultBudgetMcp builds its server without the seed, so its
default-budget cases still exercise the shipped default.
Comment thread vitest.config.ts Resolved
The test environment seeds the largest agent result budget so spawned
processes deliver complete Evidence. In-memory servers built by
createApplicationMcpHarness (and connectGhidraMcp, which uses it) inherit
process.env too, so a test that chose testDelivery "budgeted" kept the
seed: the 600-row list_procedures case and the omitted-detail web page
views returned complete Evidence instead of a summary.

testDeliveryEnvironment now owns that choice: a budgeted test's server
environment drops the seed and uses the shipped default. The application
harness applies it to every server it builds.
…ace refusal

A view with no --detail now selects summary delivery, so its refusal
names the missing evidence_output bundle; --detail complete still refuses
the view. The trace test still expected a view refusal in both cases.
# Conflicts:
#	scripts/lib/ghidra-reference-snapshot-e2e.mjs
Comment on lines +66 to +77
const buildSerializedChunks = (evidence: Evidence): SerializedEvidenceJson => {
const chunks: string[] = [];
const starts: number[] = [];
let totalLength = 0;
for (const part of jsonParts(evidence)) {
if (part.length === 0) continue;
starts.push(totalLength);
chunks.push(part);
totalLength += part.length;
}
starts.push(totalLength);
return { chunks, starts, totalLength };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Paging keeps uncounted full copies

evidence-json caches the entire escaped record even when the caller requests one code unit. The retained-record path checks neither live memory nor the ledger allowance before allocating these chunks. The cache then keeps them while the parent remains retained, so paging large records can exhaust server memory despite successful retention admission.

Bound this cache or charge its escaped size before allocation. The repository requires retained state and serialization growth to stay bounded.

Context Used: AGENTS.md (source)

Knowledge Base Used: Session evidence and results

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/analysisView/evidenceJsonView.ts
Line: 66-77

Comment:
**Paging keeps uncounted full copies**

`evidence-json` caches the entire escaped record even when the caller requests one code unit. The retained-record path checks neither live memory nor the ledger allowance before allocating these chunks. The cache then keeps them while the parent remains retained, so paging large records can exhaust server memory despite successful retention admission.

Bound this cache or charge its escaped size before allocation. The repository requires retained state and serialization growth to stay bounded.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

**Knowledge Base Used:** [Session evidence and results](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fsession-evidence-and-results.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Codex

Comment on lines +65 to +67
`delivery.agent_result_budget_bytes` is a delivery budget, not an admission
limit: an over-budget result is retained and delivered as its summary with an
`inspect_analysis_view` cursor, never refused.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Delivery guidance has duplicate owners

This paragraph repeats the delivery and recovery contract owned by limits-and-recovery.md#agent-result-budget. The documentation rule requires one canonical owner and links instead of copied claims. Keeping both explanations means future changes can leave readers with conflicting recovery advice.

Replace this paragraph with a link to the shared section. This repository requirement must be satisfied before merging.

Suggested change
`delivery.agent_result_budget_bytes` is a delivery budget, not an admission
limit: an over-budget result is retained and delivered as its summary with an
`inspect_analysis_view` cursor, never refused.
See [Agent result budget](limits-and-recovery.md#agent-result-budget) for
`delivery.agent_result_budget_bytes` delivery and recovery behavior.

Context Used: Documentation (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: docs/reference/rea-limit-inventory.md
Line: 65-67

Comment:
**Delivery guidance has duplicate owners**

This paragraph repeats the delivery and recovery contract owned by `limits-and-recovery.md#agent-result-budget`. The documentation rule requires one canonical owner and links instead of copied claims. Keeping both explanations means future changes can leave readers with conflicting recovery advice.

Replace this paragraph with a link to the shared section. This repository requirement must be satisfied before merging.

```suggestion
See [Agent result budget](limits-and-recovery.md#agent-result-budget) for
`delivery.agent_result_budget_bytes` delivery and recovery behavior.
```

**Context Used:** Documentation ([source](https://github.com/morluto/rea/blob/main/docs))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Codex

@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings could not be posted inline.

  • P1 Paging keeps uncounted full copies src/domain/analysisView/evidenceJsonView.ts:66 ▶

    evidence-json caches the entire escaped record even when the caller requests one code unit. The retained-record path checks neither live memory nor the ledger allowance before allocating these chunks. The cache then keeps them while the parent remains retained, so paging large records can exhaust server memory despite successful retention admission.

    Bound this cache or charge its escaped size before allocation. The repository requires retained state and serialization growth to stay bounded.

  • P2 Delivery guidance has duplicate owners docs/reference/rea-limit-inventory.md:65 ▶

    This paragraph repeats the delivery and recovery contract owned by limits-and-recovery.md#agent-result-budget. The documentation rule requires one canonical owner and links instead of copied claims. Keeping both explanations means future changes can leave readers with conflicting recovery advice.

    Replace this paragraph with a link to the shared section. This repository requirement must be satisfied before merging.

    See [Agent result budget](limits-and-recovery.md#agent-result-budget) for
    `delivery.agent_result_budget_bytes` delivery and recovery behavior.
    

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@morluto
morluto disabled auto-merge November 25, 2026 16:25
@morluto
morluto merged commit 123b693 into main Nov 25, 2026
60 of 61 checks passed
@morluto
morluto deleted the feat/agent-result-budget branch November 25, 2026 16:25
vincentkoc added a commit that referenced this pull request Nov 25, 2026
…-artifact-cancellation-projection

* commit '3d4633176f15f3bd8072751af788bf31c7f2e0d8':
  refactor(views): reuse JSON record and request-line projections (#14582)
  test(cutter): share loopback listener and descriptor fixtures (#14578)
  ci(apple): give the macOS lane room for the discovered macOS-gated tests
  test(native): accept plutil nesting diagnostics on stdout
  fix(native): admit the missing-UUID dyld_info refusal when it exits 0
  refactor(ghidra): share the executable file probe (#14573)
  refactor(artifacts): reuse carrier ranges and Mach-O field decoding (#14574)
  perf(tar): update global PAX map in place after budget accounting (#14580)
  refactor(manifest): share ordered sibling group traversal (#14571)
  test(browser): reuse page and Evidence inspection fixtures (#14581)
  ci(apple): run the macOS lane when a pull request changes a macOS-gated test
  test(cli): use the registered argument schemas directly (#14586)
  test(bun): share the file-handle read observer (#14577)
  test(mcp): share the successful tool assertion (#14576)
  test(uefi): reuse the driver file across firmware fixtures (#14570)
  feat(delivery)!: bound default results by an agent result budget (#14252)
vincentkoc added a commit that referenced this pull request Nov 25, 2026
* commit '3d4633176f15f3bd8072751af788bf31c7f2e0d8':
  refactor(views): reuse JSON record and request-line projections (#14582)
  test(cutter): share loopback listener and descriptor fixtures (#14578)
  ci(apple): give the macOS lane room for the discovered macOS-gated tests
  test(native): accept plutil nesting diagnostics on stdout
  fix(native): admit the missing-UUID dyld_info refusal when it exits 0
  refactor(ghidra): share the executable file probe (#14573)
  refactor(artifacts): reuse carrier ranges and Mach-O field decoding (#14574)
  perf(tar): update global PAX map in place after budget accounting (#14580)
  refactor(manifest): share ordered sibling group traversal (#14571)
  test(browser): reuse page and Evidence inspection fixtures (#14581)
  ci(apple): run the macOS lane when a pull request changes a macOS-gated test
  test(cli): use the registered argument schemas directly (#14586)
  test(bun): share the file-handle read observer (#14577)
  test(mcp): share the successful tool assertion (#14576)
  test(uefi): reuse the driver file across firmware fixtures (#14570)
  feat(delivery)!: bound default results by an agent result budget (#14252)
  ci(apple): discover and run every macOS-gated test on macOS
  test(apple): expect path-selected inspect_artifact in resource-only sessions
  fix(errors)!: keep only changed reader integrity checks retryable
morluto added a commit that referenced this pull request Nov 25, 2026
PR #14252 added explicit complete-detail requests across tests before the
vitest REA_AGENT_RESULT_BUDGET_BYTES seed and the complete-Evidence harness
existed. Restore the pre-#14252 form where the seed or the harness already
delivers complete Evidence.

Keep the requests that are load-bearing: delivery, summary and budget tests,
tools whose omitted detail is summary, and callers that neither the seed nor
the harness reaches (unwrapped SDK clients on servers with an explicit
environment, and in-process CLIs). Those were found by running the touched
files with the shipped budget lowered to its 4 KiB minimum.
@morluto morluto added the enhancement New feature or request label Nov 26, 2026
Comment on lines +187 to +195
if (evidenceOutput === undefined) {
if (overBudget === undefined) return complete;
const summary = await overBudgetSummary(complete);
return summary === undefined
? complete
: {
summary,
delivery: deliveryJson(overBudget({ kind: "not-retained" })),
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Large JSON Lines exports fail

list-procedures <target> --format jsonl now fails when its Evidence exceeds the budget. This branch replaces the Evidence with {summary, delivery}, but prepareJsonLines only accepts arrays at the result, page, or normalized_result. It rejects the wrapper with invalid_request, so the caller receives neither rows nor the delivery advice. Without --evidence_output, nothing was saved either.

Preserve complete delivery for JSON Lines, as for --filter-output, or let the JSON Lines writer emit the summary and delivery facts as a successful result.

Knowledge Base Used: Command-line interface

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/cli/analysisEvidenceDelivery.ts
Line: 187-195

Comment:
**Large JSON Lines exports fail**

`list-procedures <target> --format jsonl` now fails when its Evidence exceeds the budget. This branch replaces the Evidence with `{summary, delivery}`, but `prepareJsonLines` only accepts arrays at the result, `page`, or `normalized_result`. It rejects the wrapper with `invalid_request`, so the caller receives neither rows nor the delivery advice. Without `--evidence_output`, nothing was saved either.

Preserve complete delivery for JSON Lines, as for `--filter-output`, or let the JSON Lines writer emit the summary and delivery facts as a successful result.

**Knowledge Base Used:** [Command-line interface](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fcommand-line-interface.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Codex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

1 participant