Skip to content

fix(diagnostics): attribute input and refusal failures to their source - #6150

Closed
agorevski wants to merge 1 commit into
morluto:mainfrom
agorevski:fix/input-diagnostics-b
Closed

agorevski wants to merge 1 commit into
morluto:mainfrom
agorevski:fix/input-diagnostics-b

Conversation

@agorevski

@agorevski agorevski commented Oct 21, 2026 •

Copy link
Copy Markdown

Summary

Ten input and diagnostic defects where REA reported the wrong cause, operation, or
recovery for a request it refused or recovered from. Each fix moves the attribution
to the boundary that owns the fact:

Problem and expected behavior

Each case was reproduced or traced in the current base (01788bac8):

  • Native matching parsed deferred Evidence without a request path, so the catch emitted
    an issue with path: []. The CLI bundle loader had the same gap and emitted no
    details.issues.
  • The compare_functions kind gate constructed EvidenceIntegrityError with no side.
  • providerConfigurationRefusal dropped failure.diagnostics, although the error
    options and projection already support them.
  • inspectAdbClient hard-coded inspect_adb_client; readAnalysisSnapshot and the JSON
    readers hard-coded read_evidence_file.
  • environmentStateGate compared counters with ===, excluding strings that countOf
    accepts.
  • #protocolFailure sent every non-resource worker failure, including io, to
    AnalysisOutputError.
  • MarshalSubset returned limit for negative sizes; PyzArchive recovers only format.
  • list-electron-targets gated the environment on "target" in result, which list
    results lack.
  • layout_impl.py omitted OverflowError from the structural-parse tuple.

Change and scope

Each change is local to the owning boundary, with no new contracts, providers, or
process launches:

  • Shared helper malformedInlineEvidence in NativeMatchingBundleSources.ts is used by
    the loader root loop and the MCP-path resolve.
  • The operation is threaded explicitly through readAnalysisSnapshot (new optional
    parameter defaulting to read_evidence_file) and readJsonObjectMembersFile.
  • renderStateList keeps a string counter as a string, so the gate's
    same(render(...), body) check still accepts digit-string totals.

Not included: no tool schema or Evidence shape change; no change to ADB, Apktool, or
pwntools launch behavior; no unrelated cleanup. One new max-params warning is
introduced in src/application/JsonFiles.ts (warning only; the operation parameter must
reach the cancellation site).

Contribution scope: not applicable. These are fixes within existing boundaries.

Contract and boundary impact

  • Semantic owner and earliest changed stage: each fix is at its producing boundary (the
    native input parser and bundle loader, the function-comparison input gate, the ADB and
    Apktool configuration projection, the snapshot reader, the JavaScript worker protocol
    mapping, the PYZ marshal classifier, the environment-state gate, the Electron evidence
    projection, and the pwntools bridge classifier).
  • Contribution scope fit and linked maintainer decision: not applicable (existing
    boundaries).
  • CLI and MCP/tool-catalog contract: no schema change. Error codes and details change
    as described under Compatibility.
  • Provider, bridge, target-format, or platform compatibility: pwntools bridge (Python,
    Linux x64). Other providers are unchanged apart from the refusal diagnostics above.
  • Evidence, artifact, provenance, or reconstruction contract: Evidence shape unchanged.
    Electron target-list Evidence now carries the same environment and limitation fields
    that inspect Evidence already carries.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable):
    not applicable. Cleanup and ownership paths are untouched.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact:
    none. No generated catalogs, skills, or dependency manifests are edited.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

Evidence type: executed tests and base-revision reproductions. Source-derived conclusions
are noted where a test was not run.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

Merge follow-up: main was merged into the branch (f2a0da223) to resolve conflicts in src/application/JsonFiles.ts and src/javascript/analysis/JavaScriptAnalysisWorker.ts. After the merge:

  • node scripts/run-typescript.mjs --noEmit — exit 0.
  • npm run test:focused -- <12 files covering the changed boundaries> — 12 files, 164 passed, 2 skipped.
  • npx oxlint on the two conflicted files — 0 errors; warnings only.
  • npx oxfmt --check on the two conflicted files — formatted.
  • Not run: the full suite.

Earlier validation (before the merge):

Each entry lists a command that ran and its observed result. Run in the worktree on Node
v22.23.1 (within engines).

  • npm run build:cached — exit 0 (rebuilt several times, including from base source for
    the CLI and stdio-MCP base runs; final dist is from the fixed tree).
  • npx vitest run src/artifacts/pyinstaller/MarshalSubset.test.ts src/domain/analysisView/environmentStateView.test.ts src/adb/AdbVersionProbe.test.ts tests/boundary/providers/adb/adbCommandFinalization.test.ts tests/boundary/filesystem/analysisSnapshotInput.test.ts tests/process-global/apktoolEnvironment.test.ts tests/boundary/mcp/functionComparisonReferenceFactsMcp.test.ts tests/boundary/cli/electronCli.test.ts tests/boundary/javascript/javascriptSourceAnalysisWorker.test.ts tests/acceptance/tools/nativeFunctionMatching.test.ts --maxWorkers 2 — 10 files, 115 tests passed.
  • REA_PWNTOOLS_PYTHON=<local pwntools 4.15.0 venv>/bin/python npx vitest run tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts — 35 passed, 1 skipped (unsupported-host case).
  • npx vitest run tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts (no runtime configured) — 34 passed, 2 skipped.
  • Base-reproduction runs (each failed on base, as listed above) — 10 of 10 failed on base.
  • npm run typecheck — exit 0.
  • npx oxlint <27 changed files> — exit 0, 0 errors; pre-existing warnings plus one new max-params warning in src/application/JsonFiles.ts.
  • npx oxfmt --check <27 changed files> — exit 0.
  • Commit pre-commit hook (lint-staged) — exit 0.
  • Manual CLI spot checks with the built runtime: list-adb-devices --json (unrecognized launcher) and match-native-functions with malformed left both returned the expected details shown above.

Not run: the full test suite, npm run check:pr, and any real-provider workflow.

Compatibility, safety, and release

  • Breaking changes or migration steps: none to tool schemas or Evidence shape. Caller-visible
    error changes:
    • compare_functions wrong-kind Evidence: invalid_request with per-side issues
      (previously evidence_integrity_mismatch).
    • JavaScript worker I/O failure: execution_failure (previously unreadable_output).
    • PYZ with negative counts or lengths: left opaque, so sibling inventory is delivered
      (previously the whole artifact failed with truncated/limit).
    • Electron target-list Evidence: now includes environment and limitation fields.
    • Capability refusals for ADB and Apktool: now include details.diagnostics.
    • Environment-state list views: digit-string totals now count as counters.
      Internal signatures changed: inspectAdbClient (adds operation), readAnalysisSnapshot
      (optional trailing operation), readJsonObjectMembersFile (adds operation).
  • Real Hopper/Ghidra, browser, or OS coverage: not run. Linux x64 only for the pwntools
    gated case.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no new process launches, target
    access, or network access. The JavaScript worker I/O diagnostic carries the source path and
    the worker's I/O message, text that was previously embedded in the output error message.
    Other redaction is unchanged.

Author readiness

Human owner: @agorevski

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

@agorevski
agorevski marked this pull request as ready for review October 21, 2026 20:31
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T18:29:39.469712Z d1f1f63 New commits
ℹ️ 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.

@greptile-apps

greptile-apps Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5 Tier: apex

[Medium impact] The PR changes diagnostics and Evidence behavior across several bounded REA workflows.

Fix the incorrect totals in paged state replies before merging; the other two findings are non-blocking.

Findings

  1. P1 Paged lists report wrong totals ▶
  2. P2 Inline comparisons repeat expensive checks ▶
  3. P2 Cleanup hides worker read failures ▶
Fix with agent prompt
### Issue 1
src/domain/analysisView/environmentStateRules.ts:663-665
A new paged query can report the page length as the full total. Capture `/api/items` with three items and `total: "03"`, followed by `?limit=1` with one item and the same total. A later `limit=2` call can select the first recorded response. This branch changes its total to `"2"`. `renderQueryList` cannot restore 3 because `queryTotalCount` rejects padded strings.

Previously, `"03"` stayed unchanged. Clients can now stop paging before fetching the last item. Keep unsupported query totals out of page counters, or teach the query renderer how to update them.

### Issue 2
src/server/registerFunctionComparisonTool.ts:47-50
Successful inline comparisons now authenticate each Evidence record twice. These new `readEvidence` calls copy and hash the payload, but the later `parseFunctionEvidence` calls still receive `resolved.value.left` and `resolved.value.right` and repeat that work.

Large function dossiers therefore get another full copy and hash on the server's main thread, delaying other requests. Parse each side once and reuse the result for the kind checks and comparison.

### Issue 3
src/javascript/analysis/JavaScriptAnalysisWorker.ts:1065-1068
The new I/O details disappear if worker cleanup also fails. `analyze` then returns `#cleanupError`, whose `execution_failure` keeps only `original.message` and captured output-not `original.diagnostics`. The new `ProviderAdapterError.message` is generic, so the returned `cleanup_incomplete` error loses the source path, phase, and I/O message.

Previously, those details survived inside `AnalysisOutputError.message`. Preserve the original error's details when building the cleanup error so users can still tell which read failed.

---

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

Summary

Improves input errors, operation names, provider diagnostics, and Evidence metadata across existing CLI and MCP paths.

  • Native matching issues name the field that contains malformed Evidence.
  • Function comparisons report which side has the wrong kind of Evidence.
  • ADB probe errors name the operation that requested the version check.
  • ADB and Apktool capability refusals retain their version-probe diagnostics.
  • Snapshot read cancellations name the operation that requested the read.
  • JavaScript worker I/O failures identify the source read that failed.
  • Electron target-list Evidence includes the browser environment and host limitation.
  • Environment-state lists recognize digit-string totals as counters.
  • PYZ tests distinguish malformed sizes from resource limits.
  • ELF structural parsing treats overflowing offsets as format failures.

Validation was source review plus git diff --check; tests were not run. Supersession status could not be checked without GitHub authentication.

Reviews (3) · Last reviewed commit: "fix(diagnostics): attribute input and re..." · Reviewed by Greptile

Make failures name the request field, operation, or provider diagnostic
that caused them, and classify malformed-but-recoverable data correctly.

- Name the malformed inline Evidence field for match_native_functions on
  the MCP and CLI bundle paths, including observation indexes.
- Report wrong-kind compare_functions Evidence per side as input issues.
- Forward ADB and Apktool version-probe diagnostics into capability
  refusals.
- Attribute ADB version-probe limits and snapshot-read cancellation to the
  requesting operation.
- Map JavaScript worker I/O failure frames to ProviderAdapterError with
  source path, phase, and I/O message.
- Count digit-string list totals in environment-state list views.
- Treat negative PYZ marshal sizes as format failures so the opaque PYZ
  recovery applies.
- Report the browser environment limitation for Electron target lists.
- Treat an overflowing ELF program-header offset in the pwntools bridge as
  a format failure.

Fixes #5716
Fixes #5917
Fixes #5932
Fixes #5950
Fixes #5968
Fixes #5974
Fixes #5981
Fixes #6094
Fixes #6114
Fixes #6120
@agorevski
agorevski force-pushed the fix/input-diagnostics-b branch from 3b942bc to d1f1f63 Compare October 23, 2026 18:22

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d1f1f63118

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +70 to +72
...input.left_observations.map(
(value, position) => [["left_observations", position], value] as const,
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Stream observation roots instead of expanding them

For requests with a large left_observations or right_observations array, these eager maps allocate a tuple and a separate path array for every element before the first root is examined, even if left itself is invalid. NativeMatchingAdmission has charged only the input representation, not this expanded object graph, so a request near the 96-MiB allowance can exceed the advertised memory bound and OOM instead of returning the typed input/resource failure; yield each (path, value) pair lazily or explicitly charge this expansion.

AGENTS.md reference: AGENTS.md:L81-L81

Useful? React with 👍 / 👎.

Comment on lines +47 to +50
const leftRead = readEvidence(resolved.value.left);
if (!leftRead.ok)
return server.delivery.toCallToolResult(leftRead, contract);
const rightRead = readEvidence(resolved.value.right);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reuse authenticated Evidence in comparison

When compare_functions receives large inline analyze_function Evidence, each new readEvidence call traverses the full record and recomputes its canonical evidence ID, but the callback later passes the original values to parseFunctionEvidence, which calls readEvidence again. Inline contract values are not immutable cache entries, so successful comparisons now validate, hash, and copy both dossiers twice, adding avoidable CPU, memory, and synchronous work before runDerivedOperation's cancellation yield; parse each side once and reuse the resulting authenticated snapshot for both the kind check and comparison.

AGENTS.md reference: AGENTS.md:L53-L54

Useful? React with 👍 / 👎.

Comment on lines +663 to +665
return Number(recorded) === items.length
? body
: replaceAt(body, pointerTo(name), String(items.length));

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 Paged lists report wrong totals

A new paged query can report the page length as the full total. Capture /api/items with three items and total: "03", followed by ?limit=1 with one item and the same total. A later limit=2 call can select the first recorded response. This branch changes its total to "2". renderQueryList cannot restore 3 because queryTotalCount rejects padded strings.

Previously, "03" stayed unchanged. Clients can now stop paging before fetching the last item. Keep unsupported query totals out of page counters, or teach the query renderer how to update them.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/analysisView/environmentStateRules.ts
Line: 663-665

Comment:
**Paged lists report wrong totals**

A new paged query can report the page length as the full total. Capture `/api/items` with three items and `total: "03"`, followed by `?limit=1` with one item and the same total. A later `limit=2` call can select the first recorded response. This branch changes its total to `"2"`. `renderQueryList` cannot restore 3 because `queryTotalCount` rejects padded strings.

Previously, `"03"` stayed unchanged. Clients can now stop paging before fetching the last item. Keep unsupported query totals out of page counters, or teach the query renderer how to update them.

---

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

Comment on lines +47 to +50
const leftRead = readEvidence(resolved.value.left);
if (!leftRead.ok)
return server.delivery.toCallToolResult(leftRead, contract);
const rightRead = readEvidence(resolved.value.right);

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 Inline comparisons repeat expensive checks

Successful inline comparisons now authenticate each Evidence record twice. These new readEvidence calls copy and hash the payload, but the later parseFunctionEvidence calls still receive resolved.value.left and resolved.value.right and repeat that work.

Large function dossiers therefore get another full copy and hash on the server's main thread, delaying other requests. Parse each side once and reuse the result for the kind checks and comparison.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/server/registerFunctionComparisonTool.ts
Line: 47-50

Comment:
**Inline comparisons repeat expensive checks**

Successful inline comparisons now authenticate each Evidence record twice. These new `readEvidence` calls copy and hash the payload, but the later `parseFunctionEvidence` calls still receive `resolved.value.left` and `resolved.value.right` and repeat that work.

Large function dossiers therefore get another full copy and hash on the server's main thread, delaying other requests. Parse each side once and reuse the result for the kind checks and comparison.

---

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

Comment on lines +1065 to +1068
diagnostics: {
source_path: path,
phase,
io_message: response.message,

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 Cleanup hides worker read failures

The new I/O details disappear if worker cleanup also fails. analyze then returns #cleanupError, whose execution_failure keeps only original.message and captured output—not original.diagnostics. The new ProviderAdapterError.message is generic, so the returned cleanup_incomplete error loses the source path, phase, and I/O message.

Previously, those details survived inside AnalysisOutputError.message. Preserve the original error's details when building the cleanup error so users can still tell which read failed.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/javascript/analysis/JavaScriptAnalysisWorker.ts
Line: 1065-1068

Comment:
**Cleanup hides worker read failures**

The new I/O details disappear if worker cleanup also fails. `analyze` then returns `#cleanupError`, whose `execution_failure` keeps only `original.message` and captured output—not `original.diagnostics`. The new `ProviderAdapterError.message` is generic, so the returned `cleanup_incomplete` error loses the source path, phase, and I/O message.

Previously, those details survived inside `AnalysisOutputError.message`. Preserve the original error's details when building the cleanup error so users can still tell which read failed.

---

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

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