diff --git a/experiments/codemode/README.md b/experiments/codemode/README.md index 957455066..64deb2e39 100644 --- a/experiments/codemode/README.md +++ b/experiments/codemode/README.md @@ -18,6 +18,39 @@ catalog to keep synchronized. A fresh QuickJS WASM context exposes only those tool calls, JSON helpers and explicit output; it has no host filesystem, network, process or module loader. +Start the bridge without changing an existing registration: + +```bash +node bridge.mjs /absolute/path/to/node /absolute/path/to/rea/scripts/rea.mjs mcp +``` + +Register that command as a separate, temporary MCP server for a trial. Existing +REA registrations keep their original tools. `rea_search` accepts a query or exact +names; use `schemas: false` for the complete lightweight name/description list. +`rea_execute` accepts a JavaScript async function body. For example: + +```js +const session = json(await tools.binary_session({})).result; +return { open: session.open, identity: session.server_identity }; +``` + +The returned projection is not a new Evidence record. `calls` preserves operation, +argument/result digests, upstream errors and actual producer Evidence IDs when +provided. The upstream ledger retains complete original Evidence for later views +and exports. Non-Evidence session responses have no invented Evidence ID. +Calls and executions sharing one active target are serialized; `Promise.all` +currently provides composition rather than parallel provider execution. + +`npm test` runs actual upstream and downstream stdio MCP against this checkout's +compiled runtime. The standalone experiment's nine tests cover discovery parity, +original results/errors, bulk promise settlement, host capability absence, CPU +deadline recovery, retained Evidence after an error, unresolved promises and the +two-tool downstream boundary. These tests do not establish real native/Android/ +firmware provider behavior. A lifecycle regression revealed that the QuickJS job +pump can allocate an additional context: the execution scope now owns every +context at creation and releases them before the runtime. Increasing memory did +not fix that regression. + Install experimental dependencies separately with `npm ci` in this directory. They do not change the production package or lockfile. Use the repository's pinned Node and npm versions. No binary, provider database or raw third-party source is @@ -32,6 +65,25 @@ Replay measurements establish mechanism costs, not model task accuracy or inference latency. Real-agent trials must additionally verify supported facts, source identity, omissions and preserved Evidence references. +`agent-trial.py` runs a real local Codex CLI with a disposable account/config and +one MCP registration. It copies authentication only, removes the profile on every +exit, and retains JSONL events, the answer and measured API usage outside the repo. +It defaults to `gpt-5.6-terra` with high reasoning, as requested. Run one task under +the resource wrapper: + +```bash +python3 resource-run.py -- python3 agent-trial.py \ + --mode direct --prompt /absolute/path/question.txt \ + --output /absolute/path/new-trial-directory +``` + +Use `--mode bridge` for the experimental server; `--mode client-code` requests +Codex's own Code Mode. Optional `--providers` selects a JSON object of explicit +provider settings. No ambient environment snapshot is retained. A configured flag +or a model's `tool_mode` does not prove the model actually composed tools or +filtered an intermediate result. Inspect the transcript, and mark accuracy as +unassessed until the requested facts and source support have been reviewed. + The supplied feedback is a research lead. Its Ghidra timing claim also changed auto-analysis options, so it does not isolate Code Mode's effect. Relevant primary sources: [Cloudflare Code Mode](https://blog.cloudflare.com/code-mode/), diff --git a/experiments/codemode/agent-trial.py b/experiments/codemode/agent-trial.py new file mode 100644 index 000000000..9c36db7cb --- /dev/null +++ b/experiments/codemode/agent-trial.py @@ -0,0 +1,156 @@ +"""Evaluate one real Codex CLI task with an isolated REA MCP registration.""" + +import argparse +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import time + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mode', choices=['direct', 'client-code', 'bridge'], required=True) + parser.add_argument('--prompt', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--model', default='gpt-5.6-terra') + parser.add_argument('--reasoning', default='high') + parser.add_argument('--timeout', type=int, default=900) + parser.add_argument('--codex', default='/usr/bin/codex') + parser.add_argument('--providers', type=Path) + args = parser.parse_args() + repository = Path(__file__).resolve().parents[2] + experiment = Path(__file__).resolve().parent + node = shutil.which('node') + if subprocess.check_output([node, '--version'], text=True).strip() != 'v24.18.0': + raise SystemExit('Use pinned Node 24.18.0 on PATH') + args.output.mkdir(parents=True, exist_ok=False, mode=0o700) + profile = Path(tempfile.mkdtemp(prefix='profile-', dir=args.output)) + trial_codex_home = profile / 'codex' + account = profile / 'account' + workspace = profile / 'workspace' + for directory in [trial_codex_home, account, workspace]: + directory.mkdir(mode=0o700) + source_auth = Path(os.environ.get('CODEX_HOME', str(Path.home() / '.codex'))) / 'auth.json' + auth = trial_codex_home / 'auth.json' + started = time.monotonic() + timeout = False + exit_code = None + environment = dict(os.environ) + environment.update({ + 'CODEX_HOME': str(trial_codex_home), 'HOME': str(account), + 'XDG_CONFIG_HOME': str(account / '.config'), + 'XDG_CACHE_HOME': str(account / '.cache'), + 'XDG_DATA_HOME': str(account / '.local/share'), + 'NODE_OPTIONS': '--max-old-space-size=512', + }) + provider_env = {'REA_LOG_LEVEL': 'silent', 'NODE_OPTIONS': '--max-old-space-size=512'} + if args.providers: + # This explicit caller file supplies only selected provider settings. + provider_env.update(json.loads(args.providers.read_text())) + command_args = [str(repository / 'scripts/rea.mjs'), 'mcp'] + if args.mode == 'bridge': + command_args = [str(experiment / 'bridge.mjs'), node, *command_args] + instruction = ( + 'Use the registered REA MCP server for this investigation. Static analysis ' + 'only: do not execute target code, fetch URLs, launch a GUI, or modify targets. ' + 'Preserve observations, derivations, inferences, limitations, and real Evidence IDs. ' + 'Prefer summary/focused views where appropriate. Do not invent successful facts ' + 'after a tool error. No other agents. Stop once the requested facts are supported.' + ) + if args.mode == 'bridge': + instruction += ( + ' Original REA operations are available through rea_search and rea_execute. ' + 'Discover tool names/schemas on demand. Execute JavaScript bodies using ' + 'tools.(original_arguments), json(reply) to parse the original ' + 'MCP result, and return only the needed facts plus their Evidence IDs and ' + 'limitations. Compose known dependent calls in one script when useful. ' + 'Await every call; the upstream session persists across scripts.' + ) + quote = json.dumps + config = '\n'.join([ + 'approval_policy = "never"', 'sandbox_mode = "read-only"', + 'web_search = "disabled"', 'model = ' + quote(args.model), + 'model_reasoning_effort = ' + quote(args.reasoning), + 'developer_instructions = ' + quote(instruction), + '[features]', 'multi_agent = false', 'shell_snapshot = false', + 'shell_tool = false', 'unified_exec = false', + 'code_mode = ' + ('true' if args.mode == 'client-code' else 'false'), + 'code_mode_only = ' + ('true' if args.mode == 'client-code' else 'false'), + '[history]', 'persistence = "none"', + '[mcp_servers.rea]', 'command = ' + quote(node), + 'args = ' + quote(command_args), 'startup_timeout_sec = 60', + 'tool_timeout_sec = 600', '[mcp_servers.rea.env]', + *[key + ' = ' + quote(value) for key, value in provider_env.items()], + '[mcp_servers.rea.tools.rea_execute]', 'approval_mode = "approve"', + ]) + '\n' + # MCP read-only hints cover normal static tools. Explicitly authorize only + # the session-opening primitive needed by the requested native tasks. + config += '[mcp_servers.rea.tools.open_binary]\napproval_mode = "approve"\n' + for tool in ['analyze_javascript_application', 'inspect_analysis_view', + 'inspect_android_package', 'search_android_classes', + 'inspect_android_class', 'inspect_android_method', + 'inspect_firmware_regions', 'inspect_managed_artifact', + 'inspect_managed_member', 'analyze_function', 'close_binary']: + config += '[mcp_servers.rea.tools.' + tool + ']\napproval_mode = "approve"\n' + try: + if source_auth.exists(): + shutil.copyfile(source_auth, auth) + auth.chmod(0o600) + (trial_codex_home / 'config.toml').write_text(config) + (trial_codex_home / 'config.toml').chmod(0o600) + prompt = args.prompt.read_text() + (args.output / 'prompt.txt').write_text(prompt) + invocation = [args.codex, '--no-daemon', 'exec', '--ephemeral', + '--skip-git-repo-check', '--ignore-rules', '--json', + '--color', 'never', '-C', str(workspace), + '--output-last-message', str(args.output.resolve() / 'answer.txt'), '-'] + with (args.output / 'events.jsonl').open('w') as events, (args.output / 'stderr.log').open('w') as errors: + child = subprocess.Popen(invocation, env=environment, cwd=workspace, + stdin=subprocess.PIPE, stdout=events, stderr=errors, text=True) + child.stdin.write(prompt) + child.stdin.close() + try: + exit_code = child.wait(timeout=args.timeout) + except subprocess.TimeoutExpired: + timeout = True + child.terminate() + try: + exit_code = child.wait(timeout=10) + except subprocess.TimeoutExpired: + child.kill() + exit_code = child.wait() + usage = [] + tools = [] + event_types = {} + for line in (args.output / 'events.jsonl').read_text().splitlines(): + event = json.loads(line) + kind = event.get('type', 'unknown') + event_types[kind] = event_types.get(kind, 0) + 1 + if 'usage' in event: + usage.append(event['usage']) + item = event.get('item', {}) + if item.get('type') == 'mcp_tool_call' and kind == 'item.completed': + tools.append({k: item.get(k) for k in ['server', 'tool', 'arguments', 'status', 'error']}) + summary = { + 'mode': args.mode, 'requested_model': args.model, 'reasoning': args.reasoning, + 'baseline_sha': 'fb94d9dde0ccda83ae520ac6fb22b1d283562cf3', + 'codex_version': subprocess.check_output([args.codex, '--version'], text=True).strip(), + 'exit_code': exit_code, 'timeout': timeout, + 'wall_seconds': round(time.monotonic() - started, 3), + 'usage': usage, 'completed_mcp_calls': tools, 'event_types': event_types, + 'factual_correctness': 'not_assessed', + 'scope': 'real_cli_trial_requires_transcript_and_fact_review', + } + (args.output / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n') + print(json.dumps(summary)) + finally: + # Always remove copied credentials, config, caches and profile state. + shutil.rmtree(profile) + raise SystemExit(124 if timeout else exit_code) + + +if __name__ == '__main__': + main() diff --git a/experiments/codemode/bridge.mjs b/experiments/codemode/bridge.mjs new file mode 100644 index 000000000..4b933fd89 --- /dev/null +++ b/experiments/codemode/bridge.mjs @@ -0,0 +1,376 @@ +import { createHash } from "node:crypto"; +import { pathToFileURL } from "node:url"; +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { McpServer } from "@modelcontextprotocol/server"; +import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; +import { compile } from "json-schema-to-typescript"; +import { newQuickJSWASMModule, Scope } from "quickjs-emscripten"; +import { z } from "zod"; + +const digest = (value) => + createHash("sha256").update(JSON.stringify(value)).digest("hex"); + +export const json = (reply) => { + if (reply.structuredContent !== undefined) return reply.structuredContent; + const texts = reply.content.filter((item) => item.type === "text"); + if (texts.length !== 1) throw new Error("Expected one REA JSON text block"); + return JSON.parse(texts[0].text); +}; + +/** One upstream session, original tool names, complete live catalog. */ +export async function connectUpstream({ + command, + args, + env, + stderr = "inherit", +}) { + const transport = new StdioClientTransport({ command, args, env, stderr }); + const client = new Client({ + name: "rea-codemode-experiment", + version: "0.0.0", + }); + try { + await client.connect(transport, { timeout: 60_000 }); + const catalog = []; + let cursor; + do { + const page = await client.listTools(cursor ? { cursor } : undefined); + catalog.push(...page.tools); + cursor = page.nextCursor; + } while (cursor !== undefined); + if (new Set(catalog.map((tool) => tool.name)).size !== catalog.length) + throw new Error("Duplicate upstream tool names"); + return { + client, + catalog, + call: (name, args, options) => + client.callTool({ name, arguments: args }, options), + close: () => client.close(), + }; + } catch (error) { + await client.close(); + throw error; + } +} + +export class CodeModeBridge { + constructor(upstream) { + this.upstream = upstream; + this.byName = new Map(upstream.catalog.map((tool) => [tool.name, tool])); + this.catalogDigest = digest(upstream.catalog); + this.queue = Promise.resolve(); + } + + /** Search exposes original schemas and generated input types on demand. */ + async search({ query = "", names = [], schemas = true }) { + const terms = query.toLowerCase().split(/\s+/).filter(Boolean); + const selected = this.upstream.catalog.filter((tool) => + names.length + ? names.includes(tool.name) + : terms.every((term) => + `${tool.name} ${tool.description ?? ""}` + .toLowerCase() + .includes(term), + ), + ); + const tools = []; + for (const tool of selected) { + const inputType = schemas + ? await compile(tool.inputSchema, `${tool.name}_Input`, { + bannerComment: "", + format: false, + unknownAny: true, + }) + : undefined; + tools.push( + schemas + ? { ...tool, typescript: inputType } + : { + name: tool.name, + description: tool.description, + annotations: tool.annotations, + }, + ); + } + return { + catalog_sha256: this.catalogDigest, + total_tools: this.byName.size, + matched_tools: tools.length, + tools, + }; + } + + /** Serialize scripts sharing the active target; no implicit batch races. */ + execute(input, options = {}) { + const work = this.queue.then(() => this.run(input, options)); + this.queue = work.catch(() => undefined); + return work; + } + + async run( + { code, timeout_ms = 120_000, memory_bytes = 128 * 1024 * 1024 }, + options, + ) { + const controller = new AbortController(); + const signal = options.signal + ? AbortSignal.any([controller.signal, options.signal]) + : controller.signal; + signal.throwIfAborted(); + const deadline = Date.now() + timeout_ms; + const timer = setTimeout( + () => controller.abort(new Error("Code Mode deadline exceeded")), + timeout_ms, + ); + const QuickJS = await newQuickJSWASMModule(); + const runtime = QuickJS.newRuntime(); + // Pending-job execution can create another context in the runtime. + // Own contexts at creation, including those allocated by the job pump. + const contexts = new Scope(); + const newContext = runtime.newContext.bind(runtime); + runtime.newContext = (options) => contexts.manage(newContext(options)); + runtime.setMemoryLimit(memory_bytes); + runtime.setMaxStackSize(1024 * 1024); + runtime.setInterruptHandler(() => signal.aborted || Date.now() > deadline); + const vm = runtime.newContext(); + const pending = new Set(); + const calls = []; + let toolQueue = Promise.resolve(); + let finished = false; + let promise; + let value; + let failure; + const checkedEval = (source) => { + const result = vm.evalCode(source); + if (result.error) { + const error = vm.dump(result.error); + result.error.dispose(); + throw new Error(JSON.stringify(error)); + } + return result.value; + }; + const pump = () => { + const result = runtime.executePendingJobs(); + if (result.error) { + failure = vm.dump(result.error); + result.error.dispose(); + finished = true; + } + }; + const fromJson = (data) => + checkedEval(`JSON.parse(${JSON.stringify(JSON.stringify(data))})`); + const callHandle = vm.newFunction("call", (nameHandle, argumentsHandle) => { + const name = vm.getString(nameHandle); + const args = JSON.parse(vm.getString(argumentsHandle)); + if (!this.byName.has(name)) + throw new Error(`Unknown upstream tool: ${name}`); + signal.throwIfAborted(); + const deferred = vm.newPromise(); + const audit = { name, arguments_sha256: digest(args) }; + calls.push(audit); + const work = toolQueue.then(async () => { + signal.throwIfAborted(); + const started = performance.now(); + try { + const reply = await this.upstream.call(name, args, { + signal, + timeout: Math.max(1, deadline - Date.now()), + onprogress: options.onprogress, + }); + audit.elapsed_ms = performance.now() - started; + audit.result_sha256 = digest(reply); + audit.is_error = reply.isError === true; + try { + const record = json(reply); + if (record.evidence_id) audit.evidence_id = record.evidence_id; + } catch { + /* Non-JSON MCP content is still preserved in reply. */ + } + const handle = fromJson(reply); + deferred.resolve(handle); + handle.dispose(); + } catch (error) { + audit.transport_error = error.message; + const handle = fromJson({ name: error.name, message: error.message }); + deferred.reject(handle); + handle.dispose(); + } finally { + deferred.dispose(); + pump(); + } + }); + const settled = work.catch((error) => { + failure = { message: error.message }; + finished = true; + }); + toolQueue = settled; + pending.add(settled); + void settled.then(() => pending.delete(settled)); + // The callback transfers its returned handle to QuickJS. Keep the + // deferred's original host handle until settlement, with a separate + // guest handle; otherwise bulk promise cleanup shares one lifetime. + return deferred.handle.dup(); + }); + const doneHandle = vm.newFunction("done", (data) => { + value = JSON.parse(vm.getString(data)); + finished = true; + }); + const failHandle = vm.newFunction("fail", (error) => { + failure = vm.dump(error); + finished = true; + }); + try { + vm.setProp(vm.global, "__call", callHandle); + vm.setProp(vm.global, "__done", doneHandle); + vm.setProp(vm.global, "__fail", failHandle); + checkedEval(` + const tools = Object.freeze(Object.fromEntries(${JSON.stringify([...this.byName.keys()])}.map( + name => [name, args => __call(name, JSON.stringify(args))] + ))); + const json = reply => { + if (reply.structuredContent !== undefined) return reply.structuredContent; + const texts = reply.content.filter(item => item.type === 'text'); + if (texts.length !== 1) throw new Error('Expected one REA JSON text block'); + return JSON.parse(texts[0].text); + }; + `).dispose(); + promise = checkedEval(`(async () => {\n${code}\n})().then( + value => __done(JSON.stringify(value === undefined ? null : value)), + error => __fail({name: error?.name, message: error?.message ?? String(error)}) + )`); + pump(); + while (!finished && !signal.aborted) { + if (pending.size) await Promise.race(pending); + else + throw new Error( + "Guest promise cannot progress: no pending tool calls", + ); + pump(); + } + signal.throwIfAborted(); + if (calls.some((call) => !call.result_sha256 && !call.transport_error)) { + controller.abort( + new Error("Code returned before awaiting all tool calls"), + ); + await Promise.allSettled(pending); + failure = { + message: + "Code returned before awaiting all tool calls; calls were cancelled", + }; + } else await Promise.allSettled(pending); + } catch (error) { + failure = { name: error.name, message: error.message }; + controller.abort(error); + await Promise.allSettled(pending); + } finally { + clearTimeout(timer); + promise?.dispose(); + callHandle.dispose(); + doneHandle.dispose(); + failHandle.dispose(); + contexts.dispose(); + runtime.dispose(); + } + return { + catalog_sha256: this.catalogDigest, + calls, + ...(failure ? { bridge_error: failure } : { value }), + }; + } +} + +export function createBridgeServer(bridge) { + const server = new McpServer({ + name: "rea-codemode-experiment", + version: "0.0.0", + }); + const reply = (result) => ({ + content: [{ type: "text", text: JSON.stringify(result) }], + ...(result.bridge_error ? { isError: true } : {}), + }); + server.registerTool( + "rea_search", + { + description: + "Discover original REA tools by all query words or exact names. Empty query lists the complete catalog. Schemas are exact upstream MCP schemas; generated TypeScript inputs are optional. Code Mode calls tools.(original_arguments); results are original MCP envelopes, parsed by json(reply).", + inputSchema: z.strictObject({ + query: z.string().default(""), + names: z.array(z.string()).default([]), + schemas: z.boolean().default(true), + }), + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + }, + async (input) => reply(await bridge.search(input)), + ); + server.registerTool( + "rea_execute", + { + description: + "Run a JavaScript async function body with tools.(original_arguments), json(reply) and return. Await every call. One upstream session persists across executions. Calls run in order, including Promise.all. All original REA effects, validation and Evidence retention apply; returned projections are caller selections, not new Evidence. No host IO or imports. Call audit and Evidence IDs survive script errors. Default deadline 120s and guest memory 128 MiB; use longer deadline for native analysis.", + inputSchema: z.strictObject({ + code: z.string(), + timeout_ms: z.number().int().positive().optional(), + memory_bytes: z + .number() + .int() + .positive() + .max(128 * 1024 * 1024) + .optional(), + }), + annotations: { + readOnlyHint: false, + destructiveHint: true, + idempotentHint: false, + openWorldHint: true, + }, + }, + async (input, context) => + reply( + await bridge.execute(input, { + signal: context.mcpReq.signal, + onprogress: + context.mcpReq._meta?.progressToken === undefined + ? undefined + : (progress) => + context.mcpReq.notify({ + method: "notifications/progress", + params: { + ...progress, + progressToken: context.mcpReq._meta.progressToken, + }, + }), + }), + ), + ); + return server; +} + +async function main() { + const [command, ...args] = process.argv.slice(2); + if (!command) throw new Error("Usage: node bridge.mjs COMMAND [ARG...]"); + const upstream = await connectUpstream({ command, args, env: process.env }); + const server = createBridgeServer(new CodeModeBridge(upstream)); + let closing = false; + const close = async () => { + if (closing) return; + closing = true; + await server.close(); + await upstream.close(); + }; + process.once("SIGINT", () => void close()); + process.once("SIGTERM", () => void close()); + const transport = new StdioServerTransport(); + transport.onclose = () => void close(); + await server.connect(transport); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); diff --git a/experiments/codemode/bridge.test.mjs b/experiments/codemode/bridge.test.mjs new file mode 100644 index 000000000..1468087cd --- /dev/null +++ b/experiments/codemode/bridge.test.mjs @@ -0,0 +1,172 @@ +import assert from "node:assert/strict"; +import { after, before, test } from "node:test"; +import { fileURLToPath } from "node:url"; +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { CodeModeBridge, connectUpstream, json } from "./bridge.mjs"; + +const entrypoint = fileURLToPath( + new URL("../../scripts/rea.mjs", import.meta.url), +); +const fixture = fileURLToPath( + new URL("../../tests/conformance/readiness/javascript-cli", import.meta.url), +); +const analysisArgs = { + input_path: fixture, + detail: "summary", + max_heap_mb: 128, +}; +let upstream; +let bridge; +before(async () => { + upstream = await connectUpstream({ + command: process.execPath, + args: [entrypoint, "mcp"], + env: { ...process.env, REA_LOG_LEVEL: "silent" }, + }); + bridge = new CodeModeBridge(upstream); +}); +after(async () => { + await upstream?.close(); +}); + +test("discovery preserves exact current REA schemas and names", async () => { + const result = await bridge.search({ names: ["binary_session"] }); + assert.equal(result.total_tools, upstream.catalog.length); + const original = upstream.catalog.find( + (tool) => tool.name === "binary_session", + ); + const { typescript, ...discovered } = result.tools[0]; + assert.deepEqual(discovered, original); + assert.match(typescript, /export interface BinarySession_Input/); + const all = await bridge.search({ schemas: false }); + assert.deepEqual( + all.tools.map((tool) => tool.name), + upstream.catalog.map((tool) => tool.name), + ); +}); + +test("raw original result and parsed result survive a real MCP call", async () => { + const result = await bridge.execute({ + code: "const r = await tools.binary_session({}); return {raw:r, parsed:json(r)};", + }); + assert.equal(result.bridge_error, undefined); + assert.deepEqual(json(result.value.raw), result.value.parsed); + assert.equal(result.calls[0].name, "binary_session"); + assert.match(result.calls[0].result_sha256, /^[a-f0-9]{64}$/); + assert.equal(result.calls[0].is_error, false); +}); + +test("Promise.all calls settle in order without losing pending work", async () => { + const result = await bridge.execute({ + code: "return await Promise.all([tools.binary_session({}), tools.binary_session({}), tools.binary_session({})]);", + }); + assert.equal(result.bridge_error, undefined); + assert.equal(result.value.length, 3); + assert.equal(result.calls.length, 3); + assert.ok(result.calls.every((call) => call.result_sha256)); +}); + +test("upstream invalid-input result remains an original MCP error envelope", async () => { + const args = { + input_path: "/nonexistent/rea-codemode-artifact", + detail: "summary", + }; + const direct = await upstream.call("analyze_javascript_application", args); + const result = await bridge.execute({ + code: `return await tools.analyze_javascript_application(${JSON.stringify(args)});`, + }); + assert.equal(result.bridge_error, undefined); + assert.equal(result.value.isError, true); + assert.deepEqual(json(result.value).error, json(direct).error); + assert.equal(result.calls[0].is_error, true); +}); + +test("guest has no Node, filesystem, fetch or module-loading capabilities", async () => { + const result = await bridge.execute({ + code: "return [typeof process,typeof require,typeof fetch,typeof Deno,Function('return typeof process')()];", + }); + assert.deepEqual(result.value, Array(5).fill("undefined")); + const imported = await bridge.execute({ + code: "return await import('node:fs');", + }); + assert.ok(imported.bridge_error); +}); + +test("CPU deadline interrupts runaway code and the next execution works", async () => { + const result = await bridge.execute({ + code: "while(true) {}", + timeout_ms: 20, + }); + assert.ok(result.bridge_error); + assert.deepEqual(result.calls, []); + assert.equal((await bridge.execute({ code: "return 42;" })).value, 42); +}); + +test("error after successful call preserves original Evidence reference", async () => { + const result = await bridge.execute({ + code: `await tools.analyze_javascript_application(${JSON.stringify(analysisArgs)}); throw new Error('after-call');`, + }); + assert.match(result.bridge_error.message, /after-call/); + assert.ok(result.calls[0].evidence_id); + const readback = await upstream.call("get_evidence_bundle", { + detail: "summary", + }); + assert.equal(readback.isError, undefined); + assert.ok( + JSON.stringify(json(readback)).includes(result.calls[0].evidence_id), + ); +}); + +test("a guest promise without any producer fails without hanging", async () => { + const result = await bridge.execute({ + code: "return await new Promise(() => {});", + }); + assert.match(result.bridge_error.message, /cannot progress/); +}); + +test("bridge's two tools are usable through actual downstream stdio MCP", async () => { + const transport = new StdioClientTransport({ + command: process.execPath, + args: [ + fileURLToPath(new URL("./bridge.mjs", import.meta.url)), + process.execPath, + entrypoint, + "mcp", + ], + env: { ...process.env, REA_LOG_LEVEL: "silent" }, + stderr: "inherit", + }); + const client = new Client({ name: "codemode-boundary-test", version: "1" }); + try { + await client.connect(transport); + const catalog = await client.listTools(); + assert.deepEqual( + catalog.tools.map((tool) => tool.name), + ["rea_search", "rea_execute"], + ); + const found = json( + await client.callTool({ + name: "rea_search", + arguments: { names: ["binary_session"] }, + }), + ); + assert.equal(found.matched_tools, 1); + const result = json( + await client.callTool({ + name: "rea_execute", + arguments: { + code: "return json(await tools.binary_session({}));", + }, + }), + ); + assert.equal(result.value.result.open, false); + const invalid = await client.callTool({ + name: "rea_execute", + arguments: { code: 7 }, + }); + assert.equal(invalid.isError, true); + } finally { + await client.close(); + } +}); diff --git a/experiments/codemode/resource-run.py b/experiments/codemode/resource-run.py index c66ac094d..14383cfbf 100644 --- a/experiments/codemode/resource-run.py +++ b/experiments/codemode/resource-run.py @@ -26,11 +26,12 @@ def main(): if available_bytes() < 8 * gib: raise SystemExit('Refusing experiment: less than 8 GiB available') unit = 'rea-codemode-' + uuid.uuid4().hex + '.scope' + cpu = max(os.sched_getaffinity(0)) command = [ 'systemd-run', '--user', '--scope', '--unit=' + unit, '-p', 'MemoryMax=4G', '-p', 'MemoryHigh=2G', '-p', 'MemorySwapMax=0', '-p', 'CPUQuota=100%', '-p', 'TasksMax=96', - 'taskset', '-c', str(min(os.sched_getaffinity(0))), *args, + 'taskset', '-c', str(cpu), *args, ] process = subprocess.Popen(command) peak = 0 @@ -70,6 +71,7 @@ def main(): 'elapsed_seconds': round(time.monotonic() - started, 3), 'abort': abort, 'hard_memory_bytes': 4 * gib, 'early_stop_bytes': 3 * gib, 'cpu_quota_percent': 100, + 'cpu_affinity': [cpu], }), file=sys.stderr) raise SystemExit(125 if abort else code)