Repository navigation
Expand file tree
/
Copy pathsearch.ts
More file actions
901 lines (874 loc) · 36.2 KB
/
Copy pathsearch.ts
File metadata and controls
901 lines (874 loc) · 36.2 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
import type { SolverRunState } from '../archive';
import type { MathAgentFailureDiagnostic } from '../../runtime/failureDiagnostic';
import type { ModelRequestStopReason } from '../../runtime/modelRequest';
import { canonicalMathJson, mathDigest } from '../../math/mathRuntimeIo';
import type { ResearchOperation } from './value';
import { proofRouteReady, type ProofRoute } from '../proofRoutes';
import { createRecordedTaskSettlement } from '../progress';
import { createProofRoutePriority } from '../routePriority';
import { automaticTaskConnection, freshTaskConnection } from '../taskConnections';
import {
allRoutesParked,
assumableLemma,
checkedUnconditionally,
groupOpen,
isAdvisoryTask,
isFeasibilityReview,
isFinalCandidateReview,
openRoutes,
taskGroup,
taskReferenceDependencies,
taskVersion,
type TaskRecord,
type RouteRecord,
type CooperativeAction,
} from '../tasks';
export type ResearchBudget = Readonly<{ maxTurns: number; remainingMs: number; aborted: boolean }>;
export type ActionPlan = Readonly<{
operation: ResearchOperation | 'stop';
reason: 'continue' | 'budget-exhausted' | 'no-operation';
}>;
/** Select dependency-ready work; worker identities belong to M5. */
export function routeAllowsTask(
task: TaskRecord['task'],
tasks: readonly TaskRecord[],
groups?: readonly RouteRecord[],
): boolean {
if ((task.status ?? 'active') !== 'active') return false;
const node = tasks.find(node => node.task.id === task.id);
if (node && (node.pendingValidation || node.routeParking?.length || allRoutesParked(node))) return false;
if (!groups) return true;
const route = groups.find(record => record.group.id === taskGroup(task));
return (
groupOpen(route) &&
(route.busy ?? tasks.filter(node => node.status === 'running' && taskGroup(node.task) === route.group.id).length) <
(route.group.maxConcurrent ?? 3)
);
}
function dispatchRouteReady(route: ProofRoute, tasks: readonly TaskRecord[]) {
if (!proofRouteReady(route, tasks)) return false;
const nodes = new Map(tasks.map(node => [node.task.id, node])),
visited = new Set<string>();
const available = (id: string): boolean => {
if (visited.has(id)) return true;
visited.add(id);
const node = nodes.get(id);
return Boolean(
node &&
!node.pendingValidation &&
(taskReferenceDependencies(node)?.map(reference => reference.taskId) ?? node.task.dependsOn).every(available),
);
};
return [route.closingTaskId, ...route.prerequisiteTaskIds].every(available);
}
/** Select one OR branch; ordinary dependsOn remains an AND requirement. */
export function selectedTaskRoute(
node: TaskRecord,
tasks: readonly TaskRecord[],
priority?: ReturnType<typeof createProofRoutePriority>,
): ProofRoute | undefined {
if (!node.alternativeRoutes?.length) return;
const assigned = node.alternativeRoutes?.find(route => route.id === node.assignment?.routeId);
const recoveringFailure = node.status === 'blocked' && node.feedback?.startsWith('math_task_repeated_failed_input\n');
// Keep the route fixed during proof and delivery. A blocked failure can
// reconsider its inputs when a freshly checked route is available.
if (assigned && node.status !== 'pending' && !recoveringFailure) return assigned;
const routes = openRoutes(node),
ready = routes.filter(route => dispatchRouteReady(route, tasks));
const readyRoute = ready.find(route => route.id === assigned?.id) ?? ready[0];
if (readyRoute || (recoveringFailure && assigned)) return readyRoute ?? assigned;
const compare = (priority ?? createProofRoutePriority(tasks)).compareRoutes;
const ranked = routes.toSorted(
(a, b) => compare(a, b) || Number(b.id === node.assignment?.routeId) - Number(a.id === node.assignment?.routeId),
);
return ranked[0];
}
export function plannedTaskDependencyIds(node: TaskRecord, tasks: readonly TaskRecord[]): readonly string[] {
const route = selectedTaskRoute(node, tasks);
return route
? [...new Set([...node.task.dependsOn, ...route.prerequisiteTaskIds, route.closingTaskId])]
: node.task.dependsOn;
}
/** The same transitive inputs are used by dispatch, proof checking and continuation. */
export function taskDependencyRecords(task: TaskRecord['task'], tasks: readonly TaskRecord[]): TaskRecord[] {
const nodes = new Map(tasks.map(node => [node.task.id, node]));
const found = new Set<string>();
const ids = (node: TaskRecord) =>
taskReferenceDependencies(node)?.map(reference => reference.taskId) ?? plannedTaskDependencyIds(node, tasks);
const visit = (id: string) => {
if (found.has(id)) return;
const node = nodes.get(id);
if (!node) throw new Error('math_plan_dependency_missing');
found.add(id);
ids(node).forEach(visit);
};
const node = nodes.get(task.id);
(node?.task === task ? ids(node) : task.dependsOn).forEach(visit);
return [...found].map(id => nodes.get(id)!);
}
/** Memoization lasts only for this selection; mutable task state never enters a global cache. */
function taskReadiness(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]) {
const nodes = new Map(tasks.map(node => [node.task.id, node]));
const checked = new Map<TaskRecord['task'], boolean>(),
available = new Map<string, boolean>();
const versions = new Map<TaskRecord['task'], string>();
const version = (task: TaskRecord['task']) => {
if (!versions.has(task)) versions.set(task, taskVersion(task));
return versions.get(task)!;
};
const dependenciesReady = (task: TaskRecord['task']): boolean => {
if (checked.has(task)) return checked.get(task)!;
checked.set(task, false); // Cyclic or malformed restored plans fail closed.
const node = nodes.get(task.id);
if (node?.pendingValidation) return false;
const references = node?.task === task ? taskReferenceDependencies(node) : undefined;
const dependencies = references ?? task.dependsOn.map(taskId => ({ taskId }));
const ready =
dependencies.every(reference => {
const dependency = nodes.get(reference.taskId);
return Boolean(
dependency &&
(!('taskDigest' in reference) || reference.taskDigest === version(dependency.task)) &&
['integrated', 'completed'].includes(dependency.status) &&
dependenciesReady(dependency.task),
);
}) &&
(!node?.alternativeRoutes?.length ||
Boolean(references) ||
node.status === 'integrated' ||
openRoutes(node).some(route => dispatchRouteReady(route, tasks)));
checked.set(task, ready);
return ready;
};
const dependencyAvailable = (id: string): boolean => {
if (available.has(id)) return available.get(id)!;
available.set(id, false);
const dependency = nodes.get(id);
const ready = Boolean(
dependency &&
!dependency.pendingValidation &&
(['integrated', 'completed'].includes(dependency.status) || assumableLemma(dependency.task)) &&
dependency.task.dependsOn.every(dependencyAvailable),
);
available.set(id, ready);
return ready;
};
const canStart = (task: TaskRecord['task']): boolean => {
if (isFinalCandidateReview(task)) return false; // These are requests for the fixed-candidate Reviewer.
const node = nodes.get(task.id);
if (
node?.pendingValidation ||
(node?.alternativeRoutes?.length && !openRoutes(node).some(route => dispatchRouteReady(route, tasks)))
)
return false;
return (
isAdvisoryTask(task) ||
dependenciesReady(task) ||
Boolean(
(task.conditional || automaticTaskConnection(task, tasks, groups)) && task.dependsOn.every(dependencyAvailable),
)
);
};
return { dependenciesReady, canStart };
}
export function taskDependenciesReady(task: TaskRecord['task'], tasks: readonly TaskRecord[]): boolean {
return taskReadiness(tasks).dependenciesReady(task);
}
/** A dependency wait is productive only when every missing premise reaches a current host-owned activity. */
export function runningTaskDependencies(
node: TaskRecord,
tasks: readonly TaskRecord[],
activeTaskIds: ReadonlySet<string>,
): string[] | undefined {
const nodes = new Map(tasks.map(item => [item.task.id, item]));
const running = new Set<string>(),
visiting = new Set<string>();
const visit = (current: TaskRecord): boolean => {
if (visiting.has(current.task.id)) return false;
if (['integrated', 'completed'].includes(current.status) && taskDependenciesReady(current.task, tasks)) return true;
if (activeTaskIds.has(current.task.id)) {
running.add(current.task.id);
return true;
}
visiting.add(current.task.id);
const references = taskReferenceDependencies(current);
const ids = references?.map(ref => ref.taskId) ?? plannedTaskDependencyIds(current, tasks);
const valid =
ids.length > 0 &&
ids.every(id => {
const dependency = nodes.get(id),
reference = references?.find(ref => ref.taskId === id);
return Boolean(
dependency && (!reference || reference.taskDigest === taskVersion(dependency.task)) && visit(dependency),
);
});
visiting.delete(current.task.id);
return valid;
};
// The waiting task itself is not a dependency, even if stale restored state labels it running.
const references = taskReferenceDependencies(node);
const ids = references?.map(ref => ref.taskId) ?? plannedTaskDependencyIds(node, tasks);
if (
!ids.length ||
!ids.every(id => {
const dependency = nodes.get(id),
reference = references?.find(ref => ref.taskId === id);
return Boolean(
dependency && (!reference || reference.taskDigest === taskVersion(dependency.task)) && visit(dependency),
);
}) ||
!running.size
)
return;
return [...running];
}
/** Fixed lemma statements can be assumed while constructing a conditional parent. */
export function taskCanStart(
task: TaskRecord['task'],
tasks: readonly TaskRecord[],
groups?: readonly RouteRecord[],
): boolean {
return taskReadiness(tasks, groups).canStart(task);
}
export function readyResearchTasks(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]): TaskRecord[] {
const readiness = taskReadiness(tasks, groups);
const priority = createProofRoutePriority(tasks, { groups });
const checked = new Set(tasks.filter(checkedUnconditionally).map(node => node.task.id));
const groupRecords = groups && new Map(groups.map(record => [record.group.id, record]));
const consumed = new Set(
tasks
.filter(node => {
if (
isAdvisoryTask(node.task) ||
node.status === 'integrated' ||
(node.task.status ?? 'active') !== 'active' ||
node.routeParking?.length ||
allRoutesParked(node)
)
return false;
return !groupRecords || groupOpen(groupRecords.get(taskGroup(node.task)));
})
.flatMap(node => [
...node.task.dependsOn,
...openRoutes(node).flatMap(route => [...route.prerequisiteTaskIds, route.closingTaskId]),
]),
);
const rank = (node: TaskRecord) =>
isAdvisoryTask(node.task) || !readiness.dependenciesReady(node.task)
? 0
: node.task.kind === 'goal'
? 2
: consumed.has(node.task.id) && node.task.dependsOn.some(id => checked.has(id))
? 1
: 0;
const ready = tasks.filter(
node => node.status === 'pending' && routeAllowsTask(node.task, tasks, groups) && readiness.canStart(node.task),
);
const compare = (a: TaskRecord, b: TaskRecord) => rank(b) - rank(a) || priority.compareTasks(a, b);
const ranked = ready.toSorted(compare);
// A yielded investigation must not repeatedly hide equally ranked, untried work.
// Reorder advisory slots within one priority tier first. A pairwise advisory-only
// tie-break would be non-transitive across proof tasks.
for (let start = 0; start < ranked.length;) {
let end = start + 1;
while (end < ranked.length && compare(ranked[start], ranked[end]) === 0) end++;
const advisory = ranked
.slice(start, end)
.filter(node => isAdvisoryTask(node.task))
.toSorted((a, b) => a.attempts - b.attempts);
let next = 0;
for (let index = start; index < end; index++)
if (isAdvisoryTask(ranked[index].task)) ranked[index] = advisory[next++];
// A resumed investigation also yields to executable inputs of planned proofs.
// Keep fresh investigations and conditional drafts in their existing slots.
const sharesProofSlot = (node: TaskRecord) =>
isAdvisoryTask(node.task)
? node.attempts > 0
: Boolean(node.task.type?.trim() && consumed.has(node.task.id) && readiness.dependenciesReady(node.task));
const proofWork = ranked
.slice(start, end)
.filter(sharesProofSlot)
.toSorted((a, b) => Number(isAdvisoryTask(a.task)) - Number(isAdvisoryTask(b.task)));
let nextProof = 0;
for (let index = start; index < end; index++)
if (sharesProofSlot(ranked[index])) ranked[index] = proofWork[nextProof++];
start = end;
}
return prioritizeEarlyRouteChecks(ranked, tasks, groups);
}
/** Offer one fresh route check before investing in its still-unproved inputs. */
function prioritizeEarlyRouteChecks(
ready: TaskRecord[],
tasks: readonly TaskRecord[],
groups?: readonly RouteRecord[],
): TaskRecord[] {
if (
tasks.some(
node =>
node.status === 'running' &&
(isFeasibilityReview(node.task) ||
((node.task.conditional || node.assignment?.connectionCheck) && !node.proof)),
)
)
return ready;
const review = ready.find(node => !node.attempts && isFeasibilityReview(node.task));
const bridge = ready.find(
node =>
freshTaskConnection(node, tasks, groups) &&
!isAdvisoryTask(node.task) &&
node.task.dependsOn.some(id =>
tasks.some(input => input.task.id === id && input.task.kind === 'lemma' && input.status !== 'integrated'),
) &&
(node.task.kind === 'goal' ||
tasks.some(
consumer =>
consumer.task.dependsOn.includes(node.task.id) ||
consumer.alternativeRoutes?.some(route => route.closingTaskId === node.task.id),
)),
);
const check = review ?? bridge;
if (!check) return ready;
const readiness = taskReadiness(tasks, groups);
const consuming = ready
.slice(0, ready.indexOf(check))
.filter(
node =>
!isAdvisoryTask(node.task) &&
readiness.dependenciesReady(node.task) &&
(node.task.kind === 'goal' ||
node.task.dependsOn.some(id => checkedUnconditionally(tasks.find(candidate => candidate.task.id === id)))),
);
return [...consuming, check, ...ready.filter(node => node !== check && !consuming.includes(node))];
}
/** The scripts/mathematics/runGoalsFirst.ts extension example: prefer ready original goals, preserving all readiness gates. */
export function goalsFirstResearchTasks(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]): TaskRecord[] {
return prioritizeEarlyRouteChecks(
readyResearchTasks(tasks, groups).toSorted(
(a, b) => Number(b.task.kind === 'goal') - Number(a.task.kind === 'goal'),
),
tasks,
groups,
);
}
/** Unit-cost dependency depth is a scheduling heuristic, not a proof-time estimate. */
export function criticalPathResearchTasks(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]): TaskRecord[] {
const unfinished = new Map(
tasks
.filter(
node =>
!['integrated', 'completed'].includes(node.status) &&
!isFinalCandidateReview(node.task) &&
(node.task.status ?? 'active') === 'active' &&
(!groups || groupOpen(groups.find(record => record.group.id === taskGroup(node.task)))),
)
.map(node => [node.task.id, node]),
);
const consumers = new Map<string, string[]>();
for (const node of unfinished.values())
for (const id of [
...node.task.dependsOn,
...(node.alternativeRoutes?.flatMap(route => [...route.prerequisiteTaskIds, route.closingTaskId]) ?? []),
]) {
const list = consumers.get(id) ?? [];
list.push(node.task.id);
consumers.set(id, list);
}
type Priority = { depth: number; goals: Set<string> };
const priorities = new Map<string, Priority>();
const priority = (id: string): Priority => {
const cached = priorities.get(id);
if (cached) return cached;
const node = unfinished.get(id);
const result: Priority = {
depth: node?.task.kind === 'goal' ? 1 : 0,
goals: new Set(node?.task.kind === 'goal' ? [id] : []),
};
priorities.set(id, result);
if (node)
for (const consumer of consumers.get(id) ?? []) {
const next = priority(consumer);
if (next.depth) result.depth = Math.max(result.depth, next.depth + 1);
for (const goal of next.goals) result.goals.add(goal);
}
return result;
};
const ready = readyResearchTasks(tasks, groups);
for (const node of ready) priority(node.task.id);
return prioritizeEarlyRouteChecks(
ready.toSorted((a, b) => {
const left = priority(a.task.id),
right = priority(b.task.id);
return right.depth - left.depth || right.goals.size - left.goals.size;
}),
tasks,
groups,
);
}
type GoalTaskFocus = Readonly<{
proofPath: ReadonlySet<string>;
frontier: ReadonlySet<string>;
proofGoals: ReadonlyMap<string, ReadonlySet<string>>;
frontierGoals: ReadonlyMap<string, ReadonlySet<string>>;
targetedResearch: ReadonlySet<string>;
support: ReadonlySet<string>;
}>;
export type OriginalGoalTaskFocus = GoalTaskFocus & Readonly<{ preferred: GoalTaskFocus }>;
function collectOriginalGoalTaskFocus(
tasks: readonly TaskRecord[],
groups?: readonly RouteRecord[],
priority?: ReturnType<typeof createProofRoutePriority>,
environmentDigest?: string,
includeParkedTasks = false,
): GoalTaskFocus {
const nodes = new Map(tasks.map(node => [node.task.id, node]));
const active = (node: TaskRecord) => {
if (
(node.task.status ?? 'active') !== 'active' ||
(!includeParkedTasks && (node.routeParking?.length || allRoutesParked(node)))
)
return false;
return !groups || groupOpen(groups.find(record => record.group.id === taskGroup(node.task)));
};
const { settled } = createRecordedTaskSettlement(tasks, { includeParkedRoutes: false, environmentDigest });
const routes = (node: TaskRecord) => {
const open = openRoutes(node);
if (!priority) return open;
const selected = selectedTaskRoute(node, tasks, priority);
return selected && open.some(route => route.id === selected.id) ? [selected] : [];
};
const inputs = (node: TaskRecord) => [
...new Set([
...node.task.dependsOn,
...routes(node).flatMap(route => [...route.prerequisiteTaskIds, route.closingTaskId]),
]),
];
const proofPath = new Set<string>(),
frontier = new Set<string>(),
proofGoals = new Map<string, Set<string>>();
const visitPath = (id: string, goalId: string) => {
if (proofGoals.get(id)?.has(goalId)) return;
const node = nodes.get(id);
if (!node || !active(node)) return;
proofPath.add(id);
const goals = proofGoals.get(id) ?? new Set<string>();
goals.add(goalId);
proofGoals.set(id, goals);
if (isAdvisoryTask(node.task) || !settled(node)) inputs(node).forEach(dependency => visitPath(dependency, goalId));
};
const frontierGoals = new Map<string, Set<string>>();
const visitFrontier = (id: string, goalId: string, visited: Set<string>) => {
if (visited.has(id)) return;
visited.add(id);
const node = nodes.get(id);
if (!node || !active(node) || settled(node)) return;
const open = node.task.dependsOn.filter(dependency => !settled(nodes.get(dependency)));
const alternatives = routes(node);
if (
alternatives.length &&
!alternatives.some(route =>
[...route.prerequisiteTaskIds, route.closingTaskId].every(dependency => settled(nodes.get(dependency))),
)
)
open.push(
...alternatives
.flatMap(route => [...route.prerequisiteTaskIds, route.closingTaskId])
.filter(dependency => !settled(nodes.get(dependency))),
);
if (open.length) open.forEach(dependency => visitFrontier(dependency, goalId, visited));
else {
frontier.add(id);
const goals = frontierGoals.get(id) ?? new Set<string>();
goals.add(goalId);
frontierGoals.set(id, goals);
}
};
for (const node of tasks)
if (node.task.kind === 'goal' && active(node) && !settled(node)) {
visitPath(node.task.id, node.task.id);
visitFrontier(node.task.id, node.task.id, new Set());
}
const reachesFrontier = (id: string, visited = new Set<string>()): boolean => {
if (frontier.has(id)) return true;
if (visited.has(id)) return false;
visited.add(id);
const node = nodes.get(id);
// A shared checked helper does not connect every later investigation to its old planned inputs.
return Boolean(
node &&
active(node) &&
!(!isAdvisoryTask(node.task) && settled(node)) &&
inputs(node).some(dependency => reachesFrontier(dependency, visited)),
);
};
// Advisory attribution is not a proof prerequisite. It can still identify research for an
// active unfinished original goal, including when that research has no typed inputs yet.
const servesGoal = (node: TaskRecord) =>
node.task.consumerGoalIds?.some(id => {
const goal = nodes.get(id);
return Boolean(
goal &&
goal.task.kind === 'goal' &&
proofPath.has(id) &&
!settled(goal) &&
(taskGroup(node.task) === taskGroup(goal.task) || goal.task.sharing !== 'group'),
);
});
const targetedResearch = new Set(
tasks
.filter(
node =>
isAdvisoryTask(node.task) &&
active(node) &&
(servesGoal(node) || inputs(node).some(id => reachesFrontier(id))),
)
.map(node => node.task.id),
);
const support = new Set(proofPath);
const visitSupport = (id: string) => {
if (support.has(id)) return;
const node = nodes.get(id);
if (!node || !active(node)) return;
support.add(id);
if (isAdvisoryTask(node.task) || !settled(node)) inputs(node).forEach(visitSupport);
};
targetedResearch.forEach(visitSupport);
return { proofPath, frontier, proofGoals, frontierGoals, targetedResearch, support };
}
/** Preserve every active frontier, with a separate evidence-ranked focus for allocation. */
export function originalGoalTaskFocus(
tasks: readonly TaskRecord[],
groups?: readonly RouteRecord[],
environmentDigest?: string,
options: {
/** Diagnose the parked obligation without reopening its proof or traversing parked OR branches. */
includeParkedTasks?: boolean;
} = {},
): OriginalGoalTaskFocus {
const full = collectOriginalGoalTaskFocus(tasks, groups, undefined, environmentDigest, options.includeParkedTasks);
return {
...full,
preferred: tasks.some(node => node.alternativeRoutes?.length)
? collectOriginalGoalTaskFocus(
tasks,
groups,
createProofRoutePriority(tasks, { groups, environmentDigest }),
environmentDigest,
options.includeParkedTasks,
)
: full,
};
}
export function originalGoalFrontierSnapshot(focus: OriginalGoalTaskFocus) {
const taskIds = [...focus.frontier],
preferredTaskIds = [...focus.preferred.frontier];
return {
evidence: 'recorded-not-replayed' as const,
count: taskIds.length,
digest: mathDigest(canonicalMathJson(taskIds)),
taskIds,
preferredTaskIds,
};
}
/** Reconnect checked helpers to unfinished original goals; ranks are facts, not success estimates. */
export function continuationResearchTasks(tasks: readonly TaskRecord[], groups?: readonly RouteRecord[]): TaskRecord[] {
const nodes = new Map(tasks.map(node => [node.task.id, node]));
const focus = originalGoalTaskFocus(tasks, groups);
const preferred = focus.preferred,
priority = createProofRoutePriority(tasks, { groups });
const ready = criticalPathResearchTasks(tasks, groups),
readiness = taskReadiness(tasks, groups);
const unconditional = (node: TaskRecord) =>
['goal', 'lemma'].includes(node.task.kind) && readiness.dependenciesReady(node.task);
const continuing = new Set(
ready
.filter(
node =>
focus.proofPath.has(node.task.id) &&
unconditional(node) &&
plannedTaskDependencyIds(node, tasks).some(id => checkedUnconditionally(nodes.get(id))),
)
.map(node => node.task.id),
);
const rank = (node: TaskRecord) =>
node.task.kind === 'goal' && unconditional(node)
? 6
: continuing.has(node.task.id)
? 5
: preferred.proofPath.has(node.task.id) && unconditional(node)
? 4
: preferred.support.has(node.task.id) && unconditional(node)
? 3
: preferred.targetedResearch.has(node.task.id)
? 2
: focus.proofPath.has(node.task.id) || focus.targetedResearch.has(node.task.id)
? 1
: 0;
const ranked = ready.toSorted(
(a, b) =>
rank(b) - rank(a) ||
Number(continuing.has(b.task.id)) - Number(continuing.has(a.task.id)) ||
Number(b.task.kind === 'goal') - Number(a.task.kind === 'goal') ||
priority.compareTasks(a, b),
);
return prioritizeEarlyRouteChecks(ranked, tasks, groups);
}
/** Candidate roots may be scoped; their prerequisites still use the complete task graph. */
export function researchCanAdvance(
tasks: readonly TaskRecord[],
groups: readonly RouteRecord[] | undefined,
liveWorkers: ReadonlySet<string>,
canAssign?: (node: TaskRecord) => boolean,
candidateIds?: ReadonlySet<string>,
stopped?: ReadonlySet<string>,
): boolean {
const nodes = new Map(tasks.map(node => [node.task.id, node]));
const memo = new Map<string, boolean>();
const readiness = taskReadiness(tasks, groups);
const visit = (id: string): boolean => {
if (memo.has(id)) return memo.get(id)!;
memo.set(id, false);
const node = nodes.get(id);
if (!node || node.status === 'blocked' || isFinalCandidateReview(node.task)) return false;
if (node.status === 'completed' && isAdvisoryTask(node.task)) {
const ready = node.task.dependsOn.every(visit);
memo.set(id, ready);
return ready;
}
if (['integrated', 'completed', 'delivered', 'running'].includes(node.status)) {
memo.set(id, true);
return true;
}
if (node.status !== 'conditional') {
const engineerId =
node.task.kind === 'goal'
? groups?.find(route => route.group.id === taskGroup(node.task))?.group.engineerId
: undefined;
// Pins of a worker stopped in this process are released, except its own capacity exploration.
const owners = [node.task.ownerId, node.assignment?.workerId, engineerId].filter(
(id): id is string => Boolean(id) && !(stopped?.has(id!) && !node.capacityExploration),
);
if (
owners.some(id => !liveWorkers.has(id) || id !== owners[0]) ||
!routeAllowsTask(node.task, tasks, groups) ||
(canAssign && !canAssign(node))
)
return false;
}
// Reuse future-progress traversal before checking whether assumed inputs allow an earlier start.
const ready =
(isAdvisoryTask(node.task) ||
node.task.dependsOn.every(visit) ||
(node.status !== 'conditional' && readiness.canStart(node.task))) &&
(!node.alternativeRoutes?.length ||
openRoutes(node).some(route => [...route.prerequisiteTaskIds, route.closingTaskId].every(visit)));
memo.set(id, ready);
return ready;
};
return tasks.some(
node =>
(!candidateIds || candidateIds.has(node.task.id)) &&
['pending', 'blocked'].includes(node.status) &&
visit(node.task.id),
);
}
/** M3 chooses actions; a selected action never changes mathematical acceptance. */
export function selectResearchAction(
state: Readonly<SolverRunState>,
options: readonly ResearchOperation[],
budget: ResearchBudget,
_assignment?: CooperativeAction,
): ActionPlan {
if (budget.aborted || budget.remainingMs <= 0 || state.turns >= budget.maxTurns)
return { operation: 'stop', reason: 'budget-exhausted' };
return options.includes('direct')
? { operation: 'direct', reason: 'continue' }
: { operation: 'stop', reason: 'no-operation' };
}
function structuredResearchFailure(diagnostic?: MathAgentFailureDiagnostic): string | undefined {
if (!diagnostic) return undefined;
const status = diagnostic.httpStatusCode;
if (diagnostic.code === 'unauthorized' || status === 401 || status === 403) return 'math_model_authentication_failed';
if (diagnostic.code === 'contextWindowExceeded') return 'math_model_context_window_exceeded';
if (['usageLimitExceeded', 'rateLimitExceeded'].includes(diagnostic.code) || status === 429)
return 'math_model_concurrency_limit';
if (status === 408) return 'math_model_request_timeout';
if (status !== undefined && status >= 400 && status < 500) return 'math_model_turn_failed';
if (
[
'httpConnectionFailed',
'responseStreamConnectionFailed',
'responseStreamDisconnected',
'responseTooManyFailedAttempts',
'flexUnavailable',
'serverOverloaded',
'internalServerError',
].includes(diagnostic.code)
)
return diagnostic.reason === 'invalid_tool_call_arguments' ? 'math_model_tool_failed' : 'math_model_request_failed';
if (diagnostic.code === 'other' && diagnostic.reason === 'invalid_tool_call_arguments')
return 'math_model_tool_failed';
if (diagnostic.code === 'other' && diagnostic.reason === 'upstream_request_failed')
return 'math_model_request_failed';
return diagnostic.code === 'other' ? undefined : 'math_model_turn_failed';
}
export function researchFailureReason(error?: string, diagnostic?: MathAgentFailureDiagnostic): string {
// Host integrity failures retain priority over provider classifications.
if (/^math_(?!(?:model_|codex_))/u.test(error ?? '')) return error!;
const structured = structuredResearchFailure(diagnostic);
if (structured) return structured;
if (
/^math_(?:model_(?:authentication_failed|concurrency_limit|request_failed|request_timeout|request_stopped|usage_unavailable|tool_failed|turn_failed|context_window_exceeded|context_capacity_blocked)|codex_transport_closed)$/u.test(
error ?? '',
)
)
return error!;
if (/^math_model_api_key_(?:missing|environment_invalid)(?::|$)/u.test(error ?? ''))
return 'math_model_authentication_failed';
if (
/\b(?:invalid|failed|missing|expired)\s+authentication\b|\bauthentication\s+(?:failed|failure|error|required)\b|\bunauthenticated\b|\bunauthorized\b|\b(?:invalid|incorrect|missing|expired|revoked)\s+(?:api[ _-]?key|access[ _-]?token|refresh[ _-]?token)\b|\bHTTP(?:\s+status)?\s*[:=]?\s*(?:401|403)\b|\bstatus(?:\s+code)?\s*[:=]?\s*(?:401|403)\b|\b(?:401\s+unauthorized|403\s+forbidden)\b/iu.test(
error ?? '',
)
)
return 'math_model_authentication_failed';
if (/Concurrency limit exceeded|rate.?limit|\b429\b/iu.test(error ?? '')) return 'math_model_concurrency_limit';
if (
/contextWindowExceeded|context (?:window|length).{0,40}(?:exceed|limit)|maximum context length/iu.test(error ?? '')
)
return 'math_model_context_window_exceeded';
if (/^math_codex_transport_closed(?::|$)/u.test(error ?? '')) return 'math_codex_transport_closed';
if (/math_codex_rpc_timeout|timed?\s*out|timeout/iu.test(error ?? '')) return 'math_model_request_timeout';
if (
/stream disconnected|error sending request|connection (?:reset|closed)|ECONNRESET|ECONNREFUSED|EAI_AGAIN|fetch failed|service unavailable|temporarily unavailable|\b(?:500|502|503|504)\b/iu.test(
error ?? '',
)
)
return 'math_model_request_failed';
if (
/(?:error parsing|failed to (?:parse|deserialize)) (?:function|tool) (?:call|arguments)|(?:function|tool) (?:call|execution|response)\b[^\n]{0,120}\b(?:interrupted|cancelled|canceled|invalid JSON)\b/iu.test(
error ?? '',
)
)
return 'math_model_tool_failed';
return 'math_model_turn_failed';
}
/** Host integrity errors precede trusted local stops, which precede provider classifications. */
export function researchFailureDetail(
error: unknown,
sessionError?: string,
diagnostic?: MathAgentFailureDiagnostic,
localStop?: ModelRequestStopReason,
): string | undefined {
const messages: string[] = [];
const seen = new Set<unknown>();
for (let current = error; current !== undefined && !seen.has(current) && seen.size < 4;) {
seen.add(current);
if (typeof current === 'string') {
messages.push(current);
break;
}
if (!(current instanceof Error)) break;
messages.push(current.message);
current = current.cause;
}
if (sessionError) messages.push(sessionError);
const first = messages[0];
const hostError = messages.find(message => /^math_(?!(?:model_|codex_))/u.test(message));
if (hostError) return hostError;
if (localStop) return localStop;
const structured = structuredResearchFailure(diagnostic);
if (structured) return structured;
const authentication = messages.find(
message => researchFailureReason(message) === 'math_model_authentication_failed',
);
if (authentication) return authentication;
return messages.find(message => researchFailureReason(message) !== 'math_model_turn_failed') ?? first;
}
export const recoverableResearchFailure = (error?: string): boolean =>
[
'math_model_concurrency_limit',
'math_model_request_failed',
'math_model_request_timeout',
'math_model_tool_failed',
'math_codex_transport_closed',
'math_model_context_window_exceeded',
].includes(researchFailureReason(error));
/** Advisory reporting only; categories never change Lean acceptance. */
export function researchFailureCategory(
error?: string,
):
| 'network'
| 'environment'
| 'source'
| 'proof'
| 'protocol'
| 'authentication'
| 'rate_limit'
| 'budget'
| 'unknown'
| undefined {
if (!error) return undefined;
if (
/math_(?:lean_toolchain|lake_packages|verifier_unavailable|runtime_|path_|trusted_source)|proof environment|dependency cache|sandbox|FUSE|mksquashfs|squashfuse/iu.test(
error,
)
)
return 'environment';
if (error === 'math_codex_provider_unreachable') return 'network';
if (/math_(?:original_|task_source|construction_|local_module_)/u.test(error)) return 'source';
if (
/^math_codex_rpc_failed(?::|$)|^math_(?:(?:research_|review_)?delivery_invalid(?:_json)?|response_invalid|math-result_missing_or_too_large|math-result_requires_one_block)$/u.test(
error,
)
)
return 'protocol';
const reason = researchFailureReason(error);
if (['math_total_token_limit', 'math_model_usage_unavailable', 'math_initial_planning_limit'].includes(reason))
return 'budget';
if (reason === 'math_model_authentication_failed') return 'authentication';
if (reason === 'math_model_concurrency_limit') return 'rate_limit';
if (reason === 'math_model_tool_failed') return 'environment';
if (['math_model_request_failed', 'math_model_request_timeout', 'math_codex_transport_closed'].includes(reason))
return 'network';
if (/unsolved goals|type mismatch|tactic.*failed|math_(?:proof_|task_proof_|lemma_)/iu.test(error)) return 'proof';
return 'unknown';
}
export function planResearchRetry(
error: string | undefined,
attempts: number,
state: Readonly<SolverRunState>,
budget: ResearchBudget,
): Readonly<{ attempt: number; delayMs: number; reason: string }> | undefined {
const reason = researchFailureReason(error);
if (
!recoverableResearchFailure(error) ||
attempts >= 3 ||
state.turns >= budget.maxTurns ||
budget.aborted ||
budget.remainingMs <= 0
)
return undefined;
return { attempt: attempts + 1, delayMs: 10_000 * 2 ** attempts, reason };
}
/** Sustained provider outages cool down unlimited runs without retiring their workers. */
export function planResearchCooldown(
error: string | undefined,
cycles: number,
budget: ResearchBudget,
): Readonly<{ cycle: number; delayMs: number; reason: string }> | undefined {
const reason = researchFailureReason(error);
if (
budget.maxTurns !== Infinity ||
budget.remainingMs !== Infinity ||
budget.aborted ||
![
'math_model_concurrency_limit',
'math_model_request_failed',
'math_model_request_timeout',
'math_codex_transport_closed',
].includes(reason)
)
return undefined;
// An oversized frame recurs while the same history is replayed; after one cooldown it is not transient.
if (error === 'math_codex_transport_closed:frame_too_large' && cycles > 0) return undefined;
return { cycle: cycles + 1, delayMs: Math.min(300_000, 60_000 * 2 ** Math.min(cycles, 3)), reason };
}