Skip to content

fix(browser): account for late script metadata - #6358

Merged
morluto merged 2 commits into
morluto:mainfrom
gongfpp:fix/browser-late-script-inventory-6231
Oct 22, 2026
Merged

morluto merged 2 commits into
morluto:mainfrom
gongfpp:fix/browser-late-script-inventory-6231

Conversation

@gongfpp

@gongfpp gongfpp commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #6231. Keep passive page script metadata/source reads tied to a fixed admitted-script snapshot, and explicitly account for additional in-scope script IDs still retained at the end of capture. Incomplete inventories must not produce a false unchanged script comparison.

Problem and expected behavior

If Debugger.scriptParsed adds a second script while the initial script's source request is pending, the old producer can return scripts.total=2, one retained item, zero dropped scripts, and no script truncation. An identical pair of those incomplete outputs can then compare as unchanged. Scripts arriving during later storage or final-frame reads can also escape accounting entirely.

The fixed producer preserves the initial metadata and selected source-read pass. At the final capture boundary it counts distinct additional IDs still retained, records them as dropped script metadata, and marks scripts truncated. For one late ID the registered MCP workflow now observes total=2, retained items =1, dropped scripts =1, and compare_web_captures reports script status unknown rather than asserting equality.

Change and scope

  • Snapshot the admitted ID-to-metadata map once, retaining the original facts and identity set even if an existing ID is subsequently replaced or removed.
  • Settle newly retained IDs once after the last CDP read/frame validation, before the completeness snapshot. Repeated events for one new ID count once.
  • Do not extend source reads, add CDP commands, or claim source byte/time-budget exhaustion for this omission.
  • Document that this is accounting for final retained IDs, not a claim to reconstruct complete page history.

This is an ordinary correctness fix within the existing passive CDP observation boundary. Maintainer scope decision: not applicable; no new execution, injection, mutation, provider, or protection-recovery capability. Coordination: #6231 (comment) . Nearby #4014 addresses comparison identities, and #6276 addresses when coverage starts; neither supplies this producer snapshot/finalization fix. No directly overlapping public implementation was found in the inspected issue timeline and open-PR search; unpublished work cannot be ruled out.

Follow the contribution scope.
Unresolved scope, authority, side effects, or required verification block
integration. Link the required maintainer scope decision for new providers or
capabilities involving target execution, injection, mutation, or protection
recovery; ordinary fixes within existing boundaries may state "not applicable".
Draft PRs may leave the scope decision pending and the readiness and merge checklists
unchecked. Maintainers can help resolve open questions.

Contract and boundary impact

  • Semantic owner and earliest changed stage: CdpPageCaptureScripts snapshots admitted script metadata before source reads; CdpPageCapture settles final omissions before normalizing completeness.
  • Contribution scope fit and linked maintainer decision: existing passive observation bug fix; not applicable for an additional scope decision.
  • CLI and MCP/tool-catalog contract: unchanged parameters, tools, and schemas. Existing totals, dropped-event counters, truncation, and uncertainty now describe the actual retained snapshot.
  • Provider, bridge, target-format, or platform compatibility: existing CDP provider only; no new dependencies or browser-specific protocol features.
  • Evidence, artifact, provenance, or reconstruction contract: initial source SHA/metadata remain intact; incomplete script evidence stays visibly incomplete. No reconstruction change.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): existing target/origin filtering, source opt-in, cancellation, and detach/socket ownership remain in place; no additional target commands.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs and skills/; edit authored instructions in .agents/skills/reverse-engineer-anything/ and never commit build outputs): no authored catalog, package, lockfile, installation, or release metadata changes; ignored generated artifacts were validated and are not committed.

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.

The changed production path attaches to an explicitly selected CDP target and reads admitted metadata/source; it does not evaluate target JavaScript. Real-browser verification uses owned local fixtures and intentionally exercises the repository's broader existing browser workflows, separate from the authority of this fix.

Evidence and regression coverage

  • Tests added or updated: Ten deterministic cases traverse the real CdpBrowserProvider and registered MCP inspect_web_page / compare_web_captures tools against a fake CDP transport. They cover source-pass, post-source, final-frame, source-disabled, duplicate-ID, shared-metadata/different-ID, foreign-origin, existing-ID replacement, deletion-plus-late-ID, and unchanged controls.
  • Assertions consume actual producer output: total/retained/dropped accounting, truncation, no fabricated resource-budget reason, original source SHA, conservative comparison, no extra source reads, detach and socket closure, and continued MCP responsiveness.
  • Base reproduction or other evidence: Exact affected base 2127095e3b4a377abbc124ca83af46b98a2a557b, with the same regression file copied in: 7 failed, 3 passed. Failures are missing drop accounting or missing final totals. With this fix: 10/10 passed, plus the four existing source-budget/cancellation tests and six existing browser MCP tests (20 passed).
  • The deterministic interleavings are transport-controlled, not represented as a reproduced real-Chrome race. The separate real Chrome verifier is regression/integration evidence for actual browser, CLI, stdio MCP, passive/active capture, script export, cancellation, and cleanup workflows.
  • User-visible CLI/MCP output (if applicable): For the one-late-ID fixture, the actual registered-tool result has scripts.total=2, one retained item, dropped_events.scripts=1, script truncation, and script comparison status unknown. No additional source read is issued.
  • Remaining proof gaps: no exhaustive timing/browser/platform matrix, no Windows/Linux or non-Chromium run, no full repository test suite, and no assertion about unrecoverable events in older stored captures.

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

Original implementation: 46681bb87062d852667681e0d30cce4fecdb120a. Current head: e329736561b647bfd96565d3540a73faebf7412f, merging upstream 791f6328b02a29f23822fe600754fcd228bf754b. The maintainer-owned cancellation assertion fix is now included; no separate JavaScript implementation or duplicate fix was added. Relative to that upstream revision, this PR still contains only the original four browser inventory files.

On macOS, Node 24.18.0, npm 11.16.0, at the current tree:

  • npm run deps:check and npm run check:fast — passed (typecheck/lint also passed the push hook).
  • Focused regression through the existing runner — 154 passed across 6 files: JavaScript artifact reconstruction, JavaScript application cancellation/service, public error projection, CDP script capture, and the 10-case registered-MCP inventory race suite. The previously failing cancellation test now passes.
  • npm run docs:check — generated/document/license checks and all 9 README consistency tests passed.
  • git diff --check and merge-tree identity check — passed; hooks did not change the validated tree.

The two local macOS complete real-browser verifier attempts below did not complete successfully. Current-head Linux real-browser CI subsequently passed (linked below); that does not erase the local macOS limitation. Two complete verifier attempts were made without changing budgets: the first CLI child was killed (the helper has a 60-second cap); the isolated full rerun reached the later module-trace verification and returned provider_timeout at the existing 20000ms server deadline. That rerun had already completed the basic real provider/CLI/stdio-MCP observation, stable source comparison, scenario/storage/service-worker, screenshot, popup, network and script-export stages. The timeout cause is not established; no unrelated timeout or module-trace change has been included. At the original implementation head, the 20 focused tests and complete Chrome 155.0.8059.85 verifier had passed. That earlier result is not claimed as a pass for the current head.

Follow-up isolation check: a separate worktree at exact upstream 791f6328b02a29f23822fe600754fcd228bf754b was installed and built using the normal runners. verifyBrowserModules then passed sequentially on that baseline and current head e329736561b647bfd96565d3540a73faebf7412f, each covering all 8 public CLI/stdio-MCP trace cases, cancellation cleanup, source/map identity and zero implicit refetches. The timeout was not reproduced in these isolated runs; its cause is still unproven, and these isolated passes alone do not establish a complete macOS verifier pass. No timeout budgets or unrelated source were changed.

All npm commands above ran via mise exec [email protected] -- .... Upstream CI and maintainer approval remain separate from these local results.

Upstream CI history and current status

At the previous head 46681bb87062d852667681e0d30cce4fecdb120a, CI run 39817264495 failed on the stale JavaScript reconstruction cancellation assertion. Baseline run 39814960190 had the same expected AnalysisCancelledError versus actual ArtifactOperationError mismatch. Upstream subsequently fixed the assertion while preserving artifact-owned cancellation/provenance; this head merges that fix. At current head e329736561b647bfd96565d3540a73faebf7412f, CI run 39827440624 completed successfully, including CI required, all eight test shards, source tests, static/docs/build checks, portable tests, Linux native package checks and the Linux real-browser verifier. The 19 unselected/skipped lanes are not passing coverage. Superseded/cancelled jobs are not reused as evidence. Human readiness and successful CI request initial review, not maintainer approval or merge permission.

Compatibility, safety, and release

  • Breaking changes or migration steps: no API/schema migration. New incomplete producer outputs truthfully become truncated/unknown; existing stored captures are not retroactively repaired.
  • Real Hopper/Ghidra, browser, or OS coverage: real Chromium-family Chrome on macOS; no Hopper/Ghidra dependency or change.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: keeps target/origin gates, original snapshot provenance, bounded source selection, and cleanup ownership; no new target execution or protection bypass. The snapshot is bounded by the existing admitted metadata retention limit.

Author readiness

Human owner: @gongfpp

AI-assisted contribution. The human owner confirmed review and requested initial maintainer review; automated/static review is not a substitute for those human declarations.

  • 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.

Pin admitted script identities and metadata before selected source reads. After the final CDP read, count unique additional retained IDs as dropped script inventory so incomplete captures stay unknown without extending source reads or inventing budget failures. Cover producer and comparison behavior through registered MCP tools.
@gongfpp
gongfpp marked this pull request as ready for review October 22, 2026 17:22
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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 ⚠️ Failed 2026-10-22T17:59:23.323786Z
We couldn’t complete this review. Comment @codex review to try again.
e329736 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 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The reviewed changes appear safe to merge; no blocking issue was found.

Summary

The PR keeps script metadata and selected source reads tied to one snapshot. Before returning the capture, it counts additional retained script IDs as dropped metadata.

  • Browser captures count late scripts as incomplete evidence.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Snapshot admitted script IDs and metadata] --> B[Read selected sources from snapshot]
  B --> C[Read workers and storage]
  C --> D[Validate final frame]
  D --> E[Count retained IDs outside snapshot]
  E --> F[Record drops and script truncation]
  F --> G[Return capture and completeness]
Loading

Reviews (2) · Last reviewed commit: "chore: sync upstream cancellation assert..." · Reviewed by Greptile

Merge upstream/main at 791f632 to include the maintainer-owned test expectation fix. The contribution relative to upstream remains the original four browser inventory files.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@CassieFox23 CassieFox23 left a comment

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.

TL;DR: Main still has this bug, and I found no problem in the fix itself. CI is green on this head, and the new test file ran and passed in CI. The body leaves out several template parts.

Findings

Should fix

  • The body does not keep the template as written.
    • "Expected effects" has a reworded lead line. The template line "Unchecked items do not establish absence" is gone.
    • In "Evidence and regression coverage", only the "Remaining proof gaps:" label is kept. These labels are gone:
      • "Tests added or updated:"
      • "Base reproduction or other evidence:"
      • "User-visible CLI/MCP output (if applicable):"
    • The "Generated metadata" label is shortened.
    • All eight "Before merge" boxes are unchecked. The template says "Draft PRs may leave pending items unchecked", and this PR is not a draft. Please tick the ones that apply.
    • Please restore the template text.

Nit

  • Line 60 of scriptInventoryRace.test.ts ties the "final" cases to the third Page.getFrameTree read with a bare frameReads === 3. A short comment would say which read that is. The capture may later add or drop a frame read. Then those cases would fire at a different point. I did not check whether they would still pass.

Looks good

  • Main (46217c6) does not have this fix. finalizeScriptInventory and CapturedScriptSnapshot do not exist there, and issue #6231 is still open.
  • The logic reads right. captureScripts copies the script map once. So the delete-and-reinsert in handleScriptParsed cannot make the snapshot smaller. finalizeScriptInventory counts live map keys that are not in the snapshot, so repeated events for one ID count once. The caller runs it right after the last CDP read and before the completeness snapshot. There is no await in between.
  • A downstream reader already treats this as incomplete. scriptsComplete returns false when dropped_events.scripts is above zero. I read this and did not run it.
  • The test file has ten cases, which matches the body. The it.each table covers these cases:
    • late
    • duplicate
    • shared-metadata
    • post-source
    • final-frame
    • source-off
    • foreign-origin
    • replaced-ID
    • deleted-ID
    • the no-late control
  • CI on this head: run 39827440624 has CI required, Static checks, all eight test shards, Source tests, Portable tests and browser / real-browser passing. The run log shows scriptInventoryRace.test.ts passing 10 of 10 in shard 1 of 8 and in Portable tests. Nineteen lanes were skipped by the workflow (I did not check why), including web_runtime, web_network and web_source_map. They are not passing coverage.
  • Greptile scored it 5/5 and left no threads. The Codex review failed on its usage limit, so it gave no result either way. There are no human comments.
  • The docs change matches the code. The new paragraph in browser-observation.md says late IDs count once, do not extend the source pass and do not imply a byte or time budget ran out. Each of those matches the code and the test assertions.
  • Main has moved since the PR's base (791f632). Main also touched one changed file, docs/browser-observation.md (in 7e8ec0e, #4476). A three-way merge of that file has no conflict. The other three files are unchanged on main.

Not run

  • No build and no tests by me. This is a read-only review of the diff against main, and the CI results above are hosted ones.
  • I did not test the merge with main's newer commits. CI ran on the PR's own base, so the combined result is unverified.
  • The base-revision result ("7 failed, 3 passed") is the author's. So are the macOS real-browser verifier runs in the body. I did not rerun them.

Thanks, gongfpp, for the fix. Thanks also for the ten-case test that drives it through the registered tools. And thanks for the clear account of what the macOS runs did and did not show.

Test setup

🤖 Written with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊

@morluto
morluto merged commit 2a3e162 into morluto:main Oct 22, 2026
47 checks passed
@gongfpp

gongfpp commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review and the accurate separation of hosted CI, author-run evidence, and skipped lanes. I have restored the missing template wording and labels, added the explicit representative registered-tool output, and completed the eight applicable author-side pre-merge checklist items from the recorded evidence and the human owner’s review. The ordinary-fix scope decision remains not applicable; these checkboxes do not assert an additional maintainer approval or new platform coverage.

The PR has already been merged, so this update changes the description only; it does not claim a post-merge code/test rerun. I also agree the bare third-frame-read scheduling deserves an explanatory comment. That remains a non-blocking fixture-maintenance suggestion in this review, not a source change being claimed here. The local macOS complete-verifier timeouts, isolated baseline/head passes, and 19 unselected CI lanes remain disclosed.

@morluto morluto added bug Something isn't working area: runtime Process capture and runtime observation labels Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: runtime Process capture and runtime observation bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Source-enabled page inspection counts a late script without returning it or reporting its omission

3 participants