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
10 changes: 6 additions & 4 deletions apps/web/client/researchLibraryProposal.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { useEffect, useRef, useState } from 'preact/hooks';
import { localizeMessage } from '../i18n';
import type { ResearchLibraryTrial, ResearchLibraryProposalTarget, ResearchLibraryTrialHistory } from '../researchLibraryTrialTypes';
import type { ResearchFeedback } from '../researchProjectTypes';
import { base, enc, ErrorBox, Field, MutationState, theoremHref, tx, useMutation, useResource, type Item, type Items } from './researchShared';
import { readLibraryProposalDraft, writeLibraryProposalDraft, type LibraryProposalDraft } from './researchLibraryProposalDraft';

export function PersonalTrialAttempt({ trial, eligible }: { trial: ResearchLibraryTrial; eligible?: boolean }) {
const data = useResource<Item<ResearchLibraryTrialHistory>>(eligible === undefined && trial.status === 'passed' ? `${base}/library-trials/${enc(trial.id)}/history` : undefined);
const allowed = eligible ?? data.data?.item.personalAttempt;
export function PersonalTrialAttempt({ trial, history }: { trial: ResearchLibraryTrial; history?: ResearchLibraryTrialHistory }) {
const data = useResource<Item<ResearchLibraryTrialHistory>>(!history && trial.status === 'passed' ? `${base}/library-trials/${enc(trial.id)}/history` : undefined);
const eligibility = history ?? data.data?.item;
return <div class="research-personal-trial-attempt" data-personal-trial-attempt>
<ErrorBox message={data.error} />{data.error && <button type="button" class="text-button" onClick={data.refresh}>{tx('重新读取后续操作', 'Reload next steps')}</button>}
{allowed && <><p>{tx('把这份候选和固定库带入你的新研究草稿,核对配置后再开始。', 'Bring this candidate and fixed library into your new research draft. Review the configuration before starting.')}</p>
{eligibility?.personalAttemptReason && <p class="research-status">{localizeMessage(eligibility.personalAttemptReason)}</p>}
{eligibility?.personalAttempt && <><p>{tx('把这份候选和固定库带入你的新研究草稿,核对配置后再开始。', 'Bring this candidate and fixed library into your new research draft. Review the configuration before starting.')}</p>
<a class="button" data-prepare-personal-trial href={`./?${new URLSearchParams({ libraryTrial: trial.id, trialDigest: trial.digest })}`}>{tx('准备个人新尝试', 'Prepare a personal attempt')}</a></>}
</div>;
}
Expand Down
2 changes: 1 addition & 1 deletion apps/web/client/researchLibraryTrialHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export function LibraryTrialHistoryReader({ id }: { id: string }) {
<div class="research-actions">{saved.current && <a class="button" data-resume-trial href={`library.html?${new URLSearchParams({ entry: saved.trial.release.assetId, version: saved.trial.release.version, trial: saved.trial.id })}`}>{tx('回到试用编辑器', 'Return to the trial editor')}</a>}
{!saved.current && <a class="button" data-reprepare-trial href={`library.html?${new URLSearchParams({ entry: saved.trial.release.assetId, version: saved.trial.release.version, run: saved.trial.target.ref.runId, task: saved.trial.target.ref.taskId,
...(saved.trial.target.ref.projectId ? { project: saved.trial.target.ref.projectId } : {}) })}`}>{tx('为当前目标准备新的试用', 'Prepare a new trial for the current goal')}</a>}</div>
<PersonalTrialAttempt trial={saved.trial} eligible={saved.personalAttempt} />
<PersonalTrialAttempt trial={saved.trial} history={saved} />
</>}
</section>;
}
52 changes: 31 additions & 21 deletions apps/web/jobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ export class WebJobs {
for (const { owner, run, creation } of this.storage.loadRuns()) {
if (creation) this.creations.set(JSON.stringify([owner, creation.requestId]), { ...creation, runId: run.id });
const provider: WebWorkerProvider = { id: run.providerId, name: run.providerId, baseUrl: '' };
const tail = this.storage.recoverRunTail(owner, run);
const recoveredObservation = tail.observation && this.applyObservation(run, tail.observation);
if (tail.actionCount !== undefined) run.actions = { ...run.actions, count: tail.actionCount };
this.jobs.set(run.id, { owner, run, provider, input: { ...run, apiKey: '' }, controller: new AbortController() });
if (run.result && (!terminal(run) || run.phase === 'interrupted' && run.result.status === 'evaluated_passed')) {
if (run.phase === 'interrupted') {
Expand All @@ -75,7 +78,10 @@ export class WebJobs {
run.failure = { kind: 'interrupted' };
delete run.queue;
this.event(run, 'interrupted', run.error);
} else if (run.phase === 'interrupted' && !run.failure) run.failure = { kind: 'interrupted' };
} else {
if (run.phase === 'interrupted' && !run.failure) run.failure = { kind: 'interrupted' };
if (recoveredObservation || tail.actionCount !== undefined) this.persist(run);
}
}
}

Expand Down Expand Up @@ -314,31 +320,34 @@ export class WebJobs {
this.persist(job.run);
}
private observe(job: Job, observation: WebObservation) {
const current = job.run.solverAttempt ?? (job.run.observation && {
solverRunId: job.run.observation.solverRunId, round: 0, sequence: job.run.observation.sequence });
if (observation.webRunId !== job.run.id || observation.snapshot.runId !== observation.solverRunId ||
if (this.applyObservation(job.run, observation)) this.persist(job.run);
}
private applyObservation(run: WebRun, observation: WebObservation) {
const current = run.solverAttempt ?? (run.observation && {
solverRunId: run.observation.solverRunId, round: 0, sequence: run.observation.sequence });
if (observation.webRunId !== run.id || observation.snapshot.runId !== observation.solverRunId ||
current && (current.solverRunId !== observation.solverRunId || current.sequence >= observation.sequence)) return;
const configuration = observation.inspection.configuration;
const actualHarness = configuration?.agentHarness, expectedHarness = job.run.harness ?? 'codex';
const actualHarness = configuration?.agentHarness, expectedHarness = run.harness ?? 'codex';
if (actualHarness && actualHarness.id !== expectedHarness || expectedHarness !== 'codex' && !actualHarness ||
job.run.agentHarness && canonicalMathJson(job.run.agentHarness) !== canonicalMathJson(actualHarness)) return;
if ((configuration?.researchMode ?? 'legacy') !== (job.run.researchMode ?? 'legacy')) return;
run.agentHarness && canonicalMathJson(run.agentHarness) !== canonicalMathJson(actualHarness)) return;
if ((configuration?.researchMode ?? 'legacy') !== (run.researchMode ?? 'legacy')) return;
if ((configuration?.researchDelegation?.mode === 'team' ? configuration.researchDelegation.maxAgents : undefined)
!== job.run.nativeTeamCapacity) return;
if (canonicalMathJson(configuration?.researchDelegation?.preferredProfiles ?? []) !== canonicalMathJson(job.run.nativeTeamPreferredProfiles ?? [])) return;
const cards = job.researchConfiguration?.personalExperts;
!== run.nativeTeamCapacity) return;
if (canonicalMathJson(configuration?.researchDelegation?.preferredProfiles ?? []) !== canonicalMathJson(run.nativeTeamPreferredProfiles ?? [])) return;
const cards = run.researchConfiguration?.personalExperts;
if (configuration?.researchDelegation?.personalExperts?.digest !== (cards?.length ? personalExpertCardsDigest(cards) : undefined)) return;
if (job.run.researchMode === 'skill') {
const skill = configuration?.researchSkill, frozen = job.run.researchSkill;
if (!skill || skill.loading !== (job.run.skillLoading ?? 'native') ||
if (run.researchMode === 'skill') {
const skill = configuration?.researchSkill, frozen = run.researchSkill;
if (!skill || skill.loading !== (run.skillLoading ?? 'native') ||
frozen && (skill.name !== frozen.name || skill.digest !== frozen.digest || skill.loading !== frozen.loading)) return;
job.run.researchSkill = { ...skill };
run.researchSkill = { ...skill };
}
if (actualHarness) job.run.agentHarness = { ...actualHarness };
job.run.solverAttempt = { solverRunId: observation.solverRunId, round: current?.round ?? 0, sequence: observation.sequence };
job.run.observation = projectStoredObservationChecks(observation);
job.run.updatedAt = observation.observedAt;
this.persist(job.run);
if (actualHarness) run.agentHarness = { ...actualHarness };
run.solverAttempt = { solverRunId: observation.solverRunId, round: current?.round ?? 0, sequence: observation.sequence };
run.observation = projectStoredObservationChecks(observation);
run.updatedAt = observation.observedAt;
return true;
}
guidance(owner: string, runId: string, id: string) {
const run = this.get(owner, runId);
Expand Down Expand Up @@ -509,8 +518,9 @@ export class WebJobs {
const tally = job.run.actions ??= { count: 0 };
if (tally.count >= webAgentActionLimits.perRun) tally.dropped = (tally.dropped ?? 0) + 1;
else {
tally.count++;
this.storage.saveAction(job.owner, job.run.id, { ...message.action, sequence: tally.count, at: new Date().toISOString() });
const sequence = tally.count + 1;
this.storage.saveAction(job.owner, job.run.id, { ...message.action, sequence, at: new Date().toISOString() });
tally.count = sequence;
}
this.actionsChanged(job.run);
} else if (message.type === 'artifact') {
Expand Down
25 changes: 24 additions & 1 deletion apps/web/observationChecks.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
import { canonicalMathJson } from '../../src/math/mathRuntimeIo';
import type { WebCheckReceipt, WebObservation } from './collaboration';

/** Earlier frames copied each original-goal receipt onto every goal in its batch. */
export function projectStoredObservationChecks(observation: WebObservation): WebObservation {
const projected = projectOriginalProblemChecks(observation);
// Task checks bind both statement hashes to the task revision. Older workers could also
// publish them as whole-problem checks, storing the actual task verdict in the batch field.
const isTaskCheck = ({ taskVersion, record }: WebCheckReceipt) =>
record.statementHash === taskVersion && record.leanStatementHash === taskVersion;
if (!projected.checks.some(check => isTaskCheck(check) && typeof check.record.originalProblemPassed === 'boolean')) return projected;

const taskChecks = new Set<string>();
const checks = projected.checks.flatMap(check => {
if (!isTaskCheck(check)) return [check];
const { originalProblemPassed, ...record } = check.record;
const normalized = typeof originalProblemPassed === 'boolean' ?
{ ...check, record: { ...record, passed: originalProblemPassed } } : check;
const key = canonicalMathJson(normalized);
if (taskChecks.has(key)) return [];
taskChecks.add(key);
return [normalized];
});
return { ...projected, checks };
}

/** Earlier frames copied each original-goal receipt onto every goal in its batch. */
function projectOriginalProblemChecks(observation: WebObservation): WebObservation {
const targets = observation.inspection.problem?.targets ?? [];
if (targets.length < 2 || observation.checks.length < 2) return observation;

Expand Down
6 changes: 3 additions & 3 deletions apps/web/researchApi.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { z } from 'zod';
import { canonicalMathJson, mathDigest } from '../../src/math/mathRuntimeIo';
import { inspectScopedLeanDeclarations } from '../../src/math/leanSource';
import { researchCandidateScopeReason } from './researchCandidateScope';
import { researchCandidateScopeReason, withResearchLibraryImports } from './researchCandidateScope';
import { WebResearchProjects } from './researchProjects';
import { WebResearchAssets } from './researchAssets';
import { researchOverview } from './researchOverview';
Expand Down Expand Up @@ -192,7 +192,7 @@ export class WebResearchApi {
? { expectedType: task.type ?? planned?.type } : {}) } : undefined;
const attachment = submission.libraryTrial;
const candidateTarget = attachment?.candidateTarget ?? inferredTarget;
const prefix = attachment?.imports.map(name => `import ${name}\n`).join('') ?? '';
const imports = attachment?.imports ?? [];
const dependencySources = attachment?.dependencySources ?? baseline.dependencySources;
const expectedKind = task?.kind === 'lemma' ? planned?.declaration === 'definition' ? 'definition' : 'theorem'
: inspectScopedLeanDeclarations(run.source).find(item => item.qualifiedName === candidateTarget?.name)?.kind ?? 'theorem';
Expand All @@ -202,7 +202,7 @@ export class WebResearchApi {
: declaration?.kind !== expectedKind ? expectedKind === 'definition' ? '此任务要求定义,请保留计划指定的声明种类。'
: '此任务要求定理或引理,请勿用定义替代证明。'
: task.kind === 'lemma' && !candidateTarget.expectedType ? '候选辅助声明的计划类型不可用,请刷新后重新选择。'
: researchCandidateScopeReason({ originalSource: prefix + run.source, baselineSource: prefix + baseline.source,
: researchCandidateScopeReason({ originalSource: withResearchLibraryImports(run.source, imports), baselineSource: withResearchLibraryImports(baseline.source, imports),
candidateSource: submission.source, targetName: candidateTarget.name });
const result = reason ? undefined : await this.runner.check!({ environment: run.environment, source: submission.source,
sourceFile: base.file, dependencySources,
Expand Down
13 changes: 12 additions & 1 deletion apps/web/researchCandidateScope.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
import { inspectLeanDeclarationRegions, inspectScopedLeanDeclarations, repeatedLeanLocalNames } from '../../src/math/leanSource';
import { maskLeanComments, maskLeanCommentsAndStrings } from '../../src/math/leanSyntax';
import { mathConstructionImports } from '../../src/math/mathConstructionSources';
import { mathConstructionHeader, mathConstructionImports } from '../../src/math/mathConstructionSources';
import { libraryForbiddenToken } from '../../src/math/libraryPacks';
import { solverMathlibImports, solverSourceContext } from '../../src/solver/sourceContext';

export type ResearchCandidateScopeInput = Readonly<{
originalSource: string; baselineSource: string; candidateSource: string; targetName: string;
}>;

/** Add the trial's imports after any Lean module/prelude directives. */
export function withResearchLibraryImports(source: string, imports: readonly string[]): string {
if (!imports.length) return source;
const added = imports.map(name => `import ${name}\n`).join('');
const { directivesEnd } = mathConstructionHeader(source);
if (!directivesEnd) return added + source;
const lineBreak = /^\r?\n/u.exec(source.slice(directivesEnd))?.[0];
const offset = directivesEnd + (lineBreak?.length ?? 0);
return source.slice(0, offset) + (lineBreak ? '' : '\n') + added + source.slice(offset);
}

const declarations = (source: string) => {
const regions = new Map(inspectLeanDeclarationRegions(source).map(item => [item.startOffset, item]));
return inspectScopedLeanDeclarations(source).map(item => ({ ...item, ...regions.get(item.startOffset)! }));
Expand Down
2 changes: 1 addition & 1 deletion apps/web/researchLibraryTrialTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,6 @@ export type ResearchLibraryTrialHistoryItem = Pick<ResearchLibraryTrial, 'id' |
current: boolean; reason?: string; receiptId?: string; checkedAt?: string;
};
export type ResearchLibraryTrialHistory = {
trial: ResearchLibraryTrial; current: boolean; reason?: string; personalAttempt: boolean;
trial: ResearchLibraryTrial; current: boolean; reason?: string; personalAttempt: boolean; personalAttemptReason?: string;
libraryPack: ResearchLibraryPack; dependencySources: { file: string; source: string }[];
};
Loading
Loading