Repository navigation
Expand file tree
/
Copy pathrun.ts
More file actions
997 lines (995 loc) · 48.1 KB
/
Copy pathrun.ts
File metadata and controls
997 lines (995 loc) · 48.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import { VerificationCheckpointError, withVerificationCheckpoints } from './verificationCheckpoint';
import { parseRunOptions, resolveRunStrategy, resolveRunLimits, frozenRunConfiguration } from './runOptions';
import { readMathBuildManifestDigest } from '../math/mathBuildManifest';
import { MathGitError } from '../math/mathGit';
import { scheduleMathTimeout } from '../math/mathTimers';
import {
mathDigest,
readMathJson,
readMathText,
withMathRuntimeLease,
writeMathJsonDurable,
type MathLease,
} from '../math/mathRuntimeIo';
import {
projectMathematicsRuntimeEnvironment,
resolveMathematicsRuntimeEnvironment,
} from '../math/mathRuntimeEnvironment';
import type { prepareMathProofEnvironment } from '../math/mathProofEnvironment';
import { resolveMathematicsLakePackagesCache } from '../math/verifier';
import { bindLeanPackages } from '../math/leanDiagnostics';
import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths';
import { git, readSolverProblem, assertSolverSources } from './problem';
import { solverSourceFeedback } from './feedback';
import {
assertMathRetrievalCorpus,
createMathRetrievalCorpus,
type MathRetrievalCorpus,
} from '../math/mathRetrievalCorpus';
import { readSolverRunState, writeSolverRunState, type SolverRunState } from './archive';
import { solverModuleConfiguration, solverMethodDigest } from './modules/moduleIdentity';
import {
configurableRuntimeModules,
configuredRuntimeModules,
defaultRuntimeConfigurations,
directRuntimeModules,
type RuntimeSolverModules,
} from './modules/runtime';
import { researchModulePlanSchema, type ResearchModulePlan } from './modules/policy';
import { concludeRun, type ResearchDriver } from './researchLoop';
import { runResearchLead, type WorkerAccess } from './research';
import { DEFAULT_TEAM_AGENTS } from './teamCapacity';
import { getPreferredAgentTeamProfiles } from './agentTeamProfiles';
import { readPersonalExperts } from './personalExperts';
import { evaluateSolverProof } from './evaluation';
import { solverProofIsCurrent } from './modules/evidence';
import { checkCodexProviderConnectivity } from '../runtime/codexConnectivity';
import { buildTokenBudget } from './usageBudget';
import { DEEPSEEK_PROVIDER } from '../runtime/deepseek';
import { WESTLAKE_NATIVE_TEAM_UNSUPPORTED, WESTLAKE_PROVIDER } from '../runtime/westlake';
import { SUB2API_PROVIDER } from '../runtime/sub2api';
import { selectedProviderProfile } from '../runtime/providerProfile';
import { copyKnowledgeSnapshot } from './theoremKnowledgeStore';
import { readAuthorizedKnowledgeCatalog } from './theoremKnowledgeAuthorization';
import { ExecutionDeadline } from '../runtime/executionDeadline';
import { readInstalledLibrarySnapshot } from './installedLibraryContext';
import { indexKnowledgeContextSnapshot } from './knowledgeContext';
import { assertLibraryCatalogAccess, LibraryInstallationRequested } from './libraryAccess';
import { readLibraryCatalog } from './libraryCatalog';
import { readLeanTaskReceipt } from '../math/leanTask';
import {
copyContinuationSnapshot,
freezeContinuationInput,
readContinuationInput,
readContinuationSnapshot,
type ContinuationSnapshot,
} from './continuationInput';
import { continuationSourceStateFile, seedSingleSolverContinuation } from './singleContinuationSeed';
import { assertActiveResearchState } from './researchRetirement';
import { verifierFailureDiagnostic } from './verifierFailure';
import type { SolverExplanations } from './automaticExplanations';
import { readMathAgentSkill } from '../runtime/agentSkills';
import { prepareResearchSkill, researchSkillIdentity } from './researchSkill';
import { prepareWorkerProject } from './workerProject';
import { prepareSolverLean } from './prepareSolverLean';
import { prepareSolverRuntimeEnvironment } from './environment';
import { assertResearchHarnessCurrent, bindResearchHarness, requireCodexHarness } from '../runtime/researchHarness';
import { planMathAgentSession } from '../runtime/agentSessionPlan';
import { assertProofWriterStopped } from './proofWriter';
function runResultFields(stateFile: string, state: SolverRunState | undefined, clock?: ExecutionDeadline) {
return {
schema: 'deepscientist.math.run.v2',
stateFile,
runId: state?.runId,
problemId: state?.problem.contract.problemId,
...(state?.solveStartedAt && state.solveFinishedAt
? { solveWallMs: state.solveFinishedAt - state.solveStartedAt }
: {}),
...(clock ? { solveExecutionMs: clock.executionMs(), solveWaitingMs: clock.waitingMs() } : {}),
turns: state?.turns,
dispatchCounts: state?.dispatchCounts,
...(state?.originalTacticAttempt ? { originalTacticAttempt: state.originalTacticAttempt } : {}),
...(state?.verifierFailure ? { verifierFailure: state.verifierFailure } : {}),
usage: state?.usage,
tokenBudget: state?.tokenBudget,
workers:
state?.agentTeam?.transport === 'codex-shared'
? [
{
id: 'lead',
role: 'lead',
turns: state.usageAccounting?.startedTurns ?? 0,
dispatchCounts: state.dispatchCounts,
usage: state.usage,
error: state.error,
},
]
: undefined,
};
}
export async function runSolver(
args: string[],
root: string,
customModules?: RuntimeSolverModules,
hostSignal?: AbortSignal,
launch:
| 'internal'
| 'cli'
| { expectedBuild: { digest: string; mismatch: string }; leanOnly: boolean }
| { onRejected: (reason: string) => void } = 'internal',
owner?: { drive: ResearchDriver; lockDescriptor: number; conclude: typeof concludeRun },
): Promise<number> {
const autoLibrary = typeof launch === 'object' && 'expectedBuild' in launch ? launch : undefined;
const onRejected = typeof launch === 'object' && 'onRejected' in launch ? launch.onRejected : undefined;
const entryPoint = typeof launch === 'string' ? launch : 'internal';
const values = parseRunOptions(args, entryPoint);
if (values.help) {
console.log(
`Usage: theorem-os run --workspace DIR --task-file FILE --output FILE --build-manifest FILE [--receipt-file FILE] [--resume] [--agent-team N | --workers 1] [--plan-approval] [--model MODEL --effort LEVEL] [--max-run-seconds N --max-turns N --max-turn-seconds N] [--max-total-tokens N] [--prepare-timeout-seconds N] [--proof-timeout-seconds N] [--evaluator-command CMD --evaluator-timeout-seconds N] [--proof-environment-cache-dir DIR] [--startup-only] [--check-statement]\nUse 0 for --prepare-timeout-seconds, --max-run-seconds, --max-turns, --max-turn-seconds, --proof-timeout-seconds or --evaluator-timeout-seconds to disable that limit. All time, turn and token limits default to 0 (unlimited). With an explicit proof-check timeout, an expired check saves a resumable checkpoint and the identical candidate gets more time on its next check.\n--max-total-tokens defaults to 0 (unlimited). A finite value stops new model turns after provider-reported consumption reaches it; in-flight turns finish and may exceed it. Resume retains cumulative usage and the saved allowance unless explicitly changed.`,
);
console.log(
'--knowledge-base FILE attaches an immutable saved-theorem catalog. Resume requires the same catalog digest. Historical knowledge never grants proof acceptance.',
);
console.log(
`New Codex runs start one Lead who can delegate up to ${DEFAULT_TEAM_AGENTS - 1} members as needed. Use --agent-team N to set the total capacity (2..8 including Lead), or --workers 1 to disable delegation. Team members use native Codex delegation in one shared proof worktree.`,
);
console.log(
'New proof runs default to --effort high. Resume retains the saved effort when --effort is omitted; an explicit effort must match the frozen run.',
);
console.log(
'--no-original-tactics skips the automatic Lean proof attempt before the first model request in a new solo run. Resume keeps the saved setting.',
'Accepted proofs automatically generate audited explanations of every original target. --explanation-language zh|en selects the language (default zh; resume keeps the previous language). --no-explanations skips generation. The result.explanations field records progress and artifact/proof.md paths. Explanation failures preserve proof acceptance and exit code; --resume retries them without solving again. Explanation time and tokens are separate from solving limits.',
);
console.log(
'--library-catalog FILE --library-catalog-sha256 DIGEST enables agent search/get/request against one pinned release. Installation requests end this frozen run for host-controlled continuation.',
);
console.log(
'--continuation-manifest FILE attaches explicit historical sources and notes without changing the verbatim task file. Resume retains the frozen attachment identity; historical material remains advisory.',
);
console.log(
'--continuation-source-run OLD_RESULT_OR_STATE initializes a new native team or solo Skill run from the old run, freshly checks its saved helpers, and starts solving in the same process. With --startup-only, the run freezes its continuation and checks saved helpers when resumed. Use --resume to retry an interrupted zero-turn initialization.',
);
console.log(
'--check-statement also elaborates the target files at startup (theorem bodies may still be sorry) and fails with math_statement_check_failed on a Lean error; statement-diagnostics.json keeps the messages.',
);
console.log(
'--plan-approval lets the native Lead publish an initial route for approval. Use inspect to read it and edit --approve-plan VERSION to approve it. Waiting pauses the solving clock.',
);
console.log(
'Use --codex FILE or --harness-executable FILE to select a Codex binary. Resume retains the frozen launch settings.',
);
console.log(
'Codex Lead delegates and communicates with native tools. Lead assigns files to members. The host checks all original targets after the entire team stops. Reproduce host scheduling experiments with their pinned historical revision.',
);
console.log(
'--skill-preferred-profiles engineer,D011 optionally suggests member work roles and domain specialties from the pinned Skill to the team Lead. The Lead chooses actual assignments and may use other profiles. Omit for no preference on a new run; resume retains the saved selection.',
);
console.log(
'--skill-expert-cards-file FILE freezes user-selected expert cards for a team run. Lead can use the local tool help to select relevant cards for a member assignment. Resume reuses the saved cards.',
);
console.log(
'Team mode makes an early collaboration decision and exposes remaining run time and turn deadlines to every member. A finite --max-turn-seconds remains a hard ceiling; at 80% the host requests a checkpoint at the next model-request boundary, allowing the current response and tools to finish first. The overall deadline and cancellation remain hard stops; missing usage still blocks finite-budget continuation.',
);
return 0;
}
const requireCurrentScheduler = (scheduler: string) => {
if (!values.resume && (scheduler === 'critical-path' || scheduler === 'continuation'))
throw new Error('math_scheduler_retired: omit --scheduler or use plan for new runs.');
};
requireCurrentScheduler(values.scheduler!);
const specified = (key: string) => args.some(arg => arg === '--' + key || arg.startsWith('--' + key + '='));
const publicRun = entryPoint !== 'internal';
const resolveConfiguration = (saved?: SolverRunState) => {
if (saved) {
assertActiveResearchState(saved);
requireCodexHarness(saved.agentHarness?.id ?? 'codex');
}
const strategyValues =
publicRun && !values.resume && values['research-mode'] === undefined
? { ...values, 'research-mode': 'skill' }
: values;
const strategy = resolveRunStrategy(strategyValues, saved, specified('model'), Boolean(customModules));
if (publicRun && values.workers === '1' && strategy.delegationMode === 'team')
throw new Error(
'--workers 1 requires a solo run. Use --agent-team N for a new team or omit --workers on resume.',
);
const configured = configuredRuntimeModules(values.method!, values.scheduler!);
const modulePlan =
values['module-plan'] &&
(researchModulePlanSchema.parse(readMathJson(values['module-plan'])) as ResearchModulePlan);
if (modulePlan) requireCurrentScheduler(modulePlan.scheduler);
const modules = modulePlan
? configurableRuntimeModules(modulePlan, strategy.coordination, 1)
: (customModules ?? configured);
return { strategy, modules, limits: resolveRunLimits(values, strategy, Boolean(saved?.planApproval)) };
};
const newRunConfiguration = values.resume ? undefined : resolveConfiguration();
const required = (key: keyof typeof values): string => {
const value = values[key];
if (typeof value !== 'string' || !value.trim()) throw new Error(`--${key} is required`);
return value;
};
const tokenLimitSpecified = specified('max-total-tokens');
const effortSpecified = specified('effort');
const workspace = fs.realpathSync(required('workspace'));
const output = path.resolve(required('output'));
assertMathCanonicalPath(output);
if (isMathPathWithin(workspace, output)) throw new Error('math_output_must_be_outside_solver_workspace');
fs.mkdirSync(path.dirname(output), { recursive: true, mode: 0o700 });
const directory = `${output}.runtime`;
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
assertMathCanonicalPath(directory);
const stat = fs.statSync(directory);
if (stat.mode & 0o077 || (process.getuid && stat.uid !== process.getuid()))
throw new Error('math_state_directory_not_private');
const stateFile = path.join(directory, 'state.json');
const requestedContinuationSource =
values['continuation-source-run'] && continuationSourceStateFile(values['continuation-source-run']);
let continuationSourceRun = requestedContinuationSource;
const controller = new AbortController();
const abort = () => controller.abort();
const hostAbort = () => controller.abort(hostSignal?.reason);
hostSignal?.addEventListener('abort', hostAbort, { once: true });
if (hostSignal?.aborted) hostAbort();
process.once('SIGINT', abort);
process.once('SIGTERM', abort);
const preparationStarted = Date.now();
let preparationTimer = newRunConfiguration && scheduleMathTimeout(abort, newRunConfiguration.limits.preparationMs);
const cancelPreparation = () => preparationTimer?.();
let preparing = true;
let executionClock: ExecutionDeadline | undefined;
let ownedState: SolverRunState | undefined;
let proofEnvironment: Awaited<ReturnType<typeof prepareMathProofEnvironment>> | undefined;
let ownsRun = false;
let publishedExit: number | undefined;
const emit = (event: string, details = {}) =>
console.log(
JSON.stringify({
event,
at: Date.now(),
...details,
...(ownedState
? {
runId: ownedState.runId,
problemReceiptDigest: ownedState.problem.receiptDigest,
environmentDigest: ownedState.environmentDigest,
}
: {}),
}),
);
const reportRejection = (error: unknown) => {
const reason = error instanceof Error ? error.message : 'math_runtime_error';
emit('rejected', { reason, ...(error instanceof MathGitError ? { git: error.diagnostic } : {}) });
onRejected?.(reason);
};
const disposeProofEnvironment = async () => {
const environment = proofEnvironment;
proofEnvironment = undefined;
await environment?.dispose();
};
const runWithLease = async (lease: MathLease): Promise<number | { configurationError: unknown }> => {
let resumedState: SolverRunState | undefined;
if (values.resume) {
try {
resumedState = readSolverRunState(stateFile);
} catch (error) {
reportRejection(error);
return 1;
}
}
let configuration: ReturnType<typeof resolveConfiguration>;
try {
configuration = newRunConfiguration ?? resolveConfiguration(resumedState);
} catch (configurationError) {
// Preserve thrown configuration errors after releasing the lock.
return { configurationError };
}
const { strategy, limits, modules } = configuration;
const { coordination, researchMode, skillLoading, delegationMode, maxAgents, model } = strategy;
const { maxRunMs, proofTimeoutMs, preparationMs, maxTurnMs, maxTurns, evaluatorMs, tokenLimit, planApproval } =
limits;
const skillMode = researchMode === 'skill';
let maxTotalTokens = tokenLimit;
const preparationDeadline = preparationStarted + preparationMs;
const timeToPrepare = preparationDeadline - Date.now();
if (timeToPrepare <= 0) abort();
lease.signal.throwIfAborted();
preparationTimer ??= scheduleMathTimeout(abort, timeToPrepare);
const execute = async (): Promise<number> => {
const signal = lease.signal;
const buildFile = fs.realpathSync(required('build-manifest'));
const bundleRoot = path.join(root, 'out', 'main');
const readBuildDigest = (expectedDigest?: string) =>
readMathBuildManifestDigest(buildFile, root, bundleRoot, expectedDigest, 'runtime', {
expectedTextDigest: autoLibrary?.expectedBuild,
});
const buildDigest = readBuildDigest();
const task = fs.readFileSync(required('task-file'), 'utf8');
const receiptFile = values['receipt-file'] || path.join(workspace, 'active-problem.json');
const problem = readSolverProblem(workspace, receiptFile);
const assertHostProblemCurrent = () => {
if (
problem.libraryBinding?.hostConfiguration &&
readSolverProblem(workspace, receiptFile).receiptDigest !== problem.receiptDigest
)
throw new Error('library_host_binding_changed');
};
if (
problem.libraryBinding?.hostConfiguration &&
(values['continuation-manifest'] || values['continuation-source-run'])
)
throw new Error('library_knowledge_history_unauthorized');
if (values['library-catalog'] || values['library-catalog-sha256']) assertLibraryCatalogAccess(problem);
if (Boolean(values['library-catalog']) !== Boolean(values['library-catalog-sha256']))
throw new Error('math_library_catalog_pin_missing');
const libraryCatalog =
values['library-catalog'] && readLibraryCatalog(values['library-catalog'], values['library-catalog-sha256']);
if (
libraryCatalog &&
(problem.kind !== 'lean-task' ||
readLeanTaskReceipt(problem.activeProblemPath).environmentDigest !==
libraryCatalog.identity.environmentDigest)
)
throw new Error('math_library_catalog_environment_changed');
const continuationIdentity = { taskDigest: mathDigest(task), problemReceiptDigest: problem.receiptDigest };
const continuationInput = values['continuation-manifest']
? readContinuationInput(values['continuation-manifest'], continuationIdentity)
: undefined;
let continuation: ContinuationSnapshot | undefined;
const worktree = path.join(directory, 'worktree');
const profileArgument = values['harness-profile'] ?? resumedState?.agentHarness?.profile;
const profile = profileArgument
? fs.realpathSync(profileArgument)
: process.env.CODEX_HOME || path.join(os.homedir(), '.config/deepscientist/math-sol-codex');
const usesBuiltInCodex = modules.M1.open === directRuntimeModules.M1.open;
const selectedProfile = selectedProviderProfile(
profile,
usesBuiltInCodex ? [DEEPSEEK_PROVIDER.id, SUB2API_PROVIDER.id, WESTLAKE_PROVIDER.id] : [WESTLAKE_PROVIDER.id],
);
const codexWestlake = selectedProfile?.id === WESTLAKE_PROVIDER.id;
const providerProfile = usesBuiltInCodex ? selectedProfile : undefined;
const sharedTeamRun =
delegationMode === 'team' && (!values.resume || resumedState?.agentTeam?.transport === 'codex-shared');
const westlakeTeamError =
WESTLAKE_NATIVE_TEAM_UNSUPPORTED + ': select a native-compatible Codex profile such as the Responses gateway.';
if (!values.resume && codexWestlake && sharedTeamRun) throw new Error(westlakeTeamError);
const preparedEnvironment = prepareSolverRuntimeEnvironment(process.env);
let { environment: env, corpusFile, corpusBytes, corpus } = preparedEnvironment;
const { mathTools } = preparedEnvironment;
const executable =
values['harness-executable'] ??
values.codex ??
resumedState?.agentHarness?.executable ??
(process.env.DEEPSCIENTIST_MATH_CODEX_EXECUTABLE || 'codex');
const pinHarness =
(publicRun && !values.resume && specified('codex')) ||
specified('harness-executable') ||
specified('harness-profile') ||
Boolean(resumedState?.agentHarness) ||
sharedTeamRun;
const agentHarness = pinHarness ? bindResearchHarness('codex', executable, profile) : undefined;
const assertHarnessCurrent = agentHarness ? () => assertResearchHarnessCurrent(agentHarness) : undefined;
const knowledge = values['knowledge-base']
? readAuthorizedKnowledgeCatalog(
values['knowledge-base'],
workspace,
values['receipt-file'] || path.join(workspace, 'active-problem.json'),
)
: undefined;
const skillFile = path.join(root, 'skills/theoremos-research/SKILL.md');
const loadedSkill = skillMode ? readMathAgentSkill(skillFile, skillLoading as 'native' | 'file') : undefined;
const researchSkill = loadedSkill && researchSkillIdentity(loadedSkill);
const savedTeam = resumedState?.researchDelegation;
const requestedProfiles =
values['skill-preferred-profiles']?.split(',') ??
(savedTeam?.mode === 'team' ? savedTeam.preferredProfiles : undefined);
const preferredProfiles =
delegationMode === 'team' && requestedProfiles
? getPreferredAgentTeamProfiles(loadedSkill!, requestedProfiles)
: undefined;
const personalExperts =
values['skill-expert-cards-file'] !== undefined
? readPersonalExperts(values['skill-expert-cards-file'])
: savedTeam?.mode === 'team'
? savedTeam.personalExperts
: undefined;
const researchDelegation: SolverRunState['researchDelegation'] =
delegationMode === 'team'
? {
mode: 'team',
maxAgents,
...(preferredProfiles?.length ? { preferredProfiles } : {}),
...(personalExperts && { personalExperts }),
}
: undefined;
const compactSoloResearch = resumedState
? resumedState.compactSoloResearch
: publicRun && skillMode && !delegationMode && !specified('skill-loading');
const sessionSkill = compactSoloResearch ? undefined : loadedSkill;
const plannedSession = planMathAgentSession({
skills: sessionSkill ? [sessionSkill] : undefined,
completedOutput: !sharedTeamRun,
});
const identity = {
taskDigest: continuationIdentity.taskDigest,
buildDigest,
providerProfile: providerProfile?.profile,
providerProfileDigest: providerProfile?.digest,
environmentDigest: preparedEnvironment.environmentDigest,
evaluatorDigest: mathDigest(values['evaluator-command'] || 'host-default'),
model,
effort: resumedState && !effortSpecified ? resumedState.effort : values.effort!,
methodDigest: solverMethodDigest(modules, coordination),
knowledgeDigest: knowledge?.digest,
libraryCatalogDigest: libraryCatalog ? libraryCatalog.identity.catalogDigest : undefined,
};
// Generation prepares its own proof environment; do not freeze solver worktree mounts into its resumable identity.
const explanationEnv = env;
const explainAccepted = async (state: SolverRunState, result: Record<string, unknown>, worktree: string) => {
const previous = result.explanations as SolverExplanations | undefined;
const language =
(values['explanation-language'] as 'zh' | 'en' | undefined) ?? (previous?.language === 'en' ? 'en' : 'zh');
const explanationDirectory = path.join(directory, 'explanations', language);
const publish = (summary: SolverExplanations) => {
lease.assertOwned();
result.explanations = summary;
writeMathJsonDurable(output, result);
};
try {
if (values['no-explanations']) {
if (!previous) publish({ status: 'disabled', language, directory: explanationDirectory, targets: [] });
return;
}
cancelPreparation();
await disposeProofEnvironment();
const { generateSolverExplanations } = await import('./automaticExplanations');
await generateSolverExplanations({
problem: state.problem,
worktree,
directory,
root,
buildManifest: buildFile,
language,
writer: {
model: state.model,
effort: state.effort,
profile: agentHarness?.profile ?? profile,
executable: agentHarness?.executable ?? executable,
...(agentHarness ? { agentHarness } : {}),
},
env: explanationEnv,
signal,
onEvent: emit,
onUpdate: publish,
});
} catch {
// The accepted result was saved first. A generation or persistence error never invalidates that proof.
const failed = result.explanations as SolverExplanations | undefined;
const reason = 'automatic_explanation_failed';
if (!values['no-explanations'] && (!failed || failed.status === 'running')) {
const status = signal.aborted ? 'stopped' : 'error';
try {
publish({
status,
language,
directory: explanationDirectory,
targets: (failed?.targets ?? []).map(target =>
target.status === 'pending' || target.status === 'running' ? { ...target, status, reason } : target,
),
});
} catch {
/* Keep the already-persisted accepted proof result. */
}
}
emit('explanation_failed', { reason, output });
}
};
const moduleConfiguration = solverModuleConfiguration(modules);
let state: SolverRunState;
let sourceFeedback: string | undefined;
let leadSkill: WorkerAccess['researchSkill'];
const prepareSkill = (worktree: string) => {
const expected = state.researchSkill;
return expected && prepareResearchSkill(root, worktree, expected, state.problem);
};
if (values.resume) {
state = resumedState!;
if (values['no-original-tactics'] && state.originalTacticsEnabled)
throw new Error('math_resume_original_tactics_changed');
const canContinueSeed =
state.phase === 'prepared' &&
state.turns === 0 &&
state.solveStartedAt === undefined &&
state.solveFinishedAt === undefined;
continuationSourceRun =
canContinueSeed && state.pendingContinuationSource
? continuationSourceStateFile(state.pendingContinuationSource)
: undefined;
assertProofWriterStopped(state);
const frozen = frozenRunConfiguration(state, {
agentHarness,
researchMode,
researchSkill,
researchDelegation,
plannedSession,
coordination,
planApproval,
workspace,
receiptDigest: problem.receiptDigest,
worktree,
identity,
hostLibrary: Boolean(problem.libraryBinding?.hostConfiguration),
legacyMethod: defaultRuntimeConfigurations.has(modules) && coordination === 'cooperative',
});
if (!tokenLimitSpecified) maxTotalTokens = frozen.tokenLimit;
if (frozen.restoreMethod) state.methodDigest = identity.methodDigest;
if (state.continuationDigest) {
continuation = readContinuationSnapshot(
path.join(directory, 'continuation.json'),
state.continuationDigest,
continuationIdentity,
);
if (continuationInput && continuationInput.digest !== state.continuationDigest)
throw new Error('math_resume_continuation_changed');
} else if (continuationInput) throw new Error('math_resume_continuation_changed');
// A repeated flag may identify an interrupted seed or a seed that already finished in startup-only mode.
const frozenContinuationSource =
continuationSourceRun ??
continuation?.manifest.attachments.find(item => item.id === 'seed-canonical')?.provenance.source;
if (requestedContinuationSource && requestedContinuationSource !== frozenContinuationSource)
throw new Error('math_resume_continuation_changed');
// Use the current authoritative receipt instead of trusting nested archived source policy.
state.problem = problem;
leadSkill = prepareSkill(state.worktree);
sourceFeedback = solverSourceFeedback(state.problem, state.worktree);
assertSolverSources(state.problem, workspace);
if (state.phase === 'finished' && fs.existsSync(output)) {
const result = readMathJson(output) as Record<string, unknown> & {
status: string;
runId: string;
solution_commit: string;
};
if (result.status === 'evaluated_passed' || result.status === 'evaluated_failed') {
assertSolverSources(state.problem, state.worktree);
if (
!state.check?.passed ||
result.runId !== state.runId ||
result.solution_commit !== state.check.commit ||
!solverProofIsCurrent(state.problem, state.worktree, state.check) ||
!solverProofIsCurrent(state.problem, workspace, state.check)
)
throw new Error('math_resume_completed_proof_changed');
if (result.status === 'evaluated_passed' && !values['startup-only'])
await explainAccepted(state, result, state.worktree);
return result.status === 'evaluated_passed' ? 0 : 2;
}
}
if (codexWestlake && sharedTeamRun) throw new Error(westlakeTeamError);
// Older runtimes could record a new seed request on a run that was already underway.
if (state.pendingContinuationSource && !continuationSourceRun) {
delete state.pendingContinuationSource;
lease.assertOwned();
writeSolverRunState(stateFile, state);
}
} else {
if (fs.existsSync(stateFile) || fs.existsSync(output)) throw new Error('math_run_exists_use_resume');
if (git(workspace, ['status', '--porcelain', '--untracked-files=no']))
throw new Error('math_workspace_has_uncommitted_sources');
if (continuationInput) continuation = freezeContinuationInput(continuationInput, directory);
ownsRun = true;
state = {
schema: 'deepscientist.math.solver.v1',
runId: crypto.randomUUID(),
problem,
...identity,
...(agentHarness ? { agentHarness } : {}),
agentSessionPlan: plannedSession,
...(compactSoloResearch && { compactSoloResearch: true as const }),
...(researchSkill ? { researchMode: 'skill', researchSkill, researchSkillWorkflow: 'full' } : {}),
...(skillMode &&
!values['no-original-tactics'] &&
!delegationMode &&
!continuation &&
!continuationSourceRun &&
!customModules &&
!values['module-plan']
? { originalTacticsEnabled: true as const }
: {}),
...(researchDelegation ? { researchDelegation } : {}),
...(sharedTeamRun
? {
agentTeam: {
schema: 'theorem-os.agent-team.v1' as const,
transport: 'codex-shared' as const,
workers: [],
events: [],
deliveries: [],
adoptions: [],
operations: [],
},
}
: {}),
...(continuation ? { continuationDigest: continuation.digest } : {}),
...(continuationSourceRun ? { pendingContinuationSource: continuationSourceRun } : {}),
worktree,
phase: 'prepared',
turns: 0,
dispatchCounts: {},
workerCount: 1,
coordination,
...(planApproval ? { planApproval } : {}),
moduleConfiguration,
tokenBudget: buildTokenBudget(
maxTotalTokens,
[],
usesBuiltInCodex && codexWestlake ? 'provider-observed-upstream-request-limit' : undefined,
),
};
git(workspace, ['worktree', 'add', '--detach', state.worktree, problem.baseCommit]);
writeSolverRunState(stateFile, state);
leadSkill = prepareSkill(state.worktree);
}
ownsRun = true;
ownedState = state;
if (state.agentTeam?.transport === 'codex-shared')
state.agentTeam.hostLimits = { maxTurns: Number.isFinite(maxTurns) ? maxTurns : null, maxTotalTokens };
state.tokenBudget = buildTokenBudget(maxTotalTokens, [state], state.tokenBudget?.enforcement);
const save = () => {
lease.assertOwned();
writeSolverRunState(stateFile, state);
};
const sourceProject = path.join(workspace, problem.projectRelative);
const sourcePackages = resolveMathematicsLakePackagesCache(sourceProject, env);
if (!sourcePackages) {
const manifestFile = path.join(sourceProject, 'lake-manifest.json');
const manifest = fs.existsSync(manifestFile)
? (readMathJson(manifestFile) as { packages?: unknown })
: undefined;
if (Array.isArray(manifest?.packages) && manifest.packages.length) {
emit('preparation_failed', {
workerId: 'solver',
diagnostics:
'No manifest-compatible Lake package cache is configured. Supply a trusted cache with the pinned Git revisions; sandboxed verification never downloads dependencies.',
});
throw new Error('math_lake_packages_unavailable');
}
}
const project = prepareWorkerProject(state.worktree, state.problem);
if (sourcePackages) bindLeanPackages(project, sourcePackages);
if (!values.resume) sourceFeedback = solverSourceFeedback(state.problem, state.worktree);
if (sourceFeedback) {
state.check = undefined;
save();
}
if (values['startup-only'] && !autoLibrary?.leanOnly) {
const connectivity = usesBuiltInCodex
? await checkCodexProviderConnectivity({ env, signal, profile })
: {
status: 'not-required',
diagnostics: 'The custom execution component does not use the built-in Codex provider.',
};
writeMathJsonDurable(path.join(directory, 'provider-connectivity.json'), connectivity);
if (connectivity.status === 'unavailable') {
emit('preparation_failed', { workerId: 'solver', diagnostics: connectivity.diagnostics });
throw new Error('math_codex_provider_unreachable');
}
}
const preparedLean = await prepareSolverLean({
problem,
project,
sourcePackages,
env,
signal,
deadlineAt: preparationDeadline,
directory,
cacheRoot: values['proof-environment-cache-dir'],
checkStatement: values['check-statement'],
checkPreparedSources: modules.M2.checkPreparedSources,
emit,
});
env = preparedLean.env;
proofEnvironment = preparedLean.proofEnvironment;
let corpusCreated = false;
if (!corpusFile && sourcePackages && fs.existsSync(path.join(sourcePackages, 'mathlib', 'Mathlib'))) {
corpusFile = path.join(project, '.lake', 'retrieval-corpus.json');
if (!fs.existsSync(corpusFile)) {
if (state.retrievalDigest) throw new Error('math_corpus_identity_changed');
emit('library_index', { phase: 'creating', package: 'mathlib' });
corpus = await createMathRetrievalCorpus(project, ['mathlib']);
corpusCreated = true;
signal.throwIfAborted();
writeMathJsonDurable(corpusFile, corpus);
}
corpusBytes = Buffer.from(readMathText(corpusFile), 'utf8');
corpus ??= JSON.parse(corpusBytes.toString('utf8')) as MathRetrievalCorpus;
const digest = mathDigest(corpusBytes);
if (state.retrievalDigest && state.retrievalDigest !== digest) throw new Error('math_corpus_identity_changed');
state.retrievalDigest = digest;
save();
env = {
...env,
DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS: corpusFile,
DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS_SHA256: digest,
};
}
const retrievalRoot = corpus?.projectSubdirectory ? state.worktree : project;
if (corpusFile) {
if (
corpus?.projectSubdirectory &&
corpus.projectSubdirectory !== state.problem.projectRelative.replaceAll(path.sep, '/')
)
throw new Error('math_corpus_project_mismatch');
// Creation already verifies every frozen source; persisted inputs need a fresh check.
if (!corpusCreated) assertMathRetrievalCorpus(retrievalRoot, corpus);
emit('library_index', { phase: 'ready', sourceFiles: corpus!.sources.length });
}
assertHostProblemCurrent();
const installedLibrary = readInstalledLibrarySnapshot(problem, state.environmentDigest);
const knowledgeSnapshot =
knowledge &&
indexKnowledgeContextSnapshot({
digest: knowledge.digest,
base: {
entries: knowledge.base.entries,
evidence: knowledge.base.evidence,
contexts: knowledge.base.contexts,
routeFindings: knowledge.base.routeFindings,
},
});
const knowledgeFile = knowledge && path.join(project, '.lake', 'theorem-knowledge.json');
if (knowledge && knowledgeFile) {
if (knowledge.base.libraryAuthorization)
readAuthorizedKnowledgeCatalog(values['knowledge-base']!, workspace, receiptFile, knowledge.digest);
copyKnowledgeSnapshot(knowledge, values['knowledge-base']!, knowledgeFile);
}
// Continuation seeding checks the frozen solver environment before replaying saved helpers.
const environmentFile = path.join(directory, 'environment-solver.json');
const environment = {
...env,
DEEPSCIENTIST_MATH_ENV_FILE: environmentFile,
DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS: corpusFile,
};
writeMathJsonDurable(environmentFile, projectMathematicsRuntimeEnvironment(environment), 0o400);
if (continuationSourceRun) {
try {
await seedSingleSolverContinuation({
sourceRun: continuationSourceRun,
run: stateFile,
root,
buildManifest: buildFile,
buildScope: 'runtime',
signal,
lease,
preparedEnvironment: env,
timeoutMs: maxRunMs === Infinity ? Infinity : Math.max(1, preparationDeadline - Date.now()),
deferChecks: values['startup-only'],
onProgress: emit,
onSeeded: (seeded, snapshot) => {
state = ownedState = seeded;
continuation = snapshot;
},
});
} catch (error) {
// The seed can save resumable progress before handing over the new state.
ownedState = readSolverRunState(stateFile);
throw error;
}
}
const worktreeContinuation = continuation && copyContinuationSnapshot(continuation, project);
const leadAccess: WorkerAccess = {
environment: resolveMathematicsRuntimeEnvironment(environment),
corpusFile,
...(assertHarnessCurrent ? { assertHarnessCurrent } : {}),
...(leadSkill ? { researchSkill: leadSkill } : {}),
retrievalRoot,
...(mathTools ? { mathTools } : {}),
...(installedLibrary ? { installedLibrary } : {}),
...(libraryCatalog
? {
libraryCatalog: {
file: path.resolve(values['library-catalog']!),
digest: libraryCatalog.identity.catalogDigest,
},
}
: {}),
...(worktreeContinuation ? { continuation: worktreeContinuation } : {}),
...(problem.libraryBinding?.hostConfiguration
? {
assertKnowledgeCurrent: () => {
if (knowledge) readAuthorizedKnowledgeCatalog(knowledgeFile!, workspace, receiptFile, knowledge.digest);
else assertHostProblemCurrent();
},
}
: {}),
...(knowledge ? { knowledgeFile, knowledgeDigest: knowledge.digest, knowledgeSnapshot } : {}),
};
emit('ready', {
runId: state.runId,
worktree: state.worktree,
workers: [{ id: 'solver', role: 'lead', worktree: state.worktree, ownedFiles: state.problem.ownedFiles }],
});
emit('preparation_finished', {
durationMs: Date.now() - preparationStarted,
dependencies: preparedLean.dependencies,
});
if (values['startup-only']) {
writeMathJsonDurable(output, {
schema: 'deepscientist.math.run.v2',
runId: state.runId,
problemId: state.problem.contract.problemId,
status: 'prepared',
startup_only: true,
evaluator: { status: 'skipped' },
stateFile,
});
return 0;
}
signal.throwIfAborted();
cancelPreparation();
preparing = false;
state.solveStartedAt = Date.now();
state.solveFinishedAt = undefined;
state.solveWaitingMs = 0;
const deadline = state.solveStartedAt + maxRunMs;
const clock = (executionClock = new ExecutionDeadline(maxRunMs, abort));
const executionBudget = {
remainingMs: () => clock.remainingMs(),
setWaiting: (waiting: boolean) => {
const previous = clock.waiting;
clock.setWaiting(waiting);
state.solveWaitingMs = clock.waitingMs();
if (previous !== clock.waiting)
emit(clock.waiting ? 'plan_approval_wait_started' : 'plan_approval_wait_ended');
},
};
emit('solve_started', { budgetMs: maxRunMs, maxTurnMs });
const winner = await withVerificationCheckpoints(
{
environmentDigest: state.environmentDigest,
problemReceiptDigest: state.problem.receiptDigest,
checkpoints: (state.verificationCheckpoints ??= []),
save,
emit,
},
() =>
runResearchLead({
drive: owner?.drive,
state,
access: leadAccess,
modules,
root,
buildFile,
taskText: task,
executable: agentHarness?.executable ?? executable,
profile,
signal,
deadline,
executionBudget,
maxTurns,
maxTurnMs,
maxTotalTokens,
proofTimeoutMs,
save,
emit,
}),
);
clock.stop();
state.solveWaitingMs = clock.waitingMs();
state.solveFinishedAt = Date.now();
let evaluation: Record<string, unknown> = { status: 'skipped', reason: 'proof_incomplete' };
if (winner?.check.passed) {
state.phase = 'evaluating';
save();
readBuildDigest(buildDigest);
const evaluationStarted = Date.now();
emit('evaluation_started', { workerId: state.winningWorker ?? 'solver' });
evaluation = await evaluateSolverProof(state.problem, winner.check, env, signal, {
command: values['evaluator-command'],
timeoutMs: evaluatorMs,
});
emit('evaluation_finished', { status: evaluation.status, durationMs: Date.now() - evaluationStarted });
}
state.phase = 'finished';
save();
const { status, code } = (owner?.conclude ?? concludeRun)({
aborted: signal.aborted,
evaluation: String(evaluation.status),
limited: Boolean(state.tokenBudget?.reason),
});
const result = {
...runResultFields(stateFile, state, clock),
status,
run_outcome: status,
solution_commit: state.check?.passed ? state.check.commit : null,
solver_ready_receipt_valid: state.check?.passed === true,
completion_signal_valid: evaluation.status === 'passed',
evaluator: evaluation,
...(status === 'runtime_error' && typeof evaluation.reason === 'string' ? { reason: evaluation.reason } : {}),
...(status === 'limit_reached' && state.tokenBudget?.reason ? { reason: state.tokenBudget.reason } : {}),
winningWorker: state.winningWorker,
};
writeMathJsonDurable(output, result);
if (status === 'evaluated_passed') await explainAccepted(state, result, winner!.worktree);
emit('finished', { status, output });
return code;
};
try {
const code = await execute();
await disposeProofEnvironment();
publishedExit = code;
return code;
} catch (error) {
// Cleanup remains under the run lock; preserve the execution error if cleanup also fails.
try {
await disposeProofEnvironment();
} catch {
/* The original failure controls the checkpoint. */
}
if (!ownsRun) {
reportRejection(error);
return 1;
}
lease.assertOwned();
const checkpoint = error instanceof VerificationCheckpointError;
const libraryRequest = error instanceof LibraryInstallationRequested ? error : undefined;
executionClock?.stop();
const stopped = controller.signal.aborted;
const limited = stopped || checkpoint;
const status = limited ? 'limit_reached' : libraryRequest ? 'library_requested' : 'runtime_error';
const errorReason = error instanceof Error ? error.message : 'math_runtime_error';
if (ownedState) {
// A zero-turn continuation can retry any preparation step, including
// snapshot distribution and startup-only output after the seed handoff.
if (!(preparing && continuationSourceRun && ownedState.phase === 'prepared')) ownedState.phase = 'finished';
if (ownedState.solveStartedAt && !ownedState.solveFinishedAt) ownedState.solveFinishedAt = Date.now();
if (executionClock) ownedState.solveWaitingMs = executionClock.waitingMs();
ownedState.error = status === 'runtime_error' ? errorReason : undefined;
const verification = verifierFailureDiagnostic(error);
if (verification) ownedState.verifierFailure = verification;
writeSolverRunState(stateFile, ownedState);
}
writeMathJsonDurable(output, {
...runResultFields(stateFile, ownedState, executionClock),
status,
run_outcome: status,
reason: stopped ? (preparing ? 'math_preparation_stopped' : 'math_run_stopped') : errorReason,
...(libraryRequest
? { libraryRequest: { request: libraryRequest.request, worktree: libraryRequest.worktree } }
: {}),
evaluator: { status: 'skipped' },
});
publishedExit = limited ? 4 : 1;
emit('finished', { status, output, ...(error instanceof MathGitError ? { git: error.diagnostic } : {}) });
return publishedExit;
}
};
let outcome: Awaited<ReturnType<typeof runWithLease>>;
try {
outcome = await withMathRuntimeLease(
{
lockPath: path.join(directory, 'run.lock'),
flockExecutable: '/usr/bin/flock',
signal: controller.signal,
inheritedDescriptor: owner?.lockDescriptor,
},
runWithLease,
);
} catch (error) {
// The lease has ended. A cancelled operation can already have published its final checkpoint.
if (publishedExit !== undefined) return publishedExit;
reportRejection(error);
return controller.signal.aborted ? 4 : 1;
} finally {
executionClock?.stop();
cancelPreparation();
hostSignal?.removeEventListener('abort', hostAbort);
process.removeListener('SIGINT', abort);
process.removeListener('SIGTERM', abort);
}
if (typeof outcome === 'number') return outcome;
throw outcome.configurationError;
}