Skip to content

fix(emergent): bound what QuickJSExecutor copies out of the guest - #168

Merged
jddunn merged 1 commit into
masterfrom
fix/quickjs-review-findings
Oct 8, 2026
Merged

jddunn merged 1 commit into
masterfrom
fix/quickjs-review-findings

Conversation

@jddunn

@jddunn jddunn commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #160 (the QuickJS executor), from its review.

What changes

  • Reads out of the guest are bounded. A host function's argument is read with a bound: a string's length is read before it is copied (a primitive string's length is its own, whatever the guest did to String.prototype), and any other value crosses as its JSON, made in the guest by a JSON.stringify captured before guest code runs. What one call hands the host counts against its memory budget, two bytes a character; past it the host function throws RangeError. Before this, install() copied each argument with dump(), so a guest could make the host copy up to about its whole memory on every call of a host function.
  • A thrown value is reported by its message, cut in the guest at 16,384 characters; a result is read only as the JSON text the wrapper makes (a forged tool that replaces JSON.stringify gets an error instead of an unbounded copy).
  • timeoutMs that is NaN, infinite or not positive is refused: the interrupt handler compares the clock with a deadline such a value never brings. The wait between pumps stays under Node's longest timer.
  • dispose() drops the call's WebAssembly.Memory. A host promise still settling after the call (a read without a ceiling has no abort) kept the run, and with it the memory, reachable.
  • Request bodies. The prelude's fetch sends bytes as bytes, URLSearchParams as form text with the form content type when none is named, and any other body as its string, as fetch reads a body. It dropped every body that was not a string. Under a ceiling the broker still sends GET and HEAD only.
  • GUEST_PRELUDE has its own TSDoc.
  • docs/architecture/EMERGENT_CAPABILITIES.md: the two new bounds in the limits table and the executor section, the body rule, the timeout rule.

Tests

tests/emergent/quickjs-executor.integration.spec.ts, new block "what the guest hands the host": the argument budget (eight copies of a four-million-character path fit a 64 MB call, the ninth is refused), the cut thrown message, the result that is not JSON text, four bad timeouts, and the four body types reaching the host's fetch. The dropped memory has no test: the run is internal and the drop shows only to a garbage collector.

🤖 Generated with Claude Code

Summary by Sourcery

Bound QuickJS guest-to-host data transfer and harden executor lifecycle, timeout, result, error, and fetch handling.

Bug Fixes:

  • Bound data copied from QuickJS guest arguments and cap reported thrown-value text to prevent unbounded host-side copying.
  • Reject non-positive, non-finite execution timeouts and release WebAssembly memory when a guest run is disposed.
  • Preserve fetch request bodies across strings, bytes, URLSearchParams, and other body values, including form content types.

Enhancements:

  • Make QuickJS results cross the boundary only through captured JSON serialization and harden guest helpers against guest overrides.

Documentation:

  • Document QuickJS host-data and thrown-text limits, timeout validation, and request-body handling.

Tests:

  • Add integration coverage for host argument budgets, truncated errors, invalid timeouts, JSON-only results, and fetch body types.

Chores:

  • Add dedicated TSDoc for the guest prelude.

Review of #160 found host copies of guest data with no bound, and three
smaller defects in the executor.

- A binding's argument is read with a bound: a string's length first,
  any other value as its JSON, made in the guest by a JSON.stringify
  taken before guest code runs. What one call hands the host counts
  against its memory budget, two bytes a character; past it the binding
  throws RangeError.
- A thrown value is reported by its message, cut in the guest at 16,384
  characters, and a result is read only as the wrapper's JSON text.
- run() refuses a timeoutMs that is not a positive finite number, which
  the interrupt handler could never reach, and the wait between pumps is
  held under Node's longest timer.
- dispose() drops the call's WebAssembly.Memory, so a host promise that
  settles late keeps none of it.
- The prelude's fetch sends bytes, URLSearchParams (with the form
  content type) and any other body as fetch reads them, instead of
  dropping every body that is not a string.
- GUEST_PRELUDE has its own TSDoc.
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 8, 2026 19:01
@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.

@sourcery-ai

sourcery-ai Bot commented Oct 8, 2026

Copy link
Copy Markdown

Sorry @jddunn, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 1 day and 11 hours by commenting @sourcery-ai review. Upgrade to get a review now.

@coderabbitai

coderabbitai Bot commented Oct 8, 2026

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 5 billable files and costs up to $1.25.

  • Ask an admin to make reviews automatic

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Or wait 6 minutes for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Repository: framerslab/agentos/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Team
  • Run ID: 6bb2fe7d-9175-46ee-8828-6a55d5f700bc
📥 Commits

Reviewing files that changed from the base of the PR and between b9c2e91 and 943627c.

📒 Files selected for processing (5)
  • docs/architecture/EMERGENT_CAPABILITIES.md
  • src/cognition/emergent/executor/QuickJSExecutor.ts
  • src/cognition/emergent/executor/guest-prelude.ts
  • src/cognition/emergent/executor/guest-surface.ts
  • tests/emergent/quickjs-executor.integration.spec.ts
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 8, 2026

Copy link
Copy Markdown

Reviewer's Guide

The QuickJS executor now bounds and controls every guest-to-host copy using captured guest helpers, validates deadlines, releases guest memory on disposal, and restores fetch body conversions, with corresponding documentation and integration tests.

Sequence diagram for bounded QuickJS guest-to-host data transfer

sequenceDiagram
    participant Guest as QuickJS guest
    participant Executor as QuickJSExecutor
    participant Binding as Host binding
    participant Host as Host service

    Guest->>Binding: invoke host function
    Binding->>Executor: take(argument)
    alt string argument
        Executor->>Executor: readString(length)
    else other data argument
        Executor->>Guest: captured JSON.stringify(value)
        Guest-->>Executor: JSON text
        Executor->>Executor: readString(json)
    end
    alt memory budget exceeded
        Executor-->>Guest: RangeError
    else within budget
        Executor->>Host: call with bounded data
        Host-->>Executor: result
        Executor-->>Guest: resolved value
    end
Loading

Sequence diagram for QuickJS result and thrown-value boundaries

sequenceDiagram
    participant Guest as QuickJS guest
    participant Executor as QuickJSExecutor
    participant Host as Host runtime

    Guest->>Host: execute forged code
    alt code returns
        Host->>Guest: wrapper result as JSON text
        Guest-->>Executor: JSON string or undefined
        Executor->>Executor: readResult()
        alt result is not JSON text
            Executor-->>Guest: execution error
        else valid JSON text
            Executor-->>Guest: parsed result
        end
    else code throws
        Host->>Guest: thrown value
        Guest->>Guest: captured message/String and cut at 16,384 characters
        Guest-->>Executor: bounded error text
        Executor-->>Guest: execution error
    end
Loading

State diagram for QuickJS executor call validation and disposal

stateDiagram-v2
    [*] --> ValidateTimeout
    ValidateTimeout --> Rejected: timeoutMs not positive finite
    ValidateTimeout --> Running: timeoutMs valid
    Running --> Completed: result or error read
    Running --> Interrupted: deadline or abort signal
    Running --> Disposed: dispose()
    Completed --> Disposed
    Interrupted --> Disposed
    Disposed --> MemoryReleased: drop context, runtime, WebAssembly.Memory
    Rejected --> [*]
    MemoryReleased --> [*]
Loading

Flow diagram for QuickJS fetch body conversion

flowchart LR
    Input[Guest fetch body] --> Kind{Body type}
    Kind -->|string| Text[Send as text]
    Kind -->|ArrayBuffer or view| Bytes[Convert to bytes]
    Kind -->|URLSearchParams| Form[Send form text]
    Kind -->|other non-null value| Stringify[String body value]
    Form --> Header[Add form content type if absent]
    Text --> Broker[Host fetch broker]
    Bytes --> Broker
    Header --> Broker
    Stringify --> Broker
Loading

File-Level Changes

Change Details Files
Bound and hardened all data copied from QuickJS into the host.
  • Capture guest intrinsics before forged code runs for JSON serialization, allocation, and bounded thrown-value text.
  • Replace unbounded argument dumping with type-aware, memory-budgeted string/JSON conversion and RangeError reporting.
  • Restrict result extraction to wrapper-produced JSON text and bound thrown messages to 16,384 characters.
  • Release the WebAssembly memory reference during disposal, including after outstanding host promises settle.
src/cognition/emergent/executor/QuickJSExecutor.ts
Validated timeout inputs and made deadline pumping safe for long durations.
  • Reject NaN, infinite, zero, and negative timeout values before loading or executing the guest.
  • Clamp pump wait timers to Node's maximum supported timer delay.
src/cognition/emergent/executor/QuickJSExecutor.ts
Preserved fetch body semantics across the guest/host boundary.
  • Forward strings directly, byte buffers as latin1-backed bytes, URLSearchParams as form text with a default content type, and other bodies via string conversion.
  • Convert byte-body transport back to a host Buffer while retaining request options and abort signals.
src/cognition/emergent/executor/guest-prelude.ts
src/cognition/emergent/executor/guest-surface.ts
Expanded documentation and integration coverage for the new boundary guarantees.
  • Document argument and thrown-text limits, timeout validation, fetch body rules, and lifecycle behavior.
  • Add tests for argument budgets, bounded errors, forged JSON.stringify results, invalid timeouts, and all supported body types.
  • Add TSDoc describing the guest prelude.
docs/architecture/EMERGENT_CAPABILITIES.md
src/cognition/emergent/executor/guest-prelude.ts
tests/emergent/quickjs-executor.integration.spec.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Summary by Qodo

Bound QuickJS guest-to-host copies and correct fetch body handling

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Bound cumulative guest-to-host arguments and thrown messages; reject non-JSON results without
 copying them.
• Reject invalid timeouts, cap timer waits, and release guest memory after calls.
• Preserve fetch body types and document and test the executor's bounds.
Diagram

graph TD
  G["Forged code"] --> P["Guest prelude"] --> B["Host bindings"] --> R["Bounded reads"] --> S["Guest surface"] --> H["Host capabilities"]
  G --> O["Result reader"]
  C["Captured helpers"] --> R
  C --> O
Loading
High-Level Assessment

The cumulative per-call budget is appropriate: a per-argument limit would still allow repeated large copies. Capturing guest intrinsics before forged code runs preserves the existing binding design without introducing a new transport protocol.

Files changed (5) +325 / -40

Bug fix (3) +228 / -38
QuickJSExecutor.tsBound guest reads and harden call lifecycle +200/-35

Bound guest reads and harden call lifecycle

• Captures guest serialization and error-description helpers before forged code runs, budgets arguments across host calls, truncates thrown messages, and refuses non-stringified results. Validates timeouts, caps timer delays, and drops the call's WebAssembly memory reference on disposal.

src/cognition/emergent/executor/QuickJSExecutor.ts

guest-prelude.tsPreserve non-string fetch request bodies +21/-1

Preserve non-string fetch request bodies

• Transports byte bodies as bytes, serializes URLSearchParams with a default form content type, and stringifies other supported bodies instead of dropping them. Adds TSDoc for the prelude source.

src/cognition/emergent/executor/guest-prelude.ts

guest-surface.tsRestore byte bodies before calling host fetch +7/-2

Restore byte bodies before calling host fetch

• Decodes the prelude's latin1 byte-body transport into a Buffer and passes the resulting options to the granted fetch function.

src/cognition/emergent/executor/guest-surface.ts

Tests (1) +93 / -0
quickjs-executor.integration.spec.tsCover guest-to-host bounds and fetch body transport +93/-0

Cover guest-to-host bounds and fetch body transport

• Tests cumulative argument accounting, truncated thrown messages, rejection of non-JSON-text results, and invalid timeouts. Verifies byte, form, string, and other stringified bodies reach host fetch.

tests/emergent/quickjs-executor.integration.spec.ts

Documentation (1) +4 / -2
EMERGENT_CAPABILITIES.mdDocument QuickJS transfer bounds and fetch body rules +4/-2

Document QuickJS transfer bounds and fetch body rules

• Adds the cumulative guest-to-host argument budget and thrown-message limit to the limits table and executor guidance. Clarifies fetch body conversion and invalid-timeout rejection.

docs/architecture/EMERGENT_CAPABILITIES.md

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Long-running tools hit a lifetime cap on host calls 🐞 Bug ≡ Correctness
Description
readString adds every argument's size to this.handed and never takes it back, so handLimit
(the memory budget) caps the total data passed to all host functions over the whole call. That data
is freed as soon as each call returns, so this caps throughput, not memory. The prelude sends whole
bodies through host functions: Response.text()/json() pass the body as latin1 to text_decode,
and crypto_update sends bytes as JSON, which escapes control bytes to six characters each. As a
result, a call that reads two 20 MB responses under a 64 MB budget, decodes one response over 32 MB,
hashes a few MB of zero bytes, or runs a million localeCompare calls in a sort now gets
RangeError, even though the response-body budget allowed the fetches and no memory was ever held.
Code

src/cognition/emergent/executor/QuickJSExecutor.ts[R601-604]

+    const bytes = counted ? 2 * length : 0;
+    if (bytes > this.handLimit - this.handed) {
+      throw new RangeError(`the data this call handed the host passed its limit of ${Math.round(this.handLimit / MIB)} MB`);
+    }
Evidence
readString checks bytes > this.handLimit - this.handed and does this.handed += bytes on every
counted read, and nothing ever lowers handed. take sends every binding argument through
readString, either directly or as JSON. The prelude calls `host.text_decode(...,
bytesToLatin1(this._take())) for Response.text, host.crypto_update(id, { b: bytesToLatin1(...) })`
for hash updates (an object, so it crosses as JSON with control-character escaping), and
host.intl_compare(String(this), String(that), ...) for each localeCompare. The fetch body budget
in guest-surface already allows memoryMB of response bytes, but decoding them costs 2x against the
new cap.

src/cognition/emergent/executor/QuickJSExecutor.ts[596-615]
src/cognition/emergent/executor/QuickJSExecutor.ts[558-587]
src/cognition/emergent/executor/guest-prelude.ts[438-438]
src/cognition/emergent/executor/guest-prelude.ts[510-517]
src/cognition/emergent/executor/guest-prelude.ts[370-370]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`GuestRun.readString` adds each host-function argument's size to `this.handed` and never subtracts it. The memory budget therefore caps the total data passed to host functions over the whole call, even though each copy is freed once the binding returns. Ordinary tools fail with RangeError: ones that decode responses (`Response.text()` passes the whole body), hash binary data (JSON escaping makes it larger) or call Intl/localeCompare many times.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[596-615]
- src/cognition/emergent/executor/QuickJSExecutor.ts[517-529]
## Recommended Fix
Bound what a single host-function invocation copies, not the running total. Reset `handed` to 0 at the start of each `install` callback, before `args.map(take)`, so the limit applies to the sum of one call's arguments. Another option is to add the bytes back once the binding's synchronous part has returned. Update the docs table and the integration test to match (for example, a single argument larger than the budget is refused).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can keep summaries lean with Findings visible per group, which tucks the rest behind a View link

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment on lines +601 to +604
const bytes = counted ? 2 * length : 0;
if (bytes > this.handLimit - this.handed) {
throw new RangeError(`the data this call handed the host passed its limit of ${Math.round(this.handLimit / MIB)} MB`);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

1. Long-running tools hit a lifetime cap on host calls 🐞 Bug ≡ Correctness

readString adds every argument's size to this.handed and never takes it back, so handLimit
(the memory budget) caps the total data passed to all host functions over the whole call. That data
is freed as soon as each call returns, so this caps throughput, not memory. The prelude sends whole
bodies through host functions: Response.text()/json() pass the body as latin1 to text_decode,
and crypto_update sends bytes as JSON, which escapes control bytes to six characters each. As a
result, a call that reads two 20 MB responses under a 64 MB budget, decodes one response over 32 MB,
hashes a few MB of zero bytes, or runs a million localeCompare calls in a sort now gets
RangeError, even though the response-body budget allowed the fetches and no memory was ever held.
Agent Prompt
## Issue description
`GuestRun.readString` adds each host-function argument's size to `this.handed` and never subtracts it. The memory budget therefore caps the total data passed to host functions over the whole call, even though each copy is freed once the binding returns. Ordinary tools fail with RangeError: ones that decode responses (`Response.text()` passes the whole body), hash binary data (JSON escaping makes it larger) or call Intl/localeCompare many times.

## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[596-615]
- src/cognition/emergent/executor/QuickJSExecutor.ts[517-529]

## Recommended Fix
Bound what a single host-function invocation copies, not the running total. Reset `handed` to 0 at the start of each `install` callback, before `args.map(take)`, so the limit applies to the sum of one call's arguments. Another option is to add the bytes back once the binding's synchronous part has returned. Update the docs table and the integration test to match (for example, a single argument larger than the budget is refused).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@jddunn
jddunn merged commit 5dd510e into master Oct 8, 2026
6 checks passed
@jddunn
jddunn deleted the fix/quickjs-review-findings branch October 8, 2026 19:06
github-actions Bot pushed a commit that referenced this pull request Oct 8, 2026
## [0.13.1](v0.13.0...v0.13.1) (2026-10-08)

### fix

* **emergent:** bound what QuickJSExecutor copies out of the guest (#168) ([5dd510e](5dd510e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant