Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Update native dependency and bootstrap compatibility

wyt7ae5ec4de0d4
diff --git a/bin/orkas-pkg.cjs b/bin/orkas-pkg.cjs
index d285a0e3..973018f7 100644
--- a/bin/orkas-pkg.cjs
+++ b/bin/orkas-pkg.cjs
@@ -156,13 +156,17 @@ function registryLockOwner(lockPath) {
if (!/^[1-9]\d*$/.test(raw)) return { state: 'unknown', pid: null };
const pid = Number(raw);
if (!Number.isSafeInteger(pid)) return { state: 'unknown', pid: null };
+ return { state: processOwnerState(pid), pid };
+}
+
+function processOwnerState(pid) {
try {
process.kill(pid, 0);
- return { state: 'alive', pid };
+ return 'alive';
} catch (e) {
// EPERM means the process exists but this user cannot signal it. Reclaim
// only on ESRCH so an unexpected platform error stays conservative.
- return { state: e && e.code === 'ESRCH' ? 'dead' : 'alive', pid };
+ return e && e.code === 'ESRCH' ? 'dead' : 'alive';
}
}
@@ -187,20 +191,58 @@ function cleanupAbandonedStaging(uid, deadPid) {
async function withRegistryLock(uid, fn) {
fs.mkdirSync(packagesDir(uid), { recursive: true });
const lockPath = path.join(packagesDir(uid), '_registry.lock');
+ const claimsDir = path.join(packagesDir(uid), '.registry-lock-claims');
+ const claimName = `${process.pid}-${crypto.randomBytes(16).toString('hex')}`;
+ const claimPath = path.join(claimsDir, claimName);
let fd = null;
let ownsLock = false;
+ let ownsClaim = false;
let abandonedOwnerPid = null;
// `die()` calls process.exit, which skips `finally`, so normal CLI exits use
// this hook. A host timeout can terminate the process without running either
// cleanup path; the next operation recovers that abandoned PID lock below.
const releaseLock = () => {
- if (!ownsLock) return;
- if (fd !== null) { try { fs.closeSync(fd); } catch { /* already closed */ } fd = null; }
- ownsLock = false;
- try { fs.unlinkSync(lockPath); } catch { /* already gone */ }
+ if (ownsLock) {
+ let identity;
+ try { identity = fs.fstatSync(fd, { bigint: true }); } catch { /* no owned file */ }
+ if (fd !== null) { try { fs.closeSync(fd); } catch { /* already closed */ } fd = null; }
+ ownsLock = false;
+ try {
+ const current = fs.lstatSync(lockPath, { bigint: true });
+ if (identity && current.isFile() && current.dev === identity.dev && current.ino === identity.ino
+ && fs.readFileSync(lockPath, 'utf8').trim() === String(process.pid)) fs.unlinkSync(lockPath);
+ } catch { /* missing or replaced locks are not ours to remove */ }
+ }
+ if (ownsClaim) {
+ ownsClaim = false;
+ try { fs.unlinkSync(claimPath); } catch { /* unique to this operation */ }
+ }
};
process.on('exit', releaseLock);
try {
+ // Publish a unique intent BEFORE inspecting other intents. If two callers
+ // overlap, at least one sees the other's live intent and backs off; both
+ // may back off. Never elect a lower-id newcomer over an active owner.
+ // Unique paths are never reused, so dead intents can be removed without
+ // racing a replacement owner. This also serializes legacy-lock recovery
+ // without introducing another shared stale lock that needs recovery.
+ fs.mkdirSync(claimsDir, { recursive: true });
+ const claimFd = fs.openSync(claimPath, 'wx');
+ ownsClaim = true;
+ fs.closeSync(claimFd);
+ for (const name of fs.readdirSync(claimsDir)) {
+ if (name === claimName) continue;
+ const match = /^([1-9]\d*)-[a-f0-9]{32}$/.exec(name);
+ if (!match) continue;
+ const pid = Number(match[1]);
+ if (Number.isSafeInteger(pid) && processOwnerState(pid) === 'dead') {
+ try { fs.unlinkSync(path.join(claimsDir, name)); } catch (error) {
+ if (!error || error.code !== 'ENOENT') throw error;
+ }
+ } else {
+ die(75, 'another orkas-pkg operation is in progress; retry shortly', { lock: lockPath });
+ }
+ }
try {
fd = fs.openSync(lockPath, 'wx');
ownsLock = true;
@@ -213,7 +255,6 @@ async function withRegistryLock(uid, fn) {
try { stale = Date.now() - fs.statSync(lockPath).mtimeMs > LOCK_STALE_MS; } catch { stale = true; }
}
if (!stale) {
- process.removeListener('exit', releaseLock); // not our lock — leave it
die(75, 'another orkas-pkg operation is in progress; retry shortly', { lock: lockPath });
}
try { fs.unlinkSync(lockPath); } catch { /* raced */ }
@@ -222,7 +263,6 @@ async function withRegistryLock(uid, fn) {
ownsLock = true;
} catch (retryError) {
if (retryError && retryError.code === 'EEXIST') {
- process.removeListener('exit', releaseLock);
die(75, 'another orkas-pkg operation is in progress; retry shortly', { lock: lockPath });
}
throw retryError;
diff --git a/bin/packaged-entrypoint-gate.cjs b/bin/packaged-entrypoint-gate.cjs
index 20e519ae..7a9f8bdf 100644
--- a/bin/packaged-entrypoint-gate.cjs
+++ b/bin/packaged-entrypoint-gate.cjs
@@ -121,8 +121,8 @@ const PACKAGED_BIN_HELPERS = Object.freeze([
'gmail-mcp-server.cjs',
'bridge-tool-input.cjs',
'skill-esm-loader.cjs',
+ 'schema-to-json.cjs',
'tool-input-compat.cjs',
- 'browser-tool-contract.cjs',
'connector-discovery-contract.cjs',
// Lark CLI shortcut contract required by local-cli-mcp-server.cjs.
'local-cli-lark.cjs',
@@ -267,8 +267,6 @@ const PACKAGED_MCP_RUNTIME_UNPACK_GLOBS = Object.freeze([
const PACKAGED_MCP_RUNTIME_FILES = Object.freeze([
{ lockPath: 'node_modules/@modelcontextprotocol/server', packageName: '@modelcontextprotocol/server', entries: ['dist/index.cjs', 'dist/stdio.cjs'] },
{ lockPath: 'node_modules/@modelcontextprotocol/core', packageName: '@modelcontextprotocol/core', entries: ['dist/index.cjs'] },
- { lockPath: 'node_modules/@modelcontextprotocol/server/node_modules/zod', packageName: 'zod', entries: ['index.cjs', 'v4/index.cjs'] },
- { lockPath: 'node_modules/@modelcontextprotocol/core/node_modules/zod', packageName: 'zod', entries: ['index.cjs', 'v4/index.cjs'] },
{
lockPath: 'node_modules/@modelcontextprotocol/sdk',
packageName: '@modelcontextprotocol/sdk',
@@ -286,7 +284,7 @@ const PACKAGED_MCP_RUNTIME_FILES = Object.freeze([
packageName: 'ajv-formats',
entries: ['dist/index.js'],
},
- { lockPath: 'node_modules/zod', packageName: 'zod', entries: ['index.cjs'] },
+ { lockPath: 'node_modules/zod', packageName: 'zod', entries: ['index.cjs', 'v4/index.cjs'] },
{
lockPath: 'node_modules/zod-to-json-schema',
packageName: 'zod-to-json-schema',
@@ -534,6 +532,7 @@ function verifyBridgeSdkRuntime(projectRoot) {
const bridgePackages = PACKAGED_MCP_RUNTIME_FILES.filter(spec =>
spec.lockPath.startsWith('node_modules/@modelcontextprotocol/server')
|| spec.lockPath.startsWith('node_modules/@modelcontextprotocol/core')
+ || spec.packageName === 'zod'
|| spec.packageName === 'zod-to-json-schema');
for (const spec of bridgePackages) {
const installed = readJson(`${spec.lockPath} package.json`, path.join(projectRoot, spec.lockPath, 'package.json'));
@@ -544,6 +543,7 @@ function verifyBridgeSdkRuntime(projectRoot) {
const fromProject = Module.createRequire(path.join(projectRoot, 'package.json'));
if (typeof fromProject('@modelcontextprotocol/server').McpServer !== 'function'
|| typeof fromProject('@modelcontextprotocol/server/stdio').serveStdio !== 'function'
+ || typeof fromProject('zod').toJSONSchema !== 'function'
|| typeof fromProject('zod-to-json-schema').zodToJsonSchema !== 'function') {
throw new Error('[packaged-entrypoint-gate] bridge dependency exports are unavailable');
}
diff --git a/bootstrap.cjs b/bootstrap.cjs
index c6083464..f43ef736 100644
--- a/bootstrap.cjs
+++ b/bootstrap.cjs
@@ -3,12 +3,14 @@
// index.ts rule + tsx/cjs transpilation). Keeps __dirname semantics identical
// to running plain JS — no compile step in dev.
//
-// Two hooks:
+// TypeScript hooks:
// - `tsx/cjs` (sync require hook) handles src/main/**/*.ts on the require()
// code path.
// - `tsx/esm` (ESM loader, registered via node:module) handles dynamic
// `import()` specifiers that resolve to .ts files — notably the
// `import('#core-agent')` subpath import that targets core-agent source.
+// Native .mjs dependencies stay on Main's native loader path so synchronous
+// ESM linking does not wait on a transpilation worker for each JavaScript edge.
'use strict';
const fs = require('node:fs');
@@ -78,6 +80,7 @@ configureWindowsVcRuntimePath();
configurePackagedEsbuildBinary();
require('tsx/cjs');
+require('./src/main/util/native-esm-loader.js').registerNativeEsmLoader();
require('tsx/esm/api').register();
require('./src/main');
diff --git a/scripts/check-installed-dependencies.mjs b/scripts/check-installed-dependencies.mjs
index fe0de4c6..d4884ccb 100644
--- a/scripts/check-installed-dependencies.mjs
+++ b/scripts/check-installed-dependencies.mjs
@@ -8,10 +8,10 @@
* `provider_catalog` report that it could not resolve `claude-fable-5`, which
* reads as a broken model catalog rather than an uninstalled dependency.
*
- * Only direct dependencies are compared, and only their installed version
- * against the lockfile's resolved version. Transitive drift surfaces through
- * the same direct packages in practice, and walking the whole tree would cost
- * more than the check is worth on every test run.
+ * Compare every locked package at its resolved location, including nested
+ * copies. A security fix can advance a transitive package while its direct
+ * parent stays unchanged. Read only the locked package manifests; do not
+ * recursively walk node_modules or inspect package contents on test startup.
*/
import fs from 'node:fs';
import path from 'node:path';
@@ -36,18 +36,19 @@ export function installedDependencyDrift(pcRoot = DEFAULT_PC_ROOT) {
const lock = readJson(path.join(pcRoot, 'package-lock.json'));
if (!pkg || !lock?.packages) return { checked: 0, drifted: [] };
- const declared = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies });
const drifted = [];
let checked = 0;
- for (const name of declared) {
- const entry = lock.packages[`node_modules/${name}`];
+ for (const [location, entry] of Object.entries(lock.packages)) {
+ if (!location.startsWith('node_modules/') || entry.link) continue;
const expected = entry?.version;
if (!expected) continue;
- // Optional packages are legitimately absent on platforms they do not build
- // for, so their absence is not drift.
- if (entry.optional) continue;
- const installedPkg = readJson(path.join(pcRoot, 'node_modules', name, 'package.json'));
+ const manifest = path.join(pcRoot, location, 'package.json');
+ // Foreign-platform optionals may be absent. If installed, they must still
+ // match: optionality is not permission to run an outdated package.
+ if (entry.optional && !fs.existsSync(manifest)) continue;
+ const name = location.slice('node_modules/'.length);
+ const installedPkg = readJson(manifest);
// A missing package.json means the dependency is absent entirely, which is
// as much drift as a version mismatch.
const installed = installedPkg?.version ?? null;
diff --git a/src/main/util/native-esm-loader.js b/src/main/util/native-esm-loader.js
new file mode 100644
index 00000000..fc722abb
--- /dev/null
+++ b/src/main/util/native-esm-loader.js
@@ -0,0 +1,55 @@
+'use strict';
+
+const fs = require('node:fs');
+const { registerHooks } = require('node:module');
+const { fileURLToPath, pathToFileURL } = require('node:url');
+
+// Native dependency .mjs files need no TypeScript transformation. Sending
+// every edge of a large JavaScript graph to the asynchronous tsx worker makes
+// Node's synchronous ESM linking block Main on hundreds of worker round trips.
+// Keep package exports, typed sources and nonstandard URLs with that loader.
+function ordinaryDependency(url, context) {
+ return url.protocol === 'file:' && url.pathname.includes('/node_modules/')
+ && url.pathname.endsWith('.mjs') && !url.search && !url.hash
+ && !Object.keys(context.importAttributes || {}).length;
+}
+
+function registerNativeEsmLoader() {
+ // Preserve older runtimes and explicit symlink-loader policies unchanged.
+ if (typeof registerHooks !== 'function'
+ || process.execArgv.some(arg => arg.startsWith('--preserve-symlinks'))
+ || String(process.env.NODE_OPTIONS || '').includes('--preserve-symlinks')) return null;
+ const nativeModules = new Set();
+ return registerHooks({
+ resolve(specifier, context, nextResolve) {
+ const isImport = !context.conditions.includes('require');
+ if (isImport && context.parentURL
+ && (specifier.startsWith('./') || specifier.startsWith('../') || specifier.startsWith('file:'))) {
+ try {
+ const url = new URL(specifier, context.parentURL);
+ if (ordinaryDependency(url, context) && fs.statSync(url).isFile()) {
+ const physical = pathToFileURL(fs.realpathSync(fileURLToPath(url)));
+ if (physical.pathname.endsWith('.mjs')) {
+ nativeModules.add(physical.href);
+ return { url: physical.href, format: 'module', shortCircuit: true };
+ }
+ }
+ } catch { /* The owning loader retains missing-file and URL errors. */ }
+ }
+ const result = nextResolve(specifier, context);
+ if (isImport && result.format === 'module' && ordinaryDependency(new URL(result.url), context)) {
+ nativeModules.add(result.url);
+ }
+ return result;
+ },
+ load(url, context, nextLoad) {
+ if (nativeModules.has(url) && !Object.keys(context.importAttributes || {}).length) {
+ try { return { format: 'module', source: fs.readFileSync(new URL(url)), shortCircuit: true }; }
+ catch { /* Preserve the owning loader's filesystem failure contract. */ }
+ }
+ return nextLoad(url, context);
+ },
+ });
+}
+
+module.exports = { registerNativeEsmLoader };
diff --git a/test/main/bootstrap-entry.test.ts b/test/main/bootstrap-entry.test.ts
new file mode 100644
index 00000000..dfae0b69
--- /dev/null
+++ b/test/main/bootstrap-entry.test.ts
@@ -0,0 +1,73 @@
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { runInNewContext } from 'node:vm';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+let root = '';
+
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-bootstrap-entry-'));
+ fs.copyFileSync(
+ path.resolve(process.cwd(), 'bootstrap.cjs'),
+ path.join(root, 'bootstrap.cjs'),
+ );
+
+ const tsxRoot = path.join(root, 'node_modules', 'tsx');
+ fs.mkdirSync(tsxRoot, { recursive: true });
+ fs.writeFileSync(path.join(tsxRoot, 'package.json'), JSON.stringify({
+ name: 'tsx',
+ version: '0.0.0-test',
+ exports: {
+ './cjs': './cjs.cjs',
+ './esm/api': './esm-api.cjs',
+ },
+ }));
+ fs.writeFileSync(path.join(tsxRoot, 'cjs.cjs'), 'module.exports = {};\n');
+ fs.writeFileSync(
+ path.join(tsxRoot, 'esm-api.cjs'),
+ 'module.exports = { register() {} };\n',
+ );
+
+ const mainRoot = path.join(root, 'src', 'main');
+ fs.mkdirSync(mainRoot, { recursive: true });
+ fs.mkdirSync(path.join(mainRoot, 'util'));
+ fs.copyFileSync(path.join(process.cwd(), 'src/main/util/native-esm-loader.js'), path.join(mainRoot, 'util/native-esm-loader.js'));
+
+});
+
+afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe('desktop bootstrap entry', () => {
+ it.each([
+ { platform: 'darwin', defaultApp: true, hide: '1', accessory: true },
+ { platform: 'darwin', defaultApp: true, hide: '0', accessory: false },
+ { platform: 'darwin', defaultApp: true, hide: '', accessory: false },
+ { platform: 'darwin', defaultApp: false, hide: '1', accessory: false },
+ { platform: 'win32', defaultApp: true, hide: '1', accessory: false },
+ ])('sets background activation before loading Main only for hidden macOS source runs: %j', (scenario) => {
+ const events: string[] = [];
+ runInNewContext(fs.readFileSync(path.join(root, 'bootstrap.cjs'), 'utf8'), {
+ __dirname: root,
+ process: {
+ platform: scenario.platform, defaultApp: scenario.defaultApp,
+ env: { ORKAS_E2E_HIDE_WINDOW: scenario.hide }, argv: [], versions: {},
+ },
+ require(name: string) {
+ if (name === 'node:fs') return fs;
+ if (name === 'node:path') return path;
+ if (name === 'electron') return { app: { setActivationPolicy: (policy: string) => events.push(policy) } };
+ if (name === 'tsx/cjs') return {};
+ if (name === 'tsx/esm/api') return { register() {} };
+ if (name === './src/main/util/native-esm-loader.js') return { registerNativeEsmLoader() {} };
+ if (name === './src/main') { events.push('main'); return {}; }
+ throw new Error(`Unexpected bootstrap import: ${name}`);
+ },
+ });
+ expect(events).toEqual(scenario.accessory ? ['accessory', 'main'] : ['main']);
+ });
+
+});
diff --git a/test/main/native-esm-loader.test.ts b/test/main/native-esm-loader.test.ts
new file mode 100644
index 00000000..ca77704c
--- /dev/null
+++ b/test/main/native-esm-loader.test.ts
@@ -0,0 +1,164 @@
+import { execFile } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+const execute = promisify(execFile);
+let root: string, dependency: string;
+const project = process.cwd();
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-native-esm-'));
+ dependency = path.join(root, 'node_modules/fixture');
+ fs.mkdirSync(dependency, { recursive: true });
+ fs.mkdirSync(path.join(root, 'src/main'), { recursive: true });
+ fs.mkdirSync(path.join(root, 'bin'), { recursive: true });
+ fs.copyFileSync(path.join(project, 'bootstrap.cjs'), path.join(root, 'bootstrap.cjs'));
+ const helper = path.join(project, 'src/main/util/native-esm-loader.js');
+ fs.mkdirSync(path.join(root, 'src/main/util'));
+ if (fs.existsSync(helper)) fs.copyFileSync(helper, path.join(root, 'src/main/util/native-esm-loader.js'));
+ fs.writeFileSync(path.join(dependency, 'package.json'), JSON.stringify({ name: 'fixture', type: 'module', exports: './index.mjs' }));
+ const tsx = path.join(root, 'node_modules/tsx');
+ fs.mkdirSync(tsx, { recursive: true });
+ fs.writeFileSync(path.join(tsx, 'package.json'), JSON.stringify({ exports: { './cjs': './cjs.cjs', './esm/api': './esm.cjs' } }));
+ fs.writeFileSync(path.join(tsx, 'cjs.cjs'), `module.exports = require(${JSON.stringify(path.join(project, 'node_modules/tsx/dist/cjs/index.cjs'))});`);
+ fs.writeFileSync(path.join(tsx, 'esm.cjs'), `
+ const api = require(${JSON.stringify(path.join(project, 'node_modules/tsx/dist/esm/api/index.cjs'))});
+ module.exports.register = () => {
+ api.register();
+ if (process.env.FAULT_NATIVE_TRANSFORM === '1') require('node:module').register('./fault-loader.mjs', require('node:url').pathToFileURL(${JSON.stringify(root + path.sep)}));
+ };
+ `);
+ // A native JavaScript graph must not depend on the TypeScript worker. This
+ // controlled failure gives the cold-load regression a deterministic signal.
+ fs.writeFileSync(path.join(root, 'fault-loader.mjs'), `
+ export function resolve(specifier, context, next) {
+ if (specifier.endsWith('.mjs')) throw Object.assign(new Error('Unnecessary native transpilation'), { code: 'E_NATIVE_TRANSFORM' });
+ return next(specifier, context);
+ }
+ export function load(url, context, next) {
+ if (url.endsWith('.mjs')) throw Object.assign(new Error('Unnecessary native transpilation'), { code: 'E_NATIVE_TRANSFORM' });
+ return next(url, context);
+ }
+ `);
+});
+afterEach(() => fs.rmSync(root, { recursive: true, force: true }));
+
+function isAsarStatsDeprecation(stderr: string, executable: string) {
+ // Node's warning formatter derives the hint from basename(process.argv0,
+ // '.exe'). execFile gives the child the executable path as its argv0.
+ const label = path.basename(executable, '.exe').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return new RegExp(`^\\(node:\\d+\\) \\[DEP0180\\] DeprecationWarning: fs\\.Stats constructor is deprecated\\.\\r?\\n\\(Use \`${label} --trace-deprecation \\.\\.\\.\` to show where the warning was created\\)\\r?\\n$`).test(stderr);
+}
+
+async function run(body: string, env: Record<string, string> = {}, packed = false) {
+ const result = path.join(root, 'result.json');
+ fs.writeFileSync(path.join(root, 'src/main/index.js'), `
+ const fs = require('node:fs');
+ (async () => { ${body} })().then(value => fs.writeFileSync(${JSON.stringify(result)}, JSON.stringify({ value })),
+ error => fs.writeFileSync(${JSON.stringify(result)}, JSON.stringify({ error: error.code || error.name })));
+ `);
+ let entry = path.join(root, 'bootstrap.cjs');
+ if (packed) {
+ const stage = path.join(root, 'stage'), archive = path.join(root, 'app.asar');
+ fs.mkdirSync(stage);
+ for (const name of ['bootstrap.cjs', 'src', 'node_modules', 'fault-loader.mjs']) {
+ fs.cpSync(path.join(root, name), path.join(stage, name), { recursive: true });
+ }
+ await (await import('@electron/asar')).createPackage(stage, archive);
+ entry = path.join(archive, 'bootstrap.cjs');
+ }
+ const output = await execute(process.execPath, [entry], {
+ cwd: root, env: { ...process.env, ...env },
+ });
+ if (packed && output.stderr) {
+ // Electron's ASAR stat adapter uses the deprecated Node Stats constructor.
+ // Retain this exact diagnostic as a review warning; all other stderr fails.
+ expect(isAsarStatsDeprecation(output.stderr, process.execPath), output.stderr).toBe(true);
+ console.warn('ASAR filesystem deprecation retained', { code: 'DEP0180' });
+ } else expect(output.stderr).toBe('');
+ return JSON.parse(fs.readFileSync(result, 'utf8'));
+}
+
+describe('native ESM dependency loading', () => {
+ it.each(['electron', 'Electron', 'electron.exe'])('recognizes only the ASAR Stats warning for executable %s', executable => {
+ const label = path.basename(executable, '.exe');
+ const warning = `(node:123) [DEP0180] DeprecationWarning: fs.Stats constructor is deprecated.\n(Use \`${label} --trace-deprecation ...\` to show where the warning was created)\n`;
+ expect(isAsarStatsDeprecation(warning, executable)).toBe(true);
+ expect(isAsarStatsDeprecation(warning + 'unexpected warning\n', executable)).toBe(false);
+ expect(isAsarStatsDeprecation(warning.replace('DEP0180', 'DEP0001'), executable)).toBe(false);
+ expect(isAsarStatsDeprecation(warning.replace('fs.Stats', 'another API'), executable)).toBe(false);
+ expect(isAsarStatsDeprecation(warning.replace(`${label} --trace`, 'other --trace'), executable)).toBe(false);
+ });
+
+ it('loads unchanged native dependency bytes and one shared instance without the transpilation worker', async () => {
+ fs.writeFileSync(path.join(dependency, 'shared.mjs'), 'globalThis.initialized = (globalThis.initialized || 0) + 1; export let value = 20; export function add() { value++; }');
+ fs.writeFileSync(path.join(dependency, 'index.mjs'), "import { value, add } from './shared.mjs'; export { value } from './shared.mjs'; add(); export const answer = value * 2;");
+ expect(await run(`const [a, b] = await Promise.all([import('fixture'), import('fixture')]); return { answer: a.answer, live: a.value, same: a === b, initialized: globalThis.initialized };`, { FAULT_NATIVE_TRANSFORM: '1' }))
+ .toEqual({ value: { answer: 42, live: 21, same: true, initialized: 1 } });
+ });
+
+ it('keeps TypeScript extension substitution and CommonJS dependency interop', async () => {
+ fs.writeFileSync(path.join(dependency, 'typed.mts'), 'export const value: number = 42;');
+ fs.writeFileSync(path.join(dependency, 'legacy.cjs'), 'module.exports = { label: "retained" };');
+ fs.writeFileSync(path.join(dependency, 'index.mjs'), "import { value } from './typed.mjs'; import legacy from './legacy.cjs'; export const result = { value, label: legacy.label };");
+ expect(await run("return (await import('fixture')).result;")).toEqual({ value: { value: 42, label: 'retained' } });
+ });
+
+ it('preserves query and fragment module identities and top-level await', async () => {
+ fs.writeFileSync(path.join(dependency, 'index.mjs'), 'await Promise.resolve(); globalThis.initialized = (globalThis.initialized || 0) + 1; export const instance = globalThis.initialized;');
+ expect(await run("const url = require('node:url').pathToFileURL(require.resolve('fixture')).href; return [(await import(url)).instance, (await import(url + '?copy')).instance, (await import(url + '#copy')).instance];"))
+ .toEqual({ value: [1, 2, 3] });
+ });
+
+ it.each([
+ ['missing', "await import('fixture/missing.mjs')", 'ERR_PACKAGE_PATH_NOT_EXPORTED'],
+ ['relative missing', "await import(require('node:url').pathToFileURL(require.resolve('fixture')).href.replace('index.mjs', 'missing.mjs'))", 'ERR_MODULE_NOT_FOUND'],
+ ['directory', "await import(require('node:url').pathToFileURL(require.resolve('fixture')).href.replace('index.mjs', 'directory.mjs'))", ['ERR_MODULE_NOT_FOUND', 'ERR_UNSUPPORTED_DIR_IMPORT']],
+ ['wrong import attribute', "await import('fixture', { with: { type: 'json' } })", 'ERR_IMPORT_ATTRIBUTE_TYPE_INCOMPATIBLE'],
+ ['source failure', "await import('fixture')", 'E_FIXTURE_SOURCE'],
+ ])('retains the owning error for %s', async (kind, action, expected) => {
+ fs.mkdirSync(path.join(dependency, 'directory.mjs'));
+ fs.writeFileSync(path.join(dependency, 'index.mjs'), kind === 'source failure'
+ ? "throw Object.assign(new Error('Fixture failure'), { code: 'E_FIXTURE_SOURCE' });" : 'export const value = 42;');
+ const result = await run(action);
+ if (Array.isArray(expected)) expect(expected).toContain(result.error);
+ else expect(result).toEqual({ error: expected });
+ });
+
+ it('keeps real-path identity for a symlinked dependency', async () => {
+ fs.writeFileSync(path.join(dependency, 'index.mjs'), 'export const identity = {};');
+ fs.symlinkSync(path.join(dependency, 'index.mjs'), path.join(dependency, 'linked.mjs'));
+ expect(await run("const url = require('node:url').pathToFileURL(require.resolve('fixture')).href; return (await import(url)).identity === (await import(url.replace('index.mjs', 'linked.mjs'))).identity;"))
+ .toEqual({ value: true });
+ });
+
+ it('delegates a native-looking symlink whose real source still needs TypeScript', async () => {
+ fs.writeFileSync(path.join(dependency, 'typed.mts'), 'export const value: number = 42;');
+ fs.symlinkSync(path.join(dependency, 'typed.mts'), path.join(dependency, 'index.mjs'));
+ expect(await run("return (await import('fixture')).value;")).toEqual({ value: 42 });
+ });
+
+ it('preserves explicit symlink policy and CommonJS callers', async () => {
+ fs.writeFileSync(path.join(dependency, 'index.mjs'), 'export const identity = {}; export const value = 42;');
+ fs.symlinkSync(path.join(dependency, 'index.mjs'), path.join(dependency, 'linked.mjs'));
+ expect(await run("const url = require('node:url').pathToFileURL(require.resolve('fixture')).href; return { shared: (await import(url)).identity === (await import(url.replace('index.mjs', 'linked.mjs'))).identity, required: require('fixture').value };", {
+ NODE_OPTIONS: [process.env.NODE_OPTIONS, '--preserve-symlinks'].filter(Boolean).join(' '),
+ })).toEqual({ value: { shared: false, required: 42 } });
+ });
+
+ it('loads encoded spaces without accepting encoded path separators', async () => {
+ fs.writeFileSync(path.join(dependency, 'space name.mjs'), 'export const value = 42;');
+ fs.writeFileSync(path.join(dependency, 'index.mjs'), "export { value } from './space%20name.mjs';");
+ expect(await run("const url = require('node:url').pathToFileURL(require.resolve('fixture')).href; let rejected = false; try { await import(url.replace('index.mjs', 'sub%2Fname.mjs')); } catch { rejected = true; } return { rejected, value: (await import('fixture')).value };"))
+ .toEqual({ value: { rejected: true, value: 42 } });
+ });
+
+ it('loads the packaged bootstrap helper and native dependency directly from ASAR', async () => {
+ fs.writeFileSync(path.join(dependency, 'shared.mjs'), 'export const value = 42;');
+ fs.writeFileSync(path.join(dependency, 'index.mjs'), "export { value } from './shared.mjs';");
+ expect(await run("return (await import('fixture')).value;", { FAULT_NATIVE_TRANSFORM: '1' }, true))
+ .toEqual({ value: 42 });
+ });
+});
diff --git a/test/main/quality/dependency-body-lifetime.test.ts b/test/main/quality/dependency-body-lifetime.test.ts
new file mode 100644
index 00000000..513e7575
--- /dev/null
+++ b/test/main/quality/dependency-body-lifetime.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest';
+import { spawnSync } from 'node:child_process';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+
+const require = createRequire(import.meta.url);
+
+// Exercise the installed parser over real loopback HTTP in a disposable child:
+// GHSA-27r3-jxmh-p828 can emit an uncaught decoder error after parsing succeeds.
+// An exception handler in the test process would hide that process-level failure.
+function bodyProbe(mode: string) {
+ const script = `
+ const assert = require('node:assert/strict');
+ const http = require('node:http');
+ const zlib = require('node:zlib');
+ const { once } = require('node:events');
+ const { createHash } = require('node:crypto');
+ const bodyParser = require(${JSON.stringify(require.resolve('body-parser'))});
+ const onFinished = require(${JSON.stringify(require.resolve('on-finished'))});
+ const mode = process.argv[1];
+ const late = mode === 'late-deflate';
+ const charset = mode === 'rejected-charset';
+ const badJson = mode === 'bad-json';
+ const gzipTail = mode === 'gzip-tail' || charset;
+ const form = mode === 'form';
+ const encoding = late ? 'deflate' : gzipTail || mode === 'gzip' ? 'gzip' : mode === 'brotli' ? 'br' : 'identity';
+ const payload = Buffer.from(form ? 'tags%5B%5D=a&tags%5B%5D=b&name=%E4%B8%AD%E6%96%87' : badJson ? '{' : '{"a":1}');
+ const compressed = encoding === 'gzip' ? zlib.gzipSync(payload) : encoding === 'deflate' ? zlib.deflateSync(payload) : encoding === 'br' ? zlib.brotliCompressSync(payload) : payload;
+ const first = late || gzipTail ? Buffer.concat([compressed, Buffer.from([0])]) : compressed;
+ const tail = Buffer.alloc(late ? 1024 : gzipTail ? 100 * 1024 : 0, 0x58);
+ const expectedHash = createHash('sha256').update(first).update(tail).digest('hex');
+ const parser = form ? bodyParser.urlencoded({ extended: true }) : bodyParser.json(charset ? { verify() {} } : {});
+ let request;
+ const server = http.createServer((req, res) => {
+ const hash = createHash('sha256');
+ req.pipe(hash);
+ const rawDone = new Promise(resolve => hash.once('finish', () => resolve(hash.digest('hex'))));
+ parser(req, res, error => {
+ const finish = () => {
+ res.statusCode = error ? error.status || 500 : 200;
+ res.end(JSON.stringify({ body: req.body, type: error && error.type, hash: req.rawHash }));
+ };
+ const requestDone = new Promise(resolve => onFinished(req, resolve));
+ Promise.all([rawDone, requestDone]).then(([digest]) => { req.rawHash = digest; finish(); });
+ if (late) request.end(tail);
+ });
+ });
+ const deadline = setTimeout(() => { process.stderr.write('probe deadline'); process.exit(2); }, 2000);
+ (async () => {
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ try {
+ const response = await new Promise((resolve, reject) => {
+ request = http.request({ host: '127.0.0.1', port: server.address().port, method: 'POST', agent: false,
+ headers: { 'Content-Type': form ? 'application/x-www-form-urlencoded' : charset ? 'application/json; charset=utf-999' : 'application/json',
+ 'Content-Encoding': encoding, 'Content-Length': first.length + tail.length } }, res => {
+ let text = '';
+ res.setEncoding('utf8');
+ res.on('data', chunk => { text += chunk; });
+ res.on('error', reject);
+ res.on('end', () => resolve({ status: res.statusCode, data: JSON.parse(text) }));
+ });
+ request.on('error', reject);
+ if (late) request.write(first);
+ else request.end(Buffer.concat([first, tail]));
+ });
+ assert.equal(response.status, charset ? 415 : badJson ? 400 : 200);
+ if (charset || badJson) assert.equal(response.data.type, charset ? 'charset.unsupported' : 'entity.parse.failed');
+ else assert.deepEqual(response.data.body, form ? { tags: ['a', 'b'], name: '中文' } : { a: 1 });
+ assert.equal(response.data.hash, expectedHash);
+ // Allow asynchronous zlib errors after the response to remain fatal,
+ // matching the upstream regression's post-response observation window.
+ await new Promise(resolve => setTimeout(resolve, 200));
+ process.stdout.write(JSON.stringify({ status: response.status, rawBodyPreserved: true }));
+ } finally {
+ request?.destroy();
+ await new Promise(resolve => server.close(resolve));
+ clearTimeout(deadline);
+ }
+ })().catch(error => { process.stderr.write(error.stack); process.exitCode = 1; });
+ `;
+ return spawnSync(process.execPath, ['-e', script, mode], {
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
+ encoding: 'utf8', timeout: 4000, maxBuffer: 16 * 1024,
+ });
+}
+
+describe('installed body-parser request lifetime', () => {
+ it.each(['late-deflate', 'gzip-tail', 'rejected-charset', 'gzip', 'brotli', 'form', 'bad-json'])(
+ 'finishes %s without crashing or detaching another body consumer', mode => {
+ const result = bodyProbe(mode);
+ expect(result.error?.message).toBeUndefined();
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stderr).toBe('');
+ expect(JSON.parse(result.stdout)).toEqual({
+ status: mode === 'rejected-charset' ? 415 : mode === 'bad-json' ? 400 : 200,
+ rawBodyPreserved: true,
+ });
+ },
+ );
+});
+
+// Exercise the application and both MCP consumers through their actual resolution.
+// Oversized inputs must fail before per-element work allocates validation issues.
+for (const owner of ['application', 'core', 'server']) {
+ const sdkRequire = createRequire(owner === 'application' ? path.resolve('package.json')
+ : path.resolve('node_modules', '@modelcontextprotocol', owner, 'package.json'));
+ const { z } = sdkRequire('zod');
+ describe(`MCP ${owner} constrained containers`, () => {
+ it.each(['array', 'set', 'map'])('rejects an oversized %s before parsing its elements', kind => {
+ let visited = 0;
+ const element = z.number().transform((value: number) => { visited++; return value; });
+ const schema = kind === 'array' ? z.array(element).max(2)
+ : kind === 'set' ? z.set(element).max(2) : z.map(element, element).max(2);
+ const input = Array.from({ length: 2048 }, (_, i) => i);
+ const result = schema.safeParse(kind === 'array' ? input : kind === 'set' ? new Set(input) : new Map(input.map(i => [i, i])));
+ expect(result.success).toBe(false);
+ expect(result.error.issues).toEqual([expect.objectContaining({ code: 'too_big', path: [] })]);
+ expect(visited).toBe(0);
+ });
+
+ it('preserves accepted containers and a transform before a later size check', () => {
+ expect(z.array(z.number()).max(2).parse([1, 2])).toEqual([1, 2]);
+ expect(z.set(z.number()).max(2).parse(new Set([1, 2]))).toEqual(new Set([1, 2]));
+ expect(z.map(z.string(), z.number()).max(2).parse(new Map([['a', 1]]))).toEqual(new Map([['a', 1]]));
+ expect(z.array(z.number()).overwrite((value: number[]) => value.slice(0, 2)).max(2).parse([1, 2, 3])).toEqual([1, 2]);
+ });
+ });
+}
diff --git a/test/main/quality/dependency-security.test.ts b/test/main/quality/dependency-security.test.ts
index 1db9c70e..597b4428 100644
--- a/test/main/quality/dependency-security.test.ts
+++ b/test/main/quality/dependency-security.test.ts
@@ -1,9 +1,70 @@
import { describe, expect, it } from 'vitest';
+import { spawnSync } from 'node:child_process';
const proxyaddr = require('proxy-addr');
const { SourceMapConsumer } = require('source-map-js');
+const { Address6 } = require('ip-address');
+const { ipKeyGenerator } = require('express-rate-limit');
+const { SocksClient } = require('socks');
describe('dependency security boundaries', () => {
+ it('rejects oversized IPv6 zones without stalling the caller process', () => {
+ // GHSA-rxp7-6hxx-x8q5: an unpatched parser takes tens of seconds on
+ // this input. Isolate it so a regression cannot block the test worker.
+ const result = spawnSync(process.execPath, ['-e', `
+ const { Address6 } = require(${JSON.stringify(require.resolve('ip-address'))});
+ const results = ['\\n', '\\r', '\\u2028', '\\u2029'].map(terminator => {
+ const address = '%'.repeat(256 * 1024) + terminator;
+ let rejected = false;
+ try { new Address6(address); } catch (error) {
+ if (error.name !== 'AddressError') throw error;
+ rejected = true;
+ }
+ return { rejected, valid: Address6.isValid(address) };
+ });
+ process.stdout.write(JSON.stringify(results));
+ `], {
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
+ encoding: 'utf8', timeout: 3_000, maxBuffer: 4096,
+ });
+ expect(result.error?.message).toBeUndefined();
+ expect(result.status).toBe(0);
+ expect(result.stderr).toBe('');
+ expect(JSON.parse(result.stdout)).toEqual(
+ Array.from({ length: 4 }, () => ({ rejected: true, valid: false })),
+ );
+ });
+
+ it('preserves valid IPv6 zones and rejects malformed addresses', () => {
+ const address = new Address6('fe80::1%eth0');
+ expect(address.correctForm()).toBe('fe80::1');
+ expect(address.zone).toBe('%eth0');
+ expect(Address6.isValid('2001:db8::1')).toBe(true);
+ expect(Address6.isValid('2001:db8::gg')).toBe(false);
+ });
+
+ it('keeps IPv6 subnet and IPv4-mapped rate-limit identities stable', () => {
+ expect(ipKeyGenerator('2001:db8:abcd:1234::1')).toBe('2001:db8:abcd:1200::/56');
+ expect(ipKeyGenerator('::ffff:192.0.2.9')).toBe('192.0.2.9');
+ expect(ipKeyGenerator('192.0.2.9')).toBe('192.0.2.9');
+ });
+
+ it('preserves the SOCKS IPv6 wire address, port and payload', () => {
+ const data = Buffer.from('fixture');
+ const frame = SocksClient.createUDPFrame({
+ remoteHost: { host: '2001:db8::1', port: 443 }, data,
+ });
+ const expected = Buffer.concat([
+ Buffer.from('0000000420010db800000000000000000000000101bb', 'hex'), data,
+ ]);
+ expect(frame).toEqual(expected);
+ expect(SocksClient.parseUDPFrame(expected)).toEqual({
+ frameNumber: 0,
+ remoteHost: { host: '2001:0db8:0000:0000:0000:0000:0000:0001', port: 443 },
+ data,
+ });
+ });
+
it.each(['203.0.113.9', '::ffff:203.0.113.9'])(
'does not accept a forwarded identity from an untrusted peer %s', address => {
const request = {
diff --git a/test/main/quality/installed-dependencies.test.ts b/test/main/quality/installed-dependencies.test.ts
index 62627b1e..1209fdb1 100644
--- a/test/main/quality/installed-dependencies.test.ts
+++ b/test/main/quality/installed-dependencies.test.ts
@@ -102,6 +102,45 @@ describe('installed dependency drift guard', () => {
}
});
+ it('detects stale nested dependencies even when the direct package matches', () => {
+ const root = fakeProject({
+ declared: { alpha: '^1.0.0' },
+ lock: { alpha: { version: '1.2.0' }, 'alpha/node_modules/beta': { version: '2.1.0' } },
+ installed: { alpha: '1.2.0', 'alpha/node_modules/beta': '2.0.0' },
+ });
+ try {
+ expect(installedDependencyDrift(root).drifted).toEqual([
+ { name: 'alpha/node_modules/beta', expected: '2.1.0', installed: '2.0.0' },
+ ]);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+
+ it('reports a missing required hoisted transitive package', () => {
+ const root = fakeProject({
+ declared: { alpha: '^1.0.0' },
+ lock: { alpha: { version: '1.2.0' }, beta: { version: '2.1.0' } },
+ installed: { alpha: '1.2.0' },
+ });
+ try {
+ expect(installedDependencyDrift(root).drifted).toEqual([
+ { name: 'beta', expected: '2.1.0', installed: null },
+ ]);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+
+ it('checks an installed optional dependency while allowing an absent platform optional', () => {
+ const root = fakeProject({
+ declared: { alpha: '^1.0.0' },
+ lock: { alpha: { version: '1.2.0' }, beta: { version: '2.1.0', optional: true }, gamma: { version: '3.0.0', optional: true } },
+ installed: { alpha: '1.2.0', beta: '2.0.0' },
+ });
+ try {
+ expect(installedDependencyDrift(root).drifted).toEqual([
+ { name: 'beta', expected: '2.1.0', installed: '2.0.0' },
+ ]);
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
+
// The runner calls this on every invocation, so the real tree must be clean —
// otherwise every test run in this repository starts with a false alarm.
it('finds no drift in the checked-in project itself', () => {
diff --git a/test/main/util/fetch-win-vc-runtime.test.ts b/test/main/util/fetch-win-vc-runtime.test.ts
index 92a538d1..10ed9350 100644
--- a/test/main/util/fetch-win-vc-runtime.test.ts
+++ b/test/main/util/fetch-win-vc-runtime.test.ts
@@ -168,14 +168,17 @@ describe('fetch-win-vc-runtime', () => {
expect(marker.sourceSha256).toBe(contract.source.sha256);
});
- it('copies the VC DLLs into the Windows app root and has no NSIS runtime installer hook', () => {
+ it('copies the VC DLLs into the Windows app root without invoking a runtime installer', () => {
const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8'));
expect(pkg.build.win.extraFiles).toEqual([{
from: 'resources/runtime/vc/win32-x64',
to: '.',
filter: ['*.dll'],
}]);
- expect(pkg.build.nsis?.include).toBeUndefined();
+ // The shared installer cleanup hook is independent of app-local VC deployment.
+ expect(pkg.build.nsis?.include).toBe('scripts/windows-installer.nsh');
+ const include = fs.readFileSync(path.join(process.cwd(), pkg.build.nsis.include), 'utf8');
+ expect(include).not.toMatch(/vc_redist|whisper-runtime|msiexec/i);
expect(fs.existsSync(path.join(process.cwd(), 'product', 'whisper-runtime.nsh'))).toBe(false);
});
diff --git a/test/main/util/orkas-pkg.test.ts b/test/main/util/orkas-pkg.test.ts
index c869db41..0d02fe27 100644
--- a/test/main/util/orkas-pkg.test.ts
+++ b/test/main/util/orkas-pkg.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterAll } from 'vitest';
-import { spawnSync } from 'node:child_process';
+import { spawn, spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
@@ -79,6 +79,81 @@ function runPkg(...args: string[]) {
return runPkgWithEnv({}, ...args);
}
+/** Pause a real CLI at a filesystem boundary; only the schedule is injected. */
+function scheduledPkg(hook: string, ...args: string[]) {
+ const id = fs.mkdtempSync(path.join(tmpDir, 'schedule-'));
+ const ready = path.join(id, 'ready');
+ const gate = path.join(id, 'gate');
+ const preload = path.join(id, 'preload.cjs');
+ fs.writeFileSync(preload, `
+ const fs = require('node:fs');
+ const lockPath = ${JSON.stringify(path.join(pkgsDir(), '_registry.lock'))};
+ const pause = () => {
+ fs.writeFileSync(${JSON.stringify(ready)}, 'ready');
+ const until = Date.now() + 10000;
+ const signal = new Int32Array(new SharedArrayBuffer(4));
+ while (!fs.existsSync(${JSON.stringify(gate)})) {
+ if (Date.now() > until) throw new Error('test schedule timed out');
+ Atomics.wait(signal, 0, 0, 5);
+ }
+ };
+ ${hook}
+ `);
+ const child = spawn(TEST_NODE, ['--require', preload, path.join(process.cwd(), 'bin', 'orkas-pkg.cjs'), ...args], {
+ cwd: process.cwd(), windowsHide: true,
+ env: { ...process.env, ORKAS_WORKSPACE_ROOT: wsRoot, ORKAS_UID: TEST_UID },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '', stderr = '';
+ child.stdout.on('data', data => { stdout += data; });
+ child.stderr.on('data', data => { stderr += data; });
+ const done = new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve, reject) => {
+ child.once('error', reject);
+ child.once('close', status => resolve({ status, stdout, stderr }));
+ }).then(result => {
+ // Account for the non-result stream as well as the JSON asserted below.
+ if (result.status === 0) expect(result.stderr).toBe('');
+ else expect(result.stdout).toBe('');
+ if (result.status === null) expect(result.stderr).toBe('');
+ return result;
+ });
+ return { child, done, release: () => fs.writeFileSync(gate, 'go'),
+ async pausedOrExited() {
+ const until = Date.now() + 5000;
+ while (!fs.existsSync(ready) && child.exitCode === null) {
+ if (Date.now() > until) throw new Error('CLI did not reach scheduled boundary');
+ await new Promise(resolve => setTimeout(resolve, 5));
+ }
+ return fs.existsSync(ready);
+ },
+ };
+}
+
+const PAUSE_AFTER_OWNER_READ = `
+ const read = fs.readFileSync;
+ let armed = true;
+ fs.readFileSync = function(file, ...args) {
+ const value = read.call(this, file, ...args);
+ if (armed && String(file) === lockPath) { armed = false; pause(); }
+ return value;
+ };
+`;
+
+const PAUSE_AFTER_OWNER_WRITE = `
+ const open = fs.openSync, write = fs.writeSync;
+ let lockFd, armed = true;
+ fs.openSync = function(file, ...args) {
+ const fd = open.call(this, file, ...args);
+ if (String(file) === lockPath) lockFd = fd;
+ return fd;
+ };
+ fs.writeSync = function(fd, ...args) {
+ const count = write.call(this, fd, ...args);
+ if (armed && fd === lockFd) { armed = false; pause(); }
+ return count;
+ };
+`;
+
function runPkgInput(input: string, ...args: string[]) {
const pcRoot = process.cwd();
const r = spawnSync(TEST_NODE, [path.join(pcRoot, 'bin', 'orkas-pkg.cjs'), ...args], {
@@ -135,6 +210,152 @@ describe('orkas-pkg.cjs source invariants', () => {
});
describe('orkas-pkg.cjs registry lock recovery', () => {
+ it('backs off before creating a shared lock when both contenders have announced', async () => {
+ const hook = `
+ const readdir = fs.readdirSync;
+ let armed = true;
+ fs.readdirSync = function(dir, ...args) {
+ if (armed && String(dir).endsWith('.registry-lock-claims')) { armed = false; pause(); }
+ return readdir.call(this, dir, ...args);
+ };
+ `;
+ const first = scheduledPkg(hook, 'remove', 'missing');
+ let second: ReturnType<typeof scheduledPkg> | undefined;
+ try {
+ expect(await first.pausedOrExited()).toBe(true);
+ second = scheduledPkg(hook, 'remove', 'missing');
+ expect(await second.pausedOrExited()).toBe(true);
+ first.release();
+ const rejected = await first.done;
+ expect(rejected.status).toBe(75);
+ expect(JSON.parse(rejected.stderr).error).toMatch(/operation is in progress/);
+ expect(fs.existsSync(path.join(pkgsDir(), '_registry.lock'))).toBe(false);
+ second.release();
+ const accepted = await second.done;
+ expect(accepted.status).toBe(66);
+ expect(JSON.parse(accepted.stderr).error).toMatch(/is not installed/);
+ expect(fs.readdirSync(path.join(pkgsDir(), '.registry-lock-claims'))).toEqual([]);
+ } finally { first.release(); second?.release(); await first.done; if (second) await second.done; }
+ });
+
+ it('does not let two reclaimers enter package mutations together', async () => {
+ fs.mkdirSync(pkgsDir(), { recursive: true });
+ const exited = spawnSync(TEST_NODE, ['-e', 'process.stdout.write(String(process.pid))'], { encoding: 'utf8' });
+ expect(exited.status).toBe(0);
+ fs.writeFileSync(path.join(pkgsDir(), '_registry.lock'), exited.stdout);
+ for (const name of ['first', 'second']) fs.mkdirSync(path.join(pkgsDir(), name));
+ fs.writeFileSync(path.join(pkgsDir(), '_registry.json'), JSON.stringify({ version: 1,
+ packages: ['first', 'second'].map(name => ({ name, kind: 'skill', skill_roots: [], bin_entries: [] })),
+ }));
+ const first = scheduledPkg(PAUSE_AFTER_OWNER_READ, 'remove', 'first');
+ let second: ReturnType<typeof scheduledPkg> | undefined;
+ try {
+ expect(await first.pausedOrExited()).toBe(true);
+ second = scheduledPkg(PAUSE_AFTER_OWNER_WRITE, 'remove', 'second');
+ const secondOwnsLock = await second.pausedOrExited();
+ first.release();
+ const a = await first.done;
+ // Either contender may win, but the other cannot mutate while it owns the lock.
+ if (secondOwnsLock) {
+ expect(a.status).toBe(75);
+ expect(fs.readFileSync(path.join(pkgsDir(), '_registry.lock'), 'utf8')).toBe(String(second.child.pid));
+ }
+ second.release();
+ const b = await second.done;
+ expect([a.status, b.status].sort()).toEqual([0, 75]);
+ const winner = a.status === 0 ? 'first' : 'second';
+ const loser = a.status === 0 ? 'second' : 'first';
+ expect(JSON.parse((a.status === 0 ? a : b).stdout)).toMatchObject({ ok: true, action: 'remove', name: winner });
+ expect(JSON.parse((a.status === 75 ? a : b).stderr)).toMatchObject({ ok: false, error: expect.stringMatching(/operation is in progress/) });
+ expect(readRegistry().packages.map((p: { name: string }) => p.name)).toEqual([loser]);
+ expect(fs.existsSync(path.join(pkgsDir(), loser))).toBe(true);
+ expect(fs.existsSync(path.join(pkgsDir(), winner))).toBe(false);
+ expect(fs.existsSync(path.join(pkgsDir(), '_registry.lock'))).toBe(false);
+ expect(fs.readdirSync(path.join(pkgsDir(), '.registry-lock-claims'))).toEqual([]);
+ } finally {
+ first.release(); second?.release();
+ await first.done; if (second) await second.done;
+ }
+ });
+
+ it.each(['replace', 'overwrite'] as const)('leaves a foreign lock intact on process.exit (%s)', async mode => {
+ fs.mkdirSync(pkgsDir(), { recursive: true });
+ const lockPath = path.join(pkgsDir(), '_registry.lock');
+ const operation = scheduledPkg(`
+ const exit = process.exit;
+ process.exit = function(code) {
+ ${mode === 'replace' ? 'fs.unlinkSync(lockPath);' : ''}
+ fs.writeFileSync(lockPath, ${JSON.stringify(String(process.pid))});
+ return exit.call(this, code);
+ };
+ `, 'remove', 'missing');
+ const result = await operation.done;
+ expect(result.status).toBe(66);
+ expect(JSON.parse(result.stderr).error).toMatch(/is not installed/);
+ expect(fs.readFileSync(lockPath, 'utf8')).toBe(String(process.pid));
+ expect(fs.readdirSync(path.join(pkgsDir(), '.registry-lock-claims'))).toEqual([]);
+ });
+
+ it('recovers after a holder is killed without leaving another permanent recovery lock', async () => {
+ const holder = scheduledPkg(PAUSE_AFTER_OWNER_WRITE, 'remove', 'missing');
+ try {
+ expect(await holder.pausedOrExited()).toBe(true);
+ expect(runPkg('remove', 'missing').status).toBe(75);
+ // The same machine can operate another account without sharing its lock.
+ const otherUser = spawnSync(TEST_NODE, [path.join(process.cwd(), 'bin', 'orkas-pkg.cjs'), 'remove', 'missing'], {
+ encoding: 'utf8', timeout: 5000, windowsHide: true,
+ env: { ...process.env, ORKAS_WORKSPACE_ROOT: wsRoot, ORKAS_UID: 'u2' },
+ });
+ expect(otherUser.status).toBe(66);
+ expect(JSON.parse(otherUser.stderr).error).toMatch(/is not installed/);
+ expect(fs.readFileSync(path.join(pkgsDir(), '_registry.lock'), 'utf8')).toBe(String(holder.child.pid));
+ holder.child.kill('SIGKILL');
+ await holder.done;
+ const recovered = runPkg('remove', 'missing');
+ expect(recovered.status).toBe(66);
+ expect(recovered.json.error).toMatch(/is not installed/);
+ expect(fs.existsSync(path.join(pkgsDir(), '_registry.lock'))).toBe(false);
+ expect(fs.readdirSync(path.join(pkgsDir(), '.registry-lock-claims'))).toEqual([]);
+ } finally { holder.release(); if (holder.child.exitCode === null) holder.child.kill(); await holder.done; }
+ });
+
+ it('cleans its intent after an acquisition exception so a subsequent operation can proceed', async () => {
+ const operation = scheduledPkg(`
+ const readdir = fs.readdirSync;
+ fs.readdirSync = function(dir, ...args) {
+ if (String(dir).endsWith('.registry-lock-claims')) throw Object.assign(new Error('fixture access denied'), { code: 'EACCES' });
+ return readdir.call(this, dir, ...args);
+ };
+ `, 'remove', 'missing');
+ const failed = await operation.done;
+ expect(failed.status).toBe(1);
+ expect(JSON.parse(failed.stderr)).toMatchObject({ ok: false, error: 'fixture access denied' });
+ expect(fs.existsSync(path.join(pkgsDir(), '_registry.lock'))).toBe(false);
+ expect(fs.readdirSync(path.join(pkgsDir(), '.registry-lock-claims'))).toEqual([]);
+ const recovered = runPkg('remove', 'missing');
+ expect(recovered.status).toBe(66);
+ expect(recovered.json.error).toMatch(/is not installed/);
+ });
+
+ it('preserves an intent whose process liveness cannot be queried', async () => {
+ const claimsDir = path.join(pkgsDir(), '.registry-lock-claims');
+ fs.mkdirSync(claimsDir, { recursive: true });
+ const foreignClaim = `${process.pid}-${'a'.repeat(32)}`;
+ fs.writeFileSync(path.join(claimsDir, foreignClaim), '');
+ const operation = scheduledPkg(`
+ const kill = process.kill;
+ process.kill = function(pid, signal) {
+ if (pid === ${process.pid}) throw Object.assign(new Error('fixture permission denied'), { code: 'EPERM' });
+ return kill.call(this, pid, signal);
+ };
+ `, 'remove', 'missing');
+ const rejected = await operation.done;
+ expect(rejected.status).toBe(75);
+ expect(JSON.parse(rejected.stderr).error).toMatch(/operation is in progress/);
+ expect(fs.readdirSync(claimsDir)).toEqual([foreignClaim]);
+ expect(fs.existsSync(path.join(pkgsDir(), '_registry.lock'))).toBe(false);
+ });
+
it('reclaims a recent lock left by an abruptly terminated package process', () => {
const exited = spawnSync(TEST_NODE, ['-e', 'process.stdout.write(String(process.pid))'], {
encoding: 'utf8',
diff --git a/test/main/util/packaged-entrypoint-gate.test.ts b/test/main/util/packaged-entrypoint-gate.test.ts
index 4b5ec74a..d2ac0dbc 100644
--- a/test/main/util/packaged-entrypoint-gate.test.ts
+++ b/test/main/util/packaged-entrypoint-gate.test.ts
@@ -120,11 +120,11 @@ describe('packaged-entrypoint-gate', () => {
expect(gate.PACKAGED_BIN_ENTRYPOINTS).not.toContain('shopify-setup-requirements.cjs');
});
- it('loads the bridge SDK closure outside the source tree and rejects a missing nested validator', () => {
+ it('loads the bridge SDK closure outside the source tree and rejects a missing shared validator', () => {
const root = packagedRuntimeFixture();
fs.copyFileSync(path.join(process.cwd(), 'package-lock.json'), path.join(root, 'package-lock.json'));
expect(() => gate.verifyBridgeSdkRuntime(root)).not.toThrow();
- fs.rmSync(path.join(root, 'node_modules', '@modelcontextprotocol', 'server', 'node_modules', 'zod'), { recursive: true });
+ fs.rmSync(path.join(root, 'node_modules', 'zod'), { recursive: true });
const child = spawnSync(process.env.ORKAS_TEST_NODE || process.execPath, ['-e',
`require(${JSON.stringify(path.join(process.cwd(), 'bin', 'packaged-entrypoint-gate.cjs'))}).verifyBridgeSdkRuntime(${JSON.stringify(root)})`,
], { encoding: 'utf8', timeout: 10000 });
diff --git a/test/main/util/windows-node-bootstrap-contract.test.ts b/test/main/util/windows-node-bootstrap-contract.test.ts
index d56a6499..cc829938 100644
--- a/test/main/util/windows-node-bootstrap-contract.test.ts
+++ b/test/main/util/windows-node-bootstrap-contract.test.ts
@@ -1,11 +1,31 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
+import * as os from 'node:os';
import { describe, expect, it } from 'vitest';
const pcRoot = process.cwd();
describe('Windows no-Node startup bootstrap contract', () => {
+ it('isolates the official CLI canary from CI Node, mixed-case PATH keys and credentials', async () => {
+ const { sanitizedEnvironment, MANIFESTS } = await import('../../windows/windows-local-cli.integration.mjs');
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-cli-canary-env-'));
+ const hostEnv = { SystemRoot: 'C:\\Windows', Path: 'C:\\CI\\node', PATH: 'D:\\GlobalNode',
+ path: 'E:\\OtherNode', TEST_TOKEN: 'must-not-reach-child' };
+ const original = { ...hostEnv };
+ try {
+ const env = sanitizedEnvironment(root, 'lark', MANIFESTS.lark, 'C:\\Orkas\\npm\\npx-cli.js', {
+ hostEnv, nodeExecutable: 'C:\\Orkas 空格\\node.exe',
+ });
+ expect(env.PATH.split(';')).toEqual(['C:\\Orkas 空格', 'C:\\Windows\\System32',
+ 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0', 'C:\\Windows']);
+ expect(Object.keys(env).filter(key => key.toUpperCase() === 'PATH')).toEqual(['PATH']);
+ expect(env.ORKAS_NODE).toBe('C:\\Orkas 空格\\node.exe');
+ expect(env.TEST_TOKEN).toBeUndefined();
+ expect(hostEnv).toEqual(original);
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
+ });
+
it('routes run.cmd through the pinned bootstrap before dependency preparation', () => {
const runCmd = fs.readFileSync(path.join(pcRoot, 'run.cmd'), 'utf8');
const bootstrapIndex = runCmd.indexOf(