From 0dff800866e0e628795edc9264ba42131bf5cf34 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Wed, 12 Aug 2026 14:58:03 -0400 Subject: [PATCH 1/3] fix(vscode): probe resolved servers through standard LSP --- docs/SERVER_PROVISIONING.md | 17 + editors/vscode/src/lspCompatibility.ts | 291 ++++++++++++++++++ editors/vscode/src/serverResolver.ts | 88 +++++- editors/vscode/test/suite/extension.test.ts | 3 +- .../test/suite/lsp_compatibility.test.ts | 162 ++++++++++ .../server_resolver_compatibility.test.ts | 75 +++++ .../test/suite/show_output_action.test.ts | 3 +- .../vscode/test/suite/testCompatibility.ts | 15 + .../test/suite/workspace_root_picker.test.ts | 3 +- .../suite/workspace_trust_transition.test.ts | 3 +- 10 files changed, 640 insertions(+), 20 deletions(-) create mode 100644 editors/vscode/src/lspCompatibility.ts create mode 100644 editors/vscode/test/suite/lsp_compatibility.test.ts create mode 100644 editors/vscode/test/suite/server_resolver_compatibility.test.ts create mode 100644 editors/vscode/test/suite/testCompatibility.ts diff --git a/docs/SERVER_PROVISIONING.md b/docs/SERVER_PROVISIONING.md index edd5c4ed886..ace8bb62cd0 100644 --- a/docs/SERVER_PROVISIONING.md +++ b/docs/SERVER_PROVISIONING.md @@ -20,6 +20,23 @@ The VS Code/Open VSX extension resolves the server in this order: `ripr.server.path` is an override for pinned or enterprise-managed binaries. The PATH fallback remains useful for local development and offline installs. +Before activation commits to any candidate, the extension first checks +`ripr --version`, then runs a bounded standard-LSP compatibility session over +`ripr lsp --stdio`: framed `initialize`, `initialized`, `shutdown`, and `exit`. +The initialize result must identify a versioned `ripr` server, select UTF-16, +and advertise the synchronization, hover, and code-action surface exercised by +the extension. Pull diagnostics, code-action resolve, execute commands, workspace +folders, and work-done progress are retained as typed optional evidence; their +absence does not inflate or reject the standard baseline. A failed probe never +becomes the active client, and resolver fallback continues only along the +existing order above. Workspace Trust remains outside and above resolution, so +an untrusted workspace spawns neither this probe nor the active server. + +This compatibility evidence is activation state, separate from the completed +install receipt and its byte-integrity evidence. It does not attest producer +provenance or use a private/experimental capability as the standard-LSP +baseline. + ## Downloaded Server Cache Downloaded servers are stored under the VS Code global storage directory: diff --git a/editors/vscode/src/lspCompatibility.ts b/editors/vscode/src/lspCompatibility.ts new file mode 100644 index 00000000000..e9c0c86b11d --- /dev/null +++ b/editors/vscode/src/lspCompatibility.ts @@ -0,0 +1,291 @@ +import * as cp from 'child_process'; + +const DEFAULT_PROBE_TIMEOUT_MS = 5000; +const MAX_MESSAGE_BYTES = 1024 * 1024; + +export type RequiredLspCapability = 'textDocumentSync' | 'hover' | 'codeAction' | 'positionEncoding'; +export type OptionalLspCapability = 'pullDiagnostics' | 'codeActionResolve' | 'executeCommand' | 'workspaceFolders' | 'workDoneProgress'; + +export interface LspCompatibilityEvidence { + readonly status: 'compatible'; + readonly serverName?: string; + readonly serverVersion?: string; + readonly positionEncoding: 'utf-16'; + readonly required: Readonly>; + readonly optional: Readonly>; + readonly processResult: 'clean_exit'; +} + +export type LspProbeFailureKind = + | 'spawn_failure' + | 'framing_failure' + | 'initialize_error' + | 'initialize_timeout' + | 'server_identity_mismatch' + | 'missing_required_capability' + | 'position_encoding_mismatch' + | 'shutdown_failure' + | 'process_failure'; + +export interface LspCompatibilityFailure { + readonly status: 'incompatible'; + readonly kind: LspProbeFailureKind; + readonly detail: string; +} + +export type LspCompatibilityResult = LspCompatibilityEvidence | LspCompatibilityFailure; + +interface JsonRpcMessage { + readonly jsonrpc?: string; + readonly id?: number | string | null; + readonly method?: string; + readonly result?: unknown; + readonly error?: { readonly code?: number; readonly message?: string }; +} + +export async function probeStandardLspCompatibility( + command: string, + useShell = false, + timeoutMs = DEFAULT_PROBE_TIMEOUT_MS +): Promise { + return new Promise((resolve) => { + let settled = false; + let phase: 'initialize' | 'shutdown' | 'exit' = 'initialize'; + let evidence: Omit | undefined; + let stdout: Buffer = Buffer.alloc(0); + const child = cp.spawn(command, ['lsp', '--stdio'], { + shell: useShell, + detached: process.platform !== 'win32', + stdio: ['pipe', 'pipe', 'pipe'] + }); + + const finish = (result: LspCompatibilityResult, kill = true): void => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); + if (kill && child.exitCode === null && child.signalCode === null) { + terminateProbeProcessTree(child); + } + resolve(result); + }; + + const fail = (kind: LspProbeFailureKind, detail: string): void => { + finish({ status: 'incompatible', kind, detail }); + }; + + const timer = setTimeout(() => { + const kind = phase === 'initialize' ? 'initialize_timeout' : 'shutdown_failure'; + fail(kind, `Timed out after ${timeoutMs}ms during the LSP ${phase} phase.`); + }, timeoutMs); + + child.once('error', (error) => fail('spawn_failure', error.message)); + child.stdin?.once('error', (error) => fail('process_failure', `LSP probe stdin failed: ${error.message}`)); + child.once('exit', (code, signal) => { + if (settled) { + return; + } + if (phase === 'exit' && code === 0 && evidence) { + finish({ ...evidence, processResult: 'clean_exit' }, false); + return; + } + fail( + 'process_failure', + `LSP probe process exited during ${phase} with code ${String(code)} and signal ${String(signal)}.` + ); + }); + + child.stdout.on('data', (chunk: Buffer) => { + if (settled) { + return; + } + stdout = Buffer.concat([stdout, chunk]); + try { + stdout = consumeMessages(stdout, onMessage); + } catch (error) { + fail('framing_failure', error instanceof Error ? error.message : String(error)); + } + }); + + const onMessage = (message: JsonRpcMessage): void => { + if (message.method && message.id !== undefined) { + writeMessage(child, { jsonrpc: '2.0', id: message.id, result: null }); + return; + } + if (phase === 'initialize' && message.id === 1) { + if (message.error) { + fail('initialize_error', message.error.message ?? `Initialize failed with code ${String(message.error.code)}.`); + return; + } + const checked = validateInitializeResult(message.result); + if (checked.status === 'incompatible') { + finish(checked); + return; + } + evidence = checked; + phase = 'shutdown'; + writeMessage(child, { jsonrpc: '2.0', method: 'initialized', params: {} }); + writeMessage(child, { jsonrpc: '2.0', id: 2, method: 'shutdown', params: null }); + return; + } + if (phase === 'shutdown' && message.id === 2) { + if (message.error) { + fail('shutdown_failure', message.error.message ?? 'The server rejected shutdown.'); + return; + } + phase = 'exit'; + writeMessage(child, { jsonrpc: '2.0', method: 'exit', params: null }); + } + }; + + writeMessage(child, { + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + processId: process.pid, + clientInfo: { name: 'ripr-vscode-compatibility-probe' }, + rootUri: null, + capabilities: { + general: { positionEncodings: ['utf-16'] }, + workspace: { configuration: true, workspaceFolders: true }, + textDocument: { + hover: { contentFormat: ['markdown', 'plaintext'] }, + codeAction: { resolveSupport: { properties: ['edit', 'command'] } }, + diagnostic: {}, + publishDiagnostics: {} + }, + window: { workDoneProgress: true } + }, + workspaceFolders: null + } + }); + }); +} + +function consumeMessages(buffer: Buffer, consume: (message: JsonRpcMessage) => void): Buffer { + let remaining = buffer; + while (remaining.length > 0) { + const headerEnd = remaining.indexOf('\r\n\r\n'); + if (headerEnd < 0) { + if (remaining.length > 8192) { + throw new Error('LSP response headers exceeded 8192 bytes or were not CRLF framed.'); + } + return remaining; + } + const header = remaining.subarray(0, headerEnd).toString('ascii'); + const lengthMatch = /^content-length:\s*(\d+)\s*$/im.exec(header); + if (!lengthMatch) { + throw new Error('LSP response omitted a valid Content-Length header.'); + } + const length = Number(lengthMatch[1]); + if (!Number.isSafeInteger(length) || length > MAX_MESSAGE_BYTES) { + throw new Error(`LSP response declared an invalid Content-Length of ${lengthMatch[1]}.`); + } + const bodyStart = headerEnd + 4; + if (remaining.length < bodyStart + length) { + return remaining; + } + const body = remaining.subarray(bodyStart, bodyStart + length).toString('utf8'); + let parsed: unknown; + try { + parsed = JSON.parse(body); + } catch { + throw new Error('LSP response body was not valid JSON.'); + } + if (!isObject(parsed)) { + throw new Error('LSP response body was not a JSON-RPC object.'); + } + consume(parsed as JsonRpcMessage); + remaining = remaining.subarray(bodyStart + length); + } + return remaining; +} + +function validateInitializeResult(result: unknown): Omit | LspCompatibilityFailure { + if (!isObject(result) || !isObject(result.capabilities)) { + return { status: 'incompatible', kind: 'initialize_error', detail: 'Initialize result omitted server capabilities.' }; + } + const capabilities = result.capabilities; + const missing: string[] = []; + if (!capabilities.textDocumentSync) missing.push('textDocumentSync'); + if (!providerEnabled(capabilities.hoverProvider)) missing.push('hoverProvider'); + if (!providerEnabled(capabilities.codeActionProvider)) missing.push('codeActionProvider'); + if (missing.length > 0) { + return { + status: 'incompatible', + kind: 'missing_required_capability', + detail: `Initialize result omitted required capabilities: ${missing.join(', ')}.` + }; + } + const positionEncoding = capabilities.positionEncoding ?? 'utf-16'; + if (positionEncoding !== 'utf-16') { + return { + status: 'incompatible', + kind: 'position_encoding_mismatch', + detail: `Server selected ${String(positionEncoding)}; the extension requires utf-16.` + }; + } + const serverInfo = isObject(result.serverInfo) ? result.serverInfo : undefined; + if (serverInfo?.name !== 'ripr' || typeof serverInfo.version !== 'string' || serverInfo.version.length === 0) { + return { + status: 'incompatible', + kind: 'server_identity_mismatch', + detail: 'Initialize result did not identify a versioned ripr server.' + }; + } + const codeAction = capabilities.codeActionProvider; + const workspace = isObject(capabilities.workspace) ? capabilities.workspace : undefined; + const workspaceFolders = workspace && isObject(workspace.workspaceFolders) ? workspace.workspaceFolders : undefined; + return { + status: 'compatible', + serverName: serverInfo.name, + serverVersion: serverInfo.version, + positionEncoding: 'utf-16', + required: { textDocumentSync: true, hover: true, codeAction: true, positionEncoding: true }, + optional: { + pullDiagnostics: providerEnabled(capabilities.diagnosticProvider), + codeActionResolve: isObject(codeAction) && codeAction.resolveProvider === true, + executeCommand: isObject(capabilities.executeCommandProvider), + workspaceFolders: workspaceFolders?.supported === true, + workDoneProgress: + (isObject(capabilities.hoverProvider) && capabilities.hoverProvider.workDoneProgress === true) || + (isObject(codeAction) && codeAction.workDoneProgress === true) + } + }; +} + +function providerEnabled(value: unknown): boolean { + return value === true || isObject(value); +} + +function writeMessage(child: cp.ChildProcess, message: object): void { + const body = Buffer.from(JSON.stringify(message), 'utf8'); + child.stdin?.write(`Content-Length: ${body.length}\r\n\r\n`); + child.stdin?.write(body); +} + +export function terminateProbeProcessTree(child: cp.ChildProcess): void { + child.stdin?.destroy(); + if (child.pid && process.platform === 'win32') { + cp.spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { + stdio: 'ignore', + windowsHide: true + }); + return; + } + if (child.pid) { + try { + process.kill(-child.pid, 'SIGKILL'); + return; + } catch { + // Fall through when the process exited between the currentness check and termination. + } + } + child.kill('SIGKILL'); +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/editors/vscode/src/serverResolver.ts b/editors/vscode/src/serverResolver.ts index 87d3aca144b..c01537fb878 100644 --- a/editors/vscode/src/serverResolver.ts +++ b/editors/vscode/src/serverResolver.ts @@ -10,6 +10,12 @@ import { validateManagedServerVersion } from './managedServerInstall'; import { currentRiprPlatform, RiprPlatform } from './platform'; +import { + LspCompatibilityEvidence, + LspCompatibilityFailure, + probeStandardLspCompatibility, + terminateProbeProcessTree +} from './lspCompatibility'; const START_TIMEOUT_MS = 5000; @@ -23,7 +29,7 @@ export interface ResolvedServer { readonly protocolVersion?: string; readonly assetDigest?: string; readonly installationState: 'unmanaged' | 'bundled' | 'complete'; - readonly compatibilityResult: 'not_established'; + readonly compatibilityResult: LspCompatibilityEvidence; /** * True when this server must be spawned through the shell (#2079): a * Windows `.cmd`/`.bat` PATH shim resolves via the shell probe, and the @@ -38,14 +44,27 @@ export interface ResolveFailure { readonly detail: string; } +export interface ServerResolverRuntime { + readonly probeCandidate: ( + command: string, + source: ServerSource, + detail: string, + useShell?: boolean, + installationState?: ResolvedServer['installationState'] + ) => Promise; +} + +const defaultResolverRuntime: ServerResolverRuntime = { probeCandidate }; + export async function resolveServer( context: vscode.ExtensionContext, config: RiprConfig, - output: vscode.OutputChannel + output: vscode.OutputChannel, + runtime: ServerResolverRuntime = defaultResolverRuntime ): Promise { const configuredPath = config.serverPath.trim(); if (configuredPath.length > 0) { - return probeCandidate(configuredPath, 'configured', `configured ripr.server.path ${configuredPath}`, false, 'unmanaged'); + return runtime.probeCandidate(configuredPath, 'configured', `configured ripr.server.path ${configuredPath}`, false, 'unmanaged'); } const platform = currentRiprPlatform(); @@ -60,14 +79,22 @@ export async function resolveServer( if (platform) { const bundled = bundledServerPath(context, platform); - const bundledResult = await probeExistingCandidate(bundled, 'bundled', `bundled server for ${platform.target}`); + const bundledResult = await probeExistingCandidate( + bundled, + 'bundled', + `bundled server for ${platform.target}`, + runtime + ); if (isResolved(bundledResult)) { return bundledResult; } + if (fs.existsSync(bundled)) { + output.appendLine(`Skipping bundled server: ${bundledResult.detail}`); + } const cached = await cachedServerInstallation(context, version, platform); if (cached) { - const cachedResult = await probeCandidate( + const cachedResult = await runtime.probeCandidate( cached.executablePath, 'managed_cache', `completed cached server ${version} for ${platform.target}`, @@ -77,12 +104,13 @@ export async function resolveServer( if (isResolved(cachedResult)) { return withManagedIdentity(cachedResult, cached); } + output.appendLine(`Skipping completed cached server: ${cachedResult.detail}`); } if (config.autoDownload) { try { const downloaded = await downloadServer(context, config, platform, version, output); - const downloadedResult = await probeCandidate( + const downloadedResult = await runtime.probeCandidate( downloaded.executablePath, 'managed_download', `atomically installed server ${version} for ${platform.target}`, @@ -93,6 +121,7 @@ export async function resolveServer( return withManagedIdentity(downloadedResult, downloaded); } downloadFailure = downloadedResult.detail; + output.appendLine(`Skipping downloaded server: ${downloadFailure}`); } catch (error) { downloadFailure = error instanceof Error ? error.message : String(error); output.appendLine(`ripr server download failed: ${downloadFailure}`); @@ -107,7 +136,7 @@ export async function resolveServer( // even though `ripr` works in a terminal (#2079). The command is the // constant string 'ripr --version' — no user input reaches the shell. const probeWithShell = process.platform === 'win32'; - const pathResult = await probeCandidate('ripr', 'path', 'ripr on PATH', probeWithShell, 'unmanaged'); + const pathResult = await runtime.probeCandidate('ripr', 'path', 'ripr on PATH', probeWithShell, 'unmanaged'); const resolvedPathResult: ResolvedServer | ResolveFailure = isResolved(pathResult) && probeWithShell ? { ...pathResult, needsShell: true } : pathResult; if (isResolved(resolvedPathResult)) { @@ -152,12 +181,13 @@ function bundledServerPath(context: vscode.ExtensionContext, platform: RiprPlatf async function probeExistingCandidate( command: string, source: ServerSource, - detail: string + detail: string, + runtime: ServerResolverRuntime ): Promise { if (!fs.existsSync(command)) { return { message: `${detail} was not found.`, detail: `${command} does not exist.` }; } - return probeCandidate(command, source, detail, false, source === 'bundled' ? 'bundled' : 'unmanaged'); + return runtime.probeCandidate(command, source, detail, false, source === 'bundled' ? 'bundled' : 'unmanaged'); } function probeCandidate( @@ -167,12 +197,36 @@ function probeCandidate( useShell = false, installationState: ResolvedServer['installationState'] = 'unmanaged' ): Promise { + return probeVersion(command, detail, useShell).then(async (versionResult) => { + if ('message' in versionResult) { + return versionResult; + } + const compatibility = await probeStandardLspCompatibility(command, useShell, START_TIMEOUT_MS); + if (compatibility.status === 'incompatible') { + return compatibilityFailure(detail, compatibility); + } + return { + command, + source, + detail, + binaryVersion: versionResult.binaryVersion, + installationState, + compatibilityResult: compatibility + }; + }); +} + +function probeVersion( + command: string, + detail: string, + useShell: boolean +): Promise<{ readonly binaryVersion?: string } | ResolveFailure> { return new Promise((resolve) => { const child = cp.spawn(command, ['--version'], { shell: useShell }); const stdoutChunks: Buffer[] = []; const stderrChunks: Buffer[] = []; const timer = setTimeout(() => { - child.kill(); + terminateProbeProcessTree(child); resolve({ message: `${detail} did not respond.`, detail: `Timed out after ${START_TIMEOUT_MS}ms while running ${command} --version.` @@ -191,12 +245,7 @@ function probeCandidate( clearTimeout(timer); if (code === 0) { resolve({ - command, - source, - detail, - binaryVersion: firstOutputLine(stdoutChunks, stderrChunks), - installationState, - compatibilityResult: 'not_established' + binaryVersion: firstOutputLine(stdoutChunks, stderrChunks) }); } else { resolve({ message: `${detail} failed version check.`, detail: `${command} --version exited with code ${code}.` }); @@ -205,6 +254,13 @@ function probeCandidate( }); } +function compatibilityFailure(detail: string, failure: LspCompatibilityFailure): ResolveFailure { + return { + message: `${detail} is not LSP compatible.`, + detail: `[${failure.kind}] ${failure.detail}` + }; +} + function withManagedIdentity( resolved: ResolvedServer, installation: ManagedServerInstallation diff --git a/editors/vscode/test/suite/extension.test.ts b/editors/vscode/test/suite/extension.test.ts index 6d516d28be2..2fed16d0761 100644 --- a/editors/vscode/test/suite/extension.test.ts +++ b/editors/vscode/test/suite/extension.test.ts @@ -10,6 +10,7 @@ import { readActionableGapQueueStatus, readFirstPrPacketStatus } from '../../src/client'; +import { compatibleLspEvidence } from './testCompatibility'; suite('Extension Smoke', () => { suiteSetup(async () => { @@ -4354,7 +4355,7 @@ function createControllerTestContext(options: ControllerTestOptions) { detail: 'test ripr on PATH', binaryVersion: options.serverVersion ?? 'ripr 0.8.0-test', installationState: 'unmanaged', - compatibilityResult: 'not_established' + compatibilityResult: compatibleLspEvidence }), createLanguageClient: (_serverOptions, options, experimental) => { clientOptions = options; diff --git a/editors/vscode/test/suite/lsp_compatibility.test.ts b/editors/vscode/test/suite/lsp_compatibility.test.ts new file mode 100644 index 00000000000..648d4e6968b --- /dev/null +++ b/editors/vscode/test/suite/lsp_compatibility.test.ts @@ -0,0 +1,162 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { probeStandardLspCompatibility } from '../../src/lspCompatibility'; + +suite('Standard LSP compatibility probe', () => { + const temporaryRoots: string[] = []; + + teardown(() => { + for (const root of temporaryRoots.splice(0)) { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + test('accepts the real packaged server through initialize and shutdown', async function () { + const server = process.env.RIPR_TEST_SERVER_PATH; + if (!server) { + this.skip(); + return; + } + const result = await probeStandardLspCompatibility(server, false, 10_000); + assert.strictEqual(result.status, 'compatible', JSON.stringify(result)); + if (result.status === 'compatible') { + assert.strictEqual(result.serverName, 'ripr'); + assert.strictEqual(result.positionEncoding, 'utf-16'); + assert.strictEqual(result.processResult, 'clean_exit'); + } + }); + + test('rejects a version-only executable that cannot frame LSP', async () => { + const fake = fakeServer('version-only'); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + assert.strictEqual(result.status, 'incompatible'); + assert.ok(result.status === 'incompatible' && ['framing_failure', 'process_failure'].includes(result.kind)); + }); + + test('requires the exercised baseline but records optional omissions', async () => { + const missing = fakeServer('missing-hover'); + const rejected = await probeStandardLspCompatibility(missing.command, missing.useShell, 1000); + assert.deepStrictEqual( + rejected.status === 'incompatible' ? rejected.kind : undefined, + 'missing_required_capability' + ); + + const optional = fakeServer('optional-omitted'); + const accepted = await probeStandardLspCompatibility(optional.command, optional.useShell, 1000); + assert.strictEqual(accepted.status, 'compatible', JSON.stringify(accepted)); + if (accepted.status === 'compatible') { + assert.deepStrictEqual(accepted.optional, { + pullDiagnostics: false, + codeActionResolve: false, + executeCommand: false, + workspaceFolders: false, + workDoneProgress: false + }); + } + }); + + test('rejects a server that selects a non-UTF-16 position encoding', async () => { + const fake = fakeServer('utf8'); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + assert.deepStrictEqual( + result.status === 'incompatible' ? result.kind : undefined, + 'position_encoding_mismatch' + ); + }); + + test('rejects a standard-capable process that does not identify as ripr', async () => { + const fake = fakeServer('wrong-identity'); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + assert.deepStrictEqual( + result.status === 'incompatible' ? result.kind : undefined, + 'server_identity_mismatch' + ); + }); + + for (const [mode, expected] of [ + ['timeout', 'initialize_timeout'], + ['malformed', 'framing_failure'], + ['partial', 'process_failure'], + ['crash', 'process_failure'], + ['nonzero', 'process_failure'], + ['shutdown-failure', 'shutdown_failure'] + ] as const) { + test(`classifies and cleans up ${mode}`, async () => { + const fake = fakeServer(mode); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, mode === 'timeout' ? 300 : 3000); + assert.strictEqual(result.status, 'incompatible'); + assert.deepStrictEqual(result.status === 'incompatible' ? result.kind : undefined, expected); + }); + } + + test('a later compatible channel can be tried after an incompatible candidate', async () => { + const first = fakeServer('missing-hover'); + const second = fakeServer('valid'); + const attempts = [first, second]; + let selected: number | undefined; + for (let index = 0; index < attempts.length; index += 1) { + const candidate = attempts[index]; + const result = await probeStandardLspCompatibility(candidate.command, candidate.useShell, 1000); + if (result.status === 'compatible') { + selected = index; + break; + } + } + assert.strictEqual(selected, 1); + }); + + function fakeServer(mode: string): { command: string; useShell: boolean } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ripr-lsp-probe-')); + temporaryRoots.push(root); + const script = path.join(root, 'server.js'); + fs.writeFileSync(script, fakeServerSource(mode)); + if (process.platform === 'win32') { + const command = path.join(root, 'ripr.cmd'); + fs.writeFileSync(command, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`); + return { command, useShell: true }; + } + const command = path.join(root, 'ripr'); + fs.writeFileSync(command, `#!/bin/sh\nexec "${process.execPath}" "${script}" "$@"\n`, { mode: 0o755 }); + return { command, useShell: false }; + } +}); + +function fakeServerSource(mode: string): string { + return ` +const mode = ${JSON.stringify(mode)}; +if (process.argv.includes('--version')) { console.log('ripr 9.9.9'); process.exit(0); } +if (mode === 'version-only') { process.stdout.write('not lsp'); process.exit(0); } +if (mode === 'timeout') { setInterval(() => {}, 1000); return; } +if (mode === 'malformed') { process.stdout.write('Content-Length: nope\\r\\n\\r\\n{}'); return; } +if (mode === 'partial') { process.stdout.write('Content-Length: 100\\r\\n\\r\\n{'); process.exit(0); } +if (mode === 'crash') { process.exit(0); } +if (mode === 'nonzero') { process.exit(17); } +let input = Buffer.alloc(0); +process.stdin.on('data', chunk => { input = Buffer.concat([input, chunk]); consume(); }); +function send(value) { + const body = Buffer.from(JSON.stringify(value)); + process.stdout.write('Content-Length: ' + body.length + '\\r\\n\\r\\n'); + process.stdout.write(body); +} +function consume() { + while (true) { + const end = input.indexOf('\\r\\n\\r\\n'); if (end < 0) return; + const header = input.subarray(0, end).toString(); + const match = /Content-Length:\\s*(\\d+)/i.exec(header); if (!match) process.exit(2); + const length = Number(match[1]); const start = end + 4; if (input.length < start + length) return; + const message = JSON.parse(input.subarray(start, start + length).toString()); input = input.subarray(start + length); + if (message.method === 'initialize') { + const capabilities = { textDocumentSync: 1, hoverProvider: true, codeActionProvider: true, positionEncoding: mode === 'utf8' ? 'utf-8' : 'utf-16' }; + if (mode === 'missing-hover') delete capabilities.hoverProvider; + if (mode === 'valid') Object.assign(capabilities, { diagnosticProvider: {}, executeCommandProvider: { commands: [] }, workspace: { workspaceFolders: { supported: true } }, workDoneProgress: true, codeActionProvider: { resolveProvider: true } }); + send({ jsonrpc: '2.0', id: message.id, result: { capabilities, serverInfo: { name: mode === 'wrong-identity' ? 'other' : 'ripr', version: '9.9.9' } } }); + } else if (message.method === 'shutdown') { + if (mode === 'shutdown-failure') send({ jsonrpc: '2.0', id: message.id, error: { code: -1, message: 'no' } }); + else send({ jsonrpc: '2.0', id: message.id, result: null }); + } else if (message.method === 'exit') { process.exit(0); } + } +} +`; +} diff --git a/editors/vscode/test/suite/server_resolver_compatibility.test.ts b/editors/vscode/test/suite/server_resolver_compatibility.test.ts new file mode 100644 index 00000000000..8edb900504e --- /dev/null +++ b/editors/vscode/test/suite/server_resolver_compatibility.test.ts @@ -0,0 +1,75 @@ +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as vscode from 'vscode'; +import { RiprConfig } from '../../src/config'; +import { currentRiprPlatform } from '../../src/platform'; +import { resolveServer, ServerResolverRuntime } from '../../src/serverResolver'; +import { compatibleLspEvidence } from './testCompatibility'; + +suite('Server resolver compatibility fallback', () => { + test('skips an incompatible bundled candidate and selects the next allowed channel', async function () { + const platform = currentRiprPlatform(); + if (!platform) { + this.skip(); + return; + } + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ripr-resolver-probe-')); + const bundled = path.join(root, 'extension', 'server', platform.target, platform.executableName); + fs.mkdirSync(path.dirname(bundled), { recursive: true }); + fs.writeFileSync(bundled, 'sentinel'); + const attempts: string[] = []; + const runtime: ServerResolverRuntime = { + probeCandidate: async (command, source, detail, _useShell, installationState = 'unmanaged') => { + attempts.push(source); + if (source === 'bundled') { + return { + message: `${detail} is not LSP compatible.`, + detail: '[missing_required_capability] hoverProvider' + }; + } + return { + command, + source, + detail, + installationState, + compatibilityResult: compatibleLspEvidence + }; + } + }; + const outputLines: string[] = []; + const context = { + extensionUri: vscode.Uri.file(path.join(root, 'extension')), + globalStorageUri: vscode.Uri.file(path.join(root, 'storage')), + extension: { packageJSON: { version: '0.10.0' } } + } as unknown as vscode.ExtensionContext; + try { + const result = await resolveServer(context, config(), { + appendLine: (line: string) => outputLines.push(line) + } as unknown as vscode.OutputChannel, runtime); + assert.ok('command' in result, JSON.stringify(result)); + assert.deepStrictEqual(attempts, ['bundled', 'path']); + assert.ok(outputLines.some((line) => line.includes('Skipping bundled server'))); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); + +function config(): RiprConfig { + return { + enabled: true, + serverPath: '', + serverArgs: ['lsp', '--stdio'], + autoDownload: false, + serverVersion: '0.10.0', + downloadBaseUrl: '', + checkMode: 'draft', + baseRef: 'origin/main', + includeUnchangedTests: true, + seamDiagnostics: true, + diagnosticProfile: 'actionable', + traceServer: 'off' + }; +} diff --git a/editors/vscode/test/suite/show_output_action.test.ts b/editors/vscode/test/suite/show_output_action.test.ts index 7ca288d94d8..58362e4eb7c 100644 --- a/editors/vscode/test/suite/show_output_action.test.ts +++ b/editors/vscode/test/suite/show_output_action.test.ts @@ -2,6 +2,7 @@ import * as assert from 'assert'; import * as vscode from 'vscode'; import { RiprClientController, RiprClientRuntime } from '../../src/client'; import { RiprConfig } from '../../src/config'; +import { compatibleLspEvidence } from './testCompatibility'; const enabledConfig: RiprConfig = { enabled: true, @@ -36,7 +37,7 @@ suite('Show Output Warning Action', () => { source: 'configured', detail: 'sentinel server', installationState: 'unmanaged', - compatibilityResult: 'not_established' + compatibilityResult: compatibleLspEvidence }), createLanguageClient: () => ({ onNotification: () => ({ dispose: () => undefined }), diff --git a/editors/vscode/test/suite/testCompatibility.ts b/editors/vscode/test/suite/testCompatibility.ts new file mode 100644 index 00000000000..e914fddec3e --- /dev/null +++ b/editors/vscode/test/suite/testCompatibility.ts @@ -0,0 +1,15 @@ +import { LspCompatibilityEvidence } from '../../src/lspCompatibility'; + +export const compatibleLspEvidence: LspCompatibilityEvidence = { + status: 'compatible', + positionEncoding: 'utf-16', + required: { textDocumentSync: true, hover: true, codeAction: true, positionEncoding: true }, + optional: { + pullDiagnostics: true, + codeActionResolve: true, + executeCommand: true, + workspaceFolders: true, + workDoneProgress: false + }, + processResult: 'clean_exit' +}; diff --git a/editors/vscode/test/suite/workspace_root_picker.test.ts b/editors/vscode/test/suite/workspace_root_picker.test.ts index ec35a26a0e2..0bc56e5ef47 100644 --- a/editors/vscode/test/suite/workspace_root_picker.test.ts +++ b/editors/vscode/test/suite/workspace_root_picker.test.ts @@ -18,6 +18,7 @@ import { workspaceRootPickItems } from '../../src/client'; import { RiprConfig } from '../../src/config'; +import { compatibleLspEvidence } from './testCompatibility'; const enabledConfig: RiprConfig = { enabled: true, @@ -93,7 +94,7 @@ function makeHarness(roots: string[], folders: vscode.WorkspaceFolder[]): FakeRu source: 'configured' as const, detail: 'sentinel multi-root server', installationState: 'unmanaged' as const, - compatibilityResult: 'not_established' as const + compatibilityResult: compatibleLspEvidence }; }, createLanguageClient: (serverOptions) => { diff --git a/editors/vscode/test/suite/workspace_trust_transition.test.ts b/editors/vscode/test/suite/workspace_trust_transition.test.ts index 42658e99cb6..f35df52c5e7 100644 --- a/editors/vscode/test/suite/workspace_trust_transition.test.ts +++ b/editors/vscode/test/suite/workspace_trust_transition.test.ts @@ -7,6 +7,7 @@ import { RiprClientRuntime } from '../../src/client'; import { RiprConfig } from '../../src/config'; +import { compatibleLspEvidence } from './testCompatibility'; import { resetLifecycleCoordinatorForTests, startAfterWorkspaceTrust, @@ -68,7 +69,7 @@ function trustedRuntime( source: 'configured', detail: 'sentinel server', installationState: 'unmanaged', - compatibilityResult: 'not_established' + compatibilityResult: compatibleLspEvidence }), createLanguageClient, createFileSystemWatcher: () => ({} as unknown as vscode.FileSystemWatcher), From befaf15a8e164716c8a16993da51eedead469dfb Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Wed, 12 Aug 2026 16:24:13 -0400 Subject: [PATCH 2/3] fix(vscode): harden compatibility admission --- .github/workflows/ci.yml | 5 - .ripr/traceability.toml | 6 ++ docs/specs/README.md | 2 +- ...R-SPEC-0129-editor-integration-contract.md | 29 +++++ editors/vscode/src/lspCompatibility.ts | 77 +++++++++++-- editors/vscode/src/serverResolver.ts | 18 ++-- .../test/suite/lsp_compatibility.test.ts | 66 ++++++++++-- .../vscode/test/suite/testCompatibility.ts | 11 +- policy/process_allowlist.txt | 4 +- xtask/src/main.rs | 101 +++++++++++++++++- 10 files changed, 282 insertions(+), 37 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae42ec6f86c..a6d41ac9063 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -215,10 +215,5 @@ jobs: - run: npm ci - run: npm run compile - run: npm run package - - name: Build local ripr server for e2e - working-directory: . - run: cargo build -p ripr - run: sudo apt-get update && sudo apt-get install -y xvfb - run: xvfb-run -a npm run test:e2e - env: - RIPR_TEST_SERVER_PATH: ${{ github.workspace }}/target/debug/ripr diff --git a/.ripr/traceability.toml b/.ripr/traceability.toml index 029fbe935c8..8b489a41c18 100644 --- a/.ripr/traceability.toml +++ b/.ripr/traceability.toml @@ -7491,6 +7491,9 @@ tests = [ "crates/ripr/src/lsp/tests.rs::hover_for_position_shows_snapshot_age_and_refresh_duration", "crates/ripr/src/lsp/tests.rs::hover_for_position_adds_snapshot_status_to_seam_hover", "crates/ripr/src/lsp/tests.rs::framed_lsp_saved_workspace_session_serves_saved_state_across_dirty_save", + "editors/vscode/test/suite/lsp_compatibility.test.ts", + "editors/vscode/test/suite/server_resolver_compatibility.test.ts", + "editors/vscode/test/suite/workspace_trust_runtime.test.ts", ] fixtures = [] code = [ @@ -7502,6 +7505,9 @@ code = [ "editors/vscode/package.json", "crates/ripr/src/lsp/client_features.rs", "crates/ripr/src/lsp/backend.rs", + "editors/vscode/src/lspCompatibility.ts", + "editors/vscode/src/serverResolver.ts", + "xtask/src/main.rs", ] outputs = [ "docs/specs/RIPR-SPEC-0129-editor-integration-contract.md", diff --git a/docs/specs/README.md b/docs/specs/README.md index f878e6edb2f..7daa32b9702 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -139,7 +139,7 @@ observable behavior. | [RIPR-SPEC-0126](RIPR-SPEC-0126-lsp-diagnostic-delivery-budget.md) | accepted | Pure deterministic finite LSP delivery budget over producer-owned canonical actionable items; explicit selected/omitted identities, byte limits, and overflow reasons | | [RIPR-SPEC-0127](RIPR-SPEC-0127-lsp-diagnostic-code-catalog.md) | accepted | Governed catalog of every emitted RIPR LSP diagnostic code (finding, seam, gap); single-source constructors, fail-closed gap emission, and resolution validation; byte-identical wire output for known kinds (#1662 slice A) | | [RIPR-SPEC-0128](RIPR-SPEC-0128-retired-active-goal-authority-audit.md) | deprecated | Reserved historical identifier for the removed active-goal-authority-audit framework (#1701) | -| [RIPR-SPEC-0129](RIPR-SPEC-0129-editor-integration-contract.md) | accepted | Three-layer editor integration contract (standard LSP, enhanced VS Code, headless riprAgent) and support matrix | +| [RIPR-SPEC-0129](RIPR-SPEC-0129-editor-integration-contract.md) | accepted | Three-layer editor integration contract, support matrix, and bounded VS Code pre-activation compatibility admission | | [RIPR-SPEC-0130](RIPR-SPEC-0130-ripr-authority-map.md) | proposed | RIPR source-of-truth authority map: canonical paths for every artifact category, plus a legacy-dialect conformance fixture | | [RIPR-SPEC-0131](RIPR-SPEC-0131-ripr-agent-protocol-contract.md) | proposed | Versioned, capability-only riprAgent protocol, DTO envelopes, closed vocabularies, schemas, and recovery rules | | [RIPR-SPEC-0132](RIPR-SPEC-0132-spec-v2-runtime-promotion.md) | proposed | First RIPR-SPEC v2 requirement and spec/governance runtime-promotion boundary | diff --git a/docs/specs/RIPR-SPEC-0129-editor-integration-contract.md b/docs/specs/RIPR-SPEC-0129-editor-integration-contract.md index 26c1d52670a..20e899f7bc5 100644 --- a/docs/specs/RIPR-SPEC-0129-editor-integration-contract.md +++ b/docs/specs/RIPR-SPEC-0129-editor-integration-contract.md @@ -105,6 +105,24 @@ Consumes everything in Layer 1, plus: - Managed server provisioning (#1624) - Workspace Trust enforcement (#1623) +Before activation, the trusted VS Code extension admits a resolved server only +after a bounded, standard JSON-RPC 2.0 `initialize` → `initialized` → +`shutdown` → `exit` exchange over LSP stdio. Admission requires the exact +surface the active client consumes: full saved-document synchronization, +UTF-16 positions, hover, code actions, pull diagnostics, workspace folders, +and the complete current server-executed `ripr.collect*`/refresh command set. +`codeAction/resolve` and work-done progress remain optional because their +absence has an existing client fallback. Missing or wrong JSON-RPC envelopes, +framing errors, timeouts, crashes, identity mismatch, and omitted required +capabilities fail closed so resolution can try the next allowed channel. + +The probe never runs for an untrusted workspace. Both the preceding version +probe and the LSP session own platform-correct process-tree cleanup: a fresh +POSIX process group or Windows tree termination, followed by reaping. The real +packaged proof stages the worktree-built server through the release archive +shape, extracts it, verifies digest identity, and probes that extracted member; +an arbitrary `RIPR_TEST_SERVER_PATH` is not packaged-identity evidence. + ### Layer 3 — Headless `riprAgent` A programmatic agent client (Codex, CI tooling) that drives the typed @@ -269,6 +287,14 @@ does not advertise fails the parity tests. the unsaved buffer as the current diagnostics authority. - `agent_protocol.rs` tests verify the fail-closed `supported_requests: []` invariant. +- `editors/vscode/test/suite/lsp_compatibility.test.ts` rejects invalid + framing/envelopes and each active-client capability omission, exercises + timeout/crash/shutdown cleanup, and admits the digest-verified server member + extracted from the test release archive. +- `editors/vscode/test/suite/server_resolver_compatibility.test.ts` proves an + incompatible candidate falls through to the next allowed channel; + `workspace_trust_runtime.test.ts` proves an untrusted activation performs + zero resolver or process work. ## Implementation Mapping @@ -286,6 +312,9 @@ does not advertise fails the parity tests. - `crates/ripr/src/lsp/client_features.rs` — negotiated `ClientFeatureProfile` consumed by the code-action command filter (#1776) - `editors/vscode/src/client.ts` — VS Code client capability advertisement +- `editors/vscode/src/lspCompatibility.ts` — bounded standard-LSP admission +- `editors/vscode/src/serverResolver.ts` — version/protocol sequencing and + fallback across allowed server channels - `editors/vscode/package.json` — `capabilities.untrustedWorkspaces` ## Metrics diff --git a/editors/vscode/src/lspCompatibility.ts b/editors/vscode/src/lspCompatibility.ts index e9c0c86b11d..227323f0477 100644 --- a/editors/vscode/src/lspCompatibility.ts +++ b/editors/vscode/src/lspCompatibility.ts @@ -3,8 +3,25 @@ import * as cp from 'child_process'; const DEFAULT_PROBE_TIMEOUT_MS = 5000; const MAX_MESSAGE_BYTES = 1024 * 1024; -export type RequiredLspCapability = 'textDocumentSync' | 'hover' | 'codeAction' | 'positionEncoding'; -export type OptionalLspCapability = 'pullDiagnostics' | 'codeActionResolve' | 'executeCommand' | 'workspaceFolders' | 'workDoneProgress'; +export type RequiredLspCapability = + | 'textDocumentSync' + | 'hover' + | 'codeAction' + | 'pullDiagnostics' + | 'executeCommand' + | 'workspaceFolders' + | 'positionEncoding'; +export type OptionalLspCapability = 'codeActionResolve' | 'workDoneProgress'; + +export const REQUIRED_SERVER_COMMANDS = [ + 'ripr.refresh', + 'ripr.collectContext', + 'ripr.collectEvidenceContext', + 'ripr.collectWorkspaceStatus', + 'ripr.collectRepairPacket', + 'ripr.collectTopLimitation', + 'ripr.collectReceiptStatus' +] as const; export interface LspCompatibilityEvidence { readonly status: 'compatible'; @@ -19,6 +36,7 @@ export interface LspCompatibilityEvidence { export type LspProbeFailureKind = | 'spawn_failure' | 'framing_failure' + | 'protocol_failure' | 'initialize_error' | 'initialize_timeout' | 'server_identity_mismatch' @@ -109,11 +127,19 @@ export async function probeStandardLspCompatibility( }); const onMessage = (message: JsonRpcMessage): void => { + if (message.jsonrpc !== '2.0') { + fail('protocol_failure', 'LSP response omitted the required JSON-RPC 2.0 envelope.'); + return; + } if (message.method && message.id !== undefined) { writeMessage(child, { jsonrpc: '2.0', id: message.id, result: null }); return; } if (phase === 'initialize' && message.id === 1) { + if (!hasResponsePayload(message)) { + fail('protocol_failure', 'Initialize response omitted both result and error.'); + return; + } if (message.error) { fail('initialize_error', message.error.message ?? `Initialize failed with code ${String(message.error.code)}.`); return; @@ -130,6 +156,10 @@ export async function probeStandardLspCompatibility( return; } if (phase === 'shutdown' && message.id === 2) { + if (!hasResponsePayload(message)) { + fail('protocol_failure', 'Shutdown response omitted both result and error.'); + return; + } if (message.error) { fail('shutdown_failure', message.error.message ?? 'The server rejected shutdown.'); return; @@ -209,9 +239,21 @@ function validateInitializeResult(result: unknown): Omit typeof command === 'string') + : []; + const missingCommands = REQUIRED_SERVER_COMMANDS.filter((command) => !commands.includes(command)); + if (missingCommands.length > 0) missing.push(`executeCommandProvider.commands (${missingCommands.join(', ')})`); + const workspace = isObject(capabilities.workspace) ? capabilities.workspace : undefined; + const workspaceFolders = workspace && isObject(workspace.workspaceFolders) ? workspace.workspaceFolders : undefined; + if (workspaceFolders?.supported !== true) missing.push('workspace.workspaceFolders.supported'); if (missing.length > 0) { return { status: 'incompatible', @@ -236,19 +278,22 @@ function validateInitializeResult(result: unknown): Omit { - return probeVersion(command, detail, useShell).then(async (versionResult) => { + return probeServerVersion(command, detail, useShell).then(async (versionResult) => { if ('message' in versionResult) { return versionResult; } @@ -216,22 +216,28 @@ function probeCandidate( }); } -function probeVersion( +export function probeServerVersion( command: string, detail: string, - useShell: boolean + useShell: boolean, + timeoutMs = START_TIMEOUT_MS ): Promise<{ readonly binaryVersion?: string } | ResolveFailure> { return new Promise((resolve) => { - const child = cp.spawn(command, ['--version'], { shell: useShell }); + // On POSIX the child leads a fresh process group so timeout cleanup can + // terminate descendants as one bounded unit. Windows uses taskkill /T. + const child = cp.spawn(command, ['--version'], { + shell: useShell, + detached: process.platform !== 'win32' + }); const stdoutChunks: Buffer[] = []; const stderrChunks: Buffer[] = []; const timer = setTimeout(() => { terminateProbeProcessTree(child); resolve({ message: `${detail} did not respond.`, - detail: `Timed out after ${START_TIMEOUT_MS}ms while running ${command} --version.` + detail: `Timed out after ${timeoutMs}ms while running ${command} --version.` }); - }, START_TIMEOUT_MS); + }, timeoutMs); child.stdout?.on('data', (chunk: Buffer) => stdoutChunks.push(chunk)); child.stderr?.on('data', (chunk: Buffer) => stderrChunks.push(chunk)); diff --git a/editors/vscode/test/suite/lsp_compatibility.test.ts b/editors/vscode/test/suite/lsp_compatibility.test.ts index 648d4e6968b..608d6d23b9a 100644 --- a/editors/vscode/test/suite/lsp_compatibility.test.ts +++ b/editors/vscode/test/suite/lsp_compatibility.test.ts @@ -1,8 +1,10 @@ import * as assert from 'assert'; +import * as crypto from 'crypto'; import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { probeStandardLspCompatibility } from '../../src/lspCompatibility'; +import { probeServerVersion } from '../../src/serverResolver'; suite('Standard LSP compatibility probe', () => { const temporaryRoots: string[] = []; @@ -14,11 +16,15 @@ suite('Standard LSP compatibility probe', () => { }); test('accepts the real packaged server through initialize and shutdown', async function () { - const server = process.env.RIPR_TEST_SERVER_PATH; + const server = process.env.RIPR_TEST_PACKAGED_SERVER_PATH; if (!server) { this.skip(); return; } + const expectedDigest = process.env.RIPR_TEST_PACKAGED_SERVER_SHA256; + assert.ok(expectedDigest, 'packaged server proof requires the archive extraction digest'); + const actualDigest = crypto.createHash('sha256').update(fs.readFileSync(server)).digest('hex'); + assert.strictEqual(actualDigest, expectedDigest, 'the probed executable must be the extracted archive member'); const result = await probeStandardLspCompatibility(server, false, 10_000); assert.strictEqual(result.status, 'compatible', JSON.stringify(result)); if (result.status === 'compatible') { @@ -35,7 +41,7 @@ suite('Standard LSP compatibility probe', () => { assert.ok(result.status === 'incompatible' && ['framing_failure', 'process_failure'].includes(result.kind)); }); - test('requires the exercised baseline but records optional omissions', async () => { + test('requires the exercised baseline but records genuinely optional omissions', async () => { const missing = fakeServer('missing-hover'); const rejected = await probeStandardLspCompatibility(missing.command, missing.useShell, 1000); assert.deepStrictEqual( @@ -43,20 +49,56 @@ suite('Standard LSP compatibility probe', () => { 'missing_required_capability' ); - const optional = fakeServer('optional-omitted'); + const optional = fakeServer('valid'); const accepted = await probeStandardLspCompatibility(optional.command, optional.useShell, 1000); assert.strictEqual(accepted.status, 'compatible', JSON.stringify(accepted)); if (accepted.status === 'compatible') { assert.deepStrictEqual(accepted.optional, { - pullDiagnostics: false, codeActionResolve: false, - executeCommand: false, - workspaceFolders: false, workDoneProgress: false }); } }); + for (const mode of ['missing-diagnostics', 'missing-workspace-folders', 'missing-command'] as const) { + test(`rejects the active-client baseline omission ${mode}`, async () => { + const fake = fakeServer(mode); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + assert.strictEqual(result.status, 'incompatible'); + assert.deepStrictEqual(result.status === 'incompatible' ? result.kind : undefined, 'missing_required_capability'); + }); + } + + for (const mode of ['missing-jsonrpc', 'wrong-jsonrpc', 'missing-response-payload'] as const) { + test(`rejects the invalid JSON-RPC envelope ${mode}`, async () => { + const fake = fakeServer(mode); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + assert.strictEqual(result.status, 'incompatible'); + assert.deepStrictEqual(result.status === 'incompatible' ? result.kind : undefined, 'protocol_failure'); + }); + } + + test('POSIX version timeout terminates the spawned process group', async function () { + if (process.platform === 'win32') { + this.skip(); + return; + } + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ripr-version-tree-')); + temporaryRoots.push(root); + const pidPath = path.join(root, 'descendant.pid'); + const script = path.join(root, 'ripr'); + fs.writeFileSync( + script, + `#!/bin/sh\n(sleep 30) &\necho $! > "${pidPath}"\nwait\n`, + { mode: 0o755 } + ); + const result = await probeServerVersion(script, 'fixture', false, 300); + assert.ok('message' in result && result.message.includes('did not respond')); + const descendantPid = Number(fs.readFileSync(pidPath, 'utf8').trim()); + await new Promise((resolve) => setTimeout(resolve, 100)); + assert.throws(() => process.kill(descendantPid, 0), (error: NodeJS.ErrnoException) => error.code === 'ESRCH'); + }); + test('rejects a server that selects a non-UTF-16 position encoding', async () => { const fake = fakeServer('utf8'); const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); @@ -148,10 +190,16 @@ function consume() { const length = Number(match[1]); const start = end + 4; if (input.length < start + length) return; const message = JSON.parse(input.subarray(start, start + length).toString()); input = input.subarray(start + length); if (message.method === 'initialize') { - const capabilities = { textDocumentSync: 1, hoverProvider: true, codeActionProvider: true, positionEncoding: mode === 'utf8' ? 'utf-8' : 'utf-16' }; + const commands = ['ripr.refresh','ripr.collectContext','ripr.collectEvidenceContext','ripr.collectWorkspaceStatus','ripr.collectRepairPacket','ripr.collectTopLimitation','ripr.collectReceiptStatus']; + const capabilities = { textDocumentSync: 1, hoverProvider: true, codeActionProvider: true, diagnosticProvider: {}, executeCommandProvider: { commands }, workspace: { workspaceFolders: { supported: true } }, positionEncoding: mode === 'utf8' ? 'utf-8' : 'utf-16' }; if (mode === 'missing-hover') delete capabilities.hoverProvider; - if (mode === 'valid') Object.assign(capabilities, { diagnosticProvider: {}, executeCommandProvider: { commands: [] }, workspace: { workspaceFolders: { supported: true } }, workDoneProgress: true, codeActionProvider: { resolveProvider: true } }); - send({ jsonrpc: '2.0', id: message.id, result: { capabilities, serverInfo: { name: mode === 'wrong-identity' ? 'other' : 'ripr', version: '9.9.9' } } }); + if (mode === 'missing-diagnostics') delete capabilities.diagnosticProvider; + if (mode === 'missing-workspace-folders') delete capabilities.workspace; + if (mode === 'missing-command') capabilities.executeCommandProvider.commands.pop(); + const envelope = { jsonrpc: mode === 'wrong-jsonrpc' ? '1.0' : '2.0', id: message.id, result: { capabilities, serverInfo: { name: mode === 'wrong-identity' ? 'other' : 'ripr', version: '9.9.9' } } }; + if (mode === 'missing-jsonrpc') delete envelope.jsonrpc; + if (mode === 'missing-response-payload') delete envelope.result; + send(envelope); } else if (message.method === 'shutdown') { if (mode === 'shutdown-failure') send({ jsonrpc: '2.0', id: message.id, error: { code: -1, message: 'no' } }); else send({ jsonrpc: '2.0', id: message.id, result: null }); diff --git a/editors/vscode/test/suite/testCompatibility.ts b/editors/vscode/test/suite/testCompatibility.ts index e914fddec3e..af103211372 100644 --- a/editors/vscode/test/suite/testCompatibility.ts +++ b/editors/vscode/test/suite/testCompatibility.ts @@ -3,12 +3,17 @@ import { LspCompatibilityEvidence } from '../../src/lspCompatibility'; export const compatibleLspEvidence: LspCompatibilityEvidence = { status: 'compatible', positionEncoding: 'utf-16', - required: { textDocumentSync: true, hover: true, codeAction: true, positionEncoding: true }, - optional: { + required: { + textDocumentSync: true, + hover: true, + codeAction: true, pullDiagnostics: true, - codeActionResolve: true, executeCommand: true, workspaceFolders: true, + positionEncoding: true + }, + optional: { + codeActionResolve: true, workDoneProgress: false }, processResult: 'clean_exit' diff --git a/policy/process_allowlist.txt b/policy/process_allowlist.txt index 99cb955ea0c..1bd143c3844 100644 --- a/policy/process_allowlist.txt +++ b/policy/process_allowlist.txt @@ -39,8 +39,10 @@ editors/vscode/src/client.ts|child_process|1|lsp/editor|VS Code client invokes r editors/vscode/src/client.ts|cp.execFile|1|lsp/editor|VS Code client invokes ripr context without shell expansion. editors/vscode/src/downloader.ts|child_process|1|lsp/editor|Downloader extracts archives with platform tools. editors/vscode/src/downloader.ts|cp.execFile|2|lsp/editor|Downloader invokes tar or PowerShell for archive extraction and probes the staged ripr executable before cache admission, without shell expansion. +editors/vscode/src/lspCompatibility.ts|child_process|1|lsp/editor|#1745 / RIPR-SPEC-0129: pre-activation compatibility proof spawns only the resolved ripr candidate for a bounded initialize/shutdown session and uses platform process-tree cleanup on deadline. +editors/vscode/src/lspCompatibility.ts|cp.spawn|2|lsp/editor|#1745 / RIPR-SPEC-0129: one bounded ripr LSP spawn plus the explicit Windows taskkill tree adapter; no user-supplied protocol command or shell expansion. editors/vscode/src/serverResolver.ts|child_process|1|lsp/editor|Server resolver probes candidate ripr binaries. -editors/vscode/src/serverResolver.ts|cp.spawn|1|lsp/editor|Server resolver runs ripr --version without shell expansion. +editors/vscode/src/serverResolver.ts|cp.spawn|1|lsp/editor|#1745 / RIPR-SPEC-0129: server resolver runs the bounded ripr --version preflight in a dedicated POSIX process group (or Windows tree) so timeout cleanup includes descendants. editors/vscode/test/runTest.ts|child_process|1|vscode-packaged-integration|#2528: packaged Electron proof creates an isolated external Git fixture and launches the opt-in trust-boundary host through bounded child-process calls; no shell expansion. xtask/src/main.rs|Command::new|1|gate-runner|#2343: diff-aware gate runner reads changed files via git diff xtask/src/reports/release_scope.rs|Command::new|2|release-scope|RIPR-SPEC-0145: candidate-only scope reconciliation invokes bounded git probes for current ref, commit, path, and preserved-path verification; no arbitrary command execution. diff --git a/xtask/src/main.rs b/xtask/src/main.rs index dd78be5e2ce..0e9603fc080 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -245,9 +245,10 @@ use repo_readiness::{ }; #[cfg(test)] pub(crate) use reports::release_server::{ - ReleaseServerAsset, create_zip_archive, normalize_release_version, release_server_archive, - release_server_assets, release_server_manifest, release_server_readme, required_release_arg, + ReleaseServerAsset, normalize_release_version, release_server_archive, release_server_assets, + release_server_manifest, release_server_readme, required_release_arg, }; +use reports::release_server::{create_zip_archive, sha256_file}; #[cfg(test)] pub(crate) use reports::{ BADGE_ENDPOINT_FILES, BadgeArtifactJob, BadgeBasisReport, BadgeBasisSignal, @@ -983,6 +984,11 @@ fn vscode_test_e2e() -> Result<(), String> { if build_server { run("cargo", &["build", "-p", "ripr"])?; } + let packaged_server = if build_server { + Some(stage_vscode_test_server_archive(&server_path)?) + } else { + None + }; vscode_compile()?; let workspace_path = vscode_test_workspace_path()?; let mut envs = vec![( @@ -990,14 +996,103 @@ fn vscode_test_e2e() -> Result<(), String> { path_to_utf8(&workspace_path, "VS Code test workspace path")?, )]; if provided_server.is_none() { + let packaged = packaged_server.as_ref().ok_or_else(|| { + "default VS Code test server was not staged through the release archive shape" + .to_string() + })?; envs.push(( "RIPR_TEST_SERVER_PATH", - path_to_utf8(&server_path, "VS Code test server path")?, + path_to_utf8(&packaged.executable, "packaged VS Code test server path")?, + )); + envs.push(( + "RIPR_TEST_PACKAGED_SERVER_PATH", + path_to_utf8(&packaged.executable, "packaged VS Code identity path")?, )); + envs.push(("RIPR_TEST_PACKAGED_SERVER_SHA256", packaged.sha256.as_str())); } run_cwd_command_with_envs(&vscode_test_e2e_command(), &envs) } +struct PackagedVscodeTestServer { + executable: PathBuf, + sha256: String, +} + +fn stage_vscode_test_server_archive( + server_path: &Path, +) -> Result { + let root = std::env::current_dir() + .map_err(|err| { + format!("failed to resolve repository root for VS Code server proof: {err}") + })? + .join("target") + .join("ripr") + .join("vscode-server-archive"); + let package = root.join("package"); + let extracted = root.join("extracted"); + let archive = root.join("ripr-server-test.zip"); + if root.exists() { + fs::remove_dir_all(&root) + .map_err(|err| format!("failed to reset {}: {err}", root.display()))?; + } + fs::create_dir_all(&package) + .map_err(|err| format!("failed to create {}: {err}", package.display()))?; + let executable_name = server_path.file_name().ok_or_else(|| { + format!( + "VS Code test server path has no file name: {}", + server_path.display() + ) + })?; + fs::copy(server_path, package.join(executable_name)).map_err(|err| { + format!( + "failed to stage {} for archive proof: {err}", + server_path.display() + ) + })?; + create_zip_archive(&package, &archive)?; + fs::create_dir_all(&extracted) + .map_err(|err| format!("failed to create {}: {err}", extracted.display()))?; + let archive_file = fs::File::open(&archive) + .map_err(|err| format!("failed to open {}: {err}", archive.display()))?; + let mut zip = zip::ZipArchive::new(archive_file) + .map_err(|err| format!("failed to read {}: {err}", archive.display()))?; + if zip.len() != 1 { + return Err(format!( + "VS Code server proof archive contained {} entries, expected 1", + zip.len() + )); + } + let mut member = zip + .by_index(0) + .map_err(|err| format!("failed to read archive member: {err}"))?; + if Path::new(member.name()).file_name() != Some(executable_name) { + return Err(format!( + "VS Code server proof archive member `{}` did not match the built executable", + member.name() + )); + } + let executable = extracted.join(executable_name); + let mut output = fs::File::create(&executable) + .map_err(|err| format!("failed to create {}: {err}", executable.display()))?; + std::io::copy(&mut member, &mut output) + .map_err(|err| format!("failed to extract {}: {err}", executable.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&executable, fs::Permissions::from_mode(0o755)) + .map_err(|err| format!("failed to mark {} executable: {err}", executable.display()))?; + } + let built_sha = sha256_file(server_path)?; + let extracted_sha = sha256_file(&executable)?; + if built_sha != extracted_sha { + return Err("VS Code server archive extraction changed the executable digest".to_string()); + } + Ok(PackagedVscodeTestServer { + executable, + sha256: extracted_sha, + }) +} + fn select_vscode_test_server( provided: Option<&Path>, built: &Path, From 80e16eeb476a06cd1af6168d81d23caf58a5b0b0 Mon Sep 17 00:00:00 2001 From: Steven Zimmerman Date: Wed, 12 Aug 2026 17:52:44 -0400 Subject: [PATCH 3/3] fix(vscode): close compatibility probe gaps --- docs/SERVER_PROVISIONING.md | 24 +- ...R-SPEC-0129-editor-integration-contract.md | 19 +- editors/vscode/src/lspCompatibility.ts | 321 ++++++++++++++++-- editors/vscode/src/serverResolver.ts | 41 ++- .../test/suite/lsp_compatibility.test.ts | 145 +++++++- policy/process_allowlist.txt | 8 +- 6 files changed, 482 insertions(+), 76 deletions(-) diff --git a/docs/SERVER_PROVISIONING.md b/docs/SERVER_PROVISIONING.md index ace8bb62cd0..7c19aa1eaca 100644 --- a/docs/SERVER_PROVISIONING.md +++ b/docs/SERVER_PROVISIONING.md @@ -23,14 +23,22 @@ PATH fallback remains useful for local development and offline installs. Before activation commits to any candidate, the extension first checks `ripr --version`, then runs a bounded standard-LSP compatibility session over `ripr lsp --stdio`: framed `initialize`, `initialized`, `shutdown`, and `exit`. -The initialize result must identify a versioned `ripr` server, select UTF-16, -and advertise the synchronization, hover, and code-action surface exercised by -the extension. Pull diagnostics, code-action resolve, execute commands, workspace -folders, and work-done progress are retained as typed optional evidence; their -absence does not inflate or reject the standard baseline. A failed probe never -becomes the active client, and resolver fallback continues only along the -existing order above. Workspace Trust remains outside and above resolution, so -an untrusted workspace spawns neither this probe nor the active server. +Each response must use JSON-RPC 2.0, the active request id, and exactly one of a +structurally valid `result` or `error`. Initialize must identify a versioned +`ripr` server, select UTF-16, and advertise full saved synchronization, hover, +code actions, pull diagnostics, workspace folders, and the complete command set +the extension executes. Only code-action resolve and work-done progress remain +typed optional evidence because the client has fallbacks for their absence. +Shutdown succeeds only with a `null` result. A failed probe never becomes the +active client, and resolver fallback continues only along the existing order +above. Workspace Trust remains outside and above resolution, so an untrusted +workspace spawns neither this probe nor the active server. + +Every terminal path after spawn owns process-tree cleanup, including a direct +child that exits successfully or unsuccessfully before cleanup runs. POSIX +probes lead a dedicated process group. Windows probes run inside a kill-on-close +Job Object whose owner relays raw stdio, so descendants cannot escape merely +because the direct process exits before `taskkill /T` can address its PID. This compatibility evidence is activation state, separate from the completed install receipt and its byte-integrity evidence. It does not attest producer diff --git a/docs/specs/RIPR-SPEC-0129-editor-integration-contract.md b/docs/specs/RIPR-SPEC-0129-editor-integration-contract.md index 20e899f7bc5..8da8eb52d88 100644 --- a/docs/specs/RIPR-SPEC-0129-editor-integration-contract.md +++ b/docs/specs/RIPR-SPEC-0129-editor-integration-contract.md @@ -112,13 +112,18 @@ surface the active client consumes: full saved-document synchronization, UTF-16 positions, hover, code actions, pull diagnostics, workspace folders, and the complete current server-executed `ripr.collect*`/refresh command set. `codeAction/resolve` and work-done progress remain optional because their -absence has an existing client fallback. Missing or wrong JSON-RPC envelopes, +absence has an existing client fallback. A response must carry JSON-RPC 2.0, +the active request id, no method, and exactly one of `result` or a structurally +valid error; initialize must carry its required result structure and shutdown +must return `result: null`. Missing, dual, malformed, or wrong envelopes, framing errors, timeouts, crashes, identity mismatch, and omitted required capabilities fail closed so resolution can try the next allowed channel. The probe never runs for an untrusted workspace. Both the preceding version -probe and the LSP session own platform-correct process-tree cleanup: a fresh -POSIX process group or Windows tree termination, followed by reaping. The real +probe and the LSP session own unconditional, idempotent process-tree cleanup on +every terminal path, even after the direct child exits first. POSIX uses a +fresh process group; Windows uses a kill-on-close Job Object with raw stdio +relay plus an explicit tree-kill fallback. The real packaged proof stages the worktree-built server through the release archive shape, extracts it, verifies digest identity, and probes that extracted member; an arbitrary `RIPR_TEST_SERVER_PATH` is not packaged-identity evidence. @@ -288,9 +293,11 @@ does not advertise fails the parity tests. - `agent_protocol.rs` tests verify the fail-closed `supported_requests: []` invariant. - `editors/vscode/test/suite/lsp_compatibility.test.ts` rejects invalid - framing/envelopes and each active-client capability omission, exercises - timeout/crash/shutdown cleanup, and admits the digest-verified server member - extracted from the test release archive. + framing, dual result/error payloads, malformed errors, wrong ids, non-null + shutdown results, and each active-client capability omission. It asserts + descendant death after version success/failure and LSP timeout, crash, + protocol failure, and normal shutdown, and admits the digest-verified server + member extracted from the test release archive. - `editors/vscode/test/suite/server_resolver_compatibility.test.ts` proves an incompatible candidate falls through to the next allowed channel; `workspace_trust_runtime.test.ts` proves an untrusted activation performs diff --git a/editors/vscode/src/lspCompatibility.ts b/editors/vscode/src/lspCompatibility.ts index 227323f0477..9f7b2639b4d 100644 --- a/editors/vscode/src/lspCompatibility.ts +++ b/editors/vscode/src/lspCompatibility.ts @@ -1,7 +1,10 @@ import * as cp from 'child_process'; +import * as crypto from 'crypto'; const DEFAULT_PROBE_TIMEOUT_MS = 5000; const MAX_MESSAGE_BYTES = 1024 * 1024; +const PROBE_EXIT_CODE_MARKER = '__RIPR_PROBE_EXIT_CODE__'; +const probeExitCodes = new WeakMap(); export type RequiredLspCapability = | 'textDocumentSync' @@ -58,9 +61,174 @@ interface JsonRpcMessage { readonly id?: number | string | null; readonly method?: string; readonly result?: unknown; - readonly error?: { readonly code?: number; readonly message?: string }; + readonly error?: unknown; } +interface JsonRpcError { + readonly code: number; + readonly message: string; +} + +const WINDOWS_PROBE_JOB_WRAPPER = String.raw` +$ErrorActionPreference = 'Stop' +Add-Type -TypeDefinition @' +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; + +public static class RiprProbeJob { + [StructLayout(LayoutKind.Sequential)] + private struct JOBOBJECT_BASIC_LIMIT_INFORMATION { + public long PerProcessUserTimeLimit; + public long PerJobUserTimeLimit; + public uint LimitFlags; + public UIntPtr MinimumWorkingSetSize; + public UIntPtr MaximumWorkingSetSize; + public uint ActiveProcessLimit; + public UIntPtr Affinity; + public uint PriorityClass; + public uint SchedulingClass; + } + + [StructLayout(LayoutKind.Sequential)] + private struct IO_COUNTERS { + public ulong ReadOperationCount; + public ulong WriteOperationCount; + public ulong OtherOperationCount; + public ulong ReadTransferCount; + public ulong WriteTransferCount; + public ulong OtherTransferCount; + } + + [StructLayout(LayoutKind.Sequential)] + private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION { + public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; + public IO_COUNTERS IoInfo; + public UIntPtr ProcessMemoryLimit; + public UIntPtr JobMemoryLimit; + public UIntPtr PeakProcessMemoryUsed; + public UIntPtr PeakJobMemoryUsed; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr CreateJobObject(IntPtr attributes, string name); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool SetInformationJobObject( + IntPtr job, + int informationClass, + ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION information, + uint informationLength); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); + + [DllImport("kernel32.dll")] + private static extern bool CloseHandle(IntPtr handle); + + public static IntPtr CreateAndAssignCurrentProcess() { + IntPtr job = CreateJobObject(IntPtr.Zero, null); + if (job == IntPtr.Zero) { + throw new Win32Exception(Marshal.GetLastWin32Error(), "CreateJobObject failed"); + } + var information = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION(); + information.BasicLimitInformation.LimitFlags = 0x00002000; + if (!SetInformationJobObject(job, 9, ref information, (uint)Marshal.SizeOf(information))) { + int error = Marshal.GetLastWin32Error(); + CloseHandle(job); + throw new Win32Exception(error, "SetInformationJobObject failed"); + } + if (!AssignProcessToJobObject(job, Process.GetCurrentProcess().Handle)) { + int error = Marshal.GetLastWin32Error(); + CloseHandle(job); + throw new Win32Exception(error, "AssignProcessToJobObject failed"); + } + return job; + } + + public static void Close(IntPtr job) { + if (job != IntPtr.Zero) { + CloseHandle(job); + } + } + + public static int Run(string command, string arguments, bool useShell) { + IntPtr job = CreateAndAssignCurrentProcess(); + try { + var start = new ProcessStartInfo { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + if (useShell) { + start.FileName = Environment.GetEnvironmentVariable("ComSpec") ?? "cmd.exe"; + start.Arguments = "/d /s /c \"\"" + command.Replace("\"", "\"\"") + "\" " + arguments + "\""; + } else { + start.FileName = command; + start.Arguments = arguments; + } + string exitNonce = Environment.GetEnvironmentVariable("RIPR_PROBE_EXIT_NONCE") ?? ""; + start.EnvironmentVariables.Remove("RIPR_PROBE_EXIT_NONCE"); + using (var process = new Process { StartInfo = start }) { + if (!process.Start()) { + throw new InvalidOperationException("Probe process did not start."); + } + var input = StartPump(Console.OpenStandardInput(), process.StandardInput.BaseStream, true); + var output = StartPump(process.StandardOutput.BaseStream, Console.OpenStandardOutput(), false); + var error = StartPump(process.StandardError.BaseStream, Console.OpenStandardError(), false); + process.WaitForExit(); + int exitCode = process.ExitCode; + Console.Error.WriteLine("__RIPR_PROBE_EXIT_CODE__" + exitNonce + "=" + exitCode); + Console.Error.Flush(); + Close(job); + job = IntPtr.Zero; + try { process.StandardInput.Close(); } catch {} + output.Join(1000); + error.Join(1000); + return exitCode; + } + } finally { + Close(job); + } + } + + private static Thread StartPump(System.IO.Stream source, System.IO.Stream destination, bool closeDestination) { + var thread = new Thread(() => { + try { + var buffer = new byte[8192]; + int count; + while ((count = source.Read(buffer, 0, buffer.Length)) > 0) { + destination.Write(buffer, 0, count); + destination.Flush(); + } + } catch (IOException) { + // The owner closes pipes during bounded process-tree cleanup. + } catch (ObjectDisposedException) { + // The owner closes pipes during bounded process-tree cleanup. + } finally { + if (closeDestination) { + try { destination.Close(); } catch {} + } + } + }); + thread.IsBackground = true; + thread.Start(); + return thread; + } +} +'@ | Out-Null + +[Environment]::Exit([RiprProbeJob]::Run( + $env:RIPR_PROBE_COMMAND, + $env:RIPR_PROBE_ARGUMENTS, + $env:RIPR_PROBE_USE_SHELL -eq '1')) +`; + export async function probeStandardLspCompatibility( command: string, useShell = false, @@ -71,21 +239,15 @@ export async function probeStandardLspCompatibility( let phase: 'initialize' | 'shutdown' | 'exit' = 'initialize'; let evidence: Omit | undefined; let stdout: Buffer = Buffer.alloc(0); - const child = cp.spawn(command, ['lsp', '--stdio'], { - shell: useShell, - detached: process.platform !== 'win32', - stdio: ['pipe', 'pipe', 'pipe'] - }); + const child = spawnProbeProcess(command, ['lsp', '--stdio'], useShell); - const finish = (result: LspCompatibilityResult, kill = true): void => { + const finish = (result: LspCompatibilityResult): void => { if (settled) { return; } settled = true; clearTimeout(timer); - if (kill && child.exitCode === null && child.signalCode === null) { - terminateProbeProcessTree(child); - } + terminateProbeProcessTree(child); resolve(result); }; @@ -100,12 +262,13 @@ export async function probeStandardLspCompatibility( child.once('error', (error) => fail('spawn_failure', error.message)); child.stdin?.once('error', (error) => fail('process_failure', `LSP probe stdin failed: ${error.message}`)); - child.once('exit', (code, signal) => { + child.once('exit', (wrapperCode, signal) => { + const code = probeProcessExitCode(child, wrapperCode); if (settled) { return; } if (phase === 'exit' && code === 0 && evidence) { - finish({ ...evidence, processResult: 'clean_exit' }, false); + finish({ ...evidence, processResult: 'clean_exit' }); return; } fail( @@ -135,16 +298,22 @@ export async function probeStandardLspCompatibility( writeMessage(child, { jsonrpc: '2.0', id: message.id, result: null }); return; } + const expectedResponseId = phase === 'initialize' ? 1 : phase === 'shutdown' ? 2 : undefined; + if (hasResponseMember(message) && message.id !== expectedResponseId) { + fail('protocol_failure', `LSP response used unexpected id ${String(message.id)} during ${phase}.`); + return; + } if (phase === 'initialize' && message.id === 1) { - if (!hasResponsePayload(message)) { - fail('protocol_failure', 'Initialize response omitted both result and error.'); + const response = validateJsonRpcResponse(message); + if (response.status === 'invalid') { + fail('protocol_failure', `Initialize response ${response.detail}`); return; } - if (message.error) { - fail('initialize_error', message.error.message ?? `Initialize failed with code ${String(message.error.code)}.`); + if (response.status === 'error') { + fail('initialize_error', response.error.message || `Initialize failed with code ${String(response.error.code)}.`); return; } - const checked = validateInitializeResult(message.result); + const checked = validateInitializeResult(response.result); if (checked.status === 'incompatible') { finish(checked); return; @@ -156,12 +325,17 @@ export async function probeStandardLspCompatibility( return; } if (phase === 'shutdown' && message.id === 2) { - if (!hasResponsePayload(message)) { - fail('protocol_failure', 'Shutdown response omitted both result and error.'); + const response = validateJsonRpcResponse(message); + if (response.status === 'invalid') { + fail('protocol_failure', `Shutdown response ${response.detail}`); return; } - if (message.error) { - fail('shutdown_failure', message.error.message ?? 'The server rejected shutdown.'); + if (response.status === 'error') { + fail('shutdown_failure', response.error.message || 'The server rejected shutdown.'); + return; + } + if (response.result !== null) { + fail('protocol_failure', 'Shutdown response result must be null.'); return; } phase = 'exit'; @@ -311,8 +485,37 @@ function supportedTextDocumentSync(value: unknown): boolean { return value.save === true || (isObject(value.save) && value.save.includeText !== false); } -function hasResponsePayload(message: JsonRpcMessage): boolean { - return Object.prototype.hasOwnProperty.call(message, 'result') || Object.prototype.hasOwnProperty.call(message, 'error'); +type CheckedJsonRpcResponse = + | { readonly status: 'result'; readonly result: unknown } + | { readonly status: 'error'; readonly error: JsonRpcError } + | { readonly status: 'invalid'; readonly detail: string }; + +function validateJsonRpcResponse(message: JsonRpcMessage): CheckedJsonRpcResponse { + if (message.method !== undefined) { + return { status: 'invalid', detail: 'must not include a method member.' }; + } + const hasResult = Object.prototype.hasOwnProperty.call(message, 'result'); + const hasError = Object.prototype.hasOwnProperty.call(message, 'error'); + if (hasResult === hasError) { + return { status: 'invalid', detail: 'must include exactly one of result or error.' }; + } + if (hasResult) { + return { status: 'result', result: message.result }; + } + if (!isObject(message.error) || !Number.isInteger(message.error.code) || typeof message.error.message !== 'string') { + return { status: 'invalid', detail: 'included a malformed error object.' }; + } + return { + status: 'error', + error: { code: message.error.code as number, message: message.error.message } + }; +} + +function hasResponseMember(message: JsonRpcMessage): boolean { + return ( + Object.prototype.hasOwnProperty.call(message, 'result') || + Object.prototype.hasOwnProperty.call(message, 'error') + ); } function providerEnabled(value: unknown): boolean { @@ -328,10 +531,15 @@ function writeMessage(child: cp.ChildProcess, message: object): void { export function terminateProbeProcessTree(child: cp.ChildProcess): void { child.stdin?.destroy(); if (child.pid && process.platform === 'win32') { - cp.spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { - stdio: 'ignore', - windowsHide: true - }); + // The wrapper's kill-on-close Job Object already owns descendants after + // wrapper exit. Address taskkill only to a still-current wrapper PID; + // using an exited PID would introduce a replacement-process deletion race. + if (child.exitCode === null && child.signalCode === null) { + cp.spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { + stdio: 'ignore', + windowsHide: true + }); + } return; } if (child.pid) { @@ -345,6 +553,65 @@ export function terminateProbeProcessTree(child: cp.ChildProcess): void { child.kill('SIGKILL'); } +export function spawnProbeProcess( + command: string, + args: readonly string[], + useShell: boolean +): cp.ChildProcessWithoutNullStreams { + if (process.platform === 'win32') { + const encodedWrapper = Buffer.from(WINDOWS_PROBE_JOB_WRAPPER, 'utf16le').toString('base64'); + const exitNonce = crypto.randomBytes(16).toString('hex'); + const child = cp.spawn( + 'powershell.exe', + [ + '-NoProfile', + '-NonInteractive', + '-InputFormat', + 'Text', + '-OutputFormat', + 'Text', + '-ExecutionPolicy', + 'Bypass', + '-EncodedCommand', + encodedWrapper + ], + { + shell: false, + windowsHide: true, + stdio: ['pipe', 'pipe', 'pipe'], + env: { + ...process.env, + RIPR_PROBE_COMMAND: command, + RIPR_PROBE_ARGUMENTS: args.join(' '), + RIPR_PROBE_EXIT_NONCE: exitNonce, + RIPR_PROBE_USE_SHELL: useShell ? '1' : '0' + } + } + ); + let stderr = ''; + child.stderr.on('data', (chunk: Buffer) => { + stderr += chunk.toString('utf8'); + const match = new RegExp(`${PROBE_EXIT_CODE_MARKER}${exitNonce}=(-?\\d+)`).exec(stderr); + if (match) { + probeExitCodes.set(child, Number(match[1])); + } + if (stderr.length > 4096) { + stderr = stderr.slice(-4096); + } + }); + return child; + } + return cp.spawn(command, args, { + shell: useShell, + detached: true, + stdio: ['pipe', 'pipe', 'pipe'] + }); +} + +export function probeProcessExitCode(child: cp.ChildProcess, wrapperCode: number | null): number | null { + return probeExitCodes.get(child) ?? wrapperCode; +} + function isObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } diff --git a/editors/vscode/src/serverResolver.ts b/editors/vscode/src/serverResolver.ts index 5bb5ea684c1..b9556581184 100644 --- a/editors/vscode/src/serverResolver.ts +++ b/editors/vscode/src/serverResolver.ts @@ -1,4 +1,3 @@ -import * as cp from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; @@ -13,11 +12,13 @@ import { currentRiprPlatform, RiprPlatform } from './platform'; import { LspCompatibilityEvidence, LspCompatibilityFailure, + probeProcessExitCode, probeStandardLspCompatibility, + spawnProbeProcess, terminateProbeProcessTree } from './lspCompatibility'; -const START_TIMEOUT_MS = 5000; +const START_TIMEOUT_MS = 10_000; export type ServerSource = 'configured' | 'bundled' | 'managed_cache' | 'managed_download' | 'path'; @@ -225,15 +226,21 @@ export function probeServerVersion( return new Promise((resolve) => { // On POSIX the child leads a fresh process group so timeout cleanup can // terminate descendants as one bounded unit. Windows uses taskkill /T. - const child = cp.spawn(command, ['--version'], { - shell: useShell, - detached: process.platform !== 'win32' - }); + const child = spawnProbeProcess(command, ['--version'], useShell); const stdoutChunks: Buffer[] = []; const stderrChunks: Buffer[] = []; - const timer = setTimeout(() => { + let settled = false; + const finish = (result: { readonly binaryVersion?: string } | ResolveFailure): void => { + if (settled) { + return; + } + settled = true; + clearTimeout(timer); terminateProbeProcessTree(child); - resolve({ + resolve(result); + }; + const timer = setTimeout(() => { + finish({ message: `${detail} did not respond.`, detail: `Timed out after ${timeoutMs}ms while running ${command} --version.` }); @@ -243,18 +250,17 @@ export function probeServerVersion( child.stderr?.on('data', (chunk: Buffer) => stderrChunks.push(chunk)); child.once('error', (error) => { - clearTimeout(timer); - resolve({ message: `${detail} could not start.`, detail: error.message }); + finish({ message: `${detail} could not start.`, detail: error.message }); }); - child.once('exit', (code) => { - clearTimeout(timer); + child.once('exit', (wrapperCode) => { + const code = probeProcessExitCode(child, wrapperCode); if (code === 0) { - resolve({ + finish({ binaryVersion: firstOutputLine(stdoutChunks, stderrChunks) }); } else { - resolve({ message: `${detail} failed version check.`, detail: `${command} --version exited with code ${code}.` }); + finish({ message: `${detail} failed version check.`, detail: `${command} --version exited with code ${code}.` }); } }); }); @@ -283,5 +289,10 @@ function firstOutputLine(stdoutChunks: Buffer[], stderrChunks: Buffer[]): string return output .split(/\r?\n/) .map((line) => line.trim()) - .find((line) => line.length > 0); + .find( + (line) => + line.length > 0 && + line !== '#< CLIXML' && + !line.startsWith('__RIPR_PROBE_EXIT_CODE__') + ); } diff --git a/editors/vscode/test/suite/lsp_compatibility.test.ts b/editors/vscode/test/suite/lsp_compatibility.test.ts index 608d6d23b9a..9ad416af137 100644 --- a/editors/vscode/test/suite/lsp_compatibility.test.ts +++ b/editors/vscode/test/suite/lsp_compatibility.test.ts @@ -7,6 +7,7 @@ import { probeStandardLspCompatibility } from '../../src/lspCompatibility'; import { probeServerVersion } from '../../src/serverResolver'; suite('Standard LSP compatibility probe', () => { + const fakeProbeTimeoutMs = 8000; const temporaryRoots: string[] = []; teardown(() => { @@ -36,21 +37,21 @@ suite('Standard LSP compatibility probe', () => { test('rejects a version-only executable that cannot frame LSP', async () => { const fake = fakeServer('version-only'); - const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, fakeProbeTimeoutMs); assert.strictEqual(result.status, 'incompatible'); assert.ok(result.status === 'incompatible' && ['framing_failure', 'process_failure'].includes(result.kind)); }); test('requires the exercised baseline but records genuinely optional omissions', async () => { const missing = fakeServer('missing-hover'); - const rejected = await probeStandardLspCompatibility(missing.command, missing.useShell, 1000); + const rejected = await probeStandardLspCompatibility(missing.command, missing.useShell, fakeProbeTimeoutMs); assert.deepStrictEqual( rejected.status === 'incompatible' ? rejected.kind : undefined, 'missing_required_capability' ); const optional = fakeServer('valid'); - const accepted = await probeStandardLspCompatibility(optional.command, optional.useShell, 1000); + const accepted = await probeStandardLspCompatibility(optional.command, optional.useShell, fakeProbeTimeoutMs); assert.strictEqual(accepted.status, 'compatible', JSON.stringify(accepted)); if (accepted.status === 'compatible') { assert.deepStrictEqual(accepted.optional, { @@ -63,21 +64,37 @@ suite('Standard LSP compatibility probe', () => { for (const mode of ['missing-diagnostics', 'missing-workspace-folders', 'missing-command'] as const) { test(`rejects the active-client baseline omission ${mode}`, async () => { const fake = fakeServer(mode); - const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, fakeProbeTimeoutMs); assert.strictEqual(result.status, 'incompatible'); assert.deepStrictEqual(result.status === 'incompatible' ? result.kind : undefined, 'missing_required_capability'); }); } - for (const mode of ['missing-jsonrpc', 'wrong-jsonrpc', 'missing-response-payload'] as const) { + for (const mode of [ + 'missing-jsonrpc', + 'wrong-jsonrpc', + 'missing-response-payload', + 'wrong-response-id', + 'initialize-result-and-error', + 'initialize-malformed-error', + 'shutdown-result-and-error', + 'shutdown-malformed-error', + 'shutdown-non-null-result' + ] as const) { test(`rejects the invalid JSON-RPC envelope ${mode}`, async () => { const fake = fakeServer(mode); - const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, fakeProbeTimeoutMs); assert.strictEqual(result.status, 'incompatible'); assert.deepStrictEqual(result.status === 'incompatible' ? result.kind : undefined, 'protocol_failure'); }); } + test('accepts a structurally valid initialize error as an initialize rejection', async () => { + const fake = fakeServer('initialize-error'); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, fakeProbeTimeoutMs); + assert.deepStrictEqual(result.status === 'incompatible' ? result.kind : undefined, 'initialize_error'); + }); + test('POSIX version timeout terminates the spawned process group', async function () { if (process.platform === 'win32') { this.skip(); @@ -99,9 +116,48 @@ suite('Standard LSP compatibility probe', () => { assert.throws(() => process.kill(descendantPid, 0), (error: NodeJS.ErrnoException) => error.code === 'ESRCH'); }); + for (const [mode, succeeds] of [ + ['version-descendant-success', true], + ['version-descendant-nonzero', false] + ] as const) { + test(`version ${mode} cannot leave its descendant alive after direct exit`, async () => { + const pidPath = descendantPidPath('ripr-version-exit-tree-'); + const fake = fakeServer(mode, pidPath); + const result = await probeServerVersion(fake.command, 'fixture', fake.useShell, 3000); + assert.strictEqual('binaryVersion' in result, succeeds, JSON.stringify(result)); + await assertDescendantStopped(pidPath); + }); + } + + for (const [mode, expected] of [ + ['lsp-descendant-crash', 'process_failure'], + ['lsp-descendant-protocol', 'protocol_failure'], + ['lsp-descendant-timeout', 'initialize_timeout'] + ] as const) { + test(`LSP ${mode} cannot leave its descendant alive`, async () => { + const pidPath = descendantPidPath('ripr-lsp-failure-tree-'); + const fake = fakeServer(mode, pidPath); + const result = await probeStandardLspCompatibility( + fake.command, + fake.useShell, + mode === 'lsp-descendant-timeout' ? 3000 : fakeProbeTimeoutMs + ); + assert.deepStrictEqual(result.status === 'incompatible' ? result.kind : undefined, expected); + await assertDescendantStopped(pidPath); + }); + } + + test('normal LSP shutdown cannot leave a descendant alive after the server exits first', async () => { + const pidPath = descendantPidPath('ripr-lsp-clean-tree-'); + const fake = fakeServer('lsp-descendant-clean-exit', pidPath); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, fakeProbeTimeoutMs); + assert.strictEqual(result.status, 'compatible', JSON.stringify(result)); + await assertDescendantStopped(pidPath); + }); + test('rejects a server that selects a non-UTF-16 position encoding', async () => { const fake = fakeServer('utf8'); - const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, fakeProbeTimeoutMs); assert.deepStrictEqual( result.status === 'incompatible' ? result.kind : undefined, 'position_encoding_mismatch' @@ -110,7 +166,7 @@ suite('Standard LSP compatibility probe', () => { test('rejects a standard-capable process that does not identify as ripr', async () => { const fake = fakeServer('wrong-identity'); - const result = await probeStandardLspCompatibility(fake.command, fake.useShell, 1000); + const result = await probeStandardLspCompatibility(fake.command, fake.useShell, fakeProbeTimeoutMs); assert.deepStrictEqual( result.status === 'incompatible' ? result.kind : undefined, 'server_identity_mismatch' @@ -127,20 +183,25 @@ suite('Standard LSP compatibility probe', () => { ] as const) { test(`classifies and cleans up ${mode}`, async () => { const fake = fakeServer(mode); - const result = await probeStandardLspCompatibility(fake.command, fake.useShell, mode === 'timeout' ? 300 : 3000); + const result = await probeStandardLspCompatibility( + fake.command, + fake.useShell, + mode === 'timeout' ? 3000 : fakeProbeTimeoutMs + ); assert.strictEqual(result.status, 'incompatible'); assert.deepStrictEqual(result.status === 'incompatible' ? result.kind : undefined, expected); }); } - test('a later compatible channel can be tried after an incompatible candidate', async () => { + test('a later compatible channel can be tried after an incompatible candidate', async function () { + this.timeout(25_000); const first = fakeServer('missing-hover'); const second = fakeServer('valid'); const attempts = [first, second]; let selected: number | undefined; for (let index = 0; index < attempts.length; index += 1) { const candidate = attempts[index]; - const result = await probeStandardLspCompatibility(candidate.command, candidate.useShell, 1000); + const result = await probeStandardLspCompatibility(candidate.command, candidate.useShell, fakeProbeTimeoutMs); if (result.status === 'compatible') { selected = index; break; @@ -149,14 +210,20 @@ suite('Standard LSP compatibility probe', () => { assert.strictEqual(selected, 1); }); - function fakeServer(mode: string): { command: string; useShell: boolean } { + function descendantPidPath(prefix: string): string { + const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + temporaryRoots.push(root); + return path.join(root, 'descendant.pid'); + } + + function fakeServer(mode: string, descendantPath?: string): { command: string; useShell: boolean } { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ripr-lsp-probe-')); temporaryRoots.push(root); const script = path.join(root, 'server.js'); - fs.writeFileSync(script, fakeServerSource(mode)); + fs.writeFileSync(script, fakeServerSource(mode, descendantPath)); if (process.platform === 'win32') { const command = path.join(root, 'ripr.cmd'); - fs.writeFileSync(command, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`); + fs.writeFileSync(command, `@echo off\r\n"${process.execPath}" "${script}" %*\r\nexit /b %errorlevel%\r\n`); return { command, useShell: true }; } const command = path.join(root, 'ripr'); @@ -165,16 +232,55 @@ suite('Standard LSP compatibility probe', () => { } }); -function fakeServerSource(mode: string): string { +async function assertDescendantStopped(pidPath: string): Promise { + assert.ok(fs.existsSync(pidPath), `fixture did not record a descendant pid at ${pidPath}`); + const pid = Number(fs.readFileSync(pidPath, 'utf8').trim()); + assert.ok(Number.isSafeInteger(pid) && pid > 0, `fixture recorded invalid descendant pid ${String(pid)}`); + const deadline = Date.now() + 3000; + while (Date.now() < deadline) { + try { + process.kill(pid, 0); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ESRCH') { + return; + } + throw error; + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + assert.fail(`probe descendant ${pid} remained after process-tree cleanup`); +} + +function fakeServerSource(mode: string, descendantPidPath?: string): string { return ` +const cp = require('child_process'); +const fs = require('fs'); const mode = ${JSON.stringify(mode)}; -if (process.argv.includes('--version')) { console.log('ripr 9.9.9'); process.exit(0); } +const descendantPidPath = ${JSON.stringify(descendantPidPath)}; +function spawnDescendant() { + const descendant = cp.spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { + detached: process.platform === 'win32', + stdio: 'ignore' + }); + descendant.unref(); + fs.writeFileSync(descendantPidPath, String(descendant.pid)); +} +if (process.argv.includes('--version')) { + if (mode === 'version-descendant-success' || mode === 'version-descendant-nonzero') spawnDescendant(); + console.log('ripr 9.9.9'); + process.exit(mode === 'version-descendant-nonzero' ? 17 : 0); +} if (mode === 'version-only') { process.stdout.write('not lsp'); process.exit(0); } if (mode === 'timeout') { setInterval(() => {}, 1000); return; } if (mode === 'malformed') { process.stdout.write('Content-Length: nope\\r\\n\\r\\n{}'); return; } if (mode === 'partial') { process.stdout.write('Content-Length: 100\\r\\n\\r\\n{'); process.exit(0); } if (mode === 'crash') { process.exit(0); } if (mode === 'nonzero') { process.exit(17); } +if (mode.startsWith('lsp-descendant-')) { + spawnDescendant(); + if (mode === 'lsp-descendant-crash') process.exit(17); + if (mode === 'lsp-descendant-timeout') { setInterval(() => {}, 1000); return; } +} let input = Buffer.alloc(0); process.stdin.on('data', chunk => { input = Buffer.concat([input, chunk]); consume(); }); function send(value) { @@ -199,9 +305,16 @@ function consume() { const envelope = { jsonrpc: mode === 'wrong-jsonrpc' ? '1.0' : '2.0', id: message.id, result: { capabilities, serverInfo: { name: mode === 'wrong-identity' ? 'other' : 'ripr', version: '9.9.9' } } }; if (mode === 'missing-jsonrpc') delete envelope.jsonrpc; if (mode === 'missing-response-payload') delete envelope.result; + if (mode === 'wrong-response-id') envelope.id = 99; + if (mode === 'initialize-result-and-error' || mode === 'lsp-descendant-protocol') envelope.error = null; + if (mode === 'initialize-malformed-error') { delete envelope.result; envelope.error = { code: '-1' }; } + if (mode === 'initialize-error') { delete envelope.result; envelope.error = { code: -32000, message: 'not compatible' }; } send(envelope); } else if (message.method === 'shutdown') { if (mode === 'shutdown-failure') send({ jsonrpc: '2.0', id: message.id, error: { code: -1, message: 'no' } }); + else if (mode === 'shutdown-result-and-error') send({ jsonrpc: '2.0', id: message.id, result: null, error: null }); + else if (mode === 'shutdown-malformed-error') send({ jsonrpc: '2.0', id: message.id, error: { code: -1 } }); + else if (mode === 'shutdown-non-null-result') send({ jsonrpc: '2.0', id: message.id, result: {} }); else send({ jsonrpc: '2.0', id: message.id, result: null }); } else if (message.method === 'exit') { process.exit(0); } } diff --git a/policy/process_allowlist.txt b/policy/process_allowlist.txt index 1bd143c3844..668bfcc3083 100644 --- a/policy/process_allowlist.txt +++ b/policy/process_allowlist.txt @@ -39,10 +39,10 @@ editors/vscode/src/client.ts|child_process|1|lsp/editor|VS Code client invokes r editors/vscode/src/client.ts|cp.execFile|1|lsp/editor|VS Code client invokes ripr context without shell expansion. editors/vscode/src/downloader.ts|child_process|1|lsp/editor|Downloader extracts archives with platform tools. editors/vscode/src/downloader.ts|cp.execFile|2|lsp/editor|Downloader invokes tar or PowerShell for archive extraction and probes the staged ripr executable before cache admission, without shell expansion. -editors/vscode/src/lspCompatibility.ts|child_process|1|lsp/editor|#1745 / RIPR-SPEC-0129: pre-activation compatibility proof spawns only the resolved ripr candidate for a bounded initialize/shutdown session and uses platform process-tree cleanup on deadline. -editors/vscode/src/lspCompatibility.ts|cp.spawn|2|lsp/editor|#1745 / RIPR-SPEC-0129: one bounded ripr LSP spawn plus the explicit Windows taskkill tree adapter; no user-supplied protocol command or shell expansion. -editors/vscode/src/serverResolver.ts|child_process|1|lsp/editor|Server resolver probes candidate ripr binaries. -editors/vscode/src/serverResolver.ts|cp.spawn|1|lsp/editor|#1745 / RIPR-SPEC-0129: server resolver runs the bounded ripr --version preflight in a dedicated POSIX process group (or Windows tree) so timeout cleanup includes descendants. +editors/vscode/src/lspCompatibility.ts|child_process|1|lsp/editor|#1745 / RIPR-SPEC-0129: the shared version/LSP probe owner spawns only the selected ripr candidate through a bounded platform process-tree controller. +editors/vscode/src/lspCompatibility.ts|cp.spawn|3|lsp/editor|#1745 / RIPR-SPEC-0129: one POSIX process-group spawn, one Windows kill-on-close Job Object wrapper spawn, and the idempotent taskkill fallback own every version/LSP terminal path; no protocol payload reaches a shell. +editors/vscode/test/suite/lsp_compatibility.test.ts|child_process|1|lsp/editor-test|#1745 / RIPR-SPEC-0129: test-only fake servers spawn a long-lived descendant to prove version and LSP cleanup after timeout, failure, and direct-parent exit. +editors/vscode/test/suite/lsp_compatibility.test.ts|cp.spawn|1|lsp/editor-test|#1745 / RIPR-SPEC-0129: the retained process-tree oracle creates one test-only descendant and asserts its PID is dead after each probe disposition. editors/vscode/test/runTest.ts|child_process|1|vscode-packaged-integration|#2528: packaged Electron proof creates an isolated external Git fixture and launches the opt-in trust-boundary host through bounded child-process calls; no shell expansion. xtask/src/main.rs|Command::new|1|gate-runner|#2343: diff-aware gate runner reads changed files via git diff xtask/src/reports/release_scope.rs|Command::new|2|release-scope|RIPR-SPEC-0145: candidate-only scope reconciliation invokes bounded git probes for current ref, commit, path, and preserved-path verification; no arbitrary command execution.