brainx-skill 1.0.16 → 1.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,7 @@ const childProcess = require('node:child_process');
4
4
  const fs = require('node:fs/promises');
5
5
  const os = require('node:os');
6
6
  const path = require('node:path');
7
+ const { codexInvocation, npmInvocation } = require('../../mcp-servers/codex/cli-invocation.cjs');
7
8
 
8
9
  const EUROPE_PMC_NAME = 'europepmc';
9
10
  const FULLTEXT_NAME = 'fulltext_resolver';
@@ -483,13 +484,18 @@ async function runLiteratureMcp(command, options = {}) {
483
484
  const pathApi = options.pathApi || path;
484
485
  const homeDir = options.homeDir || os.homedir();
485
486
  const packageRoot = options.packageRoot || path.resolve(__dirname, '../..');
486
- const runner = options.runner || defaultRunner;
487
487
  const stdout = options.stdout || process.stdout;
488
488
  const stderr = options.stderr || process.stderr;
489
489
  const codexBin = options.codexBin || 'codex';
490
490
  const npmBin = options.npmBin || 'npm';
491
491
  const uvBin = options.uvBin || 'uv';
492
492
  const platform = options.platform || process.platform;
493
+ const runner = options.runner || ((binary, args, runOptions) => {
494
+ let invocation = { binary, prefixArgs: args };
495
+ if (binary === codexBin) invocation = codexInvocation(binary, args);
496
+ if (binary === npmBin) invocation = npmInvocation(binary, args);
497
+ return defaultRunner(invocation.binary, invocation.prefixArgs, runOptions);
498
+ });
493
499
  const paths = runtimePaths(homeDir, pathApi, platform);
494
500
  const expected = expectedServers(paths, options.nodeBin || process.execPath);
495
501
 
@@ -1,24 +1,34 @@
1
1
  # BrainX Codex MCP server
2
2
 
3
- This server preserves the open-source Codex CLI MCP implementation while specializing fresh sessions for independent BrainX scientific review. It delegates execution and persistence to `codex mcp-server`, so `codex-reply` continues the same native thread with its existing context.
4
-
5
- The proxy changes only fresh `codex` calls:
6
-
7
- - `base-instructions` receives `system-prompt.md`;
8
- - `developer-instructions` identifies the allowed BrainX domain skills and the
9
- exact training and fitting review-reference paths;
10
- - `skills.config` exposes the skill directories listed in `skills.json`.
11
-
12
- The modeling-loop skill is not exposed to the reviewer. The reviewer opens only
13
- `training-workflow.md` and/or `parameter-fitting-workflow.md` when the supplied
14
- `ACTIVE_COVERAGE` requires them.
15
-
16
- All `codex-reply` calls and other MCP messages pass through unchanged.
3
+ This adapter exposes the `codex` and `codex-reply` MCP tools for independent
4
+ BrainX scientific review and runs them through `codex app-server --listen
5
+ stdio://`. Codex owns native thread history and persistence; the adapter returns
6
+ the completed Markdown report and native thread ID to the MCP caller.
7
+
8
+ Use `codex` for a fresh thread and `codex-reply` for `thread/resume` followed by
9
+ another turn in that thread, including after the adapter restarts. Both paths
10
+ enforce the BrainX system prompt, allowed skills, `read-only` sandbox and
11
+ `never` approval policy. Caller settings cannot replace these constraints.
12
+ The reviewer disables the MCP registrations in the effective workspace
13
+ configuration to prevent recursive startup. Tool callers cannot add MCP
14
+ registrations through `config`. When the host uses a custom `CODEX_HOME` or
15
+ environment credentials, list those variable names in the MCP registration's
16
+ `env_vars`; the Codex MCP host filters unlisted environment variables.
17
+
18
+ `system-prompt.md` supplies the scientific review contract. `skills.json` selects
19
+ the exposed domain skills. The developer instructions identify the exact
20
+ training and fitting review references; the modeling-loop workflow itself is
21
+ not exposed as a reviewer skill.
22
+
23
+ The adapter waits for native turn completion, excludes commentary from the
24
+ report, surfaces failed/interrupted/empty turns as MCP tool errors, and
25
+ translates MCP cancellation to `turn/interrupt`. Interactive approval requests
26
+ are declined; unsupported interactive requests return protocol errors.
17
27
 
18
28
  ## Requirements
19
29
 
20
30
  - Node.js 18 or later
21
- - Codex CLI with `codex mcp-server` support
31
+ - Codex CLI with App Server stdio support (tested on 0.166.0 and 0.170.0)
22
32
  - a working Codex login
23
33
 
24
34
  ## Register
@@ -58,11 +68,13 @@ review commonly exceeds Codex's default MCP tool-call budget; when the host
58
68
  cancels that call, the caller may report `user cancelled MCP tool call` even
59
69
  though no user cancelled it.
60
70
 
61
- The proxy forces fresh reviews to `sandbox = "read-only"` and
62
- `approval-policy = "never"` before forwarding them upstream. Auto-approving the
63
- MCP tool therefore does not grant the reviewer write access or command approval.
71
+ The adapter forces fresh and resumed reviews to `sandbox = "read-only"` and
72
+ `approvalPolicy = "never"`. Auto-approving the MCP tool does not grant the
73
+ reviewer write access or command approval.
64
74
 
65
75
  Set `BRAINX_CODEX_BIN` only when `codex` is not on `PATH` for the MCP host.
76
+ On Windows, npm `.cmd`/`.ps1` shims resolve to the package JavaScript entry and
77
+ run through Node without a shell. Custom wrappers should expose an executable.
66
78
 
67
79
  ## Use
68
80
 
@@ -70,13 +82,27 @@ Start a review with `mcp__codex__codex`. Its returned `content` is the reviewer
70
82
  response available to the calling agent in the same turn. The response is a
71
83
  complete Markdown document; the reviewer remains read-only and does not create
72
84
  the file. The calling modeling agent saves `content` verbatim as
73
- `reviews/iteration-<N>.md`, records that path and the returned `threadId`, and
85
+ `reviews/iteration-<N>.md`, records that path and `structuredContent.threadId`, and
74
86
  uses `codex-reply` only for a follow-up that must continue the reviewer's context.
75
87
 
88
+ The successful tool result contains `content: [{type: "text", text: report}]`
89
+ and `structuredContent: {threadId, content: report}`. `codex-reply` accepts
90
+ `{threadId, prompt}`. Fresh calls accept `prompt`, optional `model`, `cwd`, and
91
+ `config`; the former `profile` option now returns an explicit unsupported-option
92
+ error. Review constraints always override legacy instruction/permission options.
93
+
76
94
  Edit `system-prompt.md` to change the reviewer contract. Edit `skills.json` to change the BrainX skills exposed to fresh reviewer sessions.
77
95
 
78
96
  ## Verify
79
97
 
80
98
  ```bash
81
- node --test mcp-servers/codex/test/*.test.mjs
99
+ npm test
100
+ node .github/scripts/smoke-reviewer.mjs
82
101
  ```
102
+
103
+ The transport is dependency-free and uses JSONL stdio on both sides. MCP
104
+ `initialize` initializes the real App Server before advertising the tools.
105
+ The smoke test uses a real Codex CLI, an isolated Codex home and a loopback
106
+ Responses fixture. It verifies the handshake, a fresh review, and continued
107
+ history after restarting the reviewer. Run `npm install` first. Pass a path to
108
+ an extracted package's `server.mjs` to verify the shipped files.
@@ -1,22 +1,26 @@
1
1
  # Upstream provenance
2
2
 
3
- The linked ARIS repository registers the Codex CLI directly:
3
+ The original reviewer forwarded the now-removed `codex mcp-server` command.
4
+ The current implementation exposes the same MCP tool names through a BrainX
5
+ adapter backed by the native Codex App Server stdio protocol.
4
6
 
5
- ```bash
6
- claude mcp add codex -s user -- codex mcp-server
7
- ```
7
+ Verified against CLI 0.166.0 and 0.170.0:
8
8
 
9
- This proxy delegates to that same command. Its tool schemas, native thread creation, persistence, event handling, and `codex-reply` continuation remain implemented by OpenAI Codex.
10
-
11
- Upstream inspected on 2026-08-23:
12
-
13
- - Repository: <https://github.com/openai/codex>
14
- - Revision: `83d1fe0e67b1323f71febc2925817732b449f1d9`
15
- - MCP configuration and schemas: `codex-rs/mcp-server/src/codex_tool_config.rs`
16
- - Session and reply execution: `codex-rs/mcp-server/src/codex_tool_runner.rs`
17
- - JSON-RPC dispatch: `codex-rs/mcp-server/src/message_processor.rs`
9
+ - Official protocol: https://learn.chatgpt.com/docs/app-server
10
+ - Removed command: https://learn.chatgpt.com/docs/developer-commands
11
+ - Version-specific schema: `codex app-server generate-json-schema --out <directory>`
12
+ - Upstream implementation: https://github.com/openai/codex/tree/main/codex-rs/app-server
18
13
  - License: Apache-2.0, the same license used by this repository
19
14
 
20
- Modified behavior is confined to `server.mjs`: fresh `codex` tool calls receive
21
- the BrainX system prompt and skill configuration and are forced to read-only,
22
- no-approval execution before being forwarded upstream.
15
+ `app-server.mjs` implements JSONL requests and native turn-event handling.
16
+ `server.mjs` owns the MCP tool schemas, maps fresh reviews to `thread/start`,
17
+ maps continuation to `thread/resume`, and maps review prompts to `turn/start`.
18
+ Codex retains responsibility for model execution, thread persistence and
19
+ history. The adapter injects BrainX instructions and skill configuration,
20
+ enforces read-only/no-approval execution, prevents recursive reviewer startup,
21
+ returns completed assistant reports, and forwards cancellation to
22
+ `turn/interrupt`. It does not copy or recreate Codex's execution engine.
23
+
24
+ The repository smoke test checks native-thread behavior against the real App
25
+ Server with a local Responses fixture. It verifies persisted-thread resume
26
+ after restarting the adapter without calling a hosted model.
@@ -0,0 +1,177 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createInterface } from 'node:readline';
3
+ import cliInvocation from './cli-invocation.cjs';
4
+
5
+ const { codexInvocation } = cliInvocation;
6
+
7
+ // App Server owns native threads and persistence. This client translates only
8
+ // transport, turn completion and cancellation; it never reconstructs history.
9
+ export class AppServerClient {
10
+ constructor({ binary = process.env.BRAINX_CODEX_BIN || 'codex', prefixArgs = [],
11
+ timeoutMs = 30 * 60 * 1000 } = {}) {
12
+ this.binary = binary;
13
+ this.prefixArgs = prefixArgs;
14
+ this.timeoutMs = timeoutMs;
15
+ this.pending = new Map();
16
+ this.turns = new Map();
17
+ this.nextId = 1;
18
+ }
19
+
20
+ initialize() {
21
+ if (!this.ready) this.ready = this.connect();
22
+ return this.ready;
23
+ }
24
+
25
+ async connect() {
26
+ const invocation = codexInvocation(this.binary, this.prefixArgs);
27
+ this.child = spawn(invocation.binary, [...invocation.prefixArgs, 'app-server', '--listen', 'stdio://'], {
28
+ env: process.env, stdio: ['pipe', 'pipe', 'inherit'],
29
+ });
30
+ this.child.on('error', (error) => this.fail(new Error(`Cannot start Codex App Server: ${error.message}`)));
31
+ this.child.on('exit', () => this.fail(new Error('Codex App Server exited. Check that the CLI supports codex app-server.')));
32
+ this.child.stdin.on('error', () => this.fail(new Error('Codex App Server input closed')));
33
+ this.lines = createInterface({ input: this.child.stdout, crlfDelay: Infinity });
34
+ this.lines.on('line', (line) => {
35
+ try { this.receive(JSON.parse(line)); }
36
+ catch { this.fail(new Error('Invalid Codex App Server response')); }
37
+ });
38
+ await this.request('initialize', {
39
+ clientInfo: { name: 'brainx_reviewer', title: 'BrainX reviewer', version: '2.0.0' },
40
+ }, 20_000);
41
+ this.send({ method: 'initialized', params: {} });
42
+ this.mcpServerNames = await this.readMcpServerNames();
43
+ }
44
+
45
+ async readMcpServerNames(cwd) {
46
+ const { config } = await this.request('config/read', { cwd, includeLayers: false }, 20_000);
47
+ return Object.keys(config.mcp_servers || {});
48
+ }
49
+
50
+ send(message) {
51
+ if (this.failure) throw this.failure;
52
+ this.child.stdin.write(`${JSON.stringify(message)}\n`);
53
+ }
54
+
55
+ request(method, params, timeoutMs = this.timeoutMs) {
56
+ if (this.failure) return Promise.reject(this.failure);
57
+ const id = this.nextId++;
58
+ return new Promise((resolve, reject) => {
59
+ const timer = setTimeout(() => {
60
+ this.pending.delete(id);
61
+ reject(new Error(`Codex App Server timed out: ${method}`));
62
+ }, timeoutMs);
63
+ this.pending.set(id, { resolve, reject, timer });
64
+ try { this.send({ id, method, params }); }
65
+ catch (error) { clearTimeout(timer); this.pending.delete(id); reject(error); }
66
+ });
67
+ }
68
+
69
+ receive(message) {
70
+ if (message.method && message.id !== undefined) {
71
+ // The reviewer never approves commands, file changes or permission
72
+ // escalation. Unknown server requests fail explicitly instead of hanging.
73
+ if (['item/commandExecution/requestApproval', 'item/fileChange/requestApproval'].includes(message.method)) {
74
+ this.send({ id: message.id, result: { decision: 'decline' } });
75
+ } else {
76
+ this.send({ id: message.id, error: { code: -32601, message: 'Reviewer does not support interactive requests' } });
77
+ }
78
+ return;
79
+ }
80
+ if (message.id !== undefined) {
81
+ const pending = this.pending.get(message.id);
82
+ if (!pending) return;
83
+ this.pending.delete(message.id);
84
+ clearTimeout(pending.timer);
85
+ if (message.error) pending.reject(new Error(message.error.message || 'Codex App Server request failed'));
86
+ else pending.resolve(message.result);
87
+ return;
88
+ }
89
+ const turn = this.turns.get(message.params?.threadId);
90
+ if (turn) {
91
+ if (!turn.id) turn.buffer.push(message);
92
+ else this.turnEvent(turn, message);
93
+ }
94
+ }
95
+
96
+ turnEvent(turn, { method, params }) {
97
+ if (params.turnId !== turn.id && params.turn?.id !== turn.id) return;
98
+ if (method === 'item/completed' && params.item?.type === 'agentMessage'
99
+ && params.item.phase !== 'commentary') {
100
+ turn.messages.set(params.item.id, params.item.text);
101
+ }
102
+ if (method === 'turn/completed') {
103
+ if (params.turn.status !== 'completed') {
104
+ turn.reject(new Error(params.turn.error?.message || `Review turn ${params.turn.status}`));
105
+ } else {
106
+ const text = [...turn.messages.values()].join('\n\n');
107
+ if (!text.trim()) turn.reject(new Error('Reviewer completed without a report'));
108
+ else turn.resolve(text);
109
+ }
110
+ }
111
+ }
112
+
113
+ async runTurn(threadId, prompt, signal) {
114
+ if (signal?.aborted) throw new Error('Review cancelled');
115
+ if (this.turns.has(threadId)) throw new Error('A review is already active on this thread');
116
+ const turn = { buffer: [], messages: new Map() };
117
+ const completion = new Promise((resolve, reject) => Object.assign(turn, { resolve, reject }));
118
+ // A process exit may reject completion while turn/start is still pending.
119
+ completion.catch(() => {});
120
+ this.turns.set(threadId, turn);
121
+ const interrupt = () => {
122
+ if (turn.id) this.request('turn/interrupt', { threadId, turnId: turn.id }, 10_000)
123
+ .catch(() => turn.reject(new Error('Review cancellation failed')));
124
+ };
125
+ const abort = () => {
126
+ interrupt();
127
+ turn.cancelTimer = setTimeout(() => {
128
+ this.fail(new Error('Review cancellation timed out'));
129
+ this.child.kill();
130
+ }, 10_000);
131
+ };
132
+ signal?.addEventListener('abort', abort, { once: true });
133
+ const timer = setTimeout(() => {
134
+ interrupt();
135
+ this.fail(new Error('Review turn timed out'));
136
+ this.child.kill();
137
+ }, this.timeoutMs);
138
+ try {
139
+ const result = await this.request('turn/start', {
140
+ threadId, input: [{ type: 'text', text: prompt, text_elements: [] }],
141
+ approvalPolicy: 'never',
142
+ });
143
+ turn.id = result.turn.id;
144
+ for (const message of turn.buffer) this.turnEvent(turn, message);
145
+ turn.buffer = [];
146
+ if (signal?.aborted) interrupt();
147
+ return await completion;
148
+ } finally {
149
+ clearTimeout(timer);
150
+ clearTimeout(turn.cancelTimer);
151
+ signal?.removeEventListener('abort', abort);
152
+ this.turns.delete(threadId);
153
+ }
154
+ }
155
+
156
+ fail(error) {
157
+ this.failure ||= error;
158
+ for (const pending of this.pending.values()) {
159
+ clearTimeout(pending.timer);
160
+ pending.reject(this.failure);
161
+ }
162
+ this.pending.clear();
163
+ for (const turn of this.turns.values()) turn.reject(this.failure);
164
+ }
165
+
166
+ close() {
167
+ this.fail(new Error('Reviewer connection closed'));
168
+ this.lines?.close();
169
+ const child = this.child;
170
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
171
+ // Let the CLI exit on EOF. An npm shim can have a native child of its own.
172
+ child.stdin.end();
173
+ const timer = setTimeout(() => child.kill(), 2_000);
174
+ timer.unref();
175
+ child.once('close', () => clearTimeout(timer));
176
+ }
177
+ }
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ const { existsSync } = require('node:fs');
4
+ const { win32 } = require('node:path');
5
+
6
+ function windowsInvocation(binary, args, packageEntry, { pathValue, exists }) {
7
+ let executable = binary;
8
+ if (!/[\\/]/.test(binary)) {
9
+ const names = win32.extname(binary) ? [binary] : [`${binary}.exe`, `${binary}.cmd`, binary];
10
+ for (const directory of pathValue.split(';')) {
11
+ const candidate = names.map((name) => win32.join(directory.replace(/^"|"$/g, ''), name)).find(exists);
12
+ if (candidate) {
13
+ executable = candidate;
14
+ break;
15
+ }
16
+ }
17
+ }
18
+ if (!/\.(cmd|bat|ps1)$/i.test(executable)) return { binary: executable, prefixArgs: args };
19
+
20
+ const directory = win32.dirname(executable);
21
+ const modules = win32.basename(directory) === '.bin'
22
+ ? win32.dirname(directory) : win32.join(directory, 'node_modules');
23
+ const entry = win32.join(modules, ...packageEntry);
24
+ if (!exists(entry)) throw new Error(`Cannot find the JavaScript entry for ${executable}. Use the installed executable or a standard npm shim.`);
25
+ return { binary: process.execPath, prefixArgs: [entry, ...args] };
26
+ }
27
+
28
+ function codexInvocation(binary, prefixArgs = [], {
29
+ platform = process.platform, pathValue = process.env.PATH || '', exists = existsSync,
30
+ } = {}) {
31
+ if (platform !== 'win32') return { binary, prefixArgs };
32
+ try {
33
+ return windowsInvocation(binary, prefixArgs, ['@openai', 'codex', 'bin', 'codex.js'], { pathValue, exists });
34
+ } catch (error) {
35
+ throw new Error(`${error.message} Set BRAINX_CODEX_BIN to a supported Codex executable.`, { cause: error });
36
+ }
37
+ }
38
+
39
+ function npmInvocation(binary, prefixArgs, {
40
+ platform = process.platform, pathValue = process.env.PATH || '', exists = existsSync,
41
+ npmExecPath = process.env.npm_execpath,
42
+ } = {}) {
43
+ if (platform !== 'win32') return { binary, prefixArgs };
44
+ if (binary === 'npm' && npmExecPath && win32.basename(npmExecPath) === 'npm-cli.js' && exists(npmExecPath)) {
45
+ return { binary: process.execPath, prefixArgs: [npmExecPath, ...prefixArgs] };
46
+ }
47
+ return windowsInvocation(binary, prefixArgs, ['npm', 'bin', 'npm-cli.js'], { pathValue, exists });
48
+ }
49
+
50
+ module.exports = { codexInvocation, npmInvocation };
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { spawn } from 'node:child_process';
4
3
  import { readFileSync } from 'node:fs';
5
4
  import { dirname, resolve } from 'node:path';
6
5
  import { createInterface } from 'node:readline';
7
- import { fileURLToPath } from 'node:url';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { AppServerClient } from './app-server.mjs';
8
8
 
9
9
  const serverDirectory = dirname(fileURLToPath(import.meta.url));
10
10
  const repositoryRoot = resolve(serverDirectory, '../..');
@@ -62,81 +62,148 @@ const skillInstructions = [
62
62
  `FITTING_REVIEW_REFERENCE: ${reviewReferences.fitting}`,
63
63
  ].join('\n');
64
64
 
65
- function transformMessage(message) {
66
- if (Array.isArray(message)) {
67
- return message.map(transformMessage);
68
- }
69
- if (
70
- message === null
71
- || typeof message !== 'object'
72
- || message.method !== 'tools/call'
73
- || message.params?.name !== 'codex'
74
- ) {
75
- return message;
76
- }
77
-
78
- const originalArguments = message.params.arguments;
79
- const args = originalArguments && typeof originalArguments === 'object'
80
- ? { ...originalArguments }
81
- : {};
82
- const config = args.config && typeof args.config === 'object'
83
- ? { ...args.config }
84
- : {};
85
-
86
- config['skills.config'] = exposedSkills;
87
-
88
- return {
89
- ...message,
90
- params: {
91
- ...message.params,
92
- arguments: {
93
- ...args,
94
- config,
95
- 'approval-policy': 'never',
96
- 'base-instructions': systemPrompt,
97
- 'developer-instructions': skillInstructions,
98
- sandbox: 'read-only',
65
+ const tools = [
66
+ {
67
+ name: 'codex', description: 'Start an independent read-only BrainX scientific review.',
68
+ inputSchema: {
69
+ type: 'object', required: ['prompt'], additionalProperties: false,
70
+ properties: {
71
+ prompt: { type: 'string' }, model: { type: 'string' }, cwd: { type: 'string' },
72
+ config: { type: 'object', additionalProperties: true },
73
+ 'approval-policy': { type: 'string', description: 'Ignored: reviews always use never.' },
74
+ sandbox: { type: 'string', description: 'Ignored: reviews always use read-only.' },
75
+ 'base-instructions': { type: 'string', description: 'Ignored: the BrainX reviewer contract is mandatory.' },
76
+ 'developer-instructions': { type: 'string', description: 'Ignored: BrainX skill guidance is mandatory.' },
77
+ profile: { type: 'string', description: 'Unsupported; use model, cwd or config overrides.' },
99
78
  },
100
79
  },
80
+ },
81
+ {
82
+ name: 'codex-reply', description: 'Continue a BrainX review in its native Codex thread.',
83
+ inputSchema: {
84
+ type: 'object', required: ['threadId', 'prompt'], additionalProperties: false,
85
+ properties: { threadId: { type: 'string' }, prompt: { type: 'string' } },
86
+ },
87
+ },
88
+ ].map((tool) => ({ ...tool, outputSchema: {
89
+ type: 'object', properties: { threadId: { type: 'string' }, content: { type: 'string' } },
90
+ required: ['threadId', 'content'],
91
+ } }));
92
+
93
+ function reviewOptions(args = {}, mcpServerNames = []) {
94
+ const overrides = Object.fromEntries(Object.entries(args.config || {}).filter(
95
+ ([key]) => key !== 'mcp_servers' && !key.startsWith('mcp_servers.'),
96
+ ));
97
+ const config = { ...overrides,
98
+ 'skills.config': exposedSkills,
99
+ approval_policy: 'never', sandbox_mode: 'read-only',
100
+ base_instructions: systemPrompt, developer_instructions: skillInstructions,
101
+ };
102
+ // Disable only registrations that actually exist. A lone enabled=false
103
+ // override creates an invalid transport when the child has no such server.
104
+ for (const name of mcpServerNames) config[`mcp_servers.${name}.enabled`] = false;
105
+ return {
106
+ ...(args.model ? { model: args.model } : {}),
107
+ ...(args.cwd ? { cwd: args.cwd } : {}),
108
+ approvalPolicy: 'never', sandbox: 'read-only',
109
+ baseInstructions: systemPrompt, developerInstructions: skillInstructions, config,
101
110
  };
102
111
  }
103
112
 
104
- const codexBinary = process.env.BRAINX_CODEX_BIN || 'codex';
105
- const child = spawn(codexBinary, ['mcp-server'], {
106
- env: process.env,
107
- stdio: ['pipe', 'pipe', 'inherit'],
108
- });
109
-
110
- child.on('error', (error) => {
111
- process.stderr.write(`Failed to start ${codexBinary} mcp-server: ${error.message}\n`);
112
- process.exitCode = 1;
113
- });
114
- child.stdin.on('error', (error) => {
115
- if (error.code !== 'EPIPE') {
116
- process.stderr.write(`Codex MCP stdin failed: ${error.message}\n`);
113
+ export function serve(client = new AppServerClient()) {
114
+ let initialization;
115
+ let initialized = false;
116
+ const active = new Map();
117
+ const locks = new Set();
118
+ const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
119
+ const write = (message) => process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`);
120
+ const error = (id, code, message) => write({ id, error: { code, message } });
121
+
122
+ async function review(name, args, signal) {
123
+ if (!args || typeof args.prompt !== 'string' || !args.prompt.trim()) {
124
+ throw new Error('prompt must be a non-empty string');
125
+ }
126
+ if (name === 'codex' && args.profile !== undefined) {
127
+ throw new Error('profile is not supported; use explicit model, cwd or config overrides');
128
+ }
129
+ let threadId;
130
+ if (name === 'codex') {
131
+ const servers = args.cwd ? await client.readMcpServerNames(args.cwd) : client.mcpServerNames;
132
+ const result = await client.request('thread/start', reviewOptions(args, servers));
133
+ threadId = result.thread.id;
134
+ } else {
135
+ if (typeof args.threadId !== 'string' || !args.threadId) throw new Error('threadId is required');
136
+ threadId = args.threadId;
137
+ }
138
+ if (locks.has(threadId)) throw new Error('A review is already active on this thread');
139
+ locks.add(threadId);
140
+ try {
141
+ if (signal.aborted) throw new Error('Review cancelled');
142
+ if (name === 'codex-reply') {
143
+ const { thread } = await client.request('thread/read', { threadId, includeTurns: false });
144
+ const servers = thread.cwd ? await client.readMcpServerNames(thread.cwd) : client.mcpServerNames;
145
+ await client.request('thread/resume', {
146
+ threadId, excludeTurns: true, ...reviewOptions({}, servers),
147
+ });
148
+ }
149
+ const content = await client.runTurn(threadId, args.prompt, signal);
150
+ return { content: [{ type: 'text', text: content }], structuredContent: { threadId, content } };
151
+ } finally { locks.delete(threadId); }
117
152
  }
118
- });
119
153
 
120
- child.stdout.pipe(process.stdout);
121
-
122
- const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
123
- input.on('line', (line) => {
124
- try {
125
- const message = JSON.parse(line);
126
- const transformed = transformMessage(message);
127
- child.stdin.write(`${JSON.stringify(transformed)}\n`);
128
- } catch {
129
- child.stdin.write(`${line}\n`);
154
+ async function dispatch(message, signal) {
155
+ const { id, method, params } = message;
156
+ if (method === 'initialize') {
157
+ if (initialization) throw Object.assign(new Error('Already initialized'), { code: -32600 });
158
+ initialization = client.initialize();
159
+ await initialization;
160
+ initialized = true;
161
+ return {
162
+ protocolVersion: ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'].includes(params?.protocolVersion)
163
+ ? params.protocolVersion : '2024-11-05',
164
+ capabilities: { tools: {} }, serverInfo: { name: 'brainx-codex-reviewer', version: '2.0.0' },
165
+ };
166
+ }
167
+ if (method === 'ping') return {};
168
+ if (!initialized) throw Object.assign(new Error('Not initialized'), { code: -32000 });
169
+ if (method === 'tools/list') return { tools };
170
+ if (method === 'tools/call') {
171
+ if (!tools.some((tool) => tool.name === params?.name)) {
172
+ throw Object.assign(new Error('Unknown reviewer tool'), { code: -32602 });
173
+ }
174
+ try { return await review(params.name, params.arguments, signal); }
175
+ catch (failure) { return { isError: true, content: [{ type: 'text', text: failure.message }] }; }
176
+ }
177
+ throw Object.assign(new Error('Method not found'), { code: -32601 });
130
178
  }
131
- });
132
- input.on('close', () => child.stdin.end());
133
179
 
134
- for (const signal of ['SIGINT', 'SIGTERM']) {
135
- process.on(signal, () => child.kill(signal));
180
+ input.on('line', (line) => {
181
+ let message;
182
+ try { message = JSON.parse(line); }
183
+ catch { error(null, -32700, 'Parse error'); return; }
184
+ if (!message || Array.isArray(message) || message.jsonrpc !== '2.0'
185
+ || typeof message.method !== 'string') {
186
+ error(message?.id ?? null, -32600, 'Invalid request'); return;
187
+ }
188
+ if (message.method === 'notifications/cancelled') {
189
+ active.get(message.params?.requestId)?.controller.abort(); return;
190
+ }
191
+ if (message.id === undefined) return;
192
+ if (active.has(message.id)) { error(message.id, -32600, 'Duplicate active request id'); return; }
193
+ const controller = new AbortController();
194
+ const task = dispatch(message, controller.signal)
195
+ .then((result) => write({ id: message.id, result }))
196
+ .catch((failure) => error(message.id, failure.code || -32603, failure.message))
197
+ .finally(() => active.delete(message.id));
198
+ active.set(message.id, { controller, task });
199
+ });
200
+ input.on('close', () => {
201
+ for (const { controller } of active.values()) controller.abort();
202
+ Promise.allSettled([...active.values()].map(({ task }) => task)).finally(() => client.close());
203
+ });
204
+ for (const signal of ['SIGINT', 'SIGTERM']) {
205
+ process.once(signal, () => { client.close(); input.close(); process.stdin.pause(); });
206
+ }
136
207
  }
137
208
 
138
- child.on('exit', (code, signal) => {
139
- input.close();
140
- process.stdin.pause();
141
- process.exitCode = code ?? (signal ? 1 : 0);
142
- });
209
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) serve();
@@ -1,6 +1,83 @@
1
- #!/usr/bin/env node
2
-
3
1
  import { createInterface } from 'node:readline';
4
2
 
3
+ const threads = new Map();
4
+ const turns = new Map();
5
+ const approvals = new Map();
6
+ let nextThread = 1;
7
+ let nextTurn = 1;
8
+ const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
9
+ function finish(threadId, turnId, prompt, decision) {
10
+ if (prompt === 'empty') {
11
+ write({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'completed' } } });
12
+ return;
13
+ }
14
+ const thread = threads.get(threadId);
15
+ write({ method: 'item/completed', params: { threadId, turnId,
16
+ item: { type: 'agentMessage', id: 'comment', phase: 'commentary', text: 'Ignore commentary' } } });
17
+ // An event from another turn must never enter the report.
18
+ write({ method: 'item/completed', params: { threadId, turnId: 'unrelated',
19
+ item: { type: 'agentMessage', id: 'wrong', text: 'Wrong turn' } } });
20
+ write({ method: 'item/completed', params: { threadId, turnId,
21
+ item: { type: 'agentMessage', id: 'report', phase: 'final_answer',
22
+ text: JSON.stringify({ thread, turn: turns.get(turnId), decision,
23
+ argv: process.argv.slice(2) }) } } });
24
+ write({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'completed' } } });
25
+ }
26
+
5
27
  const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
6
- input.on('line', (line) => process.stdout.write(`${line}\n`));
28
+ input.on('line', (line) => {
29
+ const { id, method, params, result } = JSON.parse(line);
30
+ if (approvals.has(id)) {
31
+ const turn = approvals.get(id); finish(...turn, result.decision); approvals.delete(id); return;
32
+ }
33
+ if (method === 'initialize') { write({ id, result: {} }); return; }
34
+ if (method === 'config/read') {
35
+ const servers = process.env.TEST_NO_MCP ? {} : { codex: { command: 'node' } };
36
+ if (params.cwd) servers.project_mcp = { command: 'node' };
37
+ write({ id, result: { config: { mcp_servers: servers } } }); return;
38
+ }
39
+ if (method === 'thread/start') {
40
+ const threadId = `thread-${nextThread++}`;
41
+ threads.set(threadId, { start: params, history: [] });
42
+ write({ id, result: { thread: { id: threadId } } }); return;
43
+ }
44
+ if (method === 'thread/resume') {
45
+ const thread = threads.get(params.threadId);
46
+ if (!thread) { write({ id, error: { code: -32000, message: 'Thread not found' } }); return; }
47
+ thread.resume = params;
48
+ write({ id, result: { thread: { id: params.threadId } } }); return;
49
+ }
50
+ if (method === 'thread/read') {
51
+ const thread = threads.get(params.threadId);
52
+ if (!thread) { write({ id, error: { code: -32000, message: 'Thread not found' } }); return; }
53
+ write({ id, result: { thread: { id: params.threadId, cwd: thread.start.cwd } } }); return;
54
+ }
55
+ if (method === 'turn/start') {
56
+ const { threadId } = params;
57
+ const turnId = `turn-${nextTurn++}`;
58
+ const prompt = params.input[0].text;
59
+ threads.get(threadId).history.push(prompt);
60
+ turns.set(turnId, params);
61
+ if (prompt === 'crash') { process.exit(1); }
62
+ if (prompt !== 'early') write({ id, result: { turn: { id: turnId } } });
63
+ if (prompt === 'stall') return;
64
+ if (prompt === 'approval') {
65
+ const approvalId = `approval-${turnId}`;
66
+ approvals.set(approvalId, [threadId, turnId, prompt]);
67
+ write({ id: approvalId, method: 'item/commandExecution/requestApproval', params: { threadId, turnId } });
68
+ return;
69
+ }
70
+ if (prompt === 'fail') {
71
+ write({ method: 'turn/completed', params: { threadId,
72
+ turn: { id: turnId, status: 'failed', error: { message: 'Model unavailable' } } } }); return;
73
+ }
74
+ finish(threadId, turnId, prompt);
75
+ if (prompt === 'early') write({ id, result: { turn: { id: turnId } } });
76
+ return;
77
+ }
78
+ if (method === 'turn/interrupt') {
79
+ write({ id, result: {} });
80
+ write({ method: 'turn/completed', params: { threadId: params.threadId,
81
+ turn: { id: params.turnId, status: 'interrupted' } } });
82
+ }
83
+ });
@@ -0,0 +1,7 @@
1
+ import { AppServerClient } from '../../app-server.mjs';
2
+ import { serve } from '../../server.mjs';
3
+ import { fileURLToPath } from 'node:url';
4
+ serve(new AppServerClient({ binary: process.execPath,
5
+ prefixArgs: [fileURLToPath(new URL('./fake-codex.mjs', import.meta.url))],
6
+ timeoutMs: Number(process.env.TEST_REVIEW_TIMEOUT_MS || 5000),
7
+ }));
@@ -1,99 +1,203 @@
1
1
  import assert from 'node:assert/strict';
2
- import { chmodSync } from 'node:fs';
3
- import { dirname, resolve } from 'node:path';
2
+ import { spawn } from 'node:child_process';
3
+ import { createInterface } from 'node:readline';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import test from 'node:test';
6
- import { spawn } from 'node:child_process';
6
+ import cliInvocation from '../cli-invocation.cjs';
7
7
 
8
- const testDirectory = dirname(fileURLToPath(import.meta.url));
9
- const server = resolve(testDirectory, '..', 'server.mjs');
10
- const fakeCodex = resolve(testDirectory, 'fixtures', 'fake-codex.mjs');
11
- chmodSync(fakeCodex, 0o755);
8
+ const { codexInvocation, npmInvocation } = cliInvocation;
12
9
 
13
- function runProxy(messages) {
14
- return new Promise((resolveOutput, reject) => {
15
- const child = spawn(process.execPath, [server], {
16
- env: { ...process.env, BRAINX_CODEX_BIN: fakeCodex },
17
- stdio: ['pipe', 'pipe', 'pipe'],
10
+ const runner = fileURLToPath(new URL('./fixtures/run-server.mjs', import.meta.url));
11
+ class Session {
12
+ constructor(t, env = {}) {
13
+ this.child = spawn(process.execPath, [runner], {
14
+ env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'],
15
+ });
16
+ this.pending = new Map();
17
+ this.nextId = 1;
18
+ this.stderr = '';
19
+ this.child.stderr.on('data', (data) => { this.stderr += data; });
20
+ this.lines = createInterface({ input: this.child.stdout });
21
+ this.lines.on('line', (line) => {
22
+ const message = JSON.parse(line);
23
+ const entry = this.pending.get(message.id);
24
+ if (!entry) return;
25
+ clearTimeout(entry.timer); this.pending.delete(message.id);
26
+ entry.resolve(message);
27
+ });
28
+ this.child.on('exit', () => {
29
+ for (const entry of this.pending.values()) { clearTimeout(entry.timer); entry.reject(new Error(this.stderr)); }
30
+ this.pending.clear();
18
31
  });
19
- let stdout = '';
20
- let stderr = '';
21
- child.stdout.on('data', (chunk) => { stdout += chunk; });
22
- child.stderr.on('data', (chunk) => { stderr += chunk; });
23
- child.on('error', reject);
24
- child.on('exit', (code) => {
25
- if (code !== 0) {
26
- reject(new Error(`proxy exited ${code}: ${stderr}`));
27
- return;
28
- }
29
- resolveOutput(stdout.trimEnd().split('\n').map((line) => JSON.parse(line)));
32
+ t.after(async () => {
33
+ this.child.stdin.end();
34
+ if (this.child.exitCode === null) await new Promise((resolve) => this.child.once('exit', resolve));
35
+ this.lines.close();
30
36
  });
31
- for (const message of messages) {
32
- child.stdin.write(`${JSON.stringify(message)}\n`);
33
- }
34
- child.stdin.end();
37
+ }
38
+ send(method, params, id) { this.child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method, params, ...(id === undefined ? {} : { id }) })}\n`); }
39
+ request(method, params) {
40
+ const id = this.nextId++;
41
+ const promise = new Promise((resolve, reject) => {
42
+ const timer = setTimeout(() => { this.child.kill(); reject(new Error(`Timed out: ${method}: ${this.stderr}`)); }, 10000);
43
+ this.pending.set(id, { resolve, reject, timer });
44
+ });
45
+ this.send(method, params, id);
46
+ return { id, promise };
47
+ }
48
+ async call(method, params) {
49
+ const response = await this.request(method, params).promise;
50
+ assert.equal(response.error, undefined, JSON.stringify(response.error));
51
+ return response.result;
52
+ }
53
+ async initialize() {
54
+ await this.call('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'test', version: '1' } });
55
+ this.send('notifications/initialized');
56
+ }
57
+ review(args, name = 'codex') { return this.call('tools/call', { name, arguments: args }); }
58
+ }
59
+
60
+ function assertContract(options) {
61
+ assert.equal(options.approvalPolicy, 'never');
62
+ assert.equal(options.sandbox, 'read-only');
63
+ assert.match(options.baseInstructions, /independent computational-neuroscience/);
64
+ assert.match(options.baseInstructions, /Open and read `brainx-general-guard` first/);
65
+ assert.match(options.baseInstructions, /RETURN_TO_STUDY/);
66
+ assert.match(options.baseInstructions, /# BrainX iteration review/);
67
+ assert.match(options.developerInstructions, /TRAINING_REVIEW_REFERENCE: .*training-workflow\.md/);
68
+ assert.match(options.developerInstructions, /FITTING_REVIEW_REFERENCE: .*parameter-fitting-workflow\.md/);
69
+ assert.doesNotMatch(options.developerInstructions, /^- brainx-modeling-loop$/m);
70
+ assert.equal(options.config['skills.config'].length, 8);
71
+ assert.ok(options.config['skills.config'].every((skill) => skill.enabled));
72
+ assert.equal(options.config['mcp_servers.codex.enabled'], false);
73
+ assert.equal(options.config.approval_policy, 'never');
74
+ assert.equal(options.config.sandbox_mode, 'read-only');
75
+ }
76
+
77
+ test('advertises legacy tool names over MCP after initializing App Server', async (t) => {
78
+ const session = new Session(t); await session.initialize();
79
+ const result = await session.call('tools/list');
80
+ assert.deepEqual(result.tools.map((tool) => tool.name), ['codex', 'codex-reply']);
81
+ assert.deepEqual(result.tools[1].inputSchema.required, ['threadId', 'prompt']);
82
+ });
83
+
84
+ test('starts a native review with enforced instructions, read-only policy and caller settings', async (t) => {
85
+ const session = new Session(t); await session.initialize();
86
+ const result = await session.review({ prompt: 'Review iteration 4', model: 'test-model', cwd: process.cwd(),
87
+ sandbox: 'danger-full-access', 'approval-policy': 'on-request',
88
+ 'base-instructions': 'bypass', config: { model_reasoning_effort: 'xhigh',
89
+ sandbox_mode: 'danger-full-access', 'skills.config': [],
90
+ mcp_servers: { other: { command: 'node' } }, 'mcp_servers.other.command': 'node' } });
91
+ assert.equal(result.isError, undefined);
92
+ const report = JSON.parse(result.content[0].text);
93
+ assertContract(report.thread.start);
94
+ assert.equal(report.thread.start.model, 'test-model');
95
+ assert.equal(report.thread.start.cwd, process.cwd());
96
+ assert.equal(report.thread.start.config.model_reasoning_effort, 'xhigh');
97
+ assert.equal(report.thread.start.config['mcp_servers.project_mcp.enabled'], false);
98
+ assert.equal(report.thread.start.config['mcp_servers.other.command'], undefined);
99
+ assert.equal(report.thread.start.config.mcp_servers, undefined);
100
+ assert.deepEqual(report.argv, ['app-server', '--listen', 'stdio://']);
101
+ assert.equal(result.structuredContent.threadId, 'thread-1');
102
+ assert.equal(result.structuredContent.content, result.content[0].text);
103
+ });
104
+
105
+ test('resumes the same native thread and reapplies reviewer constraints', async (t) => {
106
+ const session = new Session(t); await session.initialize();
107
+ const first = await session.review({ prompt: 'first', cwd: process.cwd() });
108
+ const threadId = first.structuredContent.threadId;
109
+ const next = await session.review({ threadId, prompt: 'follow-up' }, 'codex-reply');
110
+ const report = JSON.parse(next.content[0].text);
111
+ assert.deepEqual(report.thread.history, ['first', 'follow-up']);
112
+ assertContract(report.thread.resume);
113
+ assert.equal(report.thread.resume.config['mcp_servers.project_mcp.enabled'], false);
114
+ assert.equal(report.thread.resume.excludeTurns, true);
115
+ assert.equal(next.structuredContent.threadId, threadId);
116
+ });
117
+
118
+ test('handles completion arriving before the turn/start response', async (t) => {
119
+ const session = new Session(t); await session.initialize();
120
+ const result = await session.review({ prompt: 'early' });
121
+ assert.equal(result.isError, undefined);
122
+ assert.deepEqual(JSON.parse(result.content[0].text).thread.history, ['early']);
123
+ });
124
+
125
+ for (const [prompt, message] of [['fail', /Model unavailable/], ['empty', /without a report/], ['crash', /exited/]]) {
126
+ test(`returns a tool error for ${prompt}`, async (t) => {
127
+ const session = new Session(t); await session.initialize();
128
+ const result = await session.review({ prompt });
129
+ assert.equal(result.isError, true); assert.match(result.content[0].text, message);
35
130
  });
36
131
  }
37
132
 
38
- test('injects the reviewer prompt and configured BrainX skills into fresh sessions', async () => {
39
- const [message] = await runProxy([{
40
- jsonrpc: '2.0',
41
- id: 1,
42
- method: 'tools/call',
43
- params: {
44
- name: 'codex',
45
- arguments: {
46
- prompt: 'Review iteration 4',
47
- 'approval-policy': 'on-request',
48
- sandbox: 'danger-full-access',
49
- config: { model_reasoning_effort: 'xhigh' },
50
- },
51
- },
52
- }]);
53
-
54
- const args = message.params.arguments;
55
- assert.match(args['base-instructions'], /independent computational-neuroscience/);
56
- assert.match(args['base-instructions'], /Open and read `brainx-general-guard` first/);
57
- assert.match(args['base-instructions'], /Is the result scientifically backed/);
58
- assert.match(args['base-instructions'], /Is the code minimal and BrainX-native/);
59
- assert.match(args['base-instructions'], /Is training or fitting good enough/);
60
- assert.match(args['base-instructions'], /\*\*Loss closure:\*\*/);
61
- assert.match(args['base-instructions'], /\*\*Architecture:\*\*/);
62
- assert.match(args['base-instructions'], /\*\*Hyperparameters and method:\*\*/);
63
- assert.match(args['base-instructions'], /BrainState's prebuilt `brainstate\.nn` layers/);
64
- assert.match(args['base-instructions'], /braintools\.optim\.Adam/);
65
- assert.match(args['base-instructions'], /BrainTools API gap/);
66
- assert.match(args['base-instructions'], /RETURN_TO_STUDY/);
67
- assert.match(args['base-instructions'], /Return a Markdown document as the tool response/);
68
- assert.match(args['base-instructions'], /# BrainX iteration review/);
69
- assert.match(args['base-instructions'], /- \*\*OUTCOME:\*\* `PASS \| REFUSE`/);
70
- assert.match(args['base-instructions'], /- \*\*LOSS_CLOSURE:\*\* `NOT_APPLICABLE/);
71
- assert.match(args['base-instructions'], /## Findings/);
72
- assert.doesNotMatch(args['base-instructions'], /```text\s+OUTCOME:/);
73
- assert.match(args['base-instructions'], /Keep plotting code minimal and clean/);
74
- assert.match(args['developer-instructions'], /brainx-general-guard/);
75
- assert.match(args['developer-instructions'], /TRAINING_REVIEW_REFERENCE: \/.*\/training-workflow\.md/);
76
- assert.match(args['developer-instructions'], /FITTING_REVIEW_REFERENCE: \/.*\/parameter-fitting-workflow\.md/);
77
- assert.doesNotMatch(args['developer-instructions'], /^- brainx-modeling-loop$/m);
78
- assert.equal(args.config.model_reasoning_effort, 'xhigh');
79
- assert.equal(args['approval-policy'], 'never');
80
- assert.equal(args.sandbox, 'read-only');
81
- assert.equal(args.config['skills.config'].length, 8);
82
- assert.ok(args.config['skills.config'].every((skill) => skill.enabled));
83
- assert.ok(args.config['skills.config'].every((skill) => skill.path.startsWith('/')));
133
+ test('declines unexpected command approval rather than granting write access', async (t) => {
134
+ const session = new Session(t); await session.initialize();
135
+ const result = await session.review({ prompt: 'approval' });
136
+ assert.equal(JSON.parse(result.content[0].text).decision, 'decline');
137
+ });
138
+
139
+ test('cancellation interrupts the native turn and leaves the thread usable', async (t) => {
140
+ const session = new Session(t); await session.initialize();
141
+ const first = await session.review({ prompt: 'first' }); const threadId = first.structuredContent.threadId;
142
+ const request = session.request('tools/call', { name: 'codex-reply', arguments: { threadId, prompt: 'stall' } });
143
+ // Let the fake backend start its stalled turn before cancellation.
144
+ await new Promise((resolve) => setTimeout(resolve, 100));
145
+ session.send('notifications/cancelled', { requestId: request.id });
146
+ const cancelled = (await request.promise).result;
147
+ assert.equal(cancelled.isError, true); assert.match(cancelled.content[0].text, /interrupted|cancelled/i);
148
+ const next = await session.review({ threadId, prompt: 'after cancellation' }, 'codex-reply');
149
+ assert.equal(next.isError, undefined);
150
+ });
151
+
152
+ test('a stalled review times out instead of leaving the MCP call pending', async (t) => {
153
+ const session = new Session(t, { TEST_REVIEW_TIMEOUT_MS: '300' }); await session.initialize();
154
+ const result = await session.review({ prompt: 'stall' });
155
+ assert.equal(result.isError, true); assert.match(result.content[0].text, /timed out/);
84
156
  });
85
157
 
86
- test('passes continuation and unrelated MCP messages through unchanged', async () => {
87
- const reply = {
88
- jsonrpc: '2.0',
89
- id: 2,
90
- method: 'tools/call',
91
- params: {
92
- name: 'codex-reply',
93
- arguments: { threadId: 'thread-1', prompt: 'Recheck finding BX-2' },
94
- },
158
+ test('rejects invalid input, unknown tools, and requests before initialization', async (t) => {
159
+ const session = new Session(t);
160
+ assert.equal((await session.request('tools/list').promise).error.code, -32000);
161
+ await session.initialize();
162
+ assert.equal((await session.review({ prompt: '' })).isError, true);
163
+ assert.equal((await session.review({ prompt: 'x', profile: 'unsafe' })).isError, true);
164
+ assert.equal((await session.request('tools/call', { name: 'unknown', arguments: {} }).promise).error.code, -32602);
165
+ });
166
+
167
+ test('resolves Windows npm shims without a shell and preserves argument boundaries', () => {
168
+ const entry = 'C:\\Program Files\\npm\\node_modules\\@openai\\codex\\bin\\codex.js';
169
+ const shim = 'C:\\Program Files\\npm\\codex.cmd';
170
+ const invocation = codexInvocation('codex', ['argument with spaces'], {
171
+ platform: 'win32', pathValue: 'C:\\missing;"C:\\Program Files\\npm"',
172
+ exists: (path) => [shim, entry].includes(path),
173
+ });
174
+ assert.equal(invocation.binary, process.execPath);
175
+ assert.deepEqual(invocation.prefixArgs, [entry, 'argument with spaces']);
176
+ assert.throws(() => codexInvocation(shim, [], { platform: 'win32', exists: () => false }), /BRAINX_CODEX_BIN/);
177
+
178
+ const localShim = 'C:\\Program Files\\npm\\node_modules\\.bin\\codex.cmd';
179
+ assert.deepEqual(codexInvocation(localShim, [], {
180
+ platform: 'win32', exists: (path) => path === entry,
181
+ }), { binary: process.execPath, prefixArgs: [entry] });
182
+ });
183
+
184
+ test('runs npm through its JavaScript entry when installing runtimes on Windows', () => {
185
+ const root = 'C:\\Program Files\\nodejs';
186
+ const entry = `${root}\\node_modules\\npm\\bin\\npm-cli.js`;
187
+ const args = ['install', '--ignore-scripts'];
188
+ const options = {
189
+ platform: 'win32', pathValue: root,
190
+ exists: (path) => [`${root}\\npm.cmd`, entry].includes(path),
95
191
  };
96
- const list = { jsonrpc: '2.0', id: 3, method: 'tools/list', params: {} };
192
+ for (const npmExecPath of ['', entry]) {
193
+ const invocation = npmInvocation('npm', args, { ...options, npmExecPath });
194
+ assert.deepEqual(invocation, { binary: process.execPath, prefixArgs: [entry, ...args] });
195
+ }
196
+ });
97
197
 
98
- assert.deepEqual(await runProxy([reply, list]), [reply, list]);
198
+ test('does not manufacture an invalid disabled MCP transport in an empty child configuration', async (t) => {
199
+ const session = new Session(t, { TEST_NO_MCP: '1' }); await session.initialize();
200
+ const result = await session.review({ prompt: 'isolated config' });
201
+ assert.equal(result.isError, undefined);
202
+ assert.equal(JSON.parse(result.content[0].text).thread.start.config['mcp_servers.codex.enabled'], undefined);
99
203
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brainx-skill",
3
- "version": "1.0.16",
3
+ "version": "1.0.17",
4
4
  "description": "Portable BrainX Agent Skills for Claude Code, Codex, Cursor, Windsurf, Gemini CLI, Antigravity, and OpenCode",
5
5
  "license": "Apache-2.0",
6
6
  "type": "commonjs",