Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/web/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
8 changes: 2 additions & 6 deletions src/runtime/researchHarness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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);
Expand Down
25 changes: 20 additions & 5 deletions src/runtime/sealedHarness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,19 @@ const object = (value: unknown): Record<string, unknown> => value && typeof valu
? value as Record<string, unknown> : {};
type Runtime = NonNullable<ReturnType<typeof readCliConfiguration>['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');
Expand All @@ -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<SealedRuntimeProjection,
'executable' | 'command' | 'prefixArgs' | 'mounts'> {
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);
Expand Down Expand Up @@ -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<MathAgentOptions, 'workspace' | 'profile'>): 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(`(?<![\\w.-])(?:${escaped.join('|')})(?![\\w-])(?!\\.[\\w-])`, 'gu');
return text.replace(pattern, host => 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');
Expand Down
33 changes: 32 additions & 1 deletion tests/sealedHarness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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); }
});
});
11 changes: 11 additions & 0 deletions tests/webHarness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading