Repository navigation
Expand file tree
/
Copy pathresearch.ts
More file actions
1272 lines (1270 loc) · 54.8 KB
/
Copy pathresearch.ts
File metadata and controls
1272 lines (1270 loc) · 54.8 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
998
999
1000
import path from 'node:path';
import fs from 'node:fs';
import crypto from 'node:crypto';
import { setTimeout as delay } from 'node:timers/promises';
import { VerificationCheckpointError } from './verificationCheckpoint';
import type { MathAgentFailureDiagnostic, MathAgentSession } from '../runtime/agentSession';
import { safeFailureDiagnostic } from '../runtime/failureDiagnostic';
import { confirmHarnessProcessStopped } from '../runtime/harnessProcess';
import { VerifierFailureError, verifierFailureDiagnostic } from './verifierFailure';
import { readMathBuildManifest } from '../math/mathBuildManifest';
import { MathGitError } from '../math/mathGit';
import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mathRuntimeIo';
import type { SolverRunState } from './archive';
import { commitSolverSources, committedSource, git, pinSolverResearchSkill } from './problem';
import { tryOriginalProofByTactics } from './originalProofTactics';
import { createResearchTurnCheckpoint, type ResearchTurnCheckpointReason } from './researchTurnCheckpoint';
import {
waitForPlanApproval,
sharedTeamPlanTool,
nativeApprovalPlanBrief,
nativePlanApprovalSchema,
planApprovalStatus,
publishNativeApprovalPlan,
} from './planApproval';
import { LeanEnvironmentHealthCheckError } from '../runtime/leanHealthCheck';
import { rememberSolverFailure, solverSourceFeedback } from './feedback';
import type { RuntimeSolverModules } from './modules/runtime';
import { solverProofIsCurrent, type ProofCheck } from './modules/evidence';
import { finalizeResearchDispatch, type ContextBundle } from './modules/context';
import type { KnowledgeContextSnapshot } from './knowledgeContext';
import type { ResearchOperation } from './modules/value';
import { type ResearchCandidate } from './modules/execution';
import {
planResearchCooldown,
researchCooldownWait,
recoverableResearchFailure,
researchFailureDetail,
researchFailureReason,
} from './modules/search';
import { buildTokenBudget, initializeUsageAccounting, modelDispatchAllowed } from './usageBudget';
import { driveResearch, type ResearchDriver, type DispatchOutcome, type SettlementOutcome } from './researchLoop';
import { ResearchUsage } from './researchUsage';
import { inspectKnowledgeUses, type KnowledgeUse } from './knowledgeUsage';
import { checkKnowledgeApplications } from './knowledgeApplications';
import { parseMathResponse } from './deliveries';
import { readCheckpointNotesDigest, savedContextCheckpoint } from './contextCheckpoint';
import type { ContinuationSnapshot } from './continuationInput';
import type { MathTools } from '../math/mathTools';
import { checkTaskProof } from './cooperativeProof';
import { writeOwnedDeclarationIndex } from './declarationIndex';
import { applyOriginalLibraryTasks } from './libraryApplication';
import {
LibraryInstallationRequested,
takeLibraryRequest,
writeLibraryAccess,
type LibraryAccess,
} from './libraryAccess';
import { prepareTacticBatteryFailureCacheRoot } from './tacticBatteryFailureCache';
import { SingleSolverProofHandoff, type SingleSolverProofSubmission } from './singleSolverProofHandoff';
import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../runtime/agentSkills';
import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContext';
import { assertProofWriterStopped, recordUnconfirmedWriterStartup, stopProofWriter } from './proofWriter';
import { createSkillProofLifecycle, originalProofHasHoles, savedProofCanResume } from './skillProofLifecycle';
import { DECLARATION_SUBMISSION_FILE } from './declarationArtifacts';
import { softSliceSettings, type SoftSliceSettings } from './softSlice';
import { materializeResearchToolHelp } from './researchToolHelp';
import { assertActiveResearchState } from './researchRetirement';
import { researchLeanHealthCheck, researchToolRoots } from './researchToolGuide';
export type WorkerAccess = {
environment: NodeJS.ProcessEnv;
corpusFile?: string;
retrievalRoot: string;
/** Execution-only credentials are never projected into host Lean or saved environment records. */
assertHarnessCurrent?: () => void;
/** Commands with no native conversation must receive the full original task on every invocation. */
researchSkill?: MathAgentSkill;
continuation?: ContinuationSnapshot;
mathTools?: MathTools;
assertKnowledgeCurrent?: () => void;
installedLibrary?: KnowledgeContextSnapshot;
libraryCatalog?: LibraryAccess;
knowledgeFile?: string;
knowledgeDigest?: string;
knowledgeSnapshot?: KnowledgeContextSnapshot;
};
/** Run the Lead writer and connect any native team members to the same proof budget. */
export async function runResearchLead(input: {
state: SolverRunState;
access: WorkerAccess;
modules: RuntimeSolverModules;
root: string;
buildFile: string;
taskText: string;
executable: string;
profile: string;
signal: AbortSignal;
deadline: number;
maxTurns: number;
maxTurnMs: number;
maxTotalTokens: number;
proofTimeoutMs?: number;
executionBudget?: { remainingMs(): number; setWaiting(waiting: boolean): void };
softSlice?: SoftSliceSettings;
drive?: ResearchDriver;
save: () => void;
emit: (event: string, details?: Record<string, unknown>) => void;
}): Promise<{ worktree: string; check: ProofCheck } | undefined> {
const { state, access, modules, save } = input;
const milestoneSettings = softSliceSettings(input.softSlice ?? {});
const { worktree, problem } = state;
const workerId = 'solver';
const worker = { id: workerId, role: 'lead' as const, worktree, ownedFiles: problem.ownedFiles };
assertActiveResearchState(state);
assertProofWriterStopped(state);
const skillMode = state.researchMode === 'skill';
const fullSkillWorkflow = skillMode && state.researchSkillWorkflow === 'full';
const sessionSkill = state.compactSoloResearch ? undefined : access.researchSkill;
const sharedTeam = state.agentTeam?.transport === 'codex-shared';
const nativePlanReview = state.planApproval && state.researchDelegation?.mode === 'team';
const mayStartProofWork = () => !nativePlanReview || planApprovalStatus(state) === 'approved';
const sharedPlanningTools =
sharedTeam && nativePlanReview
? {
definitions: [sharedTeamPlanTool],
call: async (_name: string, args: unknown) =>
publishNativeApprovalPlan(state, nativePlanApprovalSchema.parse(args), save, input.emit),
}
: undefined;
if (
nativePlanReview &&
planApprovalStatus(state) === 'approved' &&
state.cooperation?.planApproval?.approvedVersion !== state.cooperation?.planVersion
)
throw new Error('math_plan_approval_version_conflict');
if (skillMode && !state.researchSkill) throw new Error('math_skill_research_state_invalid');
if (
state.pendingProofCheck &&
(!skillMode ||
state.pendingProofCheck.environmentDigest !== state.environmentDigest ||
state.pendingProofCheck.problemReceiptDigest !== problem.receiptDigest)
)
throw new Error('math_proof_checkpoint_identity_changed');
if (
state.pendingResearchFreeze &&
(!skillMode ||
state.pendingResearchFreeze.environmentDigest !== state.environmentDigest ||
state.pendingResearchFreeze.problemReceiptDigest !== problem.receiptDigest)
)
throw new Error('math_research_freeze_identity_changed');
if (state.researchDelegation && !skillMode) throw new Error('math_native_delegation_requires_skill');
if (skillMode) {
const skill = access.researchSkill;
const identity = state.researchSkill;
if (!skill || !identity || skill.digest !== identity.digest || skill.loading !== identity.loading)
throw new Error('math_research_skill_changed');
pinSolverResearchSkill(problem, worktree, skill);
}
initializeUsageAccounting(state);
const enforcement = state.tokenBudget?.enforcement;
state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [state], enforcement);
const dispatchAllowed = () => modelDispatchAllowed(state.tokenBudget!);
if (
savedProofCanResume(state, !nativePlanReview || planApprovalStatus(state) === 'approved') &&
state.check &&
!solverSourceFeedback(problem, worktree) &&
solverProofIsCurrent(problem, worktree, state.check)
) {
if (state.pendingProofCheck) {
if (
state.pendingProofCheck.commit !== state.check.commit ||
state.pendingProofCheck.sourceDigest !== state.check.sourceDigest
)
throw new Error('math_proof_checkpoint_identity_changed');
state.pendingProofCheck = undefined;
save();
}
return { worktree, check: state.check };
}
if (state.check?.passed) {
state.check = undefined;
state.winningWorker = undefined;
save();
}
if (
state.originalTacticsEnabled &&
!state.originalTacticAttempt &&
!state.continuationDigest &&
state.phase === 'prepared' &&
state.turns === 0 &&
!state.threadId
) {
const started = Date.now();
const remaining = input.executionBudget?.remainingMs() ?? input.deadline - started;
const timeoutMs = Math.min(5_000, input.proofTimeoutMs ?? Infinity, Math.floor(remaining / 10));
const sourcePaths = problem.ownedFiles.map(file => path.join(problem.projectRelative, file));
const sourcesClean = () => !git(worktree, ['status', '--porcelain', '--', ...sourcePaths]);
if (timeoutMs > 0 && sourcesClean()) {
const head = git(worktree, ['rev-parse', 'HEAD']);
input.emit('original_tactics_started', { timeoutMs });
const check = await tryOriginalProofByTactics({
problem,
worktree,
env: access.environment,
signal: input.signal,
timeoutMs,
});
input.signal.throwIfAborted();
if (check?.passed && sourcesClean() && git(worktree, ['rev-parse', 'HEAD']) === head) {
git(worktree, ['merge', '--ff-only', '--no-edit', check.commit]);
if (!solverProofIsCurrent(problem, worktree, check)) throw new Error('math_original_tactics_source_changed');
state.phase = 'checking';
state.check = check;
state.originalTacticAttempt = { durationMs: Date.now() - started, commit: check.commit };
save();
input.emit('original_tactics_finished', { ...state.originalTacticAttempt, passed: true });
input.emit('candidate_selected', { workerId, commit: check.commit, method: 'original_tactics' });
return { worktree, check };
}
state.originalTacticAttempt = { durationMs: Date.now() - started };
save();
input.emit('original_tactics_finished', { ...state.originalTacticAttempt, passed: false });
}
}
const controller = new AbortController();
const signal = controller.signal;
const abort = () => controller.abort();
input.signal.addEventListener('abort', abort, { once: true });
if (input.signal.aborted) abort();
const budget = () => ({
maxTurns: input.maxTurns,
remainingMs: input.executionBudget?.remainingMs() ?? Math.max(0, input.deadline - Date.now()),
aborted: signal.aborted,
});
let winner: { worktree: string; check: ProofCheck } | undefined;
const turnTiming = sharedTeam
? teamTurnTiming(input.maxTurnMs)
: { turnTimeoutMs: Number.isFinite(input.maxTurnMs) ? input.maxTurnMs : undefined };
const updateUsage = () => {
const previous = state.tokenBudget!.status;
const next = (state.tokenBudget = buildTokenBudget(input.maxTotalTokens, [state], enforcement));
if (next.status !== previous && !modelDispatchAllowed(next)) input.emit('model_budget_stopped', { ...next });
};
let failure: { error: unknown } | undefined;
let cleanupFailure: { error: unknown } | undefined;
state.error = undefined;
try {
let session: MathAgentSession | undefined;
let sessionInstructions: string | undefined;
let closing: Promise<void> | undefined;
let retries = 0;
let lastCheck: ProofCheck | undefined;
const emit = (event: string, details = {}) => input.emit(event, { workerId, ...details });
const singleHandoff = sharedTeam
? undefined
: new SingleSolverProofHandoff(
problem,
worktree,
submission => emit('proof_ready_checkpoint_requested', { ...submission, reason: 'current-lean-diagnostics' }),
skillMode ? details => emit('lean_stall_detected', details) : undefined,
);
const sourceFeedback = () => solverSourceFeedback(problem, worktree);
const recovered = () => {
const recovery = state.recovery;
if (!recovery || recovery.phase === 'recovered') return;
recovery.phase = 'recovered';
recovery.recoveredAt = Date.now();
emit('worker_recovered', { reason: recovery.reason, cycles: recovery.cycles, waitedMs: recovery.waitedMs });
save();
};
const waitForRecovery = async (resumed = false) => {
const recovery = state.recovery;
if (recovery?.phase !== 'cooling-down') return;
const started = Date.now();
const delayMs = researchCooldownWait(
recovery.nextRetryAt,
started,
dispatchAllowed(),
state.turns - Number(reservedTurn),
input.maxTurns,
budget().remainingMs,
);
if (delayMs === undefined) return;
signal.throwIfAborted();
if (resumed)
emit('worker_recovery_resumed', {
reason: recovery.reason,
cycle: recovery.cycles,
delayMs,
nextRetryAt: recovery.nextRetryAt,
});
try {
if (delayMs > 0) await delay(delayMs, undefined, { signal });
signal.throwIfAborted();
recovery.phase = 'retrying';
} finally {
recovery.waitedMs += Math.max(0, Date.now() - started);
save();
}
};
const context = (feedback?: string, previousCheck?: ProofCheck, previousFailures = state.failures) => {
access.assertKnowledgeCurrent?.();
if (access.libraryCatalog) writeLibraryAccess(problem, worktree, access.libraryCatalog);
const contextAccess = {
root: input.root,
worktree,
taskText: input.taskText,
...access,
...(modules.M4.tools ? { tools: modules.M4.tools } : {}),
sourceFeedback: feedback,
previousCheck,
previousFailures,
maxOptionalContextBytes: state.contextOverflow?.maxOptionalContextBytes,
...(skillMode ? { executionLimits: { ...turnTiming, remainingRunMs: () => budget().remainingMs } } : {}),
};
const currentContext =
skillMode && !fullSkillWorkflow
? buildSkillResearchContext(problem, state, { ...contextAccess, researchSkill: access.researchSkill! })
: modules.M4.build(problem, state, contextAccess);
materializeResearchToolHelp(currentContext, worktree);
return { ...currentContext };
};
let feedbackCheck: ProofCheck | undefined;
let feedbackFailures = state.failures;
let reservedTurn = false;
let activeCheckpoint: ReturnType<typeof createResearchTurnCheckpoint> | undefined;
let explicitCompaction = false,
contextUsageVersion = 0,
compactedUsageVersion = -1;
let sessionHasHistory = false;
let turnContext: { digest: string; fresh: boolean } | undefined;
let dispatched: { responsibility: string; threadId: string } | undefined;
const usage = new ResearchUsage({
state,
research: state,
signal,
remainingMs: () => budget().remainingMs,
changed: () => {
updateUsage();
save();
},
emit,
});
const failureDetail = (error: unknown, sessionError?: string, diagnostic?: MathAgentFailureDiagnostic) =>
researchFailureDetail(error, sessionError, diagnostic, usage.stopReason);
const locallyStopped = (detail?: string) => usage.stopReason !== undefined && detail === usage.stopReason;
const checkpointNotesDigest = () => readCheckpointNotesDigest(worktree);
const currentCheckpointNotesDigest = () => savedContextCheckpoint(state, worktree);
const contextCheckpointInstruction =
'Before further searches or experiments, save the exact current argument, ' +
'attempted methods, useful declaration and file references, and the unresolved inference in RESEARCH.md.';
const requestContextCheckpoint = (lastInputTokens: number) => {
const threadId = state.threadId;
if (!threadId || (state.contextCheckpoint?.threadId === threadId && state.contextCheckpoint.requestId))
return false;
state.contextCheckpoint = {
threadId,
requestId: crypto.randomUUID(),
requestedAt: Date.now(),
notesDigest: checkpointNotesDigest(),
};
emit('context_checkpoint_requested', { threadId, reason: 'context-threshold', lastInputTokens });
save();
return true;
};
const reserveTurn = () => {
if (!dispatchAllowed() || state.turns >= input.maxTurns || budget().remainingMs <= 0 || signal.aborted)
return false;
// Reserve before session startup. Return the slot if the turn never starts.
reservedTurn = true;
state.turns++;
state.phase = 'running';
save();
return true;
};
/** Return a reserved but unstarted turn to the shared budget; false when none was reserved. */
const unreserveTurn = () => {
if (!reservedTurn) return false;
state.turns--;
reservedTurn = false;
return true;
};
const close = async () => {
if (!session) {
await closing;
return;
}
const current = session,
closingSessionId = usage.sessionId;
session = undefined;
try {
closing = current.close();
await closing;
if (
sharedTeam &&
current.processIdentity &&
confirmHarnessProcessStopped(current.processIdentity).status === 'stopped'
) {
state.writerProcess = undefined;
save();
}
} catch (error) {
cleanupFailure ??= { error };
throw error;
} finally {
usage.sessionClosed(closingSessionId);
}
};
const stopWriter = (current: MathAgentSession, submission?: SingleSolverProofSubmission) =>
stopProofWriter({
session: current,
record: state,
workerId,
close,
save,
deferred: reason => emit('proof_ready_freeze_deferred', { ...submission, reason }),
confirmed: reason => emit('proof_ready_freeze_confirmed', { ...submission, reason }),
});
const cancel = () => {
void close().catch(() => {});
};
signal.addEventListener('abort', cancel, { once: true });
const rememberSessionThread = (threadId: string) => {
if (state.threadId === threadId) return false;
state.contextCheckpointBaseline = { threadId, notesDigest: checkpointNotesDigest() };
state.threadId = threadId;
return true;
};
const openResearchSession = async (instructions: string): Promise<'ready' | DispatchOutcome> => {
const project = path.join(worktree, problem.projectRelative);
while (!session) {
signal.throwIfAborted();
if (!dispatchAllowed() || budget().remainingMs <= 0) return 'stopped';
try {
const sessionId = crypto.randomUUID();
const resumingThread = state.threadId;
const usageCallbacks = usage.bindSession(sessionId, () => session?.lastInputTokens);
if (usageCallbacks.requestGate)
usageCallbacks.requestGate.checkpoint = () =>
Boolean(sharedTeam && nativePlanReview && planApprovalStatus(state) === 'pending') ||
(activeCheckpoint?.atRequestBoundary() ?? false);
access.assertHarnessCurrent?.();
session = await modules.M1.open({
executable: input.executable,
profile: input.profile,
...(sessionSkill ? { skills: [sessionSkill] } : {}),
...(sharedTeam
? {
sharedProofTeam: {
capacity: state.researchDelegation!.mode === 'team' ? state.researchDelegation!.maxAgents : 1,
requireMetering: input.maxTotalTokens > 0,
},
isolateProcess: true,
leanHealthCheck: researchLeanHealthCheck(input.root, project, modules.M4.tools),
...(!mayStartProofWork() ? { readOnlyWorkspace: true, tools: sharedPlanningTools } : {}),
}
: {}),
hiddenRoots: [prepareTacticBatteryFailureCacheRoot()],
soloProofWorkspace: !sharedTeam,
readableRoots: researchToolRoots(input.root, modules.M4.tools),
proofProjectRoot: project,
...(singleHandoff ? { completedOutput: singleHandoff.output } : {}),
workspace: worktree,
environment: {
...access.environment,
DEEPSCIENTIST_MATH_WORKER_ID: workerId,
DEEPSCIENTIST_MATH_WORKER_WORKTREE: worktree,
},
model: state.model,
effort: state.effort,
threadId: state.threadId,
...turnTiming,
instructions,
onActivity: activity => {
state.lastActivity = { ...activity, at: Date.now() };
emit('worker_activity', { activity: activity.event, itemType: activity.itemType });
if (activity.event === 'lean_environment_ready')
emit('lean_environment_ready', { workerId, health: activity.health });
activeCheckpoint?.onActivity(activity);
},
...usageCallbacks,
onUsage: (value, context) => {
usageCallbacks.onUsage(value, context);
if (!explicitCompaction) contextUsageVersion++;
},
});
if (
state.agentSessionPlan &&
session.executionPlan &&
canonicalMathJson(state.agentSessionPlan) !== canonicalMathJson(session.executionPlan)
)
throw new Error('math_agent_session_plan_changed');
usage.sessionOpened(session);
sessionHasHistory = Boolean(resumingThread && resumingThread === session.threadId);
if (sharedTeam && session.processIdentity) {
state.writerProcess = session.processIdentity;
save();
}
} catch (error) {
if (recordUnconfirmedWriterStartup(state, error, save)) throw error;
signal.throwIfAborted();
if (error instanceof LeanEnvironmentHealthCheckError)
emit('lean_environment_unavailable', { workerId, health: error.health });
const detail = failureDetail(error);
if (!recoverableResearchFailure(detail)) throw error;
await retryFailedTurn(detail);
if (researchFailureReason(detail) === 'math_model_context_window_exceeded') return 'rebuild';
}
}
if (signal.aborted) {
await close();
signal.throwIfAborted();
}
sessionInstructions = instructions;
if (session.threadId) {
rememberSessionThread(session.threadId);
save();
}
return 'ready';
};
const beginTurn = async (
currentContext: ContextBundle,
operation: ResearchOperation,
): Promise<'ready' | DispatchOutcome> => {
// A new session validates its launch inputs immediately before opening, including retries.
if (session) access.assertHarnessCurrent?.();
usage.resetTurn();
turnContext = {
digest: mathDigest(
canonicalMathJson({
instructions: currentContext.instructions,
operation,
problem: problem.receiptDigest,
environment: state.environmentDigest,
model: state.model,
optionalBytes: state.contextOverflow?.maxOptionalContextBytes ?? currentContext.manifest?.maxOptionalBytes,
sources: problem.ownedFiles.map(file => [
file,
mathDigest(fs.readFileSync(path.join(worktree, problem.projectRelative, file))),
]),
}),
),
fresh: !state.threadId,
};
if (turnContext.fresh && state.contextOverflow?.failedFreshContextDigests.includes(turnContext.digest))
throw new Error('math_model_context_capacity_blocked');
writeOwnedDeclarationIndex(problem, worktree);
if (currentContext.manifest) {
state.lastContextManifest = currentContext.manifest;
writeMathJsonDurable(path.join(worktree, 'CONTEXT-MANIFEST.json'), currentContext.manifest);
emit('context_compiled', {
contentDigest: currentContext.manifest.contentDigest,
requiredTaskIds: currentContext.manifest.requiredTaskIds,
included: currentContext.manifest.included.length,
omitted: currentContext.manifest.omitted.length,
usedBytes: currentContext.manifest.usedBytes,
mandatoryBytes: currentContext.manifest.mandatoryBytes,
optionalBytes: currentContext.manifest.optionalBytes,
maxOptionalBytes: currentContext.manifest.maxOptionalBytes,
maxBytes: currentContext.manifest.maxBytes,
});
}
if (!reserveTurn()) return 'stopped';
if (currentContext.knowledgeRetrievals?.length && currentContext.manifest) {
const ledger = (state.knowledgeRetrievals ??= { dropped: 0, observations: [] });
for (const retrieval of currentContext.knowledgeRetrievals) {
const observation = {
...retrieval,
workerId,
workerTurn: state.turns,
runTurn: state.turns,
contextDigest: currentContext.manifest.contentDigest,
at: Date.now(),
};
ledger.observations.push(observation);
emit('knowledge_retrieval_observed', { ...observation });
}
const excess = Math.max(0, ledger.observations.length - 128);
ledger.observations.splice(0, excess);
ledger.dropped += excess;
save();
}
const opened = session ? 'ready' : await openResearchSession(currentContext.instructions);
if (opened === 'stopped') return opened;
if (opened === 'rebuild' || (await maintainContext())) {
// Recompile the turn after recovering from an overflow or changing thread history.
if (unreserveTurn()) save();
return 'rebuild';
}
return dispatchAllowed() ? 'ready' : 'stopped';
};
const retryFailedTurn = async (error?: string, diagnostic?: MathAgentFailureDiagnostic): Promise<void> => {
state.lastFailure = {
at: Date.now(),
reason: researchFailureReason(error, diagnostic),
...(diagnostic ? { diagnostic: safeFailureDiagnostic(diagnostic) } : {}),
};
save();
if (!dispatchAllowed()) return;
if (researchFailureReason(error) === 'math_model_context_window_exceeded') {
const overflow = (state.contextOverflow ??= { maxOptionalContextBytes: 0, failedFreshContextDigests: [] });
overflow.maxOptionalContextBytes = 0;
if (turnContext?.fresh && !overflow.failedFreshContextDigests.includes(turnContext.digest))
overflow.failedFreshContextDigests.push(turnContext.digest);
await rotateSession('context');
retries = 0;
emit('worker_context_recovering', {
reason: state.lastFailure.reason,
contextDigest: turnContext?.digest,
maxOptionalContextBytes: 0,
});
save();
return;
}
const retry = modules.M3.retry(error, retries, { ...state, turns: state.turns - Number(reservedTurn) }, budget());
if (!retry) {
const previous = state.recovery?.phase !== 'recovered' ? state.recovery : undefined;
const cooldown = retries >= 3 ? planResearchCooldown(error, previous?.cycles ?? 0, budget()) : undefined;
if (!cooldown) throw new Error(researchFailureReason(error));
await rotateSession('request');
const now = Date.now();
state.recovery = {
phase: 'cooling-down',
reason: cooldown.reason,
cycles: cooldown.cycle,
startedAt: previous?.startedAt ?? now,
nextRetryAt: now + cooldown.delayMs,
waitedMs: previous?.waitedMs ?? 0,
};
emit('worker_cooling_down', {
reason: cooldown.reason,
cycle: cooldown.cycle,
delayMs: cooldown.delayMs,
nextRetryAt: state.recovery.nextRetryAt,
});
save();
await waitForRecovery();
retries = 0;
return;
}
retries = retry.attempt;
// Close failed writers before rotating the thread.
if (
state.threadId &&
(retry.reason === 'math_model_tool_failed' ||
(retry.reason === 'math_model_request_failed' && retries === 2) ||
(retries === 1 && ['math_model_request_timeout', 'math_codex_transport_closed'].includes(retry.reason)))
)
await rotateSession('request');
emit('worker_recovering', { reason: retry.reason, attempt: retries, delayMs: retry.delayMs });
emit('turn_retry', {
reason: retry.reason,
attempt: retries,
delayMs: retry.delayMs,
...(error?.startsWith('math_codex_transport_closed:') ? { detail: error } : {}),
});
await delay(retry.delayMs, undefined, { signal });
};
const rotateSession = async (reason: 'context' | 'request') => {
dispatched = undefined;
sessionInstructions = undefined;
const previous = state.threadId;
await close();
if (previous) state.previousThreadIds = [...(state.previousThreadIds ?? []), previous];
state.threadId = undefined;
state.lastInputTokens = undefined;
state.contextCheckpoint = undefined;
state.contextCheckpointBaseline = undefined;
sessionHasHistory = false;
compactedUsageVersion = -1;
state.usageBeforeThread = state.usage;
save();
emit('context_restarted', { previousThreadId: previous, turns: state.turns, reason });
};
const maintainContext = async (): Promise<boolean> => {
if (skillMode || !state.threadId) return false;
const threadId = state.threadId;
const notesDigest = currentCheckpointNotesDigest();
if (session && !sessionHasHistory) return false;
const lastInputTokens = Math.max(session?.lastInputTokens ?? 0, state.lastInputTokens ?? 0);
if (!notesDigest && (!session || lastInputTokens < 96_000)) return false;
// Wait for new usage or saved notes before asking for native compaction again.
if (session?.compact && compactedUsageVersion === contextUsageVersion && !notesDigest) return false;
if (notesDigest) emit('context_checkpoint_ready', { threadId, notesDigest });
if (session?.compact) {
const startedAt = Date.now();
emit('context_compaction_requested', { threadId, lastInputTokens });
usage.beginMaintenance();
explicitCompaction = true;
try {
await session.compact();
signal.throwIfAborted();
dispatched = undefined;
compactedUsageVersion = contextUsageVersion;
state.contextCheckpoint = undefined;
state.contextCheckpointBaseline = { threadId, notesDigest: checkpointNotesDigest() };
state.lastInputTokens = session.lastInputTokens;
emit('context_compaction_completed', { threadId, maintenanceMs: Date.now() - startedAt });
save();
return true;
} catch (error) {
signal.throwIfAborted();
emit('context_compaction_failed', { threadId, reason: failureDetail(error) });
} finally {
explicitCompaction = false;
usage.finishMaintenance();
}
}
await rotateSession('context');
return true;
};
const recordKnowledgeUses = (uses: readonly KnowledgeUse[], commit: string) => {
const records = (state.knowledgeUses ??= []);
for (const use of uses) {
const record = { ...use, workerId, commit };
const key = canonicalMathJson(record);
if (records.some(previous => canonicalMathJson(previous) === key)) continue;
records.push(record);
emit('knowledge_use_observed', { ...record });
}
};
const checkWhole = async (candidate = state.candidate) => {
const previousFailures = state.failures;
const checkStarted = Date.now();
emit('proof_check_started', { turn: state.turns });
const check = (state.check = await modules.M2.check(
problem,
worktree,
access.environment,
signal,
lastCheck,
input.proofTimeoutMs,
));
state.failures = rememberSolverFailure(check, previousFailures);
const reused = check === lastCheck || check.verification === lastCheck?.verification;
emit('proof_checked', {
passed: check.passed,
commit: check.commit,
reused,
durationMs: Date.now() - checkStarted,
});
if (access.knowledgeSnapshot || access.installedLibrary) {
let claims: unknown;
try {
claims = parseMathResponse(
committedSource(worktree, check.commit, 'RESEARCH.md'),
'math-result',
{},
'summary',
).knowledgeUses;
} catch {
/* Ordinary notes need no usage response. */
}
const records = (state.knowledgeUses ??= []);
for (const [index, target] of problem.targets.entries()) {
const task = {
id: `original_goal_${index + 1}`,
kind: 'goal' as const,
objective: `Prove ${target.theoremName}`,
revision: 0,
dependsOn: [],
...target,
};
const observed = inspectKnowledgeUses(claims, access.knowledgeSnapshot, task, check, access.installedLibrary);
const checked = await checkKnowledgeApplications(observed.uses, {
task,
projectRoot: path.join(worktree, problem.projectRelative),
env: access.environment,
environmentDigest: state.environmentDigest,
commit: check.commit,
signal,
timeoutMs: input.proofTimeoutMs ?? Infinity,
originalContexts: problem.targets,
previous: records,
sourceAtCommit: file =>
committedSource(worktree, check.commit, path.posix.join(problem.projectRelative, file)),
});
recordKnowledgeUses(checked, check.commit);
if (observed.rejected) emit('knowledge_use_rejected', { commit: check.commit, rejected: observed.rejected });
}
if (records.length > 256) records.splice(0, records.length - 256);
}
lastCheck = check;
save();
if (check.passed) {
state.candidate = candidate;
winner = { worktree, check };
save();
emit('candidate_selected', { commit: check.commit });
abort();
return;
}
if (['unavailable', 'blocked'].includes(check.verification.status))
throw new VerifierFailureError({
stage: 'solver-proof-check',
sourceCommit: check.commit,
verification: check.verification,
});
};
const skillProofLifecycle = skillMode
? createSkillProofLifecycle({
state,
worktree,
environment: access.environment,
skill: access.researchSkill!,
signal,
proofTimeoutMs: input.proofTimeoutMs,
writerStopped: () => !session && !state.writerStopUnconfirmed,
checkHelpers: !sharedTeam,
sourceFeedback,
checkWhole,
save,
emit,
})
: undefined;
const resumeSkillProofWork = async () => {
if (!mayStartProofWork()) return;
await skillProofLifecycle?.resumePending();
};
let deliveredApprovedPlan = false;
let liveDraft = false;
type DispatchedTurn = {
candidate: ResearchCandidate;
operation: ResearchOperation;
turnSession: MathAgentSession;
executionError?: string;
checkpointReason?: ResearchTurnCheckpointReason;
};
type ProofTurn = { candidate: ResearchCandidate; turnError?: string; diagnostic?: MathAgentFailureDiagnostic };
const dispatchTurn = async (): Promise<DispatchedTurn | DispatchOutcome> => {
if (
!skillMode &&
state.threadId &&
state.contextCheckpoint?.threadId === state.threadId &&
!state.contextCheckpoint.requestId
)
requestContextCheckpoint(Math.max(session?.lastInputTokens ?? 0, state.lastInputTokens ?? 0));
await maintainContext();
const options: readonly ResearchOperation[] = ['direct'];
const action =
skillMode && !fullSkillWorkflow
? { operation: 'direct' as const, reason: 'continue' as const }
: modules.M3.select(state, options, budget());
if (action.operation === 'stop') return 'stopped';
const operation = action.operation;
if (!options.includes(action.operation)) throw new Error('math_research_operation_unavailable');
emit('research_action', { operation: action.operation, reason: action.reason });
readMathBuildManifest(input.buildFile, input.root, path.join(input.root, 'out', 'main'), 'runtime');
const onStarted = (turnId: string) => {
// Some headless CLIs report a native ID only after starting. Persist that exact
// identity before publishing a turn; an empty ID cannot stand for a saved thread.
const threadId = session?.threadId;
if (!threadId) throw new Error('math_agent_session_binding_missing');
if (rememberSessionThread(threadId)) save();
emit('turn_started', { turnId, threadId, turn: state.turns, totalTurns: state.turns });
};
const repair = sourceFeedback();
if (repair) state.check = undefined;
const currentContext = context(repair, feedbackCheck, feedbackFailures);
const responsibility = skillMode ? mathDigest(currentContext.instructions) : undefined;
const continuation =
responsibility !== undefined &&
dispatched?.responsibility === responsibility &&
Boolean(state.threadId) &&
dispatched.threadId === state.threadId &&
currentContext.continuationMessage !== undefined;
const checkpointInstruction =
state.threadId && state.contextCheckpoint?.threadId === state.threadId && !currentCheckpointNotesDigest()
? contextCheckpointInstruction
: undefined;
Object.assign(currentContext, finalizeResearchDispatch(currentContext, { continuation, checkpointInstruction }));
if (nativePlanReview && !deliveredApprovedPlan) {
const approval = state.cooperation?.planApproval;
currentContext.message =
(mayStartProofWork()
? `The human approved plan version ${approval!.approvedVersion}. Begin proof research and coordinate the native team. Approved route:\n` +
nativeApprovalPlanBrief(state.cooperation!.tasks)
: 'This turn is for planning only. Read the frozen statement and publish one concrete route objective for each original theorem ' +
'through theoremos_team publish_plan. You may include investigations for unresolved steps. Do not write proofs or dispatch agents yet. ' +
'The workspace is read-only except .scratch. Save any planning notes there, then return as soon as the host records the proposal.') +
'\n\n' +
currentContext.message;
}
if (session && sessionInstructions !== currentContext.instructions) await close();
const admission = await beginTurn(currentContext, operation);
if (admission !== 'ready') return admission;
const turnSession = session!;
let candidate: ResearchCandidate;
let executionError: string | undefined;
let checkpoint: ReturnType<typeof createResearchTurnCheckpoint> | undefined;
try {
if (!dispatchAllowed() || budget().remainingMs <= 0 || signal.aborted) return 'stopped';
const kind = mayStartProofWork() ? 'proof' : 'planning';
const counts = (state.dispatchCounts ??= {});
counts[kind] = (counts[kind] ?? 0) + 1;
reservedTurn = false;
usage.begin();
let completed = false;
try {
const turnCheckpoint = createResearchTurnCheckpoint({
session: turnSession,
signal,
milestone:
kind === 'proof'
? { settings: milestoneSettings, mode: sharedTeam ? 'team' : skillMode ? 'skill' : 'legacy' }
: undefined,
// Only existing runs with pinned edit probes use a speculative checker.
savedEdit:
state.savedEditChecks && !sharedTeam && skillMode
? {
problem,
worktree,
env: access.environment,
timeoutMs: Math.min(5_000, input.proofTimeoutMs ?? Infinity),
}
: undefined,
isCurrent: () => session === turnSession,
close,
onCompaction: () => {
dispatched = undefined;
},
failureDetail,
emit,
});
checkpoint = activeCheckpoint = turnCheckpoint;
candidate = await modules.M1.execute(
problem,
currentContext,
operation,
worker,
turnSession,
signal,
turnId => {
if (nativePlanReview && mayStartProofWork()) deliveredApprovedPlan = true;
dispatched =
responsibility === undefined ? undefined : { responsibility, threadId: turnSession.threadId };
emit('context_dispatched', {
mode: continuation ? 'continuation' : 'full',
threadId: turnSession.threadId,
messageBytes: Buffer.byteLength(currentContext.message),
messageDigest: mathDigest(currentContext.message),
compiledContentDigest: currentContext.manifest?.contentDigest,
});
onStarted(turnId);
turnCheckpoint.start(turnId);
},
);
const detail = failureDetail(undefined, turnSession.lastError, turnSession.lastFailureDiagnostic);
if (usage.stopReason && detail !== usage.stopReason) throw new Error(detail);
completed = candidate.status === 'completed';
if (completed) recovered();
} finally {
activeCheckpoint = undefined;
try {
await checkpoint?.finish(completed);
} finally {
usage.finish(completed);
}
}
} catch (error) {
signal.throwIfAborted();
executionError = failureDetail(error, turnSession.lastError, turnSession.lastFailureDiagnostic);
if (
!checkpoint?.reason &&
!(nativePlanReview && planApprovalStatus(state) === 'pending') &&
!recoverableResearchFailure(executionError) &&
!locallyStopped(executionError)
)
throw error;
candidate = {
status: 'failed',
worktree,
problemReceiptDigest: problem.receiptDigest,
operation,
provenance: { workerId, threadId: turnSession.threadId },
};
}
return { candidate, operation, turnSession, executionError, checkpointReason: checkpoint?.reason };
};
const settleTurn = async ({
candidate,
operation,
turnSession,
executionError,
checkpointReason,
}: DispatchedTurn): Promise<ProofTurn | SettlementOutcome> => {
const reason =
checkpointReason ??
(candidate.status !== 'failed' && currentCheckpointNotesDigest()
? 'math_context_scheduling_checkpoint'
: undefined);
if (reason) candidate = { ...candidate, status: 'checkpoint' };
const lastInputTokens = session?.lastInputTokens;
sessionHasHistory = true;
const diagnostic = safeFailureDiagnostic(session?.lastFailureDiagnostic);
const turnError = executionError ?? failureDetail(session?.lastError, undefined, diagnostic);
if (!mayStartProofWork()) {
// The planner's response never becomes a proof candidate. Stop its process before
// pausing the execution clock and wait in the host, outside any model turn.