From 78f95ca12e8ef4a9835f2cbe87ba257b0a86d3e0 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:19:40 +0800 Subject: [PATCH] Harden harness path projection, executable lookup and profile init - sealedRoleText rewrites host workspace/profile paths only as whole path components, in one pass, so /runs/w no longer corrupts /runs/w-profile, /runs/w2 or /mnt/runs/w, and a nested workspace maps correctly. - Research and sealed launches share locateHarnessExecutable: absolute, cwd-relative with a separator, else the first executable regular file on absolute PATH entries. Sealed lookup no longer accepts directories or non-executable files; a script run through runtime.interpreter still only needs to be a regular file. - bindWebWorkerProfile discards a profile copy left by an interrupted first binding instead of failing on mkdir forever. Co-Authored-By: Claude Opus 5.5 --- apps/web/harness.ts | 2 ++ src/runtime/researchHarness.ts | 8 ++------ src/runtime/sealedHarness.ts | 25 ++++++++++++++++++++----- tests/sealedHarness.test.ts | 33 ++++++++++++++++++++++++++++++++- tests/webHarness.test.ts | 11 +++++++++++ 5 files changed, 67 insertions(+), 12 deletions(-) diff --git a/apps/web/harness.ts b/apps/web/harness.ts index 677907c5..21066c60 100644 --- a/apps/web/harness.ts +++ b/apps/web/harness.ts @@ -86,6 +86,8 @@ export function bindWebWorkerProfile(options: MathAgentOptions, provider: WebWor const profile = path.join(directory, name), bindingFile = path.join(directory, name + '.binding.json'); assertMathCanonicalPath(profile); assertMathCanonicalPath(bindingFile); if (!fs.existsSync(bindingFile)) { + // No binding means no session ever used this profile; discard a copy left by an interrupted initialization. + fs.rmSync(profile, { recursive: true, force: true }); fs.mkdirSync(profile, { mode: 0o700 }); const names = id === 'claude-code' ? ['settings.json'] : id === 'opencode' ? ['opencode.json'] : ['cli.json', ...readCliConfiguration(parent).configurationFiles]; diff --git a/src/runtime/researchHarness.ts b/src/runtime/researchHarness.ts index fe409702..6d30d2d3 100644 --- a/src/runtime/researchHarness.ts +++ b/src/runtime/researchHarness.ts @@ -9,7 +9,7 @@ import { createClaudeCodeMathSession } from './claudeCodeSession'; import { createOpenCodeMathSession } from './openCodeSession'; import { createCliMathSession } from './cliSession'; import { readCliConfiguration, CLI_CONFIGURATION_FILE } from './cliConfiguration'; -import { sealedRuntimeIdentity } from './sealedHarness'; +import { locateHarnessExecutable, sealedRuntimeIdentity } from './sealedHarness'; export { planMathAgentSession } from './agentSessionPlan'; export type ResearchHarnessIdentity = { @@ -71,11 +71,7 @@ export function researchHarness(id: string) { /** Pin executable and explicit provider/settings files, excluding mutable sessions and authentication. */ export function bindResearchHarness(id: ResearchHarnessIdentity['id'], command: string, profile: string, environment: NodeJS.ProcessEnv = process.env, model?: string): ResearchHarnessIdentity { - const candidates = path.isAbsolute(command) ? [command] : command.includes(path.sep) ? [path.resolve(command)] : - (environment.PATH ?? '').split(path.delimiter).map(directory => path.join(directory, command)); - const executable = candidates.find(file => { - try { return fs.statSync(file).isFile() && (fs.accessSync(file, fs.constants.X_OK), true); } catch { return false; } - }); + const executable = locateHarnessExecutable(command, environment.PATH ?? ''); if (!executable) throw new Error(`math_harness_executable_unavailable:${id}`); const binary = fs.realpathSync(executable); assertMathCanonicalPath(profile); diff --git a/src/runtime/sealedHarness.ts b/src/runtime/sealedHarness.ts index 88b4791d..8c51efca 100644 --- a/src/runtime/sealedHarness.ts +++ b/src/runtime/sealedHarness.ts @@ -15,9 +15,19 @@ const object = (value: unknown): Record => value && typeof valu ? value as Record : {}; type Runtime = NonNullable['sealedRole']>['runtime']; -function resolveExecutable(value: string, env: NodeJS.ProcessEnv): string { - const candidate = path.isAbsolute(value) ? value : (env.PATH ?? process.env.PATH ?? '').split(path.delimiter) - .filter(directory => path.isAbsolute(directory)).map(directory => path.join(directory, value)).find(file => fs.existsSync(file)); +/** Research and sealed launches resolve a command identically: absolute, cwd-relative with a separator, + * else the first regular file on the absolute PATH entries. A script passed to an interpreter need not be executable. */ +export function locateHarnessExecutable(command: string, searchPath: string, requireExecute = true): string | undefined { + const candidates = path.isAbsolute(command) ? [command] : command.includes(path.sep) ? [path.resolve(command)] : + searchPath.split(path.delimiter).filter(directory => path.isAbsolute(directory)).map(directory => path.join(directory, command)); + return candidates.find(file => { + try { return fs.statSync(file).isFile() && (!requireExecute || (fs.accessSync(file, fs.constants.X_OK), true)); } + catch { return false; } + }); +} + +function resolveExecutable(value: string, env: NodeJS.ProcessEnv, requireExecute = true): string { + const candidate = locateHarnessExecutable(value, env.PATH ?? process.env.PATH ?? '', requireExecute); if (!candidate) throw new Error('math_sealed_executable_unavailable'); const canonical = fs.realpathSync(candidate); assertMathCanonicalPath(canonical); if (!fs.statSync(canonical).isFile()) throw new Error('math_sealed_executable_invalid'); @@ -28,7 +38,7 @@ function resolveExecutable(value: string, env: NodeJS.ProcessEnv): string { * No host directory, profile, source tree or global credential store is mounted. */ function runtimeProjection(executable: string, env: NodeJS.ProcessEnv, runtime?: Runtime): Pick { - const original = resolveExecutable(executable, env), command = '/opt/harness/bin/agent'; + const original = resolveExecutable(executable, env, !runtime?.interpreter), command = '/opt/harness/bin/agent'; const mounts = (runtime?.resources ?? []).map(resource => { assertMathCanonicalPath(resource.source); const source = fs.realpathSync(resource.source), target = path.posix.normalize(resource.target); @@ -157,7 +167,12 @@ export async function prepareSealedHarness(harness: 'claude-code' | 'opencode' | /** Paths embedded in host prompts refer only to their role projection. */ export function sealedRoleText(text: string, options: Pick): string { - return text.replaceAll(path.resolve(options.workspace), '/workspace').replaceAll(path.resolve(options.profile), '/profile'); + const projections = [[path.resolve(options.workspace), '/workspace'], [path.resolve(options.profile), '/profile']] + .sort((left, right) => right[0].length - left[0].length); + const escaped = projections.map(([host]) => host.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')); + // Whole path components only, in one pass: /runs/w never rewrites /runs/w-profile, /runs/w2 or /mnt/runs/w. + const pattern = new RegExp(`(? projections.find(([candidate]) => candidate === host)![1]); } export function sealedRolePath(file: string, workspace: string): string { if (!isMathPathWithin(workspace, file)) throw new Error('math_sealed_output_outside_role'); diff --git a/tests/sealedHarness.test.ts b/tests/sealedHarness.test.ts index c9443bba..80ab8c31 100644 --- a/tests/sealedHarness.test.ts +++ b/tests/sealedHarness.test.ts @@ -8,7 +8,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { createClaudeCodeMathSession } from '../src/runtime/claudeCodeSession'; import { createOpenCodeMathSession } from '../src/runtime/openCodeSession'; import { createCliMathSession } from '../src/runtime/cliSession'; -import { prepareSealedHarness, sealedOpenCodeProvider } from '../src/runtime/sealedHarness'; +import { locateHarnessExecutable, prepareSealedHarness, sealedOpenCodeProvider, sealedRoleText } from '../src/runtime/sealedHarness'; import { sealedRoleProtocol } from '../src/runtime/sealedRoleProtocol'; import { mathDigest } from '../src/math/mathRuntimeIo'; import { getLeanTaskEnvironment } from '../src/math/leanTaskEnvironment'; @@ -271,3 +271,34 @@ describe('sealed OpenCode provider references', () => { expect(selected.environment.THEOREMOS_SEALED_HOST_KEY).toBe('corp-key'); }); }); + +describe('sealed role projections', () => { + it('rewrites only whole host path components', () => { + const options = { workspace: '/runs/w', profile: '/runs/w-profile' }; + expect(sealedRoleText('ws=/runs/w, file /runs/w/a.lean. cfg=/runs/w-profile/settings.json', options)) + .toBe('ws=/workspace, file /workspace/a.lean. cfg=/profile/settings.json'); + expect(sealedRoleText('/runs/w2/x /mnt/runs/w /runs/w.bak "/runs/w"', options)) + .toBe('/runs/w2/x /mnt/runs/w /runs/w.bak "/workspace"'); + expect(sealedRoleText('/runs/p/w and /runs/p', { workspace: '/runs/p/w', profile: '/runs/p' })) + .toBe('/workspace and /profile'); + }); + + it('locates executables with the same rules for research and sealed launches', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-lookup-')); roots.push(root); + const shadow = path.join(root, 'shadow'), plain = path.join(root, 'plain'), bin = path.join(root, 'bin'); + for (const directory of [shadow, plain, bin]) fs.mkdirSync(directory); + fs.mkdirSync(path.join(shadow, 'agent')); + fs.writeFileSync(path.join(plain, 'agent'), '', { mode: 0o600 }); + fs.writeFileSync(path.join(bin, 'agent'), '#!/bin/sh\n', { mode: 0o700 }); + const searchPath = ['relative-entry', shadow, plain, bin].join(path.delimiter); + expect(locateHarnessExecutable('agent', searchPath)).toBe(path.join(bin, 'agent')); + expect(locateHarnessExecutable('missing', searchPath)).toBeUndefined(); + const cwd = process.cwd(); + try { + process.chdir(root); + expect(locateHarnessExecutable('./bin/agent', '')).toBe(path.join(root, 'bin/agent')); + expect(locateHarnessExecutable('./plain/agent', '')).toBeUndefined(); + expect(locateHarnessExecutable('./plain/agent', '', false)).toBe(path.join(root, 'plain/agent')); + } finally { process.chdir(cwd); } + }); +}); diff --git a/tests/webHarness.test.ts b/tests/webHarness.test.ts index 3037ecb4..bd926e24 100644 --- a/tests/webHarness.test.ts +++ b/tests/webHarness.test.ts @@ -72,6 +72,17 @@ describe('Web server-selected harnesses', () => { expect(fs.readFileSync(path.join(f.profile, settings), 'utf8')).not.toContain(input().apiKey); }); + it('recovers a worker profile left behind by an interrupted first binding', () => { + const f = fixture('cli'), directory = path.join(path.dirname(fs.realpathSync(f.profile)), 'native-sessions'); + const leftover = path.join(directory, mathDigest(f.workspace).slice(0, 32)); + fs.mkdirSync(leftover, { recursive: true }); fs.writeFileSync(path.join(leftover, 'cli.json'), 'partial'); + const binding = bindWebWorkerProfile(f.options, f.provider); + expect(binding.profile).toBe(leftover); + expect(fs.readFileSync(path.join(leftover, 'cli.json'), 'utf8')).toBe(fs.readFileSync(path.join(f.profile, 'cli.json'), 'utf8')); + expect(() => binding.assertCurrent()).not.toThrow(); + expect(bindWebWorkerProfile(f.options, f.provider).identity).toEqual(binding.identity); + }); + it('rejects changed native settings at dispatch and after stopping a writer', async () => { const f = fixture('cli'), session = await webSolverModules({ id: 'fixture', input: input(), provider: f.provider }).M1.open(f.options); sessions.push(session);