@operad-io/dev 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +795 -2
  3. package/dev.schema.json +602 -0
  4. package/flows/chat-worktree.flow.ts +18 -0
  5. package/flows/dev.flow.ts +7 -0
  6. package/package.json +29 -4
  7. package/src/actions.ts +591 -0
  8. package/src/announce.ts +225 -0
  9. package/src/chat.ts +234 -0
  10. package/src/check.ts +80 -0
  11. package/src/commands.ts +417 -0
  12. package/src/editor.ts +55 -0
  13. package/src/flaky.ts +716 -0
  14. package/src/flow-compiler.ts +858 -0
  15. package/src/followups.ts +223 -0
  16. package/src/gate.ts +2897 -0
  17. package/src/git.ts +138 -0
  18. package/src/index.ts +226 -0
  19. package/src/integrate.ts +1201 -0
  20. package/src/integration-queue.ts +393 -0
  21. package/src/lock.ts +36 -0
  22. package/src/mainclone.ts +102 -0
  23. package/src/marks.ts +126 -0
  24. package/src/model.ts +1165 -0
  25. package/src/notcode.ts +266 -0
  26. package/src/place-order.ts +161 -0
  27. package/src/place-wait.ts +64 -0
  28. package/src/places.ts +368 -0
  29. package/src/prepare.ts +106 -0
  30. package/src/progress.ts +115 -0
  31. package/src/project-flows.ts +160 -0
  32. package/src/project-settings.ts +185 -0
  33. package/src/refusals.ts +336 -0
  34. package/src/rerun.ts +378 -0
  35. package/src/reruns.ts +62 -0
  36. package/src/retry.ts +212 -0
  37. package/src/rework.ts +366 -0
  38. package/src/schedule.ts +1052 -0
  39. package/src/service.ts +2160 -0
  40. package/src/settings.ts +1463 -0
  41. package/src/standing.ts +87 -0
  42. package/src/stdin.ts +105 -0
  43. package/src/steps.ts +1775 -0
  44. package/src/stops.ts +103 -0
  45. package/src/throughput.ts +347 -0
  46. package/src/timeouts.ts +60 -0
  47. package/src/views.ts +1167 -0
  48. package/src/waits.ts +105 -0
@@ -0,0 +1,1052 @@
1
+ /**
2
+ * The dev plugin's scheduler. The kernel calls `onTick`; this module decides
3
+ * which ready tasks start, which reviewed task auto merge answers, and when a
4
+ * plan is finished. Scheduling lives here, not in the kernel (operad decision 12).
5
+ */
6
+
7
+ import { DEFAULT_POOL } from "@operad-io/pool";
8
+ import { readFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import {
11
+ ActiveRunError,
12
+ StateError,
13
+ type FlowDefinition,
14
+ type ObjectStore,
15
+ type StoredObject,
16
+ type TickContext,
17
+ } from "@operad-io/engine";
18
+ import {
19
+ bareId,
20
+ changeClock,
21
+ dependencyKey,
22
+ dependencyLabel,
23
+ listAll,
24
+ planData,
25
+ priorityIndex,
26
+ storeKey,
27
+ taskData,
28
+ type PlanData,
29
+ type RepositoryData,
30
+ type TaskData,
31
+ } from "./model.ts";
32
+ import {
33
+ claimTaskStart,
34
+ getPlan,
35
+ setAreaHold,
36
+ setDependencyHold,
37
+ setFlowNote,
38
+ setSlotHold,
39
+ clearOldestPlanSlot,
40
+ listRepositories,
41
+ recordAutoMerge,
42
+ recordMergeReported,
43
+ moveTaskPhase,
44
+ recordPlanStart,
45
+ recordPlanFinishedReported,
46
+ refreshPlanCounts,
47
+ reopenTask,
48
+ releaseTaskClaim,
49
+ } from "./service.ts";
50
+ import { loadProjectFlows, PROJECT_FLOWS_DIR } from "./project-flows.ts";
51
+ import { collectFollowups } from "./followups.ts";
52
+ import { missingPlugins } from "./standing.ts";
53
+ import {
54
+ compileDevFlow,
55
+ DEFAULT_FLOW_NAME,
56
+ flowNameFor,
57
+ } from "./flow-compiler.ts";
58
+ import {
59
+ DEV_SETTINGS_FILE,
60
+ readDevSettings,
61
+ flowPool,
62
+ repositoryTaskCap,
63
+ runningTaskCap,
64
+ settingsProblem,
65
+ type DevSettings,
66
+ } from "./settings.ts";
67
+
68
+ /** Where a scheduler change goes: the kernel loop's output. */
69
+ export const schedulerTestHooks: {
70
+ write?: ((line: string) => void) | undefined;
71
+ } = {};
72
+
73
+ export function writeSchedulerLine(line: string): void {
74
+ const write = schedulerTestHooks.write ?? ((text: string) => console.log(text));
75
+ write(line);
76
+ }
77
+
78
+ function isActive(task: TaskData): boolean {
79
+ return task.phase === "running" || task.phase === "review";
80
+ }
81
+
82
+ function planOf(task: TaskData): string {
83
+ return task.plan;
84
+ }
85
+
86
+ /** The flow a ready task starts when it has no flow recorded yet. */
87
+ interface StartFlow {
88
+ readonly name: string;
89
+ readonly graph?: FlowDefinition | undefined;
90
+ }
91
+
92
+ /** Every flow a repository declares, by name, and the one `default` means. */
93
+ interface RepositoryFlows {
94
+ readonly named: ReadonlyMap<string, StartFlow>;
95
+ readonly fallback: StartFlow;
96
+ /** Names dev refused, each with the reason. */
97
+ readonly refused: ReadonlyMap<string, string>;
98
+ }
99
+
100
+ /**
101
+ * Declares every flow the repository sets. A repository that writes no `flows`
102
+ * runs the built-in `dev` flow, so its old runs and tests keep their ids.
103
+ */
104
+ async function declareRepositoryFlows(
105
+ ctx: TickContext,
106
+ repository: RepositoryData,
107
+ settings: DevSettings,
108
+ ): Promise<RepositoryFlows> {
109
+ const named = new Map<string, StartFlow>();
110
+ let fallback: StartFlow = { name: DEFAULT_FLOW_NAME };
111
+ const project = await loadProjectFlows(repository.path, repository.name, settings);
112
+ const refused = new Map(project.refused);
113
+ for (const [flowName, spec] of Object.entries(settings.flows)) {
114
+ if (refused.has(flowName)) continue;
115
+ const name = flowNameFor(repository.name, flowName, spec);
116
+ const start = {
117
+ name,
118
+ graph: compileDevFlow(name, spec.stages, { gradingName: flowName }),
119
+ };
120
+ ctx.declareFlow(start.graph);
121
+ named.set(flowName, start);
122
+ if (flowName === "default") fallback = start;
123
+ }
124
+ for (const [flowName, graph] of project.flows) {
125
+ try {
126
+ ctx.declareFlow(graph);
127
+ } catch (error) {
128
+ refused.set(
129
+ flowName,
130
+ `${PROJECT_FLOWS_DIR}/${flowName}.flow.ts: ${error instanceof Error ? error.message : String(error)}`,
131
+ );
132
+ continue;
133
+ }
134
+ const start = { name: graph.name, graph };
135
+ named.set(flowName, start);
136
+ if (flowName === "default") fallback = start;
137
+ }
138
+ named.set("default", fallback);
139
+ return { named, fallback, refused };
140
+ }
141
+
142
+ /** The repository flow a task starts with, or undefined when it names none. */
143
+ function flowFor(
144
+ flows: RepositoryFlows,
145
+ name: string | undefined,
146
+ ): StartFlow | undefined {
147
+ const wanted = name ?? "default";
148
+ if (flows.refused.has(wanted)) return undefined;
149
+ return flows.named.get(wanted);
150
+ }
151
+
152
+ /** What the scheduler last said about a task whose flow name is unknown. */
153
+ const reportedFlowProblems = new Map<string, string>();
154
+
155
+ /** Says once per task and name that its flow is not in dev.json. */
156
+ function reportFlowProblem(
157
+ id: string,
158
+ name: string | undefined,
159
+ refused?: string,
160
+ ): void {
161
+ const wanted = name ?? "default";
162
+ if (reportedFlowProblems.get(id) === wanted) return;
163
+ reportedFlowProblems.set(id, wanted);
164
+ writeSchedulerLine(
165
+ `${bareId(id)} ready -> ready (${refused ?? `no flow "${wanted}" in dev.json`})`,
166
+ );
167
+ }
168
+
169
+ /** Re-declares the graph every task started with, so a fresh process resumes it. */
170
+ function declareStoredFlows(ctx: TickContext, tasks: readonly StoredObject[]): void {
171
+ for (const object of tasks) {
172
+ const graph = taskData(object.data).flowGraph;
173
+ if (graph !== undefined) ctx.declareFlow(graph);
174
+ }
175
+ }
176
+
177
+ function tasksOf(
178
+ tasks: readonly StoredObject[],
179
+ repository: string,
180
+ ): readonly StoredObject[] {
181
+ return tasks.filter(
182
+ (object) => taskData(object.data).repository === repository,
183
+ );
184
+ }
185
+
186
+ function plansOf(
187
+ plans: readonly StoredObject[],
188
+ repository: string,
189
+ ): readonly StoredObject[] {
190
+ return plans.filter(
191
+ (object) => planData(object.data).repository === repository,
192
+ );
193
+ }
194
+
195
+ /**
196
+ * Whether a task's flow has a configured human stage that no review stage
197
+ * comes before, and the work and check before it finished well: the wait the
198
+ * task is in is that stage. A review before the human stage is answered
199
+ * through its pass; a review after it has not run yet at that wait.
200
+ */
201
+ function atHumanStage(task: TaskData): boolean {
202
+ const steps = task.flowGraph?.steps;
203
+ const attempt = task.attempt;
204
+ if (steps === undefined || attempt === undefined) return false;
205
+ const indexOf = (kind: string): number =>
206
+ steps.findIndex((step) => new RegExp(`^${kind}(_\\d+)?$`).test(step.id));
207
+ const human = indexOf("human");
208
+ if (human < 0) return false;
209
+ const review = indexOf("review");
210
+ if (review >= 0 && review < human) return false;
211
+ // A review after the human stage has not run while the task waits here.
212
+ if (review > human && attempt.review !== undefined && attempt.review !== null) {
213
+ return false;
214
+ }
215
+ if (attempt.result !== undefined && attempt.result !== null && attempt.result !== "done") {
216
+ return false;
217
+ }
218
+ const check = indexOf("check");
219
+ if (check >= 0 && check < human) return attempt.verify?.result === "pass";
220
+ return attempt.worked === true;
221
+ }
222
+
223
+ /**
224
+ * Whether a task waits for a merge answer the scheduler gives at auto merge:
225
+ * its review passed, its integrate has not run and it was not answered for
226
+ * this attempt yet. Whether the plan is at auto merge is the caller's check.
227
+ */
228
+ function autoMergeWaits(task: TaskData): boolean {
229
+ const attempt = task.attempt;
230
+ if (task.phase !== "waiting" || task.run === null) return false;
231
+ if (attempt === undefined) return false;
232
+ const review = attempt.review;
233
+ const passed =
234
+ review?.decision === "passed" ||
235
+ review?.result === "pass" ||
236
+ review?.result === "passed";
237
+ if (!passed && !atHumanStage(task)) return false;
238
+ // An integrate that failed is a person wait, never a second answer.
239
+ if (attempt.integration !== undefined && attempt.integration !== null) {
240
+ return false;
241
+ }
242
+ return task.autoMergeAttempt !== attempt.number;
243
+ }
244
+
245
+ /**
246
+ * Whether a task's wait is one the scheduler is about to answer: the task's
247
+ * plan is confirmed at auto merge and the wait is a merge wait. It reads the
248
+ * plan now, so a changed auto level or a refused answer ends the mark.
249
+ */
250
+ export async function taskWaitAnsweredAutomatically(
251
+ data: Record<string, unknown>,
252
+ ctx: { readonly store: ObjectStore },
253
+ ): Promise<boolean> {
254
+ const task = taskData(data);
255
+ if (!autoMergeWaits(task)) return false;
256
+ const plan = await ctx.store.get("plan", storeKey(task.repository, planOf(task)));
257
+ if (plan === undefined) return false;
258
+ const found = planData(plan.data);
259
+ if (found.status !== "confirmed" || found.auto !== "merge") return false;
260
+ // The scheduler returns early for a repository whose settings are invalid,
261
+ // so it answers nothing there: the wait stays visible to a person.
262
+ const repository = (await listRepositories(ctx.store)).find(
263
+ (item) => item.name === task.repository,
264
+ );
265
+ if (repository === undefined) return false;
266
+ try {
267
+ await readDevSettings(repository.path);
268
+ } catch {
269
+ return false;
270
+ }
271
+ return true;
272
+ }
273
+
274
+ function planTasks(
275
+ tasks: readonly StoredObject[],
276
+ plan: string,
277
+ ): readonly StoredObject[] {
278
+ return tasks.filter((object) => planOf(taskData(object.data)) === plan);
279
+ }
280
+
281
+ /** Plans in the order the scheduler considers them: most urgent first. */
282
+ function orderPlans(plans: readonly StoredObject[]): readonly StoredObject[] {
283
+ return [...plans].sort((left, right) => {
284
+ const leftPlan = planData(left.data);
285
+ const rightPlan = planData(right.data);
286
+ const byPriority =
287
+ priorityIndex(leftPlan.priority) - priorityIndex(rightPlan.priority);
288
+ if (byPriority !== 0) return byPriority;
289
+ return bareId(left.id).localeCompare(bareId(right.id));
290
+ });
291
+ }
292
+
293
+ interface DependencyState {
294
+ readonly ready: boolean;
295
+ readonly cancelled?: string | undefined;
296
+ /** The tasks not merged yet, as a note names them. */
297
+ readonly waitingFor: readonly string[];
298
+ }
299
+
300
+ /**
301
+ * A task starts once every task it follows is merged, in any plan and any
302
+ * repository. `byKey` holds the tasks of every repository by store key.
303
+ */
304
+ function dependencyState(
305
+ task: TaskData,
306
+ byKey: ReadonlyMap<string, TaskData>,
307
+ ): DependencyState {
308
+ const waitingFor: string[] = [];
309
+ let cancelled: string | undefined;
310
+ for (const entry of task.after) {
311
+ const key = dependencyKey(task.repository, entry);
312
+ const label = dependencyLabel(task.repository, key);
313
+ const dependency = byKey.get(key);
314
+ if (dependency?.phase === "merged") continue;
315
+ waitingFor.push(label);
316
+ if (dependency?.phase === "cancelled" && cancelled === undefined) {
317
+ cancelled = label;
318
+ }
319
+ }
320
+ return {
321
+ ready: waitingFor.length === 0,
322
+ ...(cancelled === undefined ? {} : { cancelled }),
323
+ waitingFor,
324
+ };
325
+ }
326
+
327
+ /** The pool of the first `dev/work` step of the graph a task started with, whatever the step is named. */
328
+ function storedGraphPool(graph: FlowDefinition | undefined): string | undefined {
329
+ for (const step of graph?.steps ?? []) {
330
+ const outer: unknown = step.params;
331
+ if (typeof outer !== "object" || outer === null) continue;
332
+ const { use, params } = outer as { use?: unknown; params?: unknown };
333
+ if (use !== "dev/work") continue;
334
+ const pool: unknown =
335
+ typeof params === "object" && params !== null
336
+ ? (params as { flowPool?: unknown }).flowPool
337
+ : undefined;
338
+ return typeof pool === "string" ? pool : DEFAULT_POOL;
339
+ }
340
+ return undefined;
341
+ }
342
+
343
+ function planConcurrency(plan: PlanData): number {
344
+ const value: unknown = plan.concurrency;
345
+ return typeof value === "number" && Number.isFinite(value) ? value : 1;
346
+ }
347
+
348
+ function repositoryConcurrency(settings: DevSettings, pool?: string): number {
349
+ const value: unknown =
350
+ pool === undefined ? repositoryTaskCap(settings) : runningTaskCap(settings, pool);
351
+ return typeof value === "number" && Number.isFinite(value) ? value : 1;
352
+ }
353
+
354
+ async function startOne(
355
+ ctx: TickContext,
356
+ object: StoredObject,
357
+ params?: Readonly<Record<string, string>>,
358
+ oldestPlanSlot = false,
359
+ fallbackFlow: StartFlow = { name: DEFAULT_FLOW_NAME },
360
+ ): Promise<boolean> {
361
+ const stored = taskData(object.data);
362
+ const flow =
363
+ stored.flowName !== undefined
364
+ ? { name: stored.flowName, graph: stored.flowGraph }
365
+ : fallbackFlow;
366
+ // A task that started before the repository's flow changed keeps the graph
367
+ // it started with; the name is content-addressed, so a new graph gets a new
368
+ // name and never replaces the running attempt's definition.
369
+ if (flow?.graph !== undefined) ctx.declareFlow(flow.graph);
370
+ // A start that only parks the task for a person (a cancelled dependency)
371
+ // runs no work, so it is not held by an area.
372
+ const claimed = await claimTaskStart(ctx.store, object.id, {
373
+ checkArea: params?.blockedBy === undefined,
374
+ oldestPlanSlot,
375
+ ...(flow === undefined
376
+ ? {}
377
+ : { flow: { name: flow.name, ...(flow.graph === undefined ? {} : { graph: flow.graph }) } }),
378
+ });
379
+ if (claimed === undefined) return false;
380
+ const token = claimed.claim?.token;
381
+ const startParams: Readonly<Record<string, string>> | undefined =
382
+ token === undefined
383
+ ? params
384
+ : { ...(params ?? {}), token };
385
+ await ctx.start({
386
+ flow: flow?.name ?? DEFAULT_FLOW_NAME,
387
+ object: { type: "task", id: object.id },
388
+ ...(startParams === undefined ? {} : { params: startParams }),
389
+ });
390
+ return true;
391
+ }
392
+
393
+ /**
394
+ * Reports what the integrate step did to a task whose merge the scheduler
395
+ * answered. The task's phase is the real one when this runs, so a failure and
396
+ * a conflict each print their own transition; only a landed merge prints
397
+ * `merged`. Each attempt is reported once.
398
+ */
399
+ async function reportIntegrationResults(
400
+ store: ObjectStore,
401
+ tasks: readonly StoredObject[],
402
+ ): Promise<void> {
403
+ for (const object of tasks) {
404
+ const task = taskData(object.data);
405
+ const attempt = task.attempt;
406
+ if (attempt === undefined || task.autoMergeAttempt !== attempt.number) {
407
+ continue;
408
+ }
409
+ if (task.mergeReportedAttempt === attempt.number) continue;
410
+ const result = attempt.integration?.result;
411
+ let phase: string | undefined;
412
+ if (result === "merged") phase = "merged";
413
+ else if (result === "failed") phase = "waiting";
414
+ else if (result === "conflict" || result === "fail") phase = "running";
415
+ if (phase === undefined) continue;
416
+ if (!(await recordMergeReported(store, object.id, attempt.number))) continue;
417
+ writeSchedulerLine(`${bareId(object.id)} integrating -> ${phase}`);
418
+ }
419
+ }
420
+
421
+ /** Marks a plan finished once, when every task has merged or been cancelled. */
422
+ async function reportFinishedPlans(
423
+ store: ObjectStore,
424
+ plans: readonly StoredObject[],
425
+ tasks: readonly StoredObject[],
426
+ ): Promise<void> {
427
+ for (const object of plans) {
428
+ const plan = planData(object.data);
429
+ if (plan.status !== "confirmed" || plan.finishedReported === true) {
430
+ continue;
431
+ }
432
+ const mine = planTasks(tasks, bareId(object.id));
433
+ if (mine.length === 0) continue;
434
+ const finished = mine.every((task) => {
435
+ const phase = taskData(task.data).phase;
436
+ return phase === "merged" || phase === "cancelled";
437
+ });
438
+ if (!finished) continue;
439
+ if (!(await recordPlanFinishedReported(store, object.id))) continue;
440
+ writeSchedulerLine(`${bareId(object.id)} confirmed -> finished`);
441
+ }
442
+ }
443
+
444
+ /**
445
+ * Ends a run that is still active on a cancelled task. A cancel that could
446
+ * not reach its run (one made where no run control was set) left the run
447
+ * waiting for a person; the task is final, so no person has anything to do.
448
+ */
449
+ async function endRunsOfCancelledTasks(
450
+ ctx: TickContext,
451
+ runs: NonNullable<TickContext["runLookup"]>,
452
+ tasks: readonly StoredObject[],
453
+ repository: string,
454
+ ): Promise<void> {
455
+ if (ctx.runs === undefined) return;
456
+ const cancelled = new Set(
457
+ tasksOf(tasks, repository)
458
+ .filter((object) => taskData(object.data).phase === "cancelled")
459
+ .map((object) => `task:${object.id}`),
460
+ );
461
+ if (cancelled.size === 0) return;
462
+ for (const run of await runs.active()) {
463
+ if (!cancelled.has(run.object)) continue;
464
+ await ctx.runs.cancel(run.runId);
465
+ writeSchedulerLine(`${run.object.slice(5)} cancelled: ended its run ${run.runId}`);
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Makes every task's phase follow its run. A task whose run paused for a
471
+ * person says `waiting`; a task whose run is gone is repaired to a waiting
472
+ * task with a pending item, never left as `running` or `waiting` with nothing
473
+ * to act on. The check needs the kernel's run lookup, which only `serve`
474
+ * supplies.
475
+ */
476
+ async function reconcileTaskRuns(
477
+ ctx: TickContext,
478
+ repository: string,
479
+ tasks: readonly StoredObject[],
480
+ canStartWork: boolean,
481
+ flows: RepositoryFlows,
482
+ ): Promise<void> {
483
+ const runs = ctx.runLookup;
484
+ if (runs === undefined) return;
485
+ for (const object of tasksOf(tasks, repository)) {
486
+ const task = taskData(object.data);
487
+ if (task.phase !== "waiting" && task.phase !== "running" && task.phase !== "review") {
488
+ continue;
489
+ }
490
+ const active = await runs.active(`task:${object.id}`);
491
+ const run = active[0];
492
+ if (run !== undefined) {
493
+ // A run paused for a person is the truth: the task is waiting.
494
+ const state = await runs.state(run.runId);
495
+ if (state?.status === "waiting_person" && task.phase !== "waiting") {
496
+ const moved = await moveTaskPhase(ctx.store, object.id, task.phase, "waiting", {
497
+ run: run.runId,
498
+ });
499
+ if (moved === undefined) continue;
500
+ writeSchedulerLine(`${bareId(object.id)} ${task.phase} -> waiting`);
501
+ }
502
+ continue;
503
+ }
504
+ // A running task with no run id is a start that never landed; the claim
505
+ // release below gives it back to ready.
506
+ if ((task.phase === "running" || task.phase === "review") && task.run === null) continue;
507
+ // A recovered run starts the dev flow again; without the plugins it
508
+ // runs through, the task waits where it is.
509
+ if (!canStartWork) continue;
510
+ const step = task.run === null ? null : await runs.lastStep(task.run);
511
+ const plan = await ctx.store.get("plan", storeKey(task.repository, task.plan));
512
+ const requested = task.flow ?? (plan === undefined ? undefined : planData(plan.data).flow);
513
+ const selected =
514
+ task.flowName !== undefined
515
+ ? { name: task.flowName, graph: task.flowGraph }
516
+ : flowFor(flows, requested);
517
+ if (selected === undefined) {
518
+ const reason =
519
+ flows.refused.get(requested ?? "default") ??
520
+ `no flow "${requested ?? "default"}" in dev.json`;
521
+ reportFlowProblem(object.id, requested, flows.refused.get(requested ?? "default"));
522
+ // There is no graph to resume. End the task's wait for its run and leave
523
+ // it for a person; a flow defined again resumes it on a later tick.
524
+ if (task.phase !== "waiting" || task.run !== null) {
525
+ const moved = await moveTaskPhase(ctx.store, object.id, task.phase, "waiting", {
526
+ run: null,
527
+ });
528
+ if (moved !== undefined) {
529
+ writeSchedulerLine(`${bareId(object.id)} ${task.phase} -> waiting (${reason})`);
530
+ }
531
+ }
532
+ continue;
533
+ }
534
+ if ((await reopenTask(ctx.store, object.id)) === undefined) continue;
535
+ try {
536
+ if (await startOne(ctx, object, { runStoppedAt: step ?? "the run" }, false, selected)) {
537
+ writeSchedulerLine(
538
+ `${bareId(object.id)} ${task.phase} -> waiting (run stopped during ${step ?? "the run"})`,
539
+ );
540
+ }
541
+ } catch (error) {
542
+ if (!(error instanceof ActiveRunError)) throw error;
543
+ }
544
+ }
545
+ }
546
+
547
+ /** What the scheduler last said about each repository's settings file. */
548
+ const reportedProblems = new Map<string, string>();
549
+
550
+ /**
551
+ * Says once per change of the settings file that it is not valid, and says
552
+ * nothing while it stays the same or is valid. The last valid settings stay
553
+ * in force either way.
554
+ */
555
+ function reportSettingsProblem(repository: RepositoryData): void {
556
+ const problem = settingsProblem(repository.path);
557
+ if (problem === undefined) {
558
+ reportedProblems.delete(repository.path);
559
+ return;
560
+ }
561
+ // The file's text counts, not only the message: two different edits can
562
+ // fail with the same message.
563
+ let text = "";
564
+ try {
565
+ text = readFileSync(join(repository.path, DEV_SETTINGS_FILE), "utf8");
566
+ } catch {
567
+ // The problem is the missing or unreadable file itself.
568
+ }
569
+ const state = `${problem}\n${text}`;
570
+ if (reportedProblems.get(repository.path) === state) return;
571
+ reportedProblems.set(repository.path, state);
572
+ console.error(`dev: repository "${repository.name}": ${problem}`);
573
+ }
574
+
575
+ async function scheduleRepository(
576
+ ctx: TickContext,
577
+ repository: RepositoryData,
578
+ initialTasks: readonly StoredObject[],
579
+ initialPlans: readonly StoredObject[],
580
+ ): Promise<void> {
581
+ reportSettingsProblem(repository);
582
+ // A cancelled task's run ends whether or not the settings can be read.
583
+ if (ctx.runLookup !== undefined) {
584
+ await endRunsOfCancelledTasks(ctx, ctx.runLookup, initialTasks, repository.name);
585
+ }
586
+ let settings: DevSettings;
587
+ try {
588
+ settings = await readDevSettings(repository.path);
589
+ } catch {
590
+ // Never valid: the problem is reported and shown as pending. Nothing
591
+ // here may touch the repository's running steps.
592
+ return;
593
+ }
594
+ // Work needs the plugins dev runs its steps through; without them a task
595
+ // stays ready instead of failing.
596
+ const canStartWork = missingPlugins(ctx.loaded).length === 0;
597
+
598
+ // Compile every repository flow once; a start records its graph on the task,
599
+ // and a graph recorded there is declared again below so a fresh process
600
+ // resumes a running attempt on the graph it started with.
601
+ const flows = await declareRepositoryFlows(ctx, repository, settings);
602
+ declareStoredFlows(ctx, initialTasks);
603
+
604
+ // Repair a run that ended without an edge, or one whose phase was left
605
+ // behind, before the scheduler reads phases and starts anything else.
606
+ await reconcileTaskRuns(ctx, repository.name, initialTasks, canStartWork, flows);
607
+
608
+ // A claim is not durable until the kernel records the run. A task left
609
+ // running with no run is a start that never landed (a crash or a kernel
610
+ // failure between the two writes): give it back to ready, and this tick
611
+ // starts it again. A run that already exists is never duplicated, because
612
+ // the kernel refuses a second run for an object.
613
+ // A claim whose run the kernel already holds is a start still landing: the
614
+ // run's first step records its id moments later. Releasing it would cancel
615
+ // that run and start another one on the next tick, forever.
616
+ for (const object of tasksOf(initialTasks, repository.name)) {
617
+ const task = taskData(object.data);
618
+ if ((task.phase !== "running" && task.phase !== "review") || task.run !== null) continue;
619
+ if (
620
+ ctx.runLookup !== undefined &&
621
+ (await ctx.runLookup.active(`task:${object.id}`)).length > 0
622
+ ) {
623
+ continue;
624
+ }
625
+ if ((await releaseTaskClaim(ctx.store, object.id)) === undefined) continue;
626
+ writeSchedulerLine(`${bareId(object.id)} running -> ready`);
627
+ }
628
+
629
+ // Findings that did not fail a review become one follow-up task once the
630
+ // plan has no open task; this runs before a plan can be reported finished.
631
+ await collectFollowups(ctx.store, repository.name, settings);
632
+
633
+ // A recovered claim changes the store; read the phases again before counting.
634
+ const allCurrent = await listAll(ctx.store, "task");
635
+ const current = tasksOf(allCurrent, repository.name);
636
+ const plans = orderPlans(plansOf(initialPlans, repository.name));
637
+ const tasksById = new Map(
638
+ allCurrent.map((object) => [object.id, taskData(object.data)]),
639
+ );
640
+ declareStoredFlows(ctx, current);
641
+
642
+ await reportIntegrationResults(ctx.store, current);
643
+ await reportFinishedPlans(ctx.store, plans, current);
644
+
645
+ const planActive = new Map<string, number>();
646
+ for (const planObject of plans) {
647
+ const id = bareId(planObject.id);
648
+ planActive.set(
649
+ id,
650
+ planTasks(current, id).filter((object) =>
651
+ isActive(taskData(object.data)),
652
+ ).length,
653
+ );
654
+ }
655
+ let repositoryActive = current.filter((object) =>
656
+ isActive(taskData(object.data)),
657
+ ).length;
658
+ // A task counts against the pool of the flow it runs.
659
+ const plansByName = new Map(plans.map((object) => [bareId(object.id), planData(object.data)]));
660
+ // A task that has started runs the graph it started with, so its pool is
661
+ // that graph's; dev.json changing meanwhile does not move it.
662
+ const poolOf = (task: TaskData): string =>
663
+ storedGraphPool(task.flowGraph) ??
664
+ flowPool(settings, task.flow ?? plansByName.get(task.plan)?.flow);
665
+ const poolActive = new Map<string, number>();
666
+ for (const object of current) {
667
+ const task = taskData(object.data);
668
+ if (!isActive(task)) continue;
669
+ const pool = poolOf(task);
670
+ poolActive.set(pool, (poolActive.get(pool) ?? 0) + 1);
671
+ }
672
+ const started = new Set<string>();
673
+ // Which running or reviewing task holds each area in this repository.
674
+ const areaActive = new Map<string, string>();
675
+ for (const object of current) {
676
+ const task = taskData(object.data);
677
+ if (task.area !== undefined && isActive(task) && !areaActive.has(task.area)) {
678
+ areaActive.set(task.area, bareId(object.id));
679
+ }
680
+ }
681
+
682
+ /** Tasks started in this tick into the slot kept for the oldest plan. */
683
+ const oldestPlanHeld = new Set<string>();
684
+ const lastStarted = new Map<string, number>(
685
+ plans.map((object) => [
686
+ bareId(object.id),
687
+ planData(object.data).lastStartedAt ?? 0,
688
+ ]),
689
+ );
690
+ const turnOf = (object: StoredObject): number =>
691
+ lastStarted.get(bareId(object.id)) ?? 0;
692
+ const byUrgency = (left: StoredObject, right: StoredObject): number =>
693
+ priorityIndex(planData(left.data).priority) -
694
+ priorityIndex(planData(right.data).priority);
695
+ const byId = (left: StoredObject, right: StoredObject): number =>
696
+ bareId(left.id).localeCompare(bareId(right.id));
697
+ /** Priority first; within one priority the plan that started longest ago. */
698
+ const turnOrder = (): readonly StoredObject[] =>
699
+ [...plans].sort(
700
+ (left, right) =>
701
+ byUrgency(left, right) || turnOf(left) - turnOf(right) || byId(left, right),
702
+ );
703
+ /** The last free slot: longest without a start first, then most urgent. */
704
+ const oldestPlanOrder = (): readonly StoredObject[] =>
705
+ [...plans].sort(
706
+ (left, right) =>
707
+ turnOf(left) - turnOf(right) || byUrgency(left, right) || byId(left, right),
708
+ );
709
+
710
+ /**
711
+ * One slot is kept for the plan that has gone longest without starting a
712
+ * task: the last free slot goes by turn only while no running task already
713
+ * holds that slot.
714
+ */
715
+ const keptSlotNext = (): boolean =>
716
+ repositoryConcurrency(settings) > 1 &&
717
+ repositoryConcurrency(settings) - repositoryActive === 1 &&
718
+ !current.some((object) => {
719
+ const task = taskData(object.data);
720
+ return task.oldestPlanSlot === true && isActive(task);
721
+ }) &&
722
+ !oldestPlanHeld.size;
723
+
724
+ /** Whether a ready task's dependencies and all three limits allow a start now. */
725
+ const canStart = (
726
+ object: StoredObject,
727
+ plan: PlanData,
728
+ planId: string,
729
+ ): boolean => {
730
+ if (started.has(object.id)) return false;
731
+ const task = taskData(object.data);
732
+ if (task.phase !== "ready") return false;
733
+ if (!dependencyState(task, tasksById).ready) return false;
734
+ if (!canStartWork) return false;
735
+ if (task.area !== undefined && areaActive.has(task.area)) return false;
736
+ if (planConcurrency(plan) - (planActive.get(planId) ?? 0) <= 0) return false;
737
+ if (repositoryActive >= repositoryConcurrency(settings)) return false;
738
+ const pool = poolOf(task);
739
+ return (poolActive.get(pool) ?? 0) < repositoryConcurrency(settings, pool);
740
+ };
741
+
742
+ /**
743
+ * Starts ready tasks one at a time. Each start changes whose turn it is, so
744
+ * plans of one priority alternate; while the repository has more than one
745
+ * slot, the last free slot goes by turn alone, whatever the priority.
746
+ */
747
+ const startReady = async (
748
+ inScope: (task: TaskData, plan: PlanData) => boolean,
749
+ flows: RepositoryFlows,
750
+ ): Promise<void> => {
751
+ const scoped = (planObject: StoredObject): readonly StoredObject[] => {
752
+ const plan = planData(planObject.data);
753
+ if (plan.status !== "confirmed") return [];
754
+ return planTasks(current, bareId(planObject.id))
755
+ .filter((object) => {
756
+ const task = taskData(object.data);
757
+ return task.phase === "ready" && inScope(task, plan);
758
+ })
759
+ .sort(byId);
760
+ };
761
+ // A cancelled dependency parks the task for a person; it takes no slot.
762
+ for (const planObject of plans) {
763
+ const plan = planData(planObject.data);
764
+ for (const object of scoped(planObject)) {
765
+ const task = taskData(object.data);
766
+ const dependencies = dependencyState(task, tasksById);
767
+ if (dependencies.cancelled === undefined || started.has(object.id)) {
768
+ continue;
769
+ }
770
+ const requested = task.flow ?? plan.flow;
771
+ const selected = flowFor(flows, requested);
772
+ if (selected === undefined) {
773
+ reportFlowProblem(object.id, requested, flows.refused.get(requested ?? "default"));
774
+ continue;
775
+ }
776
+ if (
777
+ await startOne(ctx, object, { blockedBy: dependencies.cancelled }, false, selected)
778
+ ) {
779
+ writeSchedulerLine(`${bareId(object.id)} ready -> waiting`);
780
+ started.add(object.id);
781
+ }
782
+ }
783
+ }
784
+ const failed = new Set<string>();
785
+ for (;;) {
786
+ const useOldestPlan = keptSlotNext();
787
+ const order = useOldestPlan ? oldestPlanOrder() : turnOrder();
788
+ let progress = false;
789
+ for (const planObject of order) {
790
+ const plan = planData(planObject.data);
791
+ const planId = bareId(planObject.id);
792
+ const pick = scoped(planObject).find(
793
+ (object) =>
794
+ !failed.has(object.id) && canStart(object, plan, planId),
795
+ );
796
+ if (pick === undefined) continue;
797
+ progress = true;
798
+ const requested = taskData(pick.data).flow ?? plan.flow;
799
+ const selected = flowFor(flows, requested);
800
+ if (selected === undefined) {
801
+ reportFlowProblem(pick.id, requested, flows.refused.get(requested ?? "default"));
802
+ failed.add(pick.id);
803
+ continue;
804
+ }
805
+ if (!(await startOne(ctx, pick, undefined, useOldestPlan, selected))) {
806
+ failed.add(pick.id);
807
+ break;
808
+ }
809
+ const task = taskData(pick.data);
810
+ writeSchedulerLine(`${bareId(pick.id)} ready -> running`);
811
+ planActive.set(planId, (planActive.get(planId) ?? 0) + 1);
812
+ repositoryActive += 1;
813
+ const startedPool = poolOf(task);
814
+ poolActive.set(startedPool, (poolActive.get(startedPool) ?? 0) + 1);
815
+ if (task.area !== undefined) areaActive.set(task.area, bareId(pick.id));
816
+ started.add(pick.id);
817
+ if (useOldestPlan) oldestPlanHeld.add(pick.id);
818
+ const at = changeClock.now();
819
+ lastStarted.set(planId, at);
820
+ await recordPlanStart(ctx.store, planObject.id, at);
821
+ break;
822
+ }
823
+ if (!progress) return;
824
+ }
825
+ };
826
+
827
+ for (const planObject of plans) {
828
+ const plan = planData(planObject.data);
829
+ if (plan.status !== "confirmed" || plan.auto !== "merge") continue;
830
+
831
+ for (const object of planTasks(current, bareId(planObject.id))) {
832
+ const task = taskData(object.data);
833
+ const attempt = task.attempt;
834
+ if (!autoMergeWaits(task) || attempt === undefined || task.run === null) {
835
+ continue;
836
+ }
837
+ try {
838
+ await ctx.answer(task.run, "merge");
839
+ } catch (error) {
840
+ // Another client answered first; the run is no longer waiting.
841
+ if (!(error instanceof StateError)) throw error;
842
+ continue;
843
+ }
844
+ await recordAutoMerge(ctx.store, object.id, attempt.number);
845
+ writeSchedulerLine(`${bareId(object.id)} waiting -> integrating`);
846
+ }
847
+ }
848
+
849
+ // A task that left running while it held the kept slot no longer holds it.
850
+ for (const object of current) {
851
+ const task = taskData(object.data);
852
+ if (task.oldestPlanSlot === true && !isActive(task)) {
853
+ await clearOldestPlanSlot(ctx.store, object.id);
854
+ }
855
+ }
856
+
857
+ // The owner's manual start is exempt from the auto level, not from the
858
+ // dependencies or the limits that keep two runs off one repository.
859
+ await startReady((task) => task.startRequested === true, flows);
860
+ await startReady(
861
+ (task, plan) => plan.auto !== "off" && task.startRequested !== true,
862
+ flows,
863
+ );
864
+
865
+ // The queue of each area: ready tasks in the order the scheduler considers
866
+ // them, manual starts first, so a waiting task can say how many are ahead.
867
+ const queued: StoredObject[] = [];
868
+ const queuedIds = new Set<string>();
869
+ const enqueue = (inScope: (task: TaskData, plan: PlanData) => boolean) => {
870
+ // The next start follows the order the loop above would use.
871
+ for (const planObject of keptSlotNext() ? oldestPlanOrder() : turnOrder()) {
872
+ const plan = planData(planObject.data);
873
+ if (plan.status !== "confirmed") continue;
874
+ for (const object of [...planTasks(current, bareId(planObject.id))].sort(byId)) {
875
+ const task = taskData(object.data);
876
+ if (task.phase !== "ready" || started.has(object.id)) continue;
877
+ if (queuedIds.has(object.id) || !inScope(task, plan)) continue;
878
+ if (!dependencyState(task, tasksById).ready) continue;
879
+ queued.push(object);
880
+ queuedIds.add(object.id);
881
+ }
882
+ }
883
+ };
884
+ enqueue((task) => task.startRequested === true);
885
+ enqueue((task, plan) => plan.auto !== "off");
886
+ const aheadOf = (object: StoredObject): number => {
887
+ const area = taskData(object.data).area;
888
+ let ahead = 0;
889
+ for (const other of queued) {
890
+ if (other.id === object.id) return ahead;
891
+ if (taskData(other.data).area === area) ahead += 1;
892
+ }
893
+ return 0;
894
+ };
895
+
896
+ // Say why a ready task whose dependencies are met is not starting: its area
897
+ // is held. The record is cleared once the area is free or the task started.
898
+ for (const object of current) {
899
+ const task = taskData(object.data);
900
+ if (task.phase !== "ready" || started.has(object.id)) continue;
901
+ const holder =
902
+ task.area !== undefined && dependencyState(task, tasksById).ready
903
+ ? areaActive.get(task.area)
904
+ : undefined;
905
+ await setAreaHold(ctx.store, object.id, holder, aheadOf(object));
906
+ const dependencies = dependencyState(task, tasksById);
907
+ await setDependencyHold(
908
+ ctx.store,
909
+ object.id,
910
+ !dependencies.ready && dependencies.cancelled === undefined,
911
+ dependencies.waitingFor,
912
+ );
913
+ }
914
+
915
+ const plansById = new Map(plans.map((object) => [bareId(object.id), planData(object.data)]));
916
+
917
+ // Say why a ready task that could otherwise start does not: the plan's or
918
+ // the repository's slots are full, or a plugin dev needs is not loaded.
919
+ const heldBy = (holders: readonly string[]): string => {
920
+ const [first = "", ...more] = holders;
921
+ return more.length === 0 ? first : `${first} and ${more.length} more`;
922
+ };
923
+ const activeIds = (inPlan: string | undefined): readonly string[] =>
924
+ current
925
+ .filter((object) => {
926
+ const task = taskData(object.data);
927
+ return (isActive(task) || started.has(object.id)) && (inPlan === undefined || task.plan === inPlan);
928
+ })
929
+ .map((object) => bareId(object.id))
930
+ .sort();
931
+ const missing = missingPlugins(ctx.loaded).map((plugin) => plugin.name);
932
+ for (const object of current) {
933
+ const task = taskData(object.data);
934
+ if (task.phase !== "ready" || started.has(object.id)) continue;
935
+ let note: string | undefined;
936
+ if (plansById.get(task.plan)?.status === "paused") {
937
+ note = "waiting for the plan to resume";
938
+ } else if (queuedIds.has(object.id)) {
939
+ const plan = plansById.get(task.plan);
940
+ const holders = activeIds(task.plan);
941
+ const all = activeIds(undefined);
942
+ if (missing.length > 0) {
943
+ note = `waiting for plugin ${missing.join(", ")}`;
944
+ } else if (task.area !== undefined && areaActive.has(task.area)) {
945
+ note = undefined;
946
+ } else if (plan !== undefined && holders.length >= planConcurrency(plan)) {
947
+ note = `waiting for the plan's slot (${heldBy(holders)})`;
948
+ } else {
949
+ const pool = poolOf(task);
950
+ const inPool = current
951
+ .filter((other) => {
952
+ const otherTask = taskData(other.data);
953
+ return (isActive(otherTask) || started.has(other.id)) && poolOf(otherTask) === pool;
954
+ })
955
+ .map((other) => bareId(other.id))
956
+ .sort();
957
+ if (
958
+ Object.keys(settings.workers.pools).length > 1 &&
959
+ inPool.length >= repositoryConcurrency(settings, pool)
960
+ ) {
961
+ // Which pool is full: a full code pool is not a full image pool.
962
+ note = `waiting for the ${pool} pool's slot (${heldBy(inPool)})`;
963
+ } else if (all.length >= repositoryConcurrency(settings)) {
964
+ note = `waiting for the repository's slot (${heldBy(all)})`;
965
+ }
966
+ }
967
+ }
968
+ await setSlotHold(ctx.store, object.id, note);
969
+ }
970
+
971
+ // Name each open task's flow when the repository defines more than one, and
972
+ // say why a ready task whose flow is not defined does not start.
973
+ for (const object of await listAll(ctx.store, "task")) {
974
+ const task = taskData(object.data);
975
+ if (task.repository !== repository.name) continue;
976
+ const requested = task.flow ?? plansById.get(task.plan)?.flow ?? "default";
977
+ const missing =
978
+ (task.phase === "ready" ||
979
+ (task.phase === "waiting" && task.run === null)) &&
980
+ task.flowName === undefined &&
981
+ flowFor(flows, requested) === undefined;
982
+ await setFlowNote(ctx.store, object.id, {
983
+ shown: flows.named.size > 1 ? requested : undefined,
984
+ held: missing
985
+ ? (flows.refused.get(requested) ?? `flow ${requested} is not defined in .operad/dev.json`)
986
+ : undefined,
987
+ });
988
+ }
989
+
990
+ // Keep each plan's cached counts, and with them its row's mark, current.
991
+ for (const planObject of plans) {
992
+ await refreshPlanCounts(ctx.store, await getPlan(ctx.store, planObject.id));
993
+ }
994
+ }
995
+
996
+ /** The pass running for a store and whether another was asked for meanwhile. */
997
+ interface PassState {
998
+ running: Promise<void> | undefined;
999
+ /** The pass that runs once after the running one, shared by every asker. */
1000
+ next: Promise<void> | undefined;
1001
+ }
1002
+
1003
+ const passes = new WeakMap<object, PassState>();
1004
+
1005
+ /**
1006
+ * One scheduler tick. Passes never overlap: a pass asked for while one runs
1007
+ * runs once after it, and every asker in between shares that one pass.
1008
+ */
1009
+ export function runScheduler(ctx: TickContext): Promise<void> {
1010
+ let state = passes.get(ctx.store);
1011
+ if (state === undefined) {
1012
+ state = { running: undefined, next: undefined };
1013
+ passes.set(ctx.store, state);
1014
+ }
1015
+ const current = state;
1016
+ const start = (): Promise<void> => {
1017
+ const pass = runPass(ctx).finally(() => {
1018
+ current.running = undefined;
1019
+ });
1020
+ current.running = pass;
1021
+ return pass;
1022
+ };
1023
+ if (current.running === undefined) return start();
1024
+ if (current.next === undefined) {
1025
+ const after = (): Promise<void> => {
1026
+ current.next = undefined;
1027
+ return start();
1028
+ };
1029
+ // The running pass failing must not stop the pass that follows it.
1030
+ current.next = current.running.then(after, after);
1031
+ }
1032
+ return current.next;
1033
+ }
1034
+
1035
+ /**
1036
+ * One pass. Each registered repository is scheduled on its own, so a slow or
1037
+ * broken repository cannot stop another one.
1038
+ */
1039
+ async function runPass(ctx: TickContext): Promise<void> {
1040
+ const repositories = await listRepositories(ctx.store);
1041
+ if (repositories.length === 0) return;
1042
+ const tasks = await listAll(ctx.store, "task");
1043
+ const plans = await listAll(ctx.store, "plan");
1044
+ for (const repository of repositories) {
1045
+ try {
1046
+ await scheduleRepository(ctx, repository, tasks, plans);
1047
+ } catch (error) {
1048
+ const message = error instanceof Error ? error.message : String(error);
1049
+ console.error(`dev: repository "${repository.name}": ${message}`);
1050
+ }
1051
+ }
1052
+ }