@cleocode/adapters 2026.11.2 → 2026.11.3-canary.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cleocode/adapters",
3
- "version": "2026.11.2",
3
+ "version": "2026.11.3-canary.1",
4
4
  "description": "Unified provider adapters for CLEO (Claude Code, OpenCode, Cursor)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -35,9 +35,9 @@
35
35
  "@ai-sdk/anthropic": "^3.0.69",
36
36
  "@ai-sdk/openai": "^2.0.53",
37
37
  "ai": "^6.0.168",
38
- "@cleocode/caamp": "2026.11.2",
39
- "@cleocode/contracts": "2026.11.2",
40
- "@cleocode/paths": "2026.11.2"
38
+ "@cleocode/caamp": "2026.11.3-canary.1",
39
+ "@cleocode/contracts": "2026.11.3-canary.1",
40
+ "@cleocode/paths": "2026.11.3-canary.1"
41
41
  },
42
42
  "license": "MIT",
43
43
  "engines": {
@@ -50,8 +50,8 @@
50
50
  "devDependencies": {
51
51
  "@types/node": "^24.3.0",
52
52
  "vitest": "^4.1.4",
53
- "@cleocode/core": "2026.11.2",
54
- "@cleocode/playbooks": "2026.11.2"
53
+ "@cleocode/core": "2026.11.3-canary.1",
54
+ "@cleocode/playbooks": "2026.11.3-canary.1"
55
55
  },
56
56
  "repository": {
57
57
  "type": "git",
@@ -363,6 +363,10 @@ export const runOrcaFixture: OrcaCommandRunner = async (_executable, args) => {
363
363
  { command: 'orchestration request-show', flags: ['request', 'full'] },
364
364
  { command: 'orchestration run-current', flags: ['from', 'full'] },
365
365
  { command: 'worktree show', flags: ['worktree'] },
366
+ { command: 'terminal create', flags: ['command', 'worktree', 'title', 'environment'] },
367
+ { command: 'terminal show', flags: ['terminal', 'environment'] },
368
+ { command: 'terminal close', flags: ['terminal', 'environment'] },
369
+ { command: 'terminal switch', flags: ['terminal', 'environment'] },
366
370
  ],
367
371
  }),
368
372
  };
@@ -345,6 +345,214 @@ describe('Orca execution process boundary', () => {
345
345
  expect(fixtureRunner).not.toHaveBeenCalled();
346
346
  });
347
347
 
348
+ it
349
+ .skipIf(process.platform === 'win32')
350
+ .each([
351
+ 'ready',
352
+ 'disconnected',
353
+ 'background',
354
+ 'hidden-after-create',
355
+ 'cleanup-unverified',
356
+ 'not-navigated',
357
+ 'pid-mismatch',
358
+ 'wrong-runtime',
359
+ 'lost-receipt',
360
+ ] as const)(
361
+ 'gates the exact terminal argv before a model turn: %s (inert executable only)',
362
+ async (condition) => {
363
+ vi.stubEnv('ORCA_TERMINAL_HANDLE', fixtureContext.coordinatorHandle);
364
+ const root = mkdtempSync(join(tmpdir(), 'orca-lead-fixture-'));
365
+ const cwd = join(root, "project ' `literal` $(literal)");
366
+ mkdirSync(cwd);
367
+ const capture = join(root, 'captured.json');
368
+ const binary = join(root, 'claude');
369
+ writeFileSync(
370
+ binary,
371
+ `#!${process.execPath}\nimport {writeFileSync} from 'node:fs';\nwriteFileSync(${JSON.stringify(capture)}, JSON.stringify({args:process.argv.slice(2),session:process.env.CLEO_SESSION_ID,role:process.env.CLEO_AGENT_ROLE,cwd:process.cwd()}));\n`,
372
+ { mode: 0o700 },
373
+ );
374
+ const args = [
375
+ '--restricted',
376
+ '--setting-sources',
377
+ '',
378
+ "literal ' `backticks` $(touch injected)",
379
+ ];
380
+ let child: ChildProcess | undefined;
381
+ let exit: Promise<void> | undefined;
382
+ const started = vi.fn<(pid: number) => Promise<void>>(async () => {
383
+ await new Promise((resolve) => setTimeout(resolve, 250));
384
+ expect(existsSync(capture)).toBe(false);
385
+ });
386
+ fixtureRunner.mockImplementation(async (...params) => {
387
+ const argv = params[1];
388
+ if (argv[0] === 'worktree')
389
+ return fixtureReply({
390
+ worktree: { id: 'workspace-fixture', path: cwd, branch: 'main', hostId: 'local' },
391
+ });
392
+ if (argv[0] === 'terminal' && argv[1] === 'create') {
393
+ const command = argv[argv.indexOf('--command') + 1];
394
+ child = spawn('/bin/sh', ['-c', command ?? 'exit 99'], { stdio: 'ignore' });
395
+ exit = new Promise<void>((resolve) => child?.once('exit', () => resolve()));
396
+ if (condition === 'lost-receipt') return { stdout: '', stderr: 'lost', exitCode: null };
397
+ return fixtureReply({
398
+ terminal: {
399
+ handle: 'term_lead',
400
+ processId: condition === 'pid-mismatch' ? (child.pid ?? 100) + 1 : child.pid,
401
+ executionHostId: 'local',
402
+ hostPlatform: process.platform,
403
+ surface: condition === 'background' ? 'background' : 'visible',
404
+ },
405
+ });
406
+ }
407
+ if (argv[0] === 'terminal' && argv[1] === 'close') {
408
+ child?.kill('SIGTERM');
409
+ return fixtureReply({
410
+ close: { handle: 'term_lead', ptyKilled: condition !== 'cleanup-unverified' },
411
+ });
412
+ }
413
+ if (argv[0] === 'terminal' && argv[1] === 'switch') {
414
+ return fixtureReply({
415
+ focus: {
416
+ handle: 'term_lead',
417
+ tabId: 'tab-lead',
418
+ worktreeId: 'workspace-fixture',
419
+ navigated: condition !== 'not-navigated',
420
+ },
421
+ });
422
+ }
423
+ if (argv[0] === 'terminal' && argv.includes('term_lead')) {
424
+ const reply = fixtureReply({
425
+ terminal: {
426
+ handle: 'term_lead',
427
+ connected: true,
428
+ writable: condition !== 'disconnected' && condition !== 'cleanup-unverified',
429
+ executionHostId: 'local',
430
+ worktreePath: cwd,
431
+ tabId: 'tab-lead',
432
+ surface: condition === 'hidden-after-create' ? 'background' : undefined,
433
+ },
434
+ });
435
+ return condition === 'wrong-runtime'
436
+ ? { ...reply, stdout: reply.stdout.replace(fixtureContext.runtimeId, 'other-runtime') }
437
+ : reply;
438
+ }
439
+ return runOrcaFixture(...params);
440
+ });
441
+ try {
442
+ const result = new OrcaExecutionBackend(fixtureRunner).startLead(
443
+ {
444
+ command: binary,
445
+ args,
446
+ cwd,
447
+ tempDir: root,
448
+ env: {
449
+ CLEO_SESSION_ID: 'ses_own',
450
+ CLEO_AGENT_ID: 'agent-own',
451
+ CLEO_AGENT_ROLE: 'lead',
452
+ },
453
+ },
454
+ started,
455
+ );
456
+ if (condition !== 'ready') {
457
+ await expect(result).rejects.toThrow();
458
+ if (condition === 'cleanup-unverified')
459
+ await expect(result).rejects.toMatchObject({
460
+ code: 'E_LEAD_TOOLS_UNSTRIPPED',
461
+ message: expect.stringContaining('cleanup is unverified'),
462
+ fix: expect.stringContaining('term_lead'),
463
+ });
464
+ expect(started).not.toHaveBeenCalled();
465
+ expect(existsSync(capture)).toBe(false);
466
+ } else {
467
+ expect(await result).toMatchObject({
468
+ terminalHandle: 'term_lead',
469
+ pid: child?.pid,
470
+ runtimeId: fixtureContext.runtimeId,
471
+ });
472
+ expect(started).toHaveBeenCalledOnce();
473
+ await exit;
474
+ expect(JSON.parse(readFileSync(capture, 'utf8'))).toEqual({
475
+ args,
476
+ session: 'ses_own',
477
+ role: 'lead',
478
+ cwd,
479
+ });
480
+ expect(existsSync(join(cwd, 'injected'))).toBe(false);
481
+ }
482
+ expect(
483
+ fixtureRunner.mock.calls.some(
484
+ ([, argv]) => argv[0] === 'account' || argv[1] === 'worker-start',
485
+ ),
486
+ ).toBe(false);
487
+ expect(fixtureRunner.mock.calls.filter(([, argv]) => argv[1] === 'create')).toHaveLength(1);
488
+ expect(fixtureRunner.mock.calls.filter(([, argv]) => argv[1] === 'close')).toHaveLength(
489
+ condition === 'ready' || condition === 'lost-receipt' ? 0 : 1,
490
+ );
491
+ if (condition === 'lost-receipt')
492
+ await expect.poll(() => child?.exitCode, { timeout: 1500 }).toBeTypeOf('number');
493
+ } finally {
494
+ child?.kill('SIGTERM');
495
+ await exit;
496
+ rmSync(root, { recursive: true, force: true });
497
+ }
498
+ },
499
+ );
500
+
501
+ it.each([
502
+ 'Windows',
503
+ 'missing-handle',
504
+ 'remote-workspace',
505
+ ] as const)('refuses %s before creating a terminal or admitting a lead', async (reason) => {
506
+ const originalPlatform = process.platform;
507
+ vi.stubEnv(
508
+ 'ORCA_TERMINAL_HANDLE',
509
+ reason === 'missing-handle' ? undefined : fixtureContext.coordinatorHandle,
510
+ );
511
+ vi.stubEnv('ORCA_WORKTREE_ID', 'partial-context');
512
+ if (reason === 'Windows')
513
+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
514
+ if (reason === 'remote-workspace')
515
+ fixtureRunner.mockImplementation(async (...args) =>
516
+ args[1][0] === 'worktree'
517
+ ? fixtureReply({
518
+ worktree: {
519
+ id: 'remote',
520
+ path: '/fixture/project',
521
+ branch: 'main',
522
+ hostId: 'ssh-host',
523
+ },
524
+ })
525
+ : runOrcaFixture(...args),
526
+ );
527
+ const admitted = vi.fn<(pid: number) => void>();
528
+ try {
529
+ await expect(
530
+ new OrcaExecutionBackend(fixtureRunner).startLead(
531
+ {
532
+ command: '/fixture/claude',
533
+ args: [],
534
+ cwd: '/fixture/project',
535
+ tempDir: '/fixture/spawn',
536
+ env: {
537
+ CLEO_SESSION_ID: 'ses_own',
538
+ CLEO_AGENT_ID: 'agent-own',
539
+ CLEO_AGENT_ROLE: 'lead',
540
+ },
541
+ },
542
+ admitted,
543
+ ),
544
+ ).rejects.toMatchObject({
545
+ code: reason === 'missing-handle' ? 'E_ORCA_CONTEXT' : 'E_LEAD_TOOLS_UNSTRIPPED',
546
+ exitCode: 63,
547
+ fix: expect.stringContaining('keep orchestrate.leadWorker.v1 enabled'),
548
+ });
549
+ expect(admitted).not.toHaveBeenCalled();
550
+ expect(fixtureRunner.mock.calls.some(([, args]) => args[1] === 'create')).toBe(false);
551
+ } finally {
552
+ Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
553
+ }
554
+ });
555
+
348
556
  it('refuses a changed runtime and an incomplete command registry before launch', async () => {
349
557
  fixtureRunner.mockImplementation(async (...args) =>
350
558
  args[1][0] === 'status'
@@ -1494,3 +1702,8 @@ describe('Orca execution process boundary', () => {
1494
1702
  });
1495
1703
  });
1496
1704
  });
1705
+
1706
+ import { type ChildProcess, spawn } from 'node:child_process';
1707
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
1708
+ import { tmpdir } from 'node:os';
1709
+ import { join } from 'node:path';
@@ -3,7 +3,9 @@
3
3
  * @packageDocumentation
4
4
  */
5
5
  import { execFile } from 'node:child_process';
6
- import { isAbsolute } from 'node:path';
6
+ import { mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
7
+ import { isAbsolute, join } from 'node:path';
8
+ import { setTimeout as delay } from 'node:timers/promises';
7
9
  import type {
8
10
  OrcaAttempt,
9
11
  OrcaCommandReply,
@@ -12,6 +14,8 @@ import type {
12
14
  OrcaContext,
13
15
  OrcaDiscovery,
14
16
  OrcaLaunch,
17
+ OrcaLeadTerminal,
18
+ OrcaLeadTerminalLaunch,
15
19
  OrcaReply,
16
20
  OrcaReportSource,
17
21
  OrcaRoutingAdapter,
@@ -221,7 +225,7 @@ export const runOrcaCommand: OrcaCommandRunner = (executable, args, cwd, input)
221
225
  * provider registry. Core persists each operation before invoking these methods.
222
226
  */
223
227
  export class OrcaExecutionBackend implements OrcaRoutingAdapter {
224
- /** Public launch APIs cannot enforce denied tools or a strict MCP allowlist. */
228
+ /** Worker launch APIs cannot enforce denied tools or a strict MCP allowlist. */
225
229
  readonly leadToolStrip = 'unsupported';
226
230
  private readonly executable: string;
227
231
 
@@ -249,6 +253,217 @@ export class OrcaExecutionBackend implements OrcaRoutingAdapter {
249
253
  );
250
254
  }
251
255
 
256
+ /**
257
+ * Host Claude Code's prepared guard argv in a local Orca terminal. The shell
258
+ * waits for a private release file, so a missing receipt, wrong runtime or
259
+ * disconnected owner terminal cannot start a model turn. Never retry create.
260
+ * @param launch - The provider's guarded command and private startup directory.
261
+ * @param onStarted - Persists the PID before any model turn is allowed.
262
+ * @returns The verified terminal handle and provider PID.
263
+ */
264
+ async startLead(
265
+ launch: OrcaLeadTerminalLaunch,
266
+ onStarted: (pid: number) => void | Promise<void>,
267
+ ): Promise<OrcaLeadTerminal> {
268
+ const refuse = (message: string) =>
269
+ new OrcaExecutionError(
270
+ ORCA_LEAD_LAUNCH_REFUSAL.code,
271
+ message,
272
+ 'Restore a visible connected local Orca terminal and use --adapter claude-code; update the CLI and runtime together if required terminal commands are unavailable; keep orchestrate.leadWorker.v1 enabled.',
273
+ );
274
+ const handle = process.env.ORCA_TERMINAL_HANDLE;
275
+ if (!handle) {
276
+ throw new OrcaExecutionError(
277
+ 'E_ORCA_CONTEXT',
278
+ 'Orca context hints have no ORCA_TERMINAL_HANDLE; a guarded lead cannot select its owner terminal.',
279
+ 'Run in the intended Orca terminal with its ORCA_TERMINAL_HANDLE, or remove stale ORCA_* hints outside Orca to use the native route; keep orchestrate.leadWorker.v1 enabled.',
280
+ );
281
+ }
282
+ if (
283
+ process.platform === 'win32' ||
284
+ !isAbsolute(launch.command) ||
285
+ !isAbsolute(launch.tempDir) ||
286
+ !launch.env.CLEO_SESSION_ID ||
287
+ !launch.env.CLEO_AGENT_ID ||
288
+ launch.env.CLEO_AGENT_ROLE !== 'lead'
289
+ ) {
290
+ throw refuse(
291
+ 'The guarded Orca lead requires a local POSIX terminal and an absolute provider binary.',
292
+ );
293
+ }
294
+ const registryResult = await this.runner(
295
+ this.executable,
296
+ ['agent-context', '--json'],
297
+ launch.cwd,
298
+ );
299
+ const registry = orcaCommandRegistrySchema.parse(JSON.parse(registryResult.stdout));
300
+ const create = registry.commands.find((entry) => entry.command === 'terminal create');
301
+ const show = registry.commands.find((entry) => entry.command === 'terminal show');
302
+ const close = registry.commands.find((entry) => entry.command === 'terminal close');
303
+ const focus = registry.commands.find((entry) => entry.command === 'terminal switch');
304
+ if (
305
+ registryResult.exitCode !== 0 ||
306
+ !create ||
307
+ !['command', 'worktree', 'title', 'environment'].every((flag) =>
308
+ create.flags.includes(flag),
309
+ ) ||
310
+ !show ||
311
+ !['terminal', 'environment'].every((flag) => show.flags.includes(flag)) ||
312
+ !close ||
313
+ !['terminal', 'environment'].every((flag) => close.flags.includes(flag)) ||
314
+ !focus ||
315
+ !['terminal', 'environment'].every((flag) => focus.flags.includes(flag))
316
+ ) {
317
+ throw refuse('Orca does not declare the guarded terminal command transport.');
318
+ }
319
+ const status = await this.invoke(['status'], launch.cwd);
320
+ const runtimeId = status._meta?.runtimeId;
321
+ if (!status.ok || !runtimeId) throw refuse('Orca did not prove a local runtime.');
322
+ const context: OrcaContext = { runtimeId, coordinatorHandle: handle, executionHostId: 'local' };
323
+ await this.verifyRuntime(launch.cwd, context);
324
+ const caller = (
325
+ await this.query(['terminal', 'show', '--terminal', handle], launch.cwd, context)
326
+ ).result?.terminal;
327
+ const workspace = (
328
+ await this.query(
329
+ ['worktree', 'show', '--worktree', `path:${launch.cwd}`],
330
+ launch.cwd,
331
+ context,
332
+ )
333
+ ).result?.worktree;
334
+ if (
335
+ caller?.handle !== handle ||
336
+ !caller.connected ||
337
+ !caller.writable ||
338
+ caller.executionHostId !== 'local' ||
339
+ !workspace ||
340
+ workspace.path !== launch.cwd ||
341
+ workspace.hostId !== 'local'
342
+ ) {
343
+ throw refuse('Orca did not prove the local caller and existing lead workspace.');
344
+ }
345
+
346
+ const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
347
+ for (const key of Object.keys(launch.env)) {
348
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw refuse('Invalid lead environment key.');
349
+ }
350
+ const dir = await mkdtemp(join(launch.tempDir, 'orca-terminal-'));
351
+ const script = join(dir, 'launch.sh');
352
+ const pidFile = join(dir, 'pid');
353
+ const release = join(dir, 'release');
354
+ let terminalHandle: string | undefined;
355
+ try {
356
+ await writeFile(
357
+ script,
358
+ [
359
+ '#!/bin/sh',
360
+ 'umask 077',
361
+ `trap ${quote(`rm -rf -- ${quote(dir)}`)} EXIT`,
362
+ `printf '%s' "$$" > ${quote(pidFile)}`,
363
+ 'attempt=0',
364
+ `while [ ! -f ${quote(release)} ]; do`,
365
+ ` [ -d ${quote(dir)} ] || exit 1`,
366
+ ' attempt=$((attempt + 1)); [ "$attempt" -le 600 ] || exit 1',
367
+ ' sleep 0.1',
368
+ 'done',
369
+ `cd ${quote(launch.cwd)} || exit 1`,
370
+ ...Object.entries(launch.env).map(([key, value]) => `export ${quote(`${key}=${value}`)}`),
371
+ `exec ${[launch.command, ...launch.args].map(quote).join(' ')}`,
372
+ '',
373
+ ].join('\n'),
374
+ { mode: 0o600 },
375
+ );
376
+ const created = await this.query(
377
+ [
378
+ 'terminal',
379
+ 'create',
380
+ '--worktree',
381
+ workspace.address?.worktree ?? `id:${workspace.id}`,
382
+ '--title',
383
+ 'CLEO no-hands lead',
384
+ '--command',
385
+ `exec /bin/sh ${quote(script)}`,
386
+ ],
387
+ launch.cwd,
388
+ context,
389
+ );
390
+ const terminal = created.result?.terminal;
391
+ if (terminal && terminal.handle !== handle && terminal.executionHostId === 'local') {
392
+ terminalHandle = terminal.handle;
393
+ }
394
+ if (
395
+ !terminal ||
396
+ terminal.handle === handle ||
397
+ terminal.executionHostId !== 'local' ||
398
+ terminal.surface !== 'visible' ||
399
+ terminal.hostPlatform !== process.platform
400
+ ) {
401
+ throw refuse('Orca returned no new local lead terminal; its first-turn gate stays closed.');
402
+ }
403
+ let pid = 0;
404
+ for (let attempt = 0; attempt < 100; attempt++) {
405
+ const text = await readFile(pidFile, 'utf8').catch(() => '');
406
+ if (/^[1-9][0-9]*$/.test(text)) {
407
+ pid = Number(text);
408
+ break;
409
+ }
410
+ await delay(100);
411
+ }
412
+ if (!Number.isSafeInteger(pid) || pid <= 0 || pid !== terminal.processId) {
413
+ throw refuse('The guarded terminal supervisor did not prove its startup PID.');
414
+ }
415
+ // Older Orca show replies omit surface; an affirmative UI navigation proves visibility now.
416
+ const focused = (
417
+ await this.query(['terminal', 'switch', '--terminal', terminal.handle], launch.cwd, context)
418
+ ).result?.focus;
419
+ const owner = (
420
+ await this.query(['terminal', 'show', '--terminal', terminal.handle], launch.cwd, context)
421
+ ).result?.terminal;
422
+ if (
423
+ owner?.handle !== terminal.handle ||
424
+ !owner.connected ||
425
+ !owner.writable ||
426
+ (owner.surface !== undefined && owner.surface !== 'visible') ||
427
+ focused?.handle !== terminal.handle ||
428
+ !focused.navigated ||
429
+ focused.worktreeId !== workspace.id ||
430
+ owner.tabId !== focused.tabId ||
431
+ owner.executionHostId !== 'local' ||
432
+ owner.worktreePath !== launch.cwd
433
+ ) {
434
+ throw refuse('The lead has no verified owner terminal; its first-turn gate stays closed.');
435
+ }
436
+ await onStarted(pid);
437
+ await writeFile(`${release}.tmp`, '', { mode: 0o600 });
438
+ await rename(`${release}.tmp`, release);
439
+ return { runtimeId, terminalHandle: terminal.handle, pid };
440
+ } catch (error) {
441
+ await rm(dir, { recursive: true, force: true });
442
+ if (terminalHandle) {
443
+ try {
444
+ await this.verifyRuntime(launch.cwd, context);
445
+ const closed = (
446
+ await this.query(
447
+ ['terminal', 'close', '--terminal', terminalHandle],
448
+ launch.cwd,
449
+ context,
450
+ )
451
+ ).result?.close;
452
+ if (closed?.handle !== terminalHandle || !closed.ptyKilled)
453
+ throw refuse('Orca did not prove terminal cleanup.');
454
+ } catch (cleanupError) {
455
+ throw new OrcaExecutionError(
456
+ error instanceof OrcaExecutionError ? error.code : ORCA_LEAD_LAUNCH_REFUSAL.code,
457
+ `${error instanceof Error ? error.message : String(error)}; terminal ${terminalHandle} cleanup is unverified: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
458
+ `${error instanceof OrcaExecutionError ? error.fix : 'Restore the guarded terminal transport.'} Inspect orca terminal show --terminal ${terminalHandle} before closing that exact terminal.`,
459
+ error instanceof OrcaExecutionError ? error.receipt : null,
460
+ );
461
+ }
462
+ }
463
+ throw error;
464
+ }
465
+ }
466
+
252
467
  /** Verify the local caller before returning a sanitized account inventory. */
253
468
  async discover(projectRoot: string): Promise<OrcaDiscovery | null> {
254
469
  if (!this.hasContextHints()) return null;
@@ -31,7 +31,10 @@ import { tmpdir } from 'node:os';
31
31
  import { join } from 'node:path';
32
32
  import type { SpawnContext } from '@cleocode/contracts';
33
33
  import { E_LEAD_NO_OWNER_CHANNEL, LEAD_DENIED_TOOLS, LEAD_RUNNER_TOOL } from '@cleocode/contracts';
34
+ import type { OrcaLeadTerminalLauncher } from '@cleocode/contracts/orca-execution.js';
34
35
  import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
36
+ import { OrcaExecutionError } from '../../../orca-execution.js';
37
+ import * as leadMcpModule from '../lead-mcp.js';
35
38
  import { LEAD_MCP_FILE, prepareLeadMcp, resolveMbxMcpServer } from '../lead-mcp.js';
36
39
  import {
37
40
  LEAD_KICKOFF_PROMPT,
@@ -83,6 +86,8 @@ describe('lead isolation on claude-code (T14363, T14423)', () => {
83
86
  });
84
87
 
85
88
  afterEach(() => {
89
+ vi.restoreAllMocks();
90
+ vi.unstubAllEnvs();
86
91
  rmSync(root, { recursive: true, force: true });
87
92
  });
88
93
 
@@ -147,6 +152,98 @@ describe('lead isolation on claude-code (T14363, T14423)', () => {
147
152
  expect(args.join(' ')).not.toContain('AskUserQuestion');
148
153
  });
149
154
 
155
+ it.skipIf(process.platform === 'win32').each(['interactive', 'detached'] as const)(
156
+ 'hands the production %s guards and settings to Orca before starting',
157
+ async (mode) => {
158
+ writeFileSync(claudeJson, JSON.stringify({ mcpServers: { mbx, shell: SHELL_SERVER } }));
159
+ for (const name of ['claude', 'cleo']) fakeBinary(join(bin, name), join(root, 'calls.log'));
160
+ vi.stubEnv('PATH', `${bin}:${process.env.PATH}`);
161
+ const prepare = prepareLeadMcp;
162
+ vi.spyOn(leadMcpModule, 'prepareLeadMcp').mockImplementation((dir, cwd, options) =>
163
+ prepare(dir, cwd, { ...options, claudeJsonPath: claudeJson }),
164
+ );
165
+ const started = vi.fn<(pid: number) => void>();
166
+ let promptFile = '';
167
+ const launcher = vi.fn<OrcaLeadTerminalLauncher>(async (launch, onStarted) => {
168
+ const value = (flag: string) => launch.args[launch.args.indexOf(flag) + 1] ?? '';
169
+ expect(launch.command).toBe(join(bin, 'claude'));
170
+ expect(launch.env).toEqual(IDENTITY);
171
+ expect(launch.args).toContain('--restricted');
172
+ expect(launch.args).toContain('--strict-mcp-config');
173
+ expect(launch.args).not.toContain('--dangerously-skip-permissions');
174
+ expect(value('--tools')).toBe(mode === 'interactive' ? 'AskUserQuestion' : '');
175
+ expect(value('--permission-mode')).toBe(mode === 'interactive' ? 'default' : 'dontAsk');
176
+ expect(value('--setting-sources')).toBe('');
177
+ expect(value('--session-id')).toBe(SESSION);
178
+ expect(value('--disallowedTools')).toBe('Bash,Edit,Write,NotebookEdit,WebFetch,WebSearch');
179
+ expect(value('--allowedTools')).toBe(
180
+ `${LEAD_RUNNER_TOOL},mcp__mbx${mode === 'interactive' ? ',AskUserQuestion' : ''}`,
181
+ );
182
+ const config = JSON.parse(readFileSync(value('--mcp-config'), 'utf8'));
183
+ expect(Object.keys(config.mcpServers).sort()).toEqual(['cleo-lead', 'mbx']);
184
+ expect(config.mcpServers['cleo-lead'].env).toEqual(IDENTITY);
185
+ const settings = JSON.parse(readFileSync(value('--settings'), 'utf8'));
186
+ expect(settings.hooks.SessionStart[0].hooks[0].command).toContain(value('--mcp-config'));
187
+ expect(settings.hooks.SessionEnd[0].hooks[0].command).toContain(`--session ${SESSION}`);
188
+ expect(statSync(value('--settings')).mode & 0o077).toBe(0);
189
+ promptFile = value('--append-system-prompt-file');
190
+ expect(readFileSync(promptFile, 'utf8')).toContain('plan');
191
+ expect(started).not.toHaveBeenCalled();
192
+ onStarted(12345);
193
+ return { runtimeId: 'runtime-fixture', terminalHandle: 'term_lead', pid: 12345 };
194
+ });
195
+ try {
196
+ const result = await new ClaudeCodeSpawnProvider().spawn({
197
+ ...lead(mode),
198
+ workingDirectory: project,
199
+ options: { ...lead(mode).options, env: IDENTITY },
200
+ leadTerminalLauncher: launcher,
201
+ onLeadStarted: started,
202
+ });
203
+ expect(result.status).toBe('running');
204
+ expect(result.leadTerminal?.terminalHandle).toBe('term_lead');
205
+ expect(result.leadTempDir).toBeTruthy();
206
+ expect(launcher).toHaveBeenCalledOnce();
207
+ expect(started).toHaveBeenCalledWith(12345);
208
+ const refusal = new OrcaExecutionError(
209
+ 'E_ORCA_CONTEXT',
210
+ 'The owner terminal was refused.',
211
+ 'Restore the owner channel.',
212
+ );
213
+ launcher.mockRejectedValueOnce(refusal);
214
+ await expect(
215
+ new ClaudeCodeSpawnProvider().spawn({
216
+ ...lead(mode),
217
+ workingDirectory: project,
218
+ options: { ...lead(mode).options, env: IDENTITY },
219
+ leadTerminalLauncher: launcher,
220
+ onLeadStarted: started,
221
+ }),
222
+ ).rejects.toBe(refusal);
223
+ const refusedDir = launcher.mock.calls.at(-1)?.[0].tempDir;
224
+ expect(refusedDir).toBeTruthy();
225
+ expect(existsSync(refusedDir ?? '')).toBe(false);
226
+ launcher.mockRejectedValueOnce(new Error('Terminal preparation failed.'));
227
+ await expect(
228
+ new ClaudeCodeSpawnProvider().spawn({
229
+ ...lead(mode),
230
+ workingDirectory: project,
231
+ options: { ...lead(mode).options, env: IDENTITY },
232
+ leadTerminalLauncher: launcher,
233
+ onLeadStarted: started,
234
+ }),
235
+ ).rejects.toMatchObject({
236
+ code: 'E_LEAD_TOOLS_UNSTRIPPED',
237
+ message: 'Terminal preparation failed.',
238
+ exitCode: 63,
239
+ fix: expect.stringContaining('keep orchestrate.leadWorker.v1 enabled'),
240
+ });
241
+ } finally {
242
+ if (promptFile) rmSync(join(promptFile, '..'), { recursive: true, force: true });
243
+ }
244
+ },
245
+ );
246
+
150
247
  it.each([
151
248
  [false, true],
152
249
  [true, false],