@operad-io/dev 0.1.1 → 0.3.0

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 (50) hide show
  1. package/README.md +1 -1
  2. package/dev.schema.json +53 -31
  3. package/package.json +9 -6
  4. package/skills/git/SKILL.md +70 -0
  5. package/skills/setup/SKILL.md +74 -0
  6. package/src/access-grants.ts +59 -0
  7. package/src/actions.ts +81 -17
  8. package/src/announce.ts +134 -17
  9. package/src/chat.ts +586 -36
  10. package/src/check-host.ts +111 -0
  11. package/src/check-load.ts +67 -0
  12. package/src/check.ts +45 -22
  13. package/src/clock.ts +29 -0
  14. package/src/clone-chat.ts +32 -0
  15. package/src/commands.ts +103 -34
  16. package/src/create-actions.ts +210 -0
  17. package/src/flaky.ts +45 -29
  18. package/src/flow-compiler.ts +156 -69
  19. package/src/followups.ts +20 -22
  20. package/src/gate.ts +254 -88
  21. package/src/git-state.ts +155 -0
  22. package/src/git.ts +92 -4
  23. package/src/index.ts +52 -6
  24. package/src/integrate.ts +162 -62
  25. package/src/integration-queue.ts +23 -10
  26. package/src/lock.ts +101 -5
  27. package/src/mainclone.ts +61 -5
  28. package/src/model-error.ts +70 -0
  29. package/src/model.ts +61 -35
  30. package/src/notcode.ts +51 -15
  31. package/src/places.ts +2 -2
  32. package/src/prepare.ts +7 -2
  33. package/src/project-flows.ts +135 -4
  34. package/src/project-settings.ts +110 -3
  35. package/src/register-requests.ts +121 -0
  36. package/src/repository-key.ts +4 -0
  37. package/src/rerun.ts +23 -7
  38. package/src/retry.ts +2 -12
  39. package/src/rework.ts +8 -0
  40. package/src/schedule.ts +342 -93
  41. package/src/service.ts +241 -185
  42. package/src/settings.ts +409 -65
  43. package/src/setup-git.ts +366 -0
  44. package/src/standing.ts +23 -6
  45. package/src/step-edge.ts +22 -0
  46. package/src/steps.ts +945 -179
  47. package/src/throughput.ts +4 -21
  48. package/src/timeouts.ts +10 -2
  49. package/src/views.ts +325 -86
  50. package/src/waits.ts +59 -0
package/src/schedule.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * plan is finished. Scheduling lives here, not in the kernel (ADR 0002 D1).
5
5
  */
6
6
 
7
+ import { isRecord, messageOf } from "@operad-io/engine";
7
8
  import { DEFAULT_POOL } from "@operad-io/pool";
8
9
  import { readFileSync } from "node:fs";
9
10
  import { join } from "node:path";
@@ -16,7 +17,8 @@ import {
16
17
  type TickContext,
17
18
  } from "@operad-io/engine";
18
19
  import {
19
- bareId,
20
+ idOfKey,
21
+ isOpenTask,
20
22
  changeClock,
21
23
  dependencyKey,
22
24
  dependencyLabel,
@@ -50,6 +52,7 @@ import {
50
52
  import { loadProjectFlows, PROJECT_FLOWS_DIR } from "./project-flows.ts";
51
53
  import { collectFollowups } from "./followups.ts";
52
54
  import { missingPlugins } from "./standing.ts";
55
+ import { checkHostWarning } from "./check-host.ts";
53
56
  import {
54
57
  compileDevFlow,
55
58
  DEFAULT_FLOW_NAME,
@@ -68,6 +71,8 @@ import {
68
71
  /** Where a scheduler change goes: the kernel loop's output. */
69
72
  export const schedulerTestHooks: {
70
73
  write?: ((line: string) => void) | undefined;
74
+ /** Called before a generated flow is handed to the kernel; a test counts them. */
75
+ declare?: ((flow: FlowDefinition) => void) | undefined;
71
76
  } = {};
72
77
 
73
78
  export function writeSchedulerLine(line: string): void {
@@ -75,8 +80,17 @@ export function writeSchedulerLine(line: string): void {
75
80
  write(line);
76
81
  }
77
82
 
83
+ /**
84
+ * A task holds a slot while it runs or is reviewed. A branch-mode task also
85
+ * holds the main clone until it is merged or cancelled, whatever it waits for:
86
+ * a person, the merge, a pause, or its next start (ADR 0039 D3).
87
+ */
78
88
  function isActive(task: TaskData): boolean {
79
- return task.phase === "running" || task.phase === "review";
89
+ return (
90
+ task.phase === "running" ||
91
+ task.phase === "review" ||
92
+ (task.attempt?.inPlace === true && isOpenTask(task))
93
+ );
80
94
  }
81
95
 
82
96
  function planOf(task: TaskData): string {
@@ -97,6 +111,76 @@ interface RepositoryFlows {
97
111
  readonly refused: ReadonlyMap<string, string>;
98
112
  }
99
113
 
114
+ /** The compiled settings flows of one repository, keyed by the settings' content. */
115
+ interface CompiledFlows {
116
+ readonly starts: ReadonlyMap<string, StartFlow>;
117
+ }
118
+
119
+ /** The compiled settings flows of each store's repositories, by repository name. */
120
+ const compiledFlows = new WeakMap<ObjectStore, Map<string, { readonly key: string; readonly value: CompiledFlows }>>();
121
+
122
+ /** The content-addressed flow names this process already declared in a store. */
123
+ const declaredFlowNames = new WeakMap<ObjectStore, Set<string>>();
124
+
125
+ function settingsKey(settings: DevSettings): string {
126
+ return JSON.stringify(settings);
127
+ }
128
+
129
+ /** Compiles a repository's settings flows once for each settings text. */
130
+ function compiledSettingsFlows(
131
+ store: ObjectStore,
132
+ repository: RepositoryData,
133
+ settings: DevSettings,
134
+ ): CompiledFlows {
135
+ let byRepository = compiledFlows.get(store);
136
+ if (byRepository === undefined) {
137
+ byRepository = new Map();
138
+ compiledFlows.set(store, byRepository);
139
+ }
140
+ const key = `${repository.name}\n${settingsKey(settings)}`;
141
+ const kept = byRepository.get(repository.name);
142
+ if (kept !== undefined && kept.key === key) return kept.value;
143
+ const starts = new Map<string, StartFlow>();
144
+ for (const [flowName, spec] of Object.entries(settings.flows)) {
145
+ const name = flowNameFor(repository.name, flowName, spec);
146
+ starts.set(flowName, {
147
+ name,
148
+ graph: compileDevFlow(name, spec.stages, { gradingName: flowName }),
149
+ });
150
+ }
151
+ const value = { starts };
152
+ byRepository.set(repository.name, { key, value });
153
+ return value;
154
+ }
155
+
156
+ /** A generated name carries a hash of its graph; the built-in `dev` does not. */
157
+ function contentAddressed(name: string): boolean {
158
+ return /^dev\/[^/]+\/[^/]+\/[0-9a-f]{12}$/.test(name);
159
+ }
160
+
161
+ /**
162
+ * Declares a content-addressed flow once per store in this process. The set
163
+ * lives beside the store object, so it serves an in-memory store as well as a
164
+ * file store; a later process starts its own set.
165
+ */
166
+ function declareFlowOnce(ctx: TickContext, graph: FlowDefinition): void {
167
+ const name = graph.name;
168
+ if (contentAddressed(name)) {
169
+ let declared = declaredFlowNames.get(ctx.store);
170
+ if (declared?.has(name)) return;
171
+ schedulerTestHooks.declare?.(graph);
172
+ ctx.declareFlow(graph);
173
+ if (declared === undefined) {
174
+ declared = new Set();
175
+ declaredFlowNames.set(ctx.store, declared);
176
+ }
177
+ declared.add(name);
178
+ return;
179
+ }
180
+ schedulerTestHooks.declare?.(graph);
181
+ ctx.declareFlow(graph);
182
+ }
183
+
100
184
  /**
101
185
  * Declares every flow the repository sets. A repository that writes no `flows`
102
186
  * runs the built-in `dev` flow, so its old runs and tests keep their ids.
@@ -110,24 +194,20 @@ async function declareRepositoryFlows(
110
194
  let fallback: StartFlow = { name: DEFAULT_FLOW_NAME };
111
195
  const project = await loadProjectFlows(repository.path, repository.name, settings);
112
196
  const refused = new Map(project.refused);
113
- for (const [flowName, spec] of Object.entries(settings.flows)) {
197
+ const compiled = compiledSettingsFlows(ctx.store, repository, settings);
198
+ for (const [flowName, start] of compiled.starts) {
114
199
  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);
200
+ if (start.graph !== undefined) declareFlowOnce(ctx, start.graph);
121
201
  named.set(flowName, start);
122
202
  if (flowName === "default") fallback = start;
123
203
  }
124
204
  for (const [flowName, graph] of project.flows) {
125
205
  try {
126
- ctx.declareFlow(graph);
206
+ declareFlowOnce(ctx, graph);
127
207
  } catch (error) {
128
208
  refused.set(
129
209
  flowName,
130
- `${PROJECT_FLOWS_DIR}/${flowName}.flow.ts: ${error instanceof Error ? error.message : String(error)}`,
210
+ `${PROJECT_FLOWS_DIR}/${flowName}.flow.ts: ${messageOf(error)}`,
131
211
  );
132
212
  continue;
133
213
  }
@@ -162,15 +242,48 @@ function reportFlowProblem(
162
242
  if (reportedFlowProblems.get(id) === wanted) return;
163
243
  reportedFlowProblems.set(id, wanted);
164
244
  writeSchedulerLine(
165
- `${bareId(id)} ready -> ready (${refused ?? `no flow "${wanted}" in dev.json`})`,
245
+ `${idOfKey(id)} ready -> ready (${refused ?? `no flow "${wanted}" in dev.json`})`,
166
246
  );
167
247
  }
168
248
 
169
- /** Re-declares the graph every task started with, so a fresh process resumes it. */
249
+ /** What the scheduler last said about each task whose recorded graph is refused. */
250
+ const reportedStoredFlows = new Map<string, string>();
251
+
252
+ /**
253
+ * Declares the graph a task started with. False when the task has none, or
254
+ * when today's steps refuse it: a graph recorded by an older dev may lack an
255
+ * edge for a result a step has since gained. The refusal is said once per
256
+ * task and reason, and only that task loses its recorded graph; the
257
+ * repository's other tasks are still scheduled.
258
+ */
259
+ function declareStoredFlow(ctx: TickContext, object: StoredObject): boolean {
260
+ const graph = taskData(object.data).flowGraph;
261
+ if (graph === undefined) return false;
262
+ try {
263
+ declareFlowOnce(ctx, graph);
264
+ reportedStoredFlows.delete(object.id);
265
+ return true;
266
+ } catch (error) {
267
+ const reason = messageOf(error);
268
+ if (reportedStoredFlows.get(object.id) !== reason) {
269
+ reportedStoredFlows.set(object.id, reason);
270
+ writeSchedulerLine(
271
+ `${idOfKey(object.id)} keeps no recorded flow: ${reason}; a new start uses the repository's flow`,
272
+ );
273
+ }
274
+ return false;
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Re-declares the graph every open task started with, so a fresh process
280
+ * resumes it. A merged or cancelled task runs nothing again.
281
+ */
170
282
  function declareStoredFlows(ctx: TickContext, tasks: readonly StoredObject[]): void {
171
283
  for (const object of tasks) {
172
- const graph = taskData(object.data).flowGraph;
173
- if (graph !== undefined) ctx.declareFlow(graph);
284
+ const phase = taskData(object.data).phase;
285
+ if (phase === "merged" || phase === "cancelled") continue;
286
+ declareStoredFlow(ctx, object);
174
287
  }
175
288
  }
176
289
 
@@ -194,7 +307,7 @@ function plansOf(
194
307
 
195
308
  /**
196
309
  * 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
310
+ * comes before, and the code and test before it finished well: the wait the
198
311
  * task is in is that stage. A review before the human stage is answered
199
312
  * through its pass; a review after it has not run yet at that wait.
200
313
  */
@@ -286,7 +399,7 @@ function orderPlans(plans: readonly StoredObject[]): readonly StoredObject[] {
286
399
  const byPriority =
287
400
  priorityIndex(leftPlan.priority) - priorityIndex(rightPlan.priority);
288
401
  if (byPriority !== 0) return byPriority;
289
- return bareId(left.id).localeCompare(bareId(right.id));
402
+ return idOfKey(left.id).localeCompare(idOfKey(right.id));
290
403
  });
291
404
  }
292
405
 
@@ -331,10 +444,7 @@ function storedGraphPool(graph: FlowDefinition | undefined): string | undefined
331
444
  if (typeof outer !== "object" || outer === null) continue;
332
445
  const { use, params } = outer as { use?: unknown; params?: unknown };
333
446
  if (use !== "dev/work") continue;
334
- const pool: unknown =
335
- typeof params === "object" && params !== null
336
- ? (params as { flowPool?: unknown }).flowPool
337
- : undefined;
447
+ const pool: unknown = isRecord(params) ? params.flowPool : undefined;
338
448
  return typeof pool === "string" ? pool : DEFAULT_POOL;
339
449
  }
340
450
  return undefined;
@@ -359,8 +469,11 @@ async function startOne(
359
469
  fallbackFlow: StartFlow = { name: DEFAULT_FLOW_NAME },
360
470
  ): Promise<boolean> {
361
471
  const stored = taskData(object.data);
472
+ // A recorded graph today's steps refuse cannot run; the start takes the
473
+ // repository's flow and records that one instead.
362
474
  const flow =
363
- stored.flowName !== undefined
475
+ stored.flowName !== undefined &&
476
+ (stored.flowGraph === undefined || declareStoredFlow(ctx, object))
364
477
  ? { name: stored.flowName, graph: stored.flowGraph }
365
478
  : fallbackFlow;
366
479
  // A task that started before the repository's flow changed keeps the graph
@@ -399,7 +512,8 @@ async function startOne(
399
512
  async function reportIntegrationResults(
400
513
  store: ObjectStore,
401
514
  tasks: readonly StoredObject[],
402
- ): Promise<void> {
515
+ ): Promise<boolean> {
516
+ let changed = false;
403
517
  for (const object of tasks) {
404
518
  const task = taskData(object.data);
405
519
  const attempt = task.attempt;
@@ -414,8 +528,10 @@ async function reportIntegrationResults(
414
528
  else if (result === "conflict" || result === "fail") phase = "running";
415
529
  if (phase === undefined) continue;
416
530
  if (!(await recordMergeReported(store, object.id, attempt.number))) continue;
417
- writeSchedulerLine(`${bareId(object.id)} integrating -> ${phase}`);
531
+ changed = true;
532
+ writeSchedulerLine(`${idOfKey(object.id)} integrating -> ${phase}`);
418
533
  }
534
+ return changed;
419
535
  }
420
536
 
421
537
  /** Marks a plan finished once, when every task has merged or been cancelled. */
@@ -429,7 +545,7 @@ async function reportFinishedPlans(
429
545
  if (plan.status !== "confirmed" || plan.finishedReported === true) {
430
546
  continue;
431
547
  }
432
- const mine = planTasks(tasks, bareId(object.id));
548
+ const mine = planTasks(tasks, idOfKey(object.id));
433
549
  if (mine.length === 0) continue;
434
550
  const finished = mine.every((task) => {
435
551
  const phase = taskData(task.data).phase;
@@ -437,7 +553,7 @@ async function reportFinishedPlans(
437
553
  });
438
554
  if (!finished) continue;
439
555
  if (!(await recordPlanFinishedReported(store, object.id))) continue;
440
- writeSchedulerLine(`${bareId(object.id)} confirmed -> finished`);
556
+ writeSchedulerLine(`${idOfKey(object.id)} confirmed -> finished`);
441
557
  }
442
558
  }
443
559
 
@@ -479,9 +595,10 @@ async function reconcileTaskRuns(
479
595
  tasks: readonly StoredObject[],
480
596
  canStartWork: boolean,
481
597
  flows: RepositoryFlows,
482
- ): Promise<void> {
598
+ ): Promise<boolean> {
483
599
  const runs = ctx.runLookup;
484
- if (runs === undefined) return;
600
+ if (runs === undefined) return false;
601
+ let changed = false;
485
602
  for (const object of tasksOf(tasks, repository)) {
486
603
  const task = taskData(object.data);
487
604
  if (task.phase !== "waiting" && task.phase !== "running" && task.phase !== "review") {
@@ -497,7 +614,8 @@ async function reconcileTaskRuns(
497
614
  run: run.runId,
498
615
  });
499
616
  if (moved === undefined) continue;
500
- writeSchedulerLine(`${bareId(object.id)} ${task.phase} -> waiting`);
617
+ changed = true;
618
+ writeSchedulerLine(`${idOfKey(object.id)} ${task.phase} -> waiting`);
501
619
  }
502
620
  continue;
503
621
  }
@@ -511,7 +629,8 @@ async function reconcileTaskRuns(
511
629
  const plan = await ctx.store.get("plan", storeKey(task.repository, task.plan));
512
630
  const requested = task.flow ?? (plan === undefined ? undefined : planData(plan.data).flow);
513
631
  const selected =
514
- task.flowName !== undefined
632
+ task.flowName !== undefined &&
633
+ (task.flowGraph === undefined || declareStoredFlow(ctx, object))
515
634
  ? { name: task.flowName, graph: task.flowGraph }
516
635
  : flowFor(flows, requested);
517
636
  if (selected === undefined) {
@@ -526,22 +645,25 @@ async function reconcileTaskRuns(
526
645
  run: null,
527
646
  });
528
647
  if (moved !== undefined) {
529
- writeSchedulerLine(`${bareId(object.id)} ${task.phase} -> waiting (${reason})`);
648
+ changed = true;
649
+ writeSchedulerLine(`${idOfKey(object.id)} ${task.phase} -> waiting (${reason})`);
530
650
  }
531
651
  }
532
652
  continue;
533
653
  }
534
654
  if ((await reopenTask(ctx.store, object.id)) === undefined) continue;
655
+ changed = true;
535
656
  try {
536
657
  if (await startOne(ctx, object, { runStoppedAt: step ?? "the run" }, false, selected)) {
537
658
  writeSchedulerLine(
538
- `${bareId(object.id)} ${task.phase} -> waiting (run stopped during ${step ?? "the run"})`,
659
+ `${idOfKey(object.id)} ${task.phase} -> waiting (run stopped during ${step ?? "the run"})`,
539
660
  );
540
661
  }
541
662
  } catch (error) {
542
663
  if (!(error instanceof ActiveRunError)) throw error;
543
664
  }
544
665
  }
666
+ return changed;
545
667
  }
546
668
 
547
669
  /** What the scheduler last said about each repository's settings file. */
@@ -572,12 +694,68 @@ function reportSettingsProblem(repository: RepositoryData): void {
572
694
  console.error(`dev: repository "${repository.name}": ${problem}`);
573
695
  }
574
696
 
697
+ /** What the scheduler last said about each repository's test host. */
698
+ const reportedCheckHosts = new Map<string, string>();
699
+
700
+ /**
701
+ * Says once per change that a repository's check commands use
702
+ * `remote-check.sh` while no test host is set. The commands run here,
703
+ * so a person must know before the checks do; a host that is set later clears
704
+ * the line, and losing it again says it once more.
705
+ */
706
+ function reportCheckHostProblem(
707
+ ctx: TickContext,
708
+ repository: RepositoryData,
709
+ settings: DevSettings,
710
+ ): void {
711
+ const warning = checkHostWarning(repository.name, settings, ctx.settings);
712
+ if (warning === undefined) {
713
+ reportedCheckHosts.delete(repository.path);
714
+ return;
715
+ }
716
+ if (reportedCheckHosts.get(repository.path) === warning) return;
717
+ reportedCheckHosts.set(repository.path, warning);
718
+ console.error(`dev: ${warning}`);
719
+ }
720
+
721
+ /** The tasks and plans one pass reads, and the tasks it refreshes after a write. */
722
+ interface PassSnapshot {
723
+ readonly store: ObjectStore;
724
+ tasks: StoredObject[];
725
+ readonly plans: readonly StoredObject[];
726
+ }
727
+
728
+ /** Replaces one repository's tasks in the pass snapshot; other repositories stay as read. */
729
+ async function refreshRepositoryTasks(
730
+ snapshot: PassSnapshot,
731
+ repository: string,
732
+ ): Promise<void> {
733
+ const fresh = await listAll(snapshot.store, "task", { repository });
734
+ snapshot.tasks = [
735
+ ...snapshot.tasks.filter(
736
+ (object) => taskData(object.data).repository !== repository,
737
+ ),
738
+ ...fresh,
739
+ ];
740
+ }
741
+
742
+ /** The versions of a plan's tasks, so an unchanged finished plan is left alone. */
743
+ const planTaskSignatures = new WeakMap<ObjectStore, Map<string, string>>();
744
+
745
+ function taskSignature(tasks: readonly StoredObject[]): string {
746
+ return tasks
747
+ .map((object) => `${object.id}:${object.version}`)
748
+ .sort()
749
+ .join("\n");
750
+ }
751
+
575
752
  async function scheduleRepository(
576
753
  ctx: TickContext,
577
754
  repository: RepositoryData,
578
- initialTasks: readonly StoredObject[],
579
- initialPlans: readonly StoredObject[],
755
+ snapshot: PassSnapshot,
580
756
  ): Promise<void> {
757
+ let dirty = false;
758
+ const initialTasks = tasksOf(snapshot.tasks, repository.name);
581
759
  reportSettingsProblem(repository);
582
760
  // A cancelled task's run ends whether or not the settings can be read.
583
761
  if (ctx.runLookup !== undefined) {
@@ -591,6 +769,7 @@ async function scheduleRepository(
591
769
  // here may touch the repository's running steps.
592
770
  return;
593
771
  }
772
+ reportCheckHostProblem(ctx, repository, settings);
594
773
  // Work needs the plugins dev runs its steps through; without them a task
595
774
  // stays ready instead of failing.
596
775
  const canStartWork = missingPlugins(ctx.loaded).length === 0;
@@ -599,11 +778,18 @@ async function scheduleRepository(
599
778
  // and a graph recorded there is declared again below so a fresh process
600
779
  // resumes a running attempt on the graph it started with.
601
780
  const flows = await declareRepositoryFlows(ctx, repository, settings);
602
- declareStoredFlows(ctx, initialTasks);
781
+ declareStoredFlows(ctx, tasksOf(snapshot.tasks, repository.name));
603
782
 
604
783
  // Repair a run that ended without an edge, or one whose phase was left
605
784
  // behind, before the scheduler reads phases and starts anything else.
606
- await reconcileTaskRuns(ctx, repository.name, initialTasks, canStartWork, flows);
785
+ dirty =
786
+ (await reconcileTaskRuns(
787
+ ctx,
788
+ repository.name,
789
+ tasksOf(snapshot.tasks, repository.name),
790
+ canStartWork,
791
+ flows,
792
+ )) || dirty;
607
793
 
608
794
  // A claim is not durable until the kernel records the run. A task left
609
795
  // running with no run is a start that never landed (a crash or a kernel
@@ -613,7 +799,7 @@ async function scheduleRepository(
613
799
  // A claim whose run the kernel already holds is a start still landing: the
614
800
  // run's first step records its id moments later. Releasing it would cancel
615
801
  // that run and start another one on the next tick, forever.
616
- for (const object of tasksOf(initialTasks, repository.name)) {
802
+ for (const object of tasksOf(snapshot.tasks, repository.name)) {
617
803
  const task = taskData(object.data);
618
804
  if ((task.phase !== "running" && task.phase !== "review") || task.run !== null) continue;
619
805
  if (
@@ -623,28 +809,37 @@ async function scheduleRepository(
623
809
  continue;
624
810
  }
625
811
  if ((await releaseTaskClaim(ctx.store, object.id)) === undefined) continue;
626
- writeSchedulerLine(`${bareId(object.id)} running -> ready`);
812
+ dirty = true;
813
+ writeSchedulerLine(`${idOfKey(object.id)} running -> ready`);
627
814
  }
628
815
 
629
816
  // Findings that did not fail a review become one follow-up task once the
630
817
  // plan has no open task; this runs before a plan can be reported finished.
631
- await collectFollowups(ctx.store, repository.name, settings);
818
+ const followupsPending = snapshot.tasks.some((object) => {
819
+ const task = taskData(object.data);
820
+ return task.repository === repository.name && task.followups?.state === "collect";
821
+ });
822
+ await collectFollowups(ctx.store, repository.name, settings, snapshot.tasks);
823
+ if (followupsPending) dirty = true;
632
824
 
633
825
  // 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));
826
+ if (dirty) {
827
+ await refreshRepositoryTasks(snapshot, repository.name);
828
+ dirty = false;
829
+ }
830
+ const current = tasksOf(snapshot.tasks, repository.name);
831
+ const plans = orderPlans(plansOf(snapshot.plans, repository.name));
637
832
  const tasksById = new Map(
638
- allCurrent.map((object) => [object.id, taskData(object.data)]),
833
+ snapshot.tasks.map((object) => [object.id, taskData(object.data)]),
639
834
  );
640
835
  declareStoredFlows(ctx, current);
641
836
 
642
- await reportIntegrationResults(ctx.store, current);
837
+ dirty = (await reportIntegrationResults(ctx.store, current)) || dirty;
643
838
  await reportFinishedPlans(ctx.store, plans, current);
644
839
 
645
840
  const planActive = new Map<string, number>();
646
841
  for (const planObject of plans) {
647
- const id = bareId(planObject.id);
842
+ const id = idOfKey(planObject.id);
648
843
  planActive.set(
649
844
  id,
650
845
  planTasks(current, id).filter((object) =>
@@ -656,7 +851,7 @@ async function scheduleRepository(
656
851
  isActive(taskData(object.data)),
657
852
  ).length;
658
853
  // 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)]));
854
+ const plansByName = new Map(plans.map((object) => [idOfKey(object.id), planData(object.data)]));
660
855
  // A task that has started runs the graph it started with, so its pool is
661
856
  // that graph's; dev.json changing meanwhile does not move it.
662
857
  const poolOf = (task: TaskData): string =>
@@ -675,7 +870,7 @@ async function scheduleRepository(
675
870
  for (const object of current) {
676
871
  const task = taskData(object.data);
677
872
  if (task.area !== undefined && isActive(task) && !areaActive.has(task.area)) {
678
- areaActive.set(task.area, bareId(object.id));
873
+ areaActive.set(task.area, idOfKey(object.id));
679
874
  }
680
875
  }
681
876
 
@@ -683,17 +878,17 @@ async function scheduleRepository(
683
878
  const oldestPlanHeld = new Set<string>();
684
879
  const lastStarted = new Map<string, number>(
685
880
  plans.map((object) => [
686
- bareId(object.id),
881
+ idOfKey(object.id),
687
882
  planData(object.data).lastStartedAt ?? 0,
688
883
  ]),
689
884
  );
690
885
  const turnOf = (object: StoredObject): number =>
691
- lastStarted.get(bareId(object.id)) ?? 0;
886
+ lastStarted.get(idOfKey(object.id)) ?? 0;
692
887
  const byUrgency = (left: StoredObject, right: StoredObject): number =>
693
888
  priorityIndex(planData(left.data).priority) -
694
889
  priorityIndex(planData(right.data).priority);
695
890
  const byId = (left: StoredObject, right: StoredObject): number =>
696
- bareId(left.id).localeCompare(bareId(right.id));
891
+ idOfKey(left.id).localeCompare(idOfKey(right.id));
697
892
  /** Priority first; within one priority the plan that started longest ago. */
698
893
  const turnOrder = (): readonly StoredObject[] =>
699
894
  [...plans].sort(
@@ -732,11 +927,16 @@ async function scheduleRepository(
732
927
  if (task.phase !== "ready") return false;
733
928
  if (!dependencyState(task, tasksById).ready) return false;
734
929
  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;
930
+ // A ready task that already holds the clone (it was paused, or its claim
931
+ // was released) does not count against itself.
932
+ const own = isActive(task) ? 1 : 0;
933
+ if (task.area !== undefined && areaActive.has(task.area) && areaActive.get(task.area) !== idOfKey(object.id)) {
934
+ return false;
935
+ }
936
+ if (planConcurrency(plan) - ((planActive.get(planId) ?? 0) - own) <= 0) return false;
937
+ if (repositoryActive - own >= repositoryConcurrency(settings)) return false;
738
938
  const pool = poolOf(task);
739
- return (poolActive.get(pool) ?? 0) < repositoryConcurrency(settings, pool);
939
+ return (poolActive.get(pool) ?? 0) - own < repositoryConcurrency(settings, pool);
740
940
  };
741
941
 
742
942
  /**
@@ -751,7 +951,7 @@ async function scheduleRepository(
751
951
  const scoped = (planObject: StoredObject): readonly StoredObject[] => {
752
952
  const plan = planData(planObject.data);
753
953
  if (plan.status !== "confirmed") return [];
754
- return planTasks(current, bareId(planObject.id))
954
+ return planTasks(current, idOfKey(planObject.id))
755
955
  .filter((object) => {
756
956
  const task = taskData(object.data);
757
957
  return task.phase === "ready" && inScope(task, plan);
@@ -776,7 +976,8 @@ async function scheduleRepository(
776
976
  if (
777
977
  await startOne(ctx, object, { blockedBy: dependencies.cancelled }, false, selected)
778
978
  ) {
779
- writeSchedulerLine(`${bareId(object.id)} ready -> waiting`);
979
+ dirty = true;
980
+ writeSchedulerLine(`${idOfKey(object.id)} ready -> waiting`);
780
981
  started.add(object.id);
781
982
  }
782
983
  }
@@ -788,7 +989,7 @@ async function scheduleRepository(
788
989
  let progress = false;
789
990
  for (const planObject of order) {
790
991
  const plan = planData(planObject.data);
791
- const planId = bareId(planObject.id);
992
+ const planId = idOfKey(planObject.id);
792
993
  const pick = scoped(planObject).find(
793
994
  (object) =>
794
995
  !failed.has(object.id) && canStart(object, plan, planId),
@@ -806,13 +1007,14 @@ async function scheduleRepository(
806
1007
  failed.add(pick.id);
807
1008
  break;
808
1009
  }
1010
+ dirty = true;
809
1011
  const task = taskData(pick.data);
810
- writeSchedulerLine(`${bareId(pick.id)} ready -> running`);
1012
+ writeSchedulerLine(`${idOfKey(pick.id)} ready -> running`);
811
1013
  planActive.set(planId, (planActive.get(planId) ?? 0) + 1);
812
1014
  repositoryActive += 1;
813
1015
  const startedPool = poolOf(task);
814
1016
  poolActive.set(startedPool, (poolActive.get(startedPool) ?? 0) + 1);
815
- if (task.area !== undefined) areaActive.set(task.area, bareId(pick.id));
1017
+ if (task.area !== undefined) areaActive.set(task.area, idOfKey(pick.id));
816
1018
  started.add(pick.id);
817
1019
  if (useOldestPlan) oldestPlanHeld.add(pick.id);
818
1020
  const at = changeClock.now();
@@ -828,7 +1030,7 @@ async function scheduleRepository(
828
1030
  const plan = planData(planObject.data);
829
1031
  if (plan.status !== "confirmed" || plan.auto !== "merge") continue;
830
1032
 
831
- for (const object of planTasks(current, bareId(planObject.id))) {
1033
+ for (const object of planTasks(current, idOfKey(planObject.id))) {
832
1034
  const task = taskData(object.data);
833
1035
  const attempt = task.attempt;
834
1036
  if (!autoMergeWaits(task) || attempt === undefined || task.run === null) {
@@ -842,7 +1044,8 @@ async function scheduleRepository(
842
1044
  continue;
843
1045
  }
844
1046
  await recordAutoMerge(ctx.store, object.id, attempt.number);
845
- writeSchedulerLine(`${bareId(object.id)} waiting -> integrating`);
1047
+ dirty = true;
1048
+ writeSchedulerLine(`${idOfKey(object.id)} waiting -> integrating`);
846
1049
  }
847
1050
  }
848
1051
 
@@ -850,7 +1053,7 @@ async function scheduleRepository(
850
1053
  for (const object of current) {
851
1054
  const task = taskData(object.data);
852
1055
  if (task.oldestPlanSlot === true && !isActive(task)) {
853
- await clearOldestPlanSlot(ctx.store, object.id);
1056
+ dirty = (await clearOldestPlanSlot(ctx.store, object.id)) || dirty;
854
1057
  }
855
1058
  }
856
1059
 
@@ -862,6 +1065,14 @@ async function scheduleRepository(
862
1065
  flows,
863
1066
  );
864
1067
 
1068
+ // Starts and repairs changed the tasks; read them once before the notes and
1069
+ // counts below. A pass that changed nothing keeps the snapshot it read.
1070
+ if (dirty) {
1071
+ await refreshRepositoryTasks(snapshot, repository.name);
1072
+ dirty = false;
1073
+ }
1074
+ const latest = tasksOf(snapshot.tasks, repository.name);
1075
+
865
1076
  // The queue of each area: ready tasks in the order the scheduler considers
866
1077
  // them, manual starts first, so a waiting task can say how many are ahead.
867
1078
  const queued: StoredObject[] = [];
@@ -871,7 +1082,7 @@ async function scheduleRepository(
871
1082
  for (const planObject of keptSlotNext() ? oldestPlanOrder() : turnOrder()) {
872
1083
  const plan = planData(planObject.data);
873
1084
  if (plan.status !== "confirmed") continue;
874
- for (const object of [...planTasks(current, bareId(planObject.id))].sort(byId)) {
1085
+ for (const object of [...planTasks(current, idOfKey(planObject.id))].sort(byId)) {
875
1086
  const task = taskData(object.data);
876
1087
  if (task.phase !== "ready" || started.has(object.id)) continue;
877
1088
  if (queuedIds.has(object.id) || !inScope(task, plan)) continue;
@@ -895,24 +1106,27 @@ async function scheduleRepository(
895
1106
 
896
1107
  // Say why a ready task whose dependencies are met is not starting: its area
897
1108
  // is held. The record is cleared once the area is free or the task started.
898
- for (const object of current) {
1109
+ for (const object of latest) {
899
1110
  const task = taskData(object.data);
900
1111
  if (task.phase !== "ready" || started.has(object.id)) continue;
901
1112
  const holder =
902
1113
  task.area !== undefined && dependencyState(task, tasksById).ready
903
1114
  ? areaActive.get(task.area)
904
1115
  : undefined;
905
- await setAreaHold(ctx.store, object.id, holder, aheadOf(object));
1116
+ dirty =
1117
+ (await setAreaHold(ctx.store, object.id, holder, aheadOf(object), task)) || dirty;
906
1118
  const dependencies = dependencyState(task, tasksById);
907
- await setDependencyHold(
908
- ctx.store,
909
- object.id,
910
- !dependencies.ready && dependencies.cancelled === undefined,
911
- dependencies.waitingFor,
912
- );
1119
+ dirty =
1120
+ (await setDependencyHold(
1121
+ ctx.store,
1122
+ object.id,
1123
+ !dependencies.ready && dependencies.cancelled === undefined,
1124
+ dependencies.waitingFor,
1125
+ task,
1126
+ )) || dirty;
913
1127
  }
914
1128
 
915
- const plansById = new Map(plans.map((object) => [bareId(object.id), planData(object.data)]));
1129
+ const plansById = new Map(plans.map((object) => [idOfKey(object.id), planData(object.data)]));
916
1130
 
917
1131
  // Say why a ready task that could otherwise start does not: the plan's or
918
1132
  // the repository's slots are full, or a plugin dev needs is not loaded.
@@ -921,15 +1135,15 @@ async function scheduleRepository(
921
1135
  return more.length === 0 ? first : `${first} and ${more.length} more`;
922
1136
  };
923
1137
  const activeIds = (inPlan: string | undefined): readonly string[] =>
924
- current
1138
+ latest
925
1139
  .filter((object) => {
926
1140
  const task = taskData(object.data);
927
1141
  return (isActive(task) || started.has(object.id)) && (inPlan === undefined || task.plan === inPlan);
928
1142
  })
929
- .map((object) => bareId(object.id))
1143
+ .map((object) => idOfKey(object.id))
930
1144
  .sort();
931
1145
  const missing = missingPlugins(ctx.loaded).map((plugin) => plugin.name);
932
- for (const object of current) {
1146
+ for (const object of latest) {
933
1147
  const task = taskData(object.data);
934
1148
  if (task.phase !== "ready" || started.has(object.id)) continue;
935
1149
  let note: string | undefined;
@@ -937,8 +1151,10 @@ async function scheduleRepository(
937
1151
  note = "waiting for the plan to resume";
938
1152
  } else if (queuedIds.has(object.id)) {
939
1153
  const plan = plansById.get(task.plan);
940
- const holders = activeIds(task.plan);
941
- const all = activeIds(undefined);
1154
+ // A ready task that holds the clone itself is not held by itself.
1155
+ const self = idOfKey(object.id);
1156
+ const holders = activeIds(task.plan).filter((held) => held !== self);
1157
+ const all = activeIds(undefined).filter((held) => held !== self);
942
1158
  if (missing.length > 0) {
943
1159
  note = `waiting for plugin ${missing.join(", ")}`;
944
1160
  } else if (task.area !== undefined && areaActive.has(task.area)) {
@@ -947,12 +1163,13 @@ async function scheduleRepository(
947
1163
  note = `waiting for the plan's slot (${heldBy(holders)})`;
948
1164
  } else {
949
1165
  const pool = poolOf(task);
950
- const inPool = current
1166
+ const inPool = latest
951
1167
  .filter((other) => {
952
1168
  const otherTask = taskData(other.data);
953
1169
  return (isActive(otherTask) || started.has(other.id)) && poolOf(otherTask) === pool;
954
1170
  })
955
- .map((other) => bareId(other.id))
1171
+ .map((other) => idOfKey(other.id))
1172
+ .filter((held) => held !== self)
956
1173
  .sort();
957
1174
  if (
958
1175
  Object.keys(settings.workers.pools).length > 1 &&
@@ -965,31 +1182,60 @@ async function scheduleRepository(
965
1182
  }
966
1183
  }
967
1184
  }
968
- await setSlotHold(ctx.store, object.id, note);
1185
+ dirty = (await setSlotHold(ctx.store, object.id, note, task)) || dirty;
969
1186
  }
970
1187
 
971
1188
  // Name each open task's flow when the repository defines more than one, and
972
1189
  // say why a ready task whose flow is not defined does not start.
973
- for (const object of await listAll(ctx.store, "task")) {
1190
+ for (const object of latest) {
974
1191
  const task = taskData(object.data);
975
- if (task.repository !== repository.name) continue;
976
1192
  const requested = task.flow ?? plansById.get(task.plan)?.flow ?? "default";
977
1193
  const missing =
978
1194
  (task.phase === "ready" ||
979
1195
  (task.phase === "waiting" && task.run === null)) &&
980
1196
  task.flowName === undefined &&
981
1197
  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
- });
1198
+ dirty =
1199
+ (await setFlowNote(
1200
+ ctx.store,
1201
+ object.id,
1202
+ {
1203
+ shown: flows.named.size > 1 ? requested : undefined,
1204
+ held: missing
1205
+ ? (flows.refused.get(requested) ?? `flow ${requested} is not defined in .operad/dev.json`)
1206
+ : undefined,
1207
+ },
1208
+ task,
1209
+ )) || dirty;
1210
+ }
1211
+
1212
+ if (dirty) {
1213
+ await refreshRepositoryTasks(snapshot, repository.name);
1214
+ dirty = false;
1215
+ }
1216
+ const final = tasksOf(snapshot.tasks, repository.name);
1217
+ const tasksByPlan = new Map<string, StoredObject[]>();
1218
+ for (const object of final) {
1219
+ const plan = taskData(object.data).plan;
1220
+ const mine = tasksByPlan.get(plan);
1221
+ if (mine === undefined) tasksByPlan.set(plan, [object]);
1222
+ else mine.push(object);
1223
+ }
1224
+ let signatures = planTaskSignatures.get(ctx.store);
1225
+ if (signatures === undefined) {
1226
+ signatures = new Map();
1227
+ planTaskSignatures.set(ctx.store, signatures);
988
1228
  }
989
1229
 
990
1230
  // Keep each plan's cached counts, and with them its row's mark, current.
991
1231
  for (const planObject of plans) {
992
- await refreshPlanCounts(ctx.store, await getPlan(ctx.store, planObject.id));
1232
+ const id = idOfKey(planObject.id);
1233
+ const mine = tasksByPlan.get(id) ?? [];
1234
+ const signature = taskSignature(mine);
1235
+ const changed = signatures.get(planObject.id) !== signature;
1236
+ if (planData(planObject.data).finishedReported === true && !changed) continue;
1237
+ await refreshPlanCounts(ctx.store, await getPlan(ctx.store, planObject.id), mine);
1238
+ signatures.set(planObject.id, signature);
993
1239
  }
994
1240
  }
995
1241
 
@@ -1039,13 +1285,16 @@ export function runScheduler(ctx: TickContext): Promise<void> {
1039
1285
  async function runPass(ctx: TickContext): Promise<void> {
1040
1286
  const repositories = await listRepositories(ctx.store);
1041
1287
  if (repositories.length === 0) return;
1042
- const tasks = await listAll(ctx.store, "task");
1043
- const plans = await listAll(ctx.store, "plan");
1288
+ const snapshot: PassSnapshot = {
1289
+ store: ctx.store,
1290
+ tasks: await listAll(ctx.store, "task"),
1291
+ plans: await listAll(ctx.store, "plan"),
1292
+ };
1044
1293
  for (const repository of repositories) {
1045
1294
  try {
1046
- await scheduleRepository(ctx, repository, tasks, plans);
1295
+ await scheduleRepository(ctx, repository, snapshot);
1047
1296
  } catch (error) {
1048
- const message = error instanceof Error ? error.message : String(error);
1297
+ const message = messageOf(error);
1049
1298
  console.error(`dev: repository "${repository.name}": ${message}`);
1050
1299
  }
1051
1300
  }