Skip to content

feat(emergent): QuickJSExecutor, an isolating executor for forged code - #160

Merged
jddunn merged 9 commits into
masterfrom
feat/quickjs-executor
Oct 8, 2026
Merged

jddunn merged 9 commits into
masterfrom
feat/quickjs-executor

Conversation

@jddunn

@jddunn jddunn commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

What this changes

  • QuickJSExecutor, a second executor for forged code: QuickJS compiled to WebAssembly, a new instance for each call on a WebAssembly.Memory capped at the call's memoryMB (never below 16 MiB, never above 2,048 MiB). It declares isolates: true. Its engine comes from two optional peer dependencies, quickjs-emscripten-core and @jitl/quickjs-wasmfile-release-sync, both pinned at 0.32.0; a host that never builds the executor installs neither, and one that builds it without them, or with another version, gets quickjs_unavailable naming both (await QuickJSExecutor.create() fails fast; new QuickJSExecutor() fails at its first call).
  • What crosses into the guest: host functions that take and return data, under a prelude that builds what the in-process context hands forged code (fetch, fs.readFile, crypto, TextEncoder, TextDecoder, URL, URLSearchParams, structuredClone, atob, btoa, a console that discards), Intl and the locale methods formatted by the host, and the refusal of string code generation the in-process context applies.
  • Per-call bounds beside memoryMB and the deadline: the result at 1 MB of UTF-8; response bodies together at memoryMB; 64 open hashes; 16 host calls in flight. A host value that does not fit what the guest has left ends the call memory_exceeded. Without a ceiling, the call's requests are aborted when it ends.
  • emergentConfig.executor picks the executor of the forge the engine builds; absent, nothing changes. A host-built sandboxForge on another executor passed beside it fails construction with executor_conflict. ForgedCodeExecutor gains an optional ready(): the engine awaits it before a forge's test cases, so a forge on an executor that cannot load is refused with its reason before any test or review. Exported: QuickJSExecutor, QuickJSUnavailableError, QUICKJS_VERSION.
  • Documentation and CI: the Executors section compares the two executors and says what the isolation claim rests on; README no longer calls the in-process context hardened, and the word check covers README and the self-extension page. A CI step runs the executor from the built package.
  • For hosts that change nothing: no behaviour changes. The two packages are optional peers pinned at 0.32.0, so a project that already holds either at another version gets npm's peer conflict at its next install.
  • The evidence run is retired: its prototype is replaced by the shipped executor, and the main suite now runs what it measured.

Tests

  • tests/emergent/quickjs-executor.integration.spec.ts: the forged-tool corpus (61 fixtures, each to the expectation it meets in-process), the memory bound (at the cap, growth to the budget, the 16 MiB floor, a host value that does not fit), six ways to spin stopped at the deadline, the stack (in the guest, in a built-in), escape probes past the forge's validation (no host global, string code generation refused through nine routes, prototype changes kept in the guest, inputs copied, no state across calls), the bindings' bounds (bodies, calls in flight, the abort at the call's end, open hashes, large host values copied exactly) and Intl parity with the in-process context.
  • tests/emergent/quickjs-unavailable.integration.spec.ts: quickjs_unavailable without the packages.
  • src/cognition/emergent/__tests__/quickjs-engine.integration.test.ts: a tool forged through forge_tool and called through processToolCall runs on emergentConfig.executor, at forge time and at call time; executor_conflict; a forge on an executor that cannot run is refused before its tests and its review.
  • Every existing emergent test passes unchanged.

🤖 Generated with Claude Code

Summary by Sourcery

Add an optional, per-call QuickJS WebAssembly executor for isolated and resource-bounded forged-code execution while retaining the in-process executor by default.

New Features:

  • Add an optional QuickJS WebAssembly executor that runs forged code in a fresh isolated instance for each call with enforced memory, timeout, stack, output, host-call, response-body, and hashing limits.
  • Allow emergent configuration and host-built forges to select the executor, including readiness checks and conflict validation.

Bug Fixes:

  • Ensure unavailable or incompatible QuickJS dependencies fail clearly before forge tests, reviews, or execution.

Enhancements:

  • Expose the executor and availability error publicly while preserving the existing in-process executor as the default.
  • Provide a QuickJS guest environment matching the documented forged-code APIs, including capability bindings, standard web utilities, crypto, and host-formatted Intl behavior.
  • Replace the executor evidence prototype with the shipped implementation and its main integration coverage.

Build:

  • Add the pinned optional QuickJS peer and development dependencies.

CI:

  • Run the QuickJS executor from the built package in CI and extend isolation-claim checks to the executor sources and documentation.

Documentation:

  • Document the two executor options, their isolation and resource guarantees, configuration, dependency requirements, and limitations; stop describing the in-process context as hardened.

Tests:

  • Add comprehensive QuickJS integration tests covering the forged-tool corpus, isolation, resource limits, bindings, deadlines, dependency failures, engine integration, and Intl parity.

Chores:

  • Remove the retired executor evidence implementation and workflow.

jddunn added 3 commits October 8, 2026 10:59
Both packages pinned exactly, as peers marked optional and as dev dependencies for the executor's tests. A host that never builds a QuickJS executor installs neither.
…tance of its own for each call

QuickJS compiled to WebAssembly from two optional peers, the variant compiled once and instantiated for every call on a memory capped at the call's memoryMB. Granted functions cross as host functions that take and return data, under a prelude that builds what the in-process context hands forged code, Intl through the host included, and refuses string code generation as the in-process context does. Per call: the result limited to 1 MB, response bodies together to memoryMB, 64 open hashes, 16 host calls in flight; a host value that does not fit the guest's memory ends the call out of memory; without a ceiling the call's requests are aborted when it ends. The corpus, the memory bound, the deadline, the stack and the escape probes run in the main suite.
@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

  • Run on-demand review

This review includes 26 billable files and costs up to $6.50.

  • 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 47 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: 33607620-967e-4a1a-b77a-b3edd5e30438
📥 Commits

Reviewing files that changed from the base of the PR and between 2aa186b and 17e1d4e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml, !**/pnpm-lock.yaml
📒 Files selected for processing (26)
  • .github/workflows/ci.yml
  • .github/workflows/forge-executor-evidence.yml
  • .gitignore
  • README.md
  • docs/SELF_EXTENSION.md
  • docs/architecture/ARCHITECTURE.md
  • docs/architecture/EMERGENT_CAPABILITIES.md
  • evidence/forge-executors/README.md
  • evidence/forge-executors/guest-surface.ts
  • evidence/forge-executors/in-process-child.ts
  • evidence/forge-executors/package.json
  • evidence/forge-executors/quickjs-executor.ts
  • evidence/forge-executors/run.ts
  • package.json
  • src/cognition/emergent/EmergentCapabilityEngine.ts
  • src/cognition/emergent/__tests__/quickjs-engine.integration.test.ts
  • src/cognition/emergent/executor/QuickJSExecutor.ts
  • src/cognition/emergent/executor/guest-prelude.ts
  • src/cognition/emergent/executor/guest-surface.ts
  • src/cognition/emergent/executor/types.ts
  • src/cognition/emergent/index.ts
  • src/cognition/emergent/types.ts
  • tests/emergent/quickjs-executor.integration.spec.ts
  • tests/emergent/quickjs-unavailable.integration.spec.ts
  • tests/fixtures/forged-tools/README.md
  • tests/fixtures/forged-tools/environment.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

This PR adds an optional QuickJS 0.32.0 WebAssembly executor that runs each forged-code call in a fresh, bounded guest with data-only capability bindings, integrates executor selection and readiness into emergent forges, and supplies extensive isolation/limit tests, documentation, and CI coverage.

Sequence diagram for a bounded QuickJS forged-code call

sequenceDiagram
    participant Caller
    participant QuickJSExecutor
    participant GuestRun
    participant QuickJSWasm
    participant HostBindings

    Caller->>QuickJSExecutor: run(request)
    QuickJSExecutor->>QuickJSExecutor: ready()
    QuickJSExecutor->>QuickJSWasm: instantiate fresh WebAssembly.Memory
    QuickJSWasm-->>QuickJSExecutor: isolated runtime and context
    QuickJSExecutor->>GuestRun: execute(request, memoryBytes, ended)
    GuestRun->>HostBindings: guestBindings(globals, limits)
    HostBindings-->>GuestRun: data-only host bindings
    GuestRun->>QuickJSWasm: evalCode(GUEST_PRELUDE)
    GuestRun->>QuickJSWasm: evalCode(forged.js)
    QuickJSWasm->>HostBindings: fetch, fs_readFile, crypto, Intl
    HostBindings-->>QuickJSWasm: copied data or promise result
    QuickJSWasm-->>GuestRun: result, timeout, or memory_exceeded
    GuestRun-->>QuickJSExecutor: ExecutorRunResult
    QuickJSExecutor->>QuickJSWasm: dispose runtime and context
    QuickJSExecutor-->>Caller: result
Loading

State diagram for QuickJS executor availability and call lifecycle

stateDiagram-v2
    [*] --> Unloaded
    Unloaded --> Loading: ready()
    Loading --> Available: loadEngine()
    Loading --> Unavailable: quickjs_unavailable
    Available --> Running: run(request)
    Running --> Completed: result returned
    Running --> TimedOut: deadline or abort
    Running --> MemoryExceeded: memory limit reached
    Completed --> Disposed: runtime.dispose()
    TimedOut --> Disposed: runtime.dispose()
    MemoryExceeded --> Disposed: runtime.dispose()
    Unavailable --> FailedCall: run(request)
    Disposed --> Available
    FailedCall --> Unavailable
Loading

File-Level Changes

Change Details Files
Add an isolated QuickJS/WebAssembly executor with per-call lifecycle, resource limits, host-data bindings, and explicit unavailable-engine handling.
  • Load and version-check the optional QuickJS peer packages, compile the WASM module once, and create a fresh runtime, context, and bounded WebAssembly memory per call.
  • Enforce memory, stack, deadline, output-size, pending-host-call, response-body, open-digest, and host-value transfer limits with distinct execution outcomes.
  • Expose only copied data and capability-backed host functions through a guest prelude, including selected Web APIs, crypto, fetch, filesystem access, Intl delegation, and disabled host/code-generation escape paths.
  • Abort outstanding unbounded host work and dispose all guest handles/runtime state when a call ends.
src/cognition/emergent/executor/QuickJSExecutor.ts
src/cognition/emergent/executor/guest-prelude.ts
src/cognition/emergent/executor/guest-surface.ts
package.json
pnpm-lock.yaml
Integrate executor selection and readiness into emergent forge construction and execution.
  • Allow emergent configuration to select the executor while preserving the existing default.
  • Reject conflicting forge/executor combinations and await executor readiness before tests and review.
  • Export the QuickJS executor, unavailable error, and pinned version metadata.
src/cognition/emergent/**
Add comprehensive integration coverage for isolation, limits, compatibility, configuration, and optional dependency behavior.
  • Run the forged-tool corpus and compare QuickJS behavior with the in-process executor, including Intl parity and all supported bindings.
  • Test memory floors/caps, deadlines, stack failures, output limits, fresh-call state, prototype/input isolation, code-generation refusal, and host resource bounds.
  • Verify unavailable-package errors, executor conflicts, readiness failures, and executor routing through forged tools and processToolCall.
tests/emergent/quickjs-executor.integration.spec.ts
tests/emergent/quickjs-unavailable.integration.spec.ts
src/cognition/emergent/__tests__/quickjs-engine.integration.test.ts
Document the executor trade-offs and update CI/package validation for the new optional runtime.
  • Compare in-process and isolated executors and clarify the basis and scope of the isolation claim.
  • Remove hardened-context wording and extend security-related word checks to the relevant documentation.
  • Run the executor from the built package in CI and retire the prototype evidence run.
README.md
docs/**
.github/**
package.json

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

jddunn added 6 commits October 8, 2026 11:08
… the server

A guest that starts a request and returns in the same turn has it aborted before it is sent, so the server saw nothing to close. The guest now awaits an endpoint that answers once the held request has arrived, and the test then waits for that connection to close.
…length

A buffer over 4 KiB returned by a binding was written into a guest buffer 64 bytes longer than itself, so TextEncoder.encode of a long string came back padded. The checked copy now allocates the buffer's own length. The call's source is checked for room before it is copied in, like any host value. Tests: a long string encoded and decoded exactly; a BigInt formatted through the host as in-process.
…ge the engine builds

Absent, the engine builds its forge on the in-process executor as before. A host-built sandboxForge on another executor passed beside it fails construction with executor_conflict. An executor may offer ready(); the engine awaits it before a forge's test cases and refuses the forge with its reason. QuickJSExecutor, QuickJSUnavailableError and QUICKJS_VERSION are exported.
The Executors section compares the two executors and says what crosses into the guest, its bounds, its memory, its thread and what the isolation claim rests on. README no longer calls the in-process context hardened or forged code TypeScript with Zod schemas; the word check now covers README, the self-extension page and the executor files, and a CI step runs the executor from the built package.
Its questions are answered and its prototype is replaced by QuickJSExecutor; the main suite runs the corpus, the memory bound, the deadline, the stack and the escape probes on the shipped executor on every change.
The checked copy wrote a large buffer into what the binding layer's getArrayBuffer returned, which is a copy of the guest buffer's bytes and not a view of them, so the guest received zeros. A buffer now takes the path every other large value takes: room for it is checked with QuickJS's allocator, then it is copied in. The test added in the last commit (a long string encoded and decoded exactly) failed on this and passes with it.
@jddunn
jddunn marked this pull request as ready for review October 8, 2026 18:21
@jddunn
jddunn requested a review from Victor-Evogor as a code owner October 8, 2026 18:21
@jddunn
jddunn merged commit 598d041 into master Oct 8, 2026
5 checks passed
@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 2 days and 22 hours by commenting @sourcery-ai review. Upgrade to get a review now.

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

Copy link
Copy Markdown

PR Summary by Qodo

Add an isolated QuickJS executor for forged tools

✨ Enhancement 🧪 Tests 📝 Documentation ⚙️ Configuration changes 🕐 40+ Minutes

Grey Divider

AI Description

• Add an optional per-call QuickJS WebAssembly executor with bounded memory, execution, and host
 capabilities.
• Let emergent configuration select an executor while retaining the in-process default and rejecting
 conflicting selections.
• Move executor evidence into integration tests and document the isolation boundary and its
 limitations.
Diagram

graph TD
  Config["Emergent config"] --> Engine["Capability engine"] --> Forge["Tool forge"] --> Executor["QuickJS executor"] --> Guest["Per-call WASM guest"] --> Prelude["Guest prelude"]
  Executor --> Bindings["Data-only bindings"] --> Capabilities["Granted capabilities"]
  Prelude --> Bindings
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Run QuickJS in a child process
  • ➕ Separates synchronous guest work from the host event loop.
  • ➕ Allows process-level termination if a guest or native binding stalls.
  • ➖ Adds process startup and IPC costs.
  • ➖ Requires a more complex capability and cancellation protocol.
2. Reuse a shared QuickJS instance
  • ➕ Could reduce per-call initialization cost.
  • ➖ Weakens the fresh-instance boundary.
  • ➖ Makes per-call WebAssembly memory caps and cleanup harder to guarantee.

Recommendation: The per-call instance is the better fit for the stated isolation and memory-bound goals. A child process is worth considering if preventing guest computation from blocking the host event loop becomes a requirement; a shared instance trades away key guarantees of this PR.

Files changed (19) +1922 / -36

Enhancement (6) +1198 / -14
EmergentCapabilityEngine.tsWire configured executors into forging +26/-3

Wire configured executors into forging

• Passes emergentConfig.executor to an engine-built forge and rejects a conflicting host-provided forge. Awaits executor readiness before forge test cases or judge review.

src/cognition/emergent/EmergentCapabilityEngine.ts

QuickJSExecutor.tsImplement per-call bounded QuickJS WebAssembly execution +703/-0

Implement per-call bounded QuickJS WebAssembly execution

• Loads and version-checks optional peers, compiles the variant once, and creates a fresh capped WebAssembly instance for each run. Bridges host data and promises into the guest while enforcing deadlines, stack, output, memory-copy, and pending-call limits.

src/cognition/emergent/executor/QuickJSExecutor.ts

guest-prelude.tsPackage guest APIs and Intl shims as a prelude +163/-11

Package guest APIs and Intl shims as a prelude

• Exports the guest script as a string for inclusion in the built package. Adds host-backed Intl and locale methods and refuses string-based code generation through eval and Function constructors.

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

guest-surface.tsProvide bounded, data-only host bindings +298/-0

Provide bounded, data-only host bindings

• Builds per-call bindings for web utilities, Intl, granted fetch, file reads, and crypto. Bounds cumulative response bodies and open digests, and connects uncapped requests to call-end cancellation.

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

types.tsAdd an optional executor readiness hook +7/-0

Add an optional executor readiness hook

• Allows executors to report load failures before the engine starts forge test cases.

src/cognition/emergent/executor/types.ts

index.tsExport the QuickJS executor API +1/-0

Export the QuickJS executor API

• Publicly exports QuickJSExecutor, QuickJSUnavailableError, and QUICKJS_VERSION.

src/cognition/emergent/index.ts

Tests (3) +601 / -0
quickjs-engine.integration.test.tsTest QuickJS selection across forge and tool calls +91/-0

Test QuickJS selection across forge and tool calls

• Verifies the selected executor handles both forge-time tests and subsequent tool calls. Covers conflicting executors and readiness failure before tests and review.

src/cognition/emergent/tests/quickjs-engine.integration.test.ts

quickjs-executor.integration.spec.tsCover QuickJS compatibility, isolation, and resource limits +473/-0

Cover QuickJS compatibility, isolation, and resource limits

• Runs the forged-tool corpus on QuickJS and tests memory caps, deadlines, stack behavior, escape probes, host-binding bounds, cancellation, output limits, and Intl parity.

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

quickjs-unavailable.integration.spec.tsTest missing QuickJS dependency failures +37/-0

Test missing QuickJS dependency failures

• Simulates an unavailable QuickJS package and verifies that both eager creation and first-call execution report quickjs_unavailable with the required packages and version.

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

Documentation (6) +61 / -18
README.mdDescribe both forging executors without calling node:vm hardened +2/-2

Describe both forging executors without calling node:vm hardened

• Replaces the in-process security claim with a description of the default node:vm context and optional per-call QuickJS WebAssembly execution. Corrects the description of forged code and its schemas.

README.md

SELF_EXTENSION.mdDocument executor selection for sandbox tools +1/-1

Document executor selection for sandbox tools

• Explains that forged JavaScript runs on the forge's executor: node:vm by default or QuickJS WebAssembly when selected.

docs/SELF_EXTENSION.md

ARCHITECTURE.mdDistinguish executor memory guarantees in the architecture guide +2/-2

Distinguish executor memory guarantees in the architecture guide

• Describes QuickJS as an alternative to the default in-process executor and distinguishes its memory limit from node:vm's observed heap delta.

docs/architecture/ARCHITECTURE.md

EMERGENT_CAPABILITIES.mdDocument executor setup, bounds, and isolation claims +53/-10

Document executor setup, bounds, and isolation claims

• Compares both executors and shows how to install and configure QuickJS. Details guest APIs, per-call limits, readiness failures, the WebAssembly isolation claim, and host-thread limitations.

docs/architecture/EMERGENT_CAPABILITIES.md

README.mdIdentify both integration-test consumers of the corpus +1/-1

Identify both integration-test consumers of the corpus

• Replaces the retired evidence-run reference with the QuickJS integration suite and notes that both executors use the same fixture expectations.

tests/fixtures/forged-tools/README.md

environment.tsDescribe the fixture environment as shared by both suites +2/-2

Describe the fixture environment as shared by both suites

• Updates the module comment to reflect its use by the in-process and QuickJS corpus tests rather than the retired evidence run.

tests/fixtures/forged-tools/environment.ts

Other (4) +62 / -4
ci.ymlExercise the built QuickJS executor in CI +15/-1

Exercise the built QuickJS executor in CI

• Adds a smoke test that imports and runs the executor from dist. Extends the isolation-claim wording check to the new executor sources, README, and self-extension documentation.

.github/workflows/ci.yml

package.jsonDeclare pinned optional QuickJS peers +10/-0

Declare pinned optional QuickJS peers

• Adds both QuickJS packages at 0.32.0 as optional peer dependencies and as development dependencies for testing.

package.json

pnpm-lock.yamlLock QuickJS packages and their shared types +25/-0

Lock QuickJS packages and their shared types

• Records the two pinned QuickJS packages and their shared FFI types dependency.

pnpm-lock.yaml

types.tsExpose executor selection in emergent configuration +12/-3

Expose executor selection in emergent configuration

• Adds the optional ForgedCodeExecutor configuration field and clarifies how memory budgets differ between the in-process and QuickJS executors.

src/cognition/emergent/types.ts

github-actions Bot pushed a commit that referenced this pull request Oct 8, 2026
## [0.12.22](v0.12.21...v0.12.22) (2026-10-08)

### feat

* **emergent:** QuickJSExecutor, an isolating executor for forged code (#160) ([598d041](598d041))
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (4) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Action required

1. Guest prelude export lacks documentation 📘 Rule violation ⚙ Maintainability
Description
GUEST_PRELUDE is exported without a symbol-level TSDoc comment; the preceding @fileoverview
documents the file instead. When a reader looks up the exported constant used by QuickJSExecutor,
there is no documentation attached to that declaration describing its contract.
Code

src/cognition/emergent/executor/guest-prelude.ts[22]

+export const GUEST_PRELUDE = String.raw`(() => {
Evidence
Rule 1 requires TSDoc for every exported symbol. The file has an @fileoverview ending at line 20,
but the new export at line 22 has no symbol-level TSDoc.

AGENTS.md: Document Exported Symbols and Non-Obvious Code
src/cognition/emergent/executor/guest-prelude.ts[1-22]

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

## Issue description
`GUEST_PRELUDE` is exported without its own TSDoc comment; the file overview does not document the symbol.

## Fix Focus Areas
- src/cognition/emergent/executor/guest-prelude.ts[20-22]

## Recommended Fix
Add a TSDoc comment immediately above the export describing the prelude string and how the executor uses it.

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


2. Guest arguments can exhaust host memory 🐞 Bug ➹ Performance
Description
install() calls context.dump() on every guest argument without a size or depth limit before
invoking a host binding. A forged tool can build a large value within its capped WebAssembly memory
and pass it to an exposed binding, causing an unbounded copy into host memory outside that cap.
Code

src/cognition/emergent/executor/QuickJSExecutor.ts[R460-464]

+      let values: unknown[];
+      try {
+        values = args.map((arg) => live.context.dump(arg) as unknown);
+      } catch (error) {
+        return { error: live.context.newError({ name: 'TypeError', message: `${name} takes data only: ${message(error)}` }) };
Evidence
The callback dumps every argument before calling the binding, while the executor's size calculation
applies only to values delivered in the opposite direction.

src/cognition/emergent/executor/QuickJSExecutor.ts[448-476]
src/cognition/emergent/executor/QuickJSExecutor.ts[434-445]
src/cognition/emergent/executor/guest-surface.ts[223-237]

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

## Issue description
Guest arguments are copied into host objects without a size or depth bound, bypassing the per-call guest-memory ceiling.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[448-465]
## Recommended Fix
Enforce a per-call argument byte and structural-depth limit before materializing guest values on the host. Reject arguments that exceed it without performing an unbounded dump.

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


3. Invalid deadlines can stall the host 🐞 Bug ☼ Reliability
Description
run() adds request.timeoutMs to the deadline without checking that it is finite, and the
interrupt handler relies on comparisons against that deadline. If a caller supplies NaN or
Infinity, a synchronous infinite loop never meets the interrupt condition; the forge passes its
requested timeout through without validating it.
Code

src/cognition/emergent/executor/QuickJSExecutor.ts[237]

+      guest = new GuestRun(runtime, memory, performance.now() + request.timeoutMs, request.signal);
Evidence
Both the synchronous interrupt check and asynchronous progress check compare the clock to the
unvalidated deadline; neither comparison becomes true for NaN or Infinity.

src/cognition/emergent/executor/QuickJSExecutor.ts[237-238]
src/cognition/emergent/executor/QuickJSExecutor.ts[278-283]
src/cognition/emergent/executor/QuickJSExecutor.ts[372-375]
src/cognition/emergent/SandboxedToolForge.ts[377-379]

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

## Issue description
Non-finite timeout values disable the interrupt deadline and let a synchronous guest loop block the host indefinitely.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[214-238]
- src/cognition/emergent/SandboxedToolForge.ts[377-379]
## Recommended Fix
Reject or normalize non-finite and non-positive timeout values before constructing the guest deadline. Keep the interrupt and progress paths tied to a finite deadline.

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



Remediation recommended

4. Stalled file reads retain guest memory 🐞 Bug ☼ Reliability
Description
bridge() attaches promise reactions that retain the GuestRun, while dispose() leaves its
WebAssembly.Memory reference in place after a timeout. If an allowed fs.readFile remains
pending, its binding has no abort signal, so repeated timed-out calls can retain a fresh guest
memory instance for each pending read.
Code

src/cognition/emergent/executor/QuickJSExecutor.ts[R498-501]

+    const settled: Promise<void> = result
+      .then(
+        (value) => this.settle(id, { value }),
+        (error: unknown) => this.settle(id, { error }),
Evidence
Promise reactions capture this; that object owns the memory, and disposal clears handles and
context but not the memory reference. The filesystem binding forwards a read promise without the
end-of-call signal.

src/cognition/emergent/executor/QuickJSExecutor.ts[261-274]
src/cognition/emergent/executor/QuickJSExecutor.ts[384-400]
src/cognition/emergent/executor/QuickJSExecutor.ts[492-509]
src/cognition/emergent/executor/guest-surface.ts[248-252]
src/cognition/emergent/SandboxedToolForge.ts[535-541]

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

## Issue description
An outstanding host promise can keep a completed guest run and its WebAssembly memory reachable after timeout.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[261-274]
- src/cognition/emergent/executor/QuickJSExecutor.ts[384-400]
- src/cognition/emergent/executor/QuickJSExecutor.ts[492-509]
- src/cognition/emergent/executor/guest-surface.ts[248-252]
## Recommended Fix
Detach outstanding host-promise reactions from the guest's memory-owning state when a call ends, and make file reads cancellable where the underlying capability permits it.

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


5. Forged POSTs with non-string bodies go out empty 🐞 Bug ≡ Correctness
Description
The guest prelude's fetch copies init.body into the options it sends to host.fetch only when
typeof init.body === 'string'. The fetch binding then forwards those options as they are, so a
body given as URLSearchParams, Uint8Array, ArrayBuffer or another typed array is dropped
without an error. The request still goes out with its method and headers but no payload. On the
in-process executor the same tool sends the body, and nothing in the forged-tool corpus covers this
case.
Code

src/cognition/emergent/executor/guest-surface.ts[R226-231]

+    bindings.fetch = async (input, init) => {
+      const options = init === null || init === undefined ? {} : (init as Record<string, unknown>);
+      const response = (await (fetchFn as (i: unknown, o?: unknown) => Promise<Response>)(
+        input,
+        limits.signal ? { ...options, signal: limits.signal } : init === null ? undefined : init,
+      )) as Response;
Evidence
Lines 476-479 of the prelude, now shipped as GUEST_PRELUDE and run by QuickJSExecutor, build
options with body set only when it is a string. Every other body type is dropped silently. The
binding at guest-surface.ts lines 226-231 passes init (or {...options, signal}) to the forge's
fetch with no other route for a body. The in-process path hands the host fetch straight to the
code, and buildExtraGlobals forwards init unchanged to globalThis.fetch (SandboxedToolForge.ts
lines 495-506). The only fetch fixture in the corpus (library.json line 199) makes a GET with no
body.

src/cognition/emergent/executor/guest-prelude.ts[473-480]
src/cognition/emergent/executor/guest-surface.ts[226-231]
src/cognition/emergent/SandboxedToolForge.ts[495-506]
tests/fixtures/forged-tools/library.json[199-199]

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

## Issue description
The QuickJS guest `fetch` in the prelude keeps `init.body` only when it is a string. A `URLSearchParams`, `ArrayBuffer`, `Uint8Array` or other typed-array body is dropped without an error, so the request goes out with no payload. The in-process executor sends these bodies.

## Fix Focus Areas
- src/cognition/emergent/executor/guest-prelude.ts[473-480]
- src/cognition/emergent/executor/guest-surface.ts[226-231]

## Recommended Fix
In the prelude, encode the body as data:
- a string becomes `{ s: body }`
- a `URLSearchParams` becomes `{ s: body.toString(), form: true }`
- an ArrayBuffer or typed array becomes `{ b: bytesToLatin1(toBytes(body)) }`
- any other type throws a `TypeError`; do not drop it.

In the `fetch` binding, decode it back before calling the forge's fetch:
- `{ s }` becomes a string
- `{ b }` becomes `Buffer.from(b, 'latin1')`
- for `form`, add `content-type: application/x-www-form-urlencoded;charset=UTF-8` when the guest set no content type.

Add an integration test that POSTs each body type to a local server and checks the bytes that arrive.

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


Grey Divider

Context sources
Review mode: Auto: 🧠 Deep: New security-sensitive executor has dense isolation, resource, API, and integration logic.

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

*/
(() => {

export const GUEST_PRELUDE = String.raw`(() => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

1. Guest prelude export lacks documentation 📘 Rule violation ⚙ Maintainability

GUEST_PRELUDE is exported without a symbol-level TSDoc comment; the preceding @fileoverview
documents the file instead. When a reader looks up the exported constant used by QuickJSExecutor,
there is no documentation attached to that declaration describing its contract.
Agent Prompt
## Issue description
`GUEST_PRELUDE` is exported without its own TSDoc comment; the file overview does not document the symbol.

## Fix Focus Areas
- src/cognition/emergent/executor/guest-prelude.ts[20-22]

## Recommended Fix
Add a TSDoc comment immediately above the export describing the prelude string and how the executor uses it.

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

Comment on lines +460 to +464
let values: unknown[];
try {
values = args.map((arg) => live.context.dump(arg) as unknown);
} catch (error) {
return { error: live.context.newError({ name: 'TypeError', message: `${name} takes data only: ${message(error)}` }) };

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

2. Guest arguments can exhaust host memory 🐞 Bug ➹ Performance

install() calls context.dump() on every guest argument without a size or depth limit before
invoking a host binding. A forged tool can build a large value within its capped WebAssembly memory
and pass it to an exposed binding, causing an unbounded copy into host memory outside that cap.
Agent Prompt
## Issue description
Guest arguments are copied into host objects without a size or depth bound, bypassing the per-call guest-memory ceiling.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[448-465]
## Recommended Fix
Enforce a per-call argument byte and structural-depth limit before materializing guest values on the host. Reject arguments that exceed it without performing an unbounded dump.

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

runtime = module.newRuntime();
runtime.setMemoryLimit(maximumPages * PAGE_BYTES);
runtime.setMaxStackSize(STACK_BYTES);
guest = new GuestRun(runtime, memory, performance.now() + request.timeoutMs, request.signal);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Action required

3. Invalid deadlines can stall the host 🐞 Bug ☼ Reliability

run() adds request.timeoutMs to the deadline without checking that it is finite, and the
interrupt handler relies on comparisons against that deadline. If a caller supplies NaN or
Infinity, a synchronous infinite loop never meets the interrupt condition; the forge passes its
requested timeout through without validating it.
Agent Prompt
## Issue description
Non-finite timeout values disable the interrupt deadline and let a synchronous guest loop block the host indefinitely.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[214-238]
- src/cognition/emergent/SandboxedToolForge.ts[377-379]
## Recommended Fix
Reject or normalize non-finite and non-positive timeout values before constructing the guest deadline. Keep the interrupt and progress paths tied to a finite deadline.

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

Comment on lines +498 to +501
const settled: Promise<void> = result
.then(
(value) => this.settle(id, { value }),
(error: unknown) => this.settle(id, { error }),

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

4. Stalled file reads retain guest memory 🐞 Bug ☼ Reliability

bridge() attaches promise reactions that retain the GuestRun, while dispose() leaves its
WebAssembly.Memory reference in place after a timeout. If an allowed fs.readFile remains
pending, its binding has no abort signal, so repeated timed-out calls can retain a fresh guest
memory instance for each pending read.
Agent Prompt
## Issue description
An outstanding host promise can keep a completed guest run and its WebAssembly memory reachable after timeout.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[261-274]
- src/cognition/emergent/executor/QuickJSExecutor.ts[384-400]
- src/cognition/emergent/executor/QuickJSExecutor.ts[492-509]
- src/cognition/emergent/executor/guest-surface.ts[248-252]
## Recommended Fix
Detach outstanding host-promise reactions from the guest's memory-owning state when a call ends, and make file reads cancellable where the underlying capability permits it.

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

Comment on lines +226 to +231
bindings.fetch = async (input, init) => {
const options = init === null || init === undefined ? {} : (init as Record<string, unknown>);
const response = (await (fetchFn as (i: unknown, o?: unknown) => Promise<Response>)(
input,
limits.signal ? { ...options, signal: limits.signal } : init === null ? undefined : init,
)) as Response;

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

5. Forged posts with non-string bodies go out empty 🐞 Bug ≡ Correctness

The guest prelude's fetch copies init.body into the options it sends to host.fetch only when
typeof init.body === 'string'. The fetch binding then forwards those options as they are, so a
body given as URLSearchParams, Uint8Array, ArrayBuffer or another typed array is dropped
without an error. The request still goes out with its method and headers but no payload. On the
in-process executor the same tool sends the body, and nothing in the forged-tool corpus covers this
case.
Agent Prompt
## Issue description
The QuickJS guest `fetch` in the prelude keeps `init.body` only when it is a string. A `URLSearchParams`, `ArrayBuffer`, `Uint8Array` or other typed-array body is dropped without an error, so the request goes out with no payload. The in-process executor sends these bodies.

## Fix Focus Areas
- src/cognition/emergent/executor/guest-prelude.ts[473-480]
- src/cognition/emergent/executor/guest-surface.ts[226-231]

## Recommended Fix
In the prelude, encode the body as data:
- a string becomes `{ s: body }`
- a `URLSearchParams` becomes `{ s: body.toString(), form: true }`
- an ArrayBuffer or typed array becomes `{ b: bytesToLatin1(toBytes(body)) }`
- any other type throws a `TypeError`; do not drop it.

In the `fetch` binding, decode it back before calling the forge's fetch:
- `{ s }` becomes a string
- `{ b }` becomes `Buffer.from(b, 'latin1')`
- for `form`, add `content-type: application/x-www-form-urlencoded;charset=UTF-8` when the guest set no content type.

Add an integration test that POSTs each body type to a local server and checks the bytes that arrive.

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

github-actions Bot pushed a commit that referenced this pull request Oct 8, 2026
## [0.13.3](v0.13.2...v0.13.3) (2026-10-08)

### feat

* **guardrails:** required guards, hold-until-final output, phrase lists and hard limits (#169) ([032fcbf](032fcbf))

### fix

* **emergent:** QuickJSExecutor follow-ups from the cold read of #160 (#178) ([2ec4535](2ec4535))
@jddunn
jddunn deleted the feat/quickjs-executor branch October 10, 2026 18:58
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