Repository navigation
Expand file tree
/
Copy pathorganization.ts
More file actions
337 lines (323 loc) · 13.8 KB
/
Copy pathorganization.ts
File metadata and controls
337 lines (323 loc) · 13.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
import {
originalGoalTaskFocus,
plannedTaskDependencyIds,
readyResearchTasks,
taskDependenciesReady,
taskDependencyRecords,
} from './search';
import {
checkedUnconditionally,
isAdvisoryTask,
isFeasibilityReview,
taskGroup,
taskVersion,
type CooperativeTask,
type RouteGroup,
type TaskRecord,
type RouteRecord,
} from '../tasks';
import { hasRunningDuplicateQuestion } from '../taskQuestions';
import { createProofRoutePriority } from '../routePriority';
import { freshTaskConnection, taskConnectionCheckCurrent } from '../taskConnections';
import { capacityExplorationWorkerCanTask } from '../capacityExploration';
export { MAX_RESEARCH_WORKERS } from './moduleIdentity';
export type ResearchRole = 'lead' | 'researcher' | 'prover' | 'engineer' | 'reviewer';
export type ResearchWorker = Readonly<{
id: string;
role: ResearchRole;
worktree: string;
ownedFiles: readonly string[];
}>;
export type ResponsibilityContext = Readonly<{
tasks: readonly TaskRecord[];
groups?: readonly RouteRecord[];
/** Workers that stopped in this process. Their owner, engineer and saved-assignment pins no longer bind live peers. */
stopped?: ReadonlySet<string>;
}>;
export type ResponsibilityAssessment =
| Readonly<{ kind: 'matches' }>
| Readonly<{
kind: 'blocked';
reason: 'role' | 'engineer' | 'owner' | 'saved-assignment' | 'review-independence' | 'running-duplicate';
}>;
/** Researchers and the Engineer retain their general task eligibility; Provers write typed helpers. */
export function researchWorkerCanTask(worker: Pick<ResearchWorker, 'role'>, task: CooperativeTask): boolean {
return (
worker.role === 'researcher' ||
worker.role === 'engineer' ||
(worker.role === 'prover' && task.kind === 'lemma' && Boolean(task.type?.trim()))
);
}
/** The only Prover advisory exception is an independently identified host exploration. */
export function researchWorkerCanNode(worker: Pick<ResearchWorker, 'id' | 'role'>, node: TaskRecord): boolean {
return researchWorkerCanTask(worker, node.task) || capacityExplorationWorkerCanTask(worker, node.task, node);
}
/** Validate the explicit worker choices in a proposed plan against the run's roster. */
export function assertPlanAssignments(
plan: { tasks: readonly CooperativeTask[]; groups: readonly RouteGroup[] },
previous: readonly TaskRecord[],
workers: readonly Pick<ResearchWorker, 'id' | 'role'>[],
): void {
const byId = new Map(workers.map(worker => [worker.id, worker]));
const previousById = new Map(previous.map(node => [node.task.id, node]));
for (const task of plan.tasks) {
const ownerId = task.ownerId ?? task.preferredOwnerId;
if (!ownerId) continue;
const owner = byId.get(ownerId),
node = previousById.get(task.id);
const ownershipTask = node?.capacityExploration ? { ...task, status: 'active' as const } : task;
if (
!owner ||
!researchWorkerCanNode(owner, { ...(node ?? { status: 'pending', attempts: 0 }), task: ownershipTask })
)
throw new Error('math_plan_task_owner_unavailable');
}
for (const group of plan.groups)
if (group.engineerId && byId.get(group.engineerId)?.role !== 'engineer')
throw new Error('math_plan_group_engineer_unavailable');
}
export function researchTaskRole(task: CooperativeTask): ResearchRole {
return isFeasibilityReview(task)
? 'reviewer'
: task.kind === 'goal'
? 'engineer'
: task.kind === 'lemma'
? 'prover'
: 'researcher';
}
export function defaultResearchRouteConcurrency(workers: readonly Pick<ResearchWorker, 'role'>[]): number {
return workers.length > 4
? Math.max(1, workers.filter(worker => ['researcher', 'prover', 'engineer'].includes(worker.role)).length)
: 3;
}
/** Save expanded capacity in the plan, so M3 and M5 use the same limit on every dispatch and resume. */
export function researchRouteGroups(
groups: readonly RouteGroup[],
workers: readonly Pick<ResearchWorker, 'role'>[],
): RouteGroup[] {
return groups.map(group =>
workers.length > 4 && group.maxConcurrent === undefined
? { ...group, maxConcurrent: defaultResearchRouteConcurrency(workers) }
: { ...group },
);
}
export function independentFeasibilityWorker(
node: TaskRecord,
worker: Pick<ResearchWorker, 'id' | 'role'>,
tasks: readonly TaskRecord[],
groups?: readonly RouteRecord[],
): boolean {
if (!isFeasibilityReview(node.task)) return true;
if (worker.role === 'lead') return false;
return node.task.dependsOn.every(id => {
const input = tasks.find(task => task.task.id === id);
const engineerId =
input?.task.kind === 'goal'
? groups?.find(group => group.group.id === taskGroup(input.task))?.group.engineerId
: undefined;
return input?.assignment?.workerId !== worker.id && input?.task.ownerId !== worker.id && engineerId !== worker.id;
});
}
/** A capacity exploration is the stopped worker's own overlay, so its pin is kept. */
export const releasedPin = (node: TaskRecord, id: string | undefined, stopped?: ReadonlySet<string>) =>
Boolean(id && stopped?.has(id) && !node.capacityExploration);
/** First responsibility mismatch only; matching does not establish readiness or proof acceptance. */
export function assessTaskResponsibility(
node: TaskRecord,
worker: Pick<ResearchWorker, 'id' | 'role'>,
{ tasks, groups, stopped }: ResponsibilityContext,
): ResponsibilityAssessment {
if (!researchWorkerCanNode(worker, node)) return { kind: 'blocked', reason: 'role' };
const engineerId =
node.task.kind === 'goal'
? groups?.find(route => route.group.id === taskGroup(node.task))?.group.engineerId
: undefined;
const pinned = (id: string | undefined) => id && id !== worker.id && !releasedPin(node, id, stopped);
if (pinned(engineerId)) return { kind: 'blocked', reason: 'engineer' };
if (pinned(node.task.ownerId)) return { kind: 'blocked', reason: 'owner' };
if (pinned(node.assignment?.workerId)) return { kind: 'blocked', reason: 'saved-assignment' };
if (
(!node.assignment || releasedPin(node, node.assignment.workerId, stopped)) &&
pinned(node.task.preferredOwnerId)
) {
const busy = tasks.some(
peer =>
peer !== node &&
peer.status === 'running' &&
peer.assignment &&
peer.assignment.workerId === node.task.preferredOwnerId &&
peer.assignment.taskId === peer.task.id &&
peer.assignment.taskDigest === taskVersion(peer.task),
);
const ownResearch = readyResearchTasks(tasks, groups).some(
peer =>
isAdvisoryTask(peer.task) &&
peer.task.ownerId === worker.id &&
assessTaskResponsibility(peer, worker, { tasks, groups, stopped }).kind === 'matches',
);
if (node.status !== 'pending' || node.attempts !== 0 || !busy || ownResearch)
return { kind: 'blocked', reason: 'owner' };
}
if (!independentFeasibilityWorker(node, worker, tasks, groups))
return { kind: 'blocked', reason: 'review-independence' };
if (hasRunningDuplicateQuestion(node, tasks)) return { kind: 'blocked', reason: 'running-duplicate' };
return { kind: 'matches' };
}
function eligibleResearchTasks(
ready: readonly TaskRecord[],
worker: ResearchWorker,
groups?: readonly RouteRecord[],
tasks: readonly TaskRecord[] = ready,
stopped?: ReadonlySet<string>,
): TaskRecord[] {
const context = { tasks, groups, stopped };
return ready.filter(node => assessTaskResponsibility(node, worker, context).kind === 'matches');
}
/** Share ranked work, reserving a final available slot for independent work when the main frontier is occupied. */
export function assignSharedResearchTask(
ready: readonly TaskRecord[],
worker: ResearchWorker,
live: readonly ResearchWorker[],
groups?: readonly RouteRecord[],
tasks: readonly TaskRecord[] = ready,
stopped?: ReadonlySet<string>,
): TaskRecord | undefined {
let eligible = eligibleResearchTasks(ready, worker, groups, tasks, stopped);
if (live.some(peer => peer.role === 'prover')) {
// Preserve M3 order within each responsibility while leaving spare generalists useful.
const preferred = (node: TaskRecord) =>
worker.role === 'researcher'
? isAdvisoryTask(node.task)
: worker.role === 'engineer' && node.task.kind === 'goal';
eligible = [...eligible.filter(preferred), ...eligible.filter(node => !preferred(node))];
}
// Optional discovery never takes a slot from an executable planned obligation.
const planned = eligible.filter(node => !node.capacityExploration);
if (planned.length) eligible = planned;
const first = eligible[0];
if (!first || eligible.length === 1) return first;
// An executable original proof can close the problem. Conditional connection checks
// only test an application and may still need unscreened mathematical research.
const connection = (node: TaskRecord) =>
node.assignment && !releasedPin(node, node.assignment.workerId, stopped)
? taskConnectionCheckCurrent(node.task, node.assignment, tasks)
: freshTaskConnection(node, tasks, groups);
if ((first.task.kind === 'goal' && !connection(first)) || (!first.attempts && isFeasibilityReview(first.task)))
return first;
if (
first.connectionCheckpoint &&
!releasedPin(first, first.assignment?.workerId, stopped) &&
first.connectionCheckpoint.basisDigest === first.assignment?.connectionCheck?.basisDigest &&
connection(first)
) {
const inputs = new Set(taskDependencyRecords(first.task, tasks));
const priority = createProofRoutePriority(tasks, { groups });
const input = eligible.find(
node =>
inputs.has(node) &&
!isAdvisoryTask(node.task) &&
node.task.type?.trim() &&
taskDependenciesReady(node.task, tasks) &&
priority.compareTasks(node, first) <= 0,
);
if (input) return input;
}
const proofWorkers = new Set(
live.filter(peer => ['researcher', 'prover', 'engineer'].includes(peer.role)).map(peer => peer.id),
);
const running = tasks.filter(
node =>
node.status === 'running' &&
node.assignment &&
node.assignment.taskId === node.task.id &&
node.assignment.taskDigest === taskVersion(node.task) &&
proofWorkers.has(node.assignment.workerId),
);
if (!running.length) return first;
const occupied = new Set(running.map(node => node.assignment!.workerId));
const group = groups?.find(route => route.group.id === taskGroup(first.task));
const groupBusy =
group?.busy ??
new Set(
running.filter(node => taskGroup(node.task) === taskGroup(first.task)).map(node => node.assignment!.workerId),
).size;
const lastSlot = proofWorkers.size - occupied.size === 1;
const lastGroupSlot = group && (group.group.maxConcurrent ?? 3) - groupBusy === 1;
if (!lastSlot && !lastGroupSlot) return first;
const connectingGoals = [...running, ...(first.attempts && first.task.kind === 'goal' ? [first] : [])].filter(
node => node.task.kind === 'goal' && taskGroup(node.task) === taskGroup(first.task) && connection(node),
);
const unscreened = eligible.find(
node =>
isAdvisoryTask(node.task) &&
!isFeasibilityReview(node.task) &&
!node.capacityExploration &&
!node.attempts &&
taskGroup(node.task) === taskGroup(first.task) &&
connectingGoals.some(
goal =>
node.task.consumerGoalIds?.includes(goal.task.id) &&
!running.some(peer => isAdvisoryTask(peer.task) && peer.task.consumerGoalIds?.includes(goal.task.id)),
),
);
if (unscreened) return unscreened;
if (first.task.kind === 'goal' || freshTaskConnection(first, tasks, groups)) return first;
const checkedInput = (id: string) => checkedUnconditionally(tasks.find(node => node.task.id === id));
if (
first.task.type &&
taskDependenciesReady(first.task, tasks) &&
plannedTaskDependencyIds(first, tasks).some(checkedInput)
)
return first;
const focus = originalGoalTaskFocus(tasks, groups),
preferred = focus.preferred.support;
if (!preferred.has(first.task.id) || running.some(node => !preferred.has(node.task.id))) return first;
// Different original goals share the support set. Give an uncovered goal a
// slot before filling every worker with inputs to goals already in progress.
const coveredGoals = new Set(running.flatMap(node => [...(focus.preferred.proofGoals.get(node.task.id) ?? [])]));
const firstGoals = focus.preferred.proofGoals.get(first.task.id);
if (firstGoals?.size && [...firstGoals].every(id => coveredGoals.has(id))) {
const independent = eligible.find(node =>
[...(focus.preferred.proofGoals.get(node.task.id) ?? [])].some(id => !coveredGoals.has(id)),
);
if (independent) return independent;
}
const priority = createProofRoutePriority(tasks, { groups });
return (
eligible
.filter(node => !preferred.has(node.task.id))
.toSorted(
(a, b) =>
Number(focus.support.has(b.task.id)) - Number(focus.support.has(a.task.id)) ||
priority.compareTasks(a, b) ||
a.attempts - b.attempts,
)[0] ?? first
);
}
export function researchWorkers(worktree: string, ownedFiles: readonly string[], count: number): ResearchWorker[] {
return Array.from({ length: count }, (_, index) => ({
id:
index === 0
? 'solver'
: index === count - 1
? 'engineer'
: index <= 2
? `researcher-${index}`
: `prover-${index - 2}`,
role: index === 0 ? 'lead' : index === count - 1 ? 'engineer' : index <= 2 ? 'researcher' : 'prover',
worktree: index === 0 ? worktree : `${worktree}-${index + 1}`,
ownedFiles,
}));
}
/** Reviewers inspect fixed work independently of its producer. */
export function assignResearchReviewer(
live: readonly ResearchWorker[],
producerId?: string,
): ResearchWorker | undefined {
const eligible = live.filter(worker => worker.role !== 'lead' && worker.id !== producerId);
return (
eligible.find(worker => worker.role === 'reviewer') ??
eligible.find(worker => worker.role === 'researcher') ??
eligible[0]
);
}