@operad-io/dev 0.1.0 → 0.2.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.
package/src/service.ts CHANGED
@@ -11,15 +11,15 @@ import {
11
11
  } from "node:fs";
12
12
  import { homedir } from "node:os";
13
13
  import { basename, isAbsolute, join, relative, resolve } from "node:path";
14
- import { objectValueAfter, ViewError } from "@operad-io/engine";
14
+ import { ViewError } from "@operad-io/engine";
15
15
  import { isBusy } from "@operad-io/engine/platform";
16
- import type { FlowDefinition, ObjectStore, PluginFact, StoredObject } from "@operad-io/engine";
16
+ import type { FlowDefinition, ObjectStore, StoredObject } from "@operad-io/engine";
17
17
  import { git } from "./git.ts";
18
+ import { withdrawIntegration } from "./integration-queue.ts";
18
19
  import { withRepositoryLock } from "./lock.ts";
19
20
  import {
20
21
  appendChange,
21
- appendRework,
22
- bareId,
22
+ idOfKey,
23
23
  dependencyKey,
24
24
  dependencyLabel,
25
25
  DevError,
@@ -66,7 +66,7 @@ import { DEFAULT_DEV_SETTINGS, DEV_SETTINGS_SCHEMA } from "./settings.ts";
66
66
  /** An optional way for the dev plugin to ask the kernel to cancel a run. */
67
67
  export interface DevRunControl {
68
68
  /** `flow` is the run's own graph, when the task stores one the loaded plugins lack. */
69
- cancel(runId: string, flow?: FlowDefinition): Promise<void> | void;
69
+ cancel(runId: string, flow?: FlowDefinition): Promise<boolean | void> | boolean | void;
70
70
  }
71
71
 
72
72
  export interface ResolveRepositoryOptions {
@@ -289,7 +289,7 @@ function noRepositoryHere(
289
289
  if (registered.length === 0) {
290
290
  return new DevError(
291
291
  "repo",
292
- `no registered repository contains ${cwd}, and none is registered; register one with \`operad repo add <path>\``,
292
+ `no registered repository contains ${cwd}, and none is registered; register one with \`operad dev repo add <path>\``,
293
293
  );
294
294
  }
295
295
  return new DevError(
@@ -308,7 +308,7 @@ function unknownRepository(
308
308
  if (registered.length === 0) {
309
309
  return new DevError(
310
310
  "repo",
311
- `no registered repository "${name}", and none is registered; register one with \`operad repo add <path>\``,
311
+ `no registered repository "${name}", and none is registered; register one with \`operad dev repo add <path>\``,
312
312
  );
313
313
  }
314
314
  return new DevError(
@@ -482,7 +482,6 @@ function writeSettings(repositoryPath: string, name: string): void {
482
482
  mainBranch: DEFAULT_DEV_SETTINGS.mainBranch,
483
483
  worktreeRoot: DEFAULT_DEV_SETTINGS.worktreeRoot,
484
484
  concurrency: DEFAULT_DEV_SETTINGS.concurrency,
485
- worker: DEFAULT_DEV_SETTINGS.worker,
486
485
  workerBrief: DEFAULT_DEV_SETTINGS.workerBrief,
487
486
  },
488
487
  null,
@@ -492,6 +491,28 @@ function writeSettings(repositoryPath: string, name: string): void {
492
491
  );
493
492
  }
494
493
 
494
+ /**
495
+ * Whether a repository has a remote. `git remote` prints nothing both for a
496
+ * repository with no remote and, under heavy load, sometimes for one that has
497
+ * one: git exits 0 with empty output. An empty answer is therefore confirmed by
498
+ * a query whose exit status is the answer: `git config --get-regexp` exits 1
499
+ * when no remote is configured. Its output is not read. The pattern needs the
500
+ * second dot that makes the key a remote's own key (`remote.<name>.<key>`):
501
+ * `remote.pushDefault` is a key of the `remote` section, not a remote.
502
+ */
503
+ function repositoryHasRemote(
504
+ path: string,
505
+ ): { readonly present: boolean; readonly err: string } {
506
+ const remotes = git(path, ["remote"]);
507
+ if (remotes.out.length > 0) return { present: true, err: "" };
508
+ const configured = git(path, ["config", "--local", "--get-regexp", "^remote\\..*\\."]);
509
+ if (configured.ok) return { present: true, err: "" };
510
+ return {
511
+ present: false,
512
+ err: remotes.err.length > 0 ? remotes.err : configured.err,
513
+ };
514
+ }
515
+
495
516
  /** Registers a git work tree that has a remote. */
496
517
  export async function addRepository(
497
518
  store: ObjectStore,
@@ -519,20 +540,22 @@ export async function addRepository(
519
540
  if (bare.ok && bare.out === "true") {
520
541
  throw new DevError("path", `"${path}" is a bare repository`);
521
542
  }
522
- const remotes = git(path, ["remote"]);
523
- if (!remotes.ok || remotes.out.length === 0) {
543
+ const remote = repositoryHasRemote(path);
544
+ if (!remote.present) {
524
545
  throw new DevError(
525
546
  "path",
526
- `"${path}" has no remote${remotes.err.length > 0 ? `: ${remotes.err}` : ""}`,
547
+ `"${path}" has no remote${remote.err.length > 0 ? `: ${remote.err}` : ""}`,
527
548
  );
528
549
  }
529
550
 
530
551
  const name = validateRepositoryName(options.name ?? basename(path));
531
- const existing = await findRepository(store, name);
532
- if (existing !== undefined) {
552
+ const existing = await findRepository(store, name, { includeRemoved: true });
553
+ const previous =
554
+ existing === undefined ? undefined : repositoryData(existing.data);
555
+ if (previous !== undefined && !previous.removed) {
533
556
  throw new DevError(
534
557
  "name",
535
- `repository "${name}" is already registered at "${repositoryData(existing.data).path}"`,
558
+ `repository "${name}" is already registered at "${previous.path}"`,
536
559
  );
537
560
  }
538
561
  const samePath = (await listRepositories(store)).find(
@@ -545,14 +568,19 @@ export async function addRepository(
545
568
  );
546
569
  }
547
570
 
548
- const data: RepositoryData = {
549
- name,
550
- path,
551
- removed: false,
552
- openPlans: 0,
553
- openTasks: 0,
554
- activeTasks: 0,
555
- };
571
+ // A removed repository is registered again under its name: its counters and
572
+ // every plan and task under that name stay, and only its path changes.
573
+ const data: RepositoryData =
574
+ previous === undefined
575
+ ? {
576
+ name,
577
+ path,
578
+ removed: false,
579
+ openPlans: 0,
580
+ openTasks: 0,
581
+ activeTasks: 0,
582
+ }
583
+ : { ...previous, name, path, removed: false };
556
584
  await store.put(REPOSITORY_TYPE, name, data, "dev:repo-add");
557
585
  writeSettings(path, name);
558
586
  ensureExcludes(path);
@@ -627,7 +655,7 @@ async function tasksOfPlan(
627
655
  planKey: string,
628
656
  ): Promise<readonly StoredObject[]> {
629
657
  const repository = keyRepository(planKey);
630
- const plan = bareId(planKey);
658
+ const plan = idOfKey(planKey);
631
659
  return (await allTasks(store)).filter((object) => {
632
660
  const task = taskData(object.data);
633
661
  return task.repository === repository && task.plan === plan;
@@ -648,14 +676,14 @@ function refuseTask(
648
676
  if (action === "confirm" && task.phase === "proposed" && plan?.state === "confirmed") {
649
677
  return false;
650
678
  }
651
- const said = taskLine(action, task, { id: bareId(key), plan });
679
+ const said = taskLine(action, task, { id: idOfKey(key), plan });
652
680
  if (said?.kind === "refuse") throw new DevRefusal(said.text);
653
681
  return said !== undefined;
654
682
  }
655
683
 
656
684
  /** As `refuseTask`, for a plan action. */
657
685
  function refusePlan(action: PlanActionName, plan: PlanData, key: string): boolean {
658
- const said = planLine(action, plan, { id: bareId(key) });
686
+ const said = planLine(action, plan, { id: idOfKey(key) });
659
687
  if (said?.kind === "refuse") throw new DevRefusal(said.text);
660
688
  return said !== undefined;
661
689
  }
@@ -666,7 +694,7 @@ export async function getPlan(
666
694
  ): Promise<StoredObject> {
667
695
  const object = await store.get(PLAN_TYPE, key);
668
696
  if (object === undefined) {
669
- throw new DevError("plan", `no plan "${bareId(key)}"`);
697
+ throw new DevError("plan", `no plan "${idOfKey(key)}"`);
670
698
  }
671
699
  return object;
672
700
  }
@@ -677,7 +705,7 @@ export async function getTask(
677
705
  ): Promise<StoredObject> {
678
706
  const object = await store.get(TASK_TYPE, key);
679
707
  if (object === undefined) {
680
- throw new DevError("task", `no task "${bareId(key)}"`);
708
+ throw new DevError("task", `no task "${idOfKey(key)}"`);
681
709
  }
682
710
  return object;
683
711
  }
@@ -772,9 +800,10 @@ function sameCostTotals(a: PlanCostTotals | undefined, b: PlanCostTotals): boole
772
800
  export async function refreshPlanCounts(
773
801
  store: ObjectStore,
774
802
  plan: StoredObject,
803
+ tasks?: readonly StoredObject[] | undefined,
775
804
  ): Promise<StoredObject> {
776
805
  try {
777
- return await recountPlan(store, plan);
806
+ return await recountPlan(store, plan, tasks);
778
807
  } catch (error) {
779
808
  if (isBusy(error)) return plan;
780
809
  throw error;
@@ -793,9 +822,10 @@ async function refreshPlanCountsOf(store: ObjectStore, key: string): Promise<voi
793
822
  async function recountPlan(
794
823
  store: ObjectStore,
795
824
  plan: StoredObject,
825
+ knownTasks?: readonly StoredObject[] | undefined,
796
826
  ): Promise<StoredObject> {
797
827
  const data = planData(plan.data);
798
- const tasks = await tasksOfPlan(store, plan.id);
828
+ const tasks = knownTasks ?? (await tasksOfPlan(store, plan.id));
799
829
  const taskCount = tasks.length;
800
830
  const mergedCount = tasks.filter(
801
831
  (object) => taskData(object.data).phase === "merged",
@@ -1026,7 +1056,7 @@ export async function addTask(
1026
1056
  const plan = await getPlan(store, options.plan);
1027
1057
  const planObject = planData(plan.data);
1028
1058
  if (planObject.status === "cancelled") {
1029
- throw new DevError("plan", `plan "${bareId(plan.id)}" is cancelled`);
1059
+ throw new DevError("plan", `plan "${idOfKey(plan.id)}" is cancelled`);
1030
1060
  }
1031
1061
  await devTestHooks.beforeLock?.("task-add");
1032
1062
  const names = await afterLockNames(
@@ -1052,13 +1082,13 @@ export async function addTaskLocked(
1052
1082
  if (current.status === "cancelled") {
1053
1083
  throw new DevError(
1054
1084
  "plan",
1055
- `plan "${bareId(currentPlan.id)}" is cancelled`,
1085
+ `plan "${idOfKey(currentPlan.id)}" is cancelled`,
1056
1086
  );
1057
1087
  }
1058
1088
  if (current.repository !== repository.name) {
1059
1089
  throw new DevError(
1060
1090
  "plan",
1061
- `plan "${bareId(currentPlan.id)}" is not in repository "${repository.name}"`,
1091
+ `plan "${idOfKey(currentPlan.id)}" is not in repository "${repository.name}"`,
1062
1092
  );
1063
1093
  }
1064
1094
  const id = await nextId(store, "task", repository.name, slug);
@@ -1075,7 +1105,7 @@ export async function addTaskLocked(
1075
1105
  options.area === undefined ? undefined : validateArea(options.area);
1076
1106
  const data: TaskData = {
1077
1107
  repository: repository.name,
1078
- plan: bareId(currentPlan.id),
1108
+ plan: idOfKey(currentPlan.id),
1079
1109
  title,
1080
1110
  brief,
1081
1111
  after,
@@ -1273,18 +1303,6 @@ export async function updateTask(
1273
1303
  return updated.object;
1274
1304
  }
1275
1305
 
1276
- /** The task after a run changed its phase. Used by later tasks and by tests. */
1277
- export async function setTaskPhase(
1278
- store: ObjectStore,
1279
- id: string,
1280
- phase: TaskPhase,
1281
- options: { readonly run?: string | null | undefined } = {},
1282
- ): Promise<StoredObject> {
1283
- const written = await changeTaskPhase(store, id, undefined, phase, options);
1284
- if (written === undefined) throw new DevError("task", `no task "${bareId(id)}"`);
1285
- return written;
1286
- }
1287
-
1288
1306
  /**
1289
1307
  * Moves a task to `to` only while it is still in phase `from`, checked under
1290
1308
  * the repository lock; undefined when another pass already moved it, so only
@@ -1300,7 +1318,7 @@ export async function moveTaskPhase(
1300
1318
  return changeTaskPhase(store, id, from, to, options);
1301
1319
  }
1302
1320
 
1303
- async function changeTaskPhase(
1321
+ export async function changeTaskPhase(
1304
1322
  store: ObjectStore,
1305
1323
  id: string,
1306
1324
  from: TaskPhase | undefined,
@@ -1373,12 +1391,11 @@ export async function claimTaskStart(
1373
1391
  const next: TaskData = {
1374
1392
  ...rest,
1375
1393
  ...(options.oldestPlanSlot === true ? { oldestPlanSlot: true } : {}),
1394
+ // The recorded graph follows the flow the start uses: a built-in flow
1395
+ // records none, so a refused graph an older dev wrote is not kept.
1376
1396
  ...(options.flow === undefined
1377
1397
  ? {}
1378
- : {
1379
- flowName: options.flow.name,
1380
- ...(options.flow.graph === undefined ? {} : { flowGraph: options.flow.graph }),
1381
- }),
1398
+ : { flowName: options.flow.name, flowGraph: options.flow.graph }),
1382
1399
  phase: "running",
1383
1400
  run: null,
1384
1401
  brief: appendChange(latest.brief, "running"),
@@ -1401,7 +1418,7 @@ export async function areaHolder(
1401
1418
  const task = taskData(object.data);
1402
1419
  if (task.repository !== repository || task.area !== area) continue;
1403
1420
  if (task.phase === "running" || task.phase === "review") {
1404
- return bareId(object.id);
1421
+ return idOfKey(object.id);
1405
1422
  }
1406
1423
  }
1407
1424
  return undefined;
@@ -1416,17 +1433,17 @@ export async function setAreaHold(
1416
1433
  id: string,
1417
1434
  holder: string | undefined,
1418
1435
  ahead = 0,
1419
- ): Promise<void> {
1436
+ known?: TaskData | undefined,
1437
+ ): Promise<boolean> {
1420
1438
  const same = (task: TaskData): boolean =>
1421
1439
  task.areaHeldBy === holder &&
1422
1440
  (holder === undefined || (task.areaAhead ?? 0) === ahead);
1423
- const initial = await getTask(store, id);
1424
- const data = taskData(initial.data);
1425
- if (same(data)) return;
1426
- await withRepoLock(store, data.repository, async () => {
1441
+ const initial = known ?? taskData((await getTask(store, id)).data);
1442
+ if (same(initial)) return false;
1443
+ return withRepoLock(store, initial.repository, async () => {
1427
1444
  const current = await getTask(store, id);
1428
1445
  const latest = taskData(current.data);
1429
- if (latest.phase !== "ready" || same(latest)) return;
1446
+ if (latest.phase !== "ready" || same(latest)) return false;
1430
1447
  const { areaHeldBy: _held, areaAhead: _ahead, ...rest } = latest;
1431
1448
  await writeTask(
1432
1449
  store,
@@ -1438,6 +1455,7 @@ export async function setAreaHold(
1438
1455
  },
1439
1456
  "dev:task-area-hold",
1440
1457
  );
1458
+ return true;
1441
1459
  });
1442
1460
  }
1443
1461
 
@@ -1450,15 +1468,18 @@ export async function setDependencyHold(
1450
1468
  id: string,
1451
1469
  held: boolean,
1452
1470
  waitingFor: readonly string[] = [],
1453
- ): Promise<void> {
1454
- const initial = await getTask(store, id);
1455
- const data = taskData(initial.data);
1471
+ known?: TaskData | undefined,
1472
+ ): Promise<boolean> {
1473
+ const initial = known ?? taskData((await getTask(store, id)).data);
1456
1474
  const same = (left: readonly string[] | undefined) =>
1457
1475
  (left ?? []).join("\n") === waitingFor.join("\n");
1458
- if ((data.dependencyHeld === true) === held && (!held || same(data.dependencyHeldFor))) {
1459
- return;
1476
+ if (
1477
+ (initial.dependencyHeld === true) === held &&
1478
+ (!held || same(initial.dependencyHeldFor))
1479
+ ) {
1480
+ return false;
1460
1481
  }
1461
- await withRepoLock(store, data.repository, async () => {
1482
+ return withRepoLock(store, initial.repository, async () => {
1462
1483
  const current = await getTask(store, id);
1463
1484
  const latest = taskData(current.data);
1464
1485
  if (
@@ -1466,7 +1487,7 @@ export async function setDependencyHold(
1466
1487
  ((latest.dependencyHeld === true) === held &&
1467
1488
  (!held || same(latest.dependencyHeldFor)))
1468
1489
  ) {
1469
- return;
1490
+ return false;
1470
1491
  }
1471
1492
  const { dependencyHeld: _waits, dependencyHeldFor: _for, ...rest } = latest;
1472
1493
  await writeTask(
@@ -1480,6 +1501,7 @@ export async function setDependencyHold(
1480
1501
  },
1481
1502
  "dev:task-dependency-hold",
1482
1503
  );
1504
+ return true;
1483
1505
  });
1484
1506
  }
1485
1507
 
@@ -1492,14 +1514,14 @@ export async function setSlotHold(
1492
1514
  store: ObjectStore,
1493
1515
  id: string,
1494
1516
  note: string | undefined,
1495
- ): Promise<void> {
1496
- const initial = await getTask(store, id);
1497
- const data = taskData(initial.data);
1498
- if (data.slotHeld === note) return;
1499
- await withRepoLock(store, data.repository, async () => {
1517
+ known?: TaskData | undefined,
1518
+ ): Promise<boolean> {
1519
+ const initial = known ?? taskData((await getTask(store, id)).data);
1520
+ if (initial.slotHeld === note) return false;
1521
+ return withRepoLock(store, initial.repository, async () => {
1500
1522
  const current = await getTask(store, id);
1501
1523
  const latest = taskData(current.data);
1502
- if (latest.phase !== "ready" || latest.slotHeld === note) return;
1524
+ if (latest.phase !== "ready" || latest.slotHeld === note) return false;
1503
1525
  const { slotHeld: _slot, ...rest } = latest;
1504
1526
  await writeTask(
1505
1527
  store,
@@ -1507,6 +1529,7 @@ export async function setSlotHold(
1507
1529
  { ...rest, ...(note === undefined ? {} : { slotHeld: note }) },
1508
1530
  "dev:task-slot-hold",
1509
1531
  );
1532
+ return true;
1510
1533
  });
1511
1534
  }
1512
1535
 
@@ -1518,15 +1541,16 @@ export async function setFlowNote(
1518
1541
  store: ObjectStore,
1519
1542
  id: string,
1520
1543
  note: { readonly shown?: string | undefined; readonly held?: string | undefined },
1521
- ): Promise<void> {
1522
- const initial = await getTask(store, id);
1544
+ known?: TaskData | undefined,
1545
+ ): Promise<boolean> {
1546
+ const initial = known ?? taskData((await getTask(store, id)).data);
1523
1547
  const same = (data: TaskData) =>
1524
1548
  data.flowShown === note.shown && data.flowHeld === note.held;
1525
- if (same(taskData(initial.data))) return;
1526
- await withRepoLock(store, taskData(initial.data).repository, async () => {
1549
+ if (same(initial)) return false;
1550
+ return withRepoLock(store, initial.repository, async () => {
1527
1551
  const current = await getTask(store, id);
1528
1552
  const latest = taskData(current.data);
1529
- if (same(latest)) return;
1553
+ if (same(latest)) return false;
1530
1554
  const { flowShown: _shown, flowHeld: _held, ...rest } = latest;
1531
1555
  await writeTask(
1532
1556
  store,
@@ -1538,6 +1562,7 @@ export async function setFlowNote(
1538
1562
  },
1539
1563
  "dev:task-flow-note",
1540
1564
  );
1565
+ return true;
1541
1566
  });
1542
1567
  }
1543
1568
 
@@ -1567,17 +1592,18 @@ export async function recordPlanStart(
1567
1592
  export async function clearOldestPlanSlot(
1568
1593
  store: ObjectStore,
1569
1594
  id: string,
1570
- ): Promise<void> {
1595
+ ): Promise<boolean> {
1571
1596
  const initial = await getTask(store, id);
1572
1597
  const data = taskData(initial.data);
1573
- if (data.oldestPlanSlot !== true) return;
1574
- await withRepoLock(store, data.repository, async () => {
1598
+ if (data.oldestPlanSlot !== true) return false;
1599
+ return withRepoLock(store, data.repository, async () => {
1575
1600
  const current = await getTask(store, id);
1576
1601
  const latest = taskData(current.data);
1577
- if (latest.oldestPlanSlot !== true) return;
1578
- if (latest.phase === "running" || latest.phase === "review") return;
1602
+ if (latest.oldestPlanSlot !== true) return false;
1603
+ if (latest.phase === "running" || latest.phase === "review") return false;
1579
1604
  const { oldestPlanSlot: _slot, ...rest } = latest;
1580
1605
  await writeTask(store, id, rest, "dev:task-slot-release");
1606
+ return true;
1581
1607
  });
1582
1608
  }
1583
1609
 
@@ -1699,7 +1725,7 @@ export async function requestTaskStart(
1699
1725
  ): Promise<StoredObject> {
1700
1726
  const initial = await getTask(store, id);
1701
1727
  const data = taskData(initial.data);
1702
- const at = `task "${bareId(id)}"`;
1728
+ const at = `task "${idOfKey(id)}"`;
1703
1729
  if (data.phase !== "ready") {
1704
1730
  throw new DevError(
1705
1731
  "phase",
@@ -1770,12 +1796,12 @@ export async function claimWaitingTask(
1770
1796
  const latest = taskData(current.data);
1771
1797
  // Where the task is now: the table's line for this action. A result that
1772
1798
  // is already true (another merge won) succeeds with its line.
1773
- const said = taskLine(action, latest, { id: bareId(id) });
1799
+ const said = taskLine(action, latest, { id: idOfKey(id) });
1774
1800
  if (said?.kind === "done") return { settled: said.text };
1775
1801
  refuseTask(action, latest, id);
1776
1802
  if (current.version !== seen) {
1777
1803
  throw new DevRefusal(
1778
- `${bareId(id)} changed since you looked; look again, then dev:${action}`,
1804
+ `${idOfKey(id)} changed since you looked; look again, then dev:${action}`,
1779
1805
  );
1780
1806
  }
1781
1807
  const claimed = await writeTask(
@@ -1803,27 +1829,6 @@ export async function releaseWaitingClaim(
1803
1829
  });
1804
1830
  }
1805
1831
 
1806
- /** Appends a rework section and records it. */
1807
- export async function addRework(
1808
- store: ObjectStore,
1809
- id: string,
1810
- source: string,
1811
- text: string,
1812
- ): Promise<StoredObject> {
1813
- const initial = await getTask(store, id);
1814
- const data = taskData(initial.data);
1815
- return withRepoLock(store, data.repository, async () => {
1816
- const current = await getTask(store, id);
1817
- const latest = taskData(current.data);
1818
- return writeTask(
1819
- store,
1820
- id,
1821
- { ...latest, brief: appendRework(latest.brief, source, text) },
1822
- "dev:task-rework",
1823
- );
1824
- });
1825
- }
1826
-
1827
1832
  export async function confirmPlan(
1828
1833
  store: ObjectStore,
1829
1834
  id: string,
@@ -1902,14 +1907,34 @@ async function cancelRuns(
1902
1907
  }
1903
1908
  }
1904
1909
 
1910
+ interface CancelledTasks {
1911
+ readonly runs: readonly RunToCancel[];
1912
+ /** The tasks a batch had already pushed; they stay merged, not cancelled. */
1913
+ readonly merged: readonly string[];
1914
+ }
1915
+
1905
1916
  async function cancelTasks(
1906
1917
  store: ObjectStore,
1907
1918
  tasks: readonly StoredObject[],
1908
- ): Promise<readonly RunToCancel[]> {
1919
+ home: string | undefined,
1920
+ repositoryPath: string,
1921
+ ): Promise<CancelledTasks> {
1909
1922
  const runs: RunToCancel[] = [];
1923
+ const merged: string[] = [];
1910
1924
  for (const object of tasks) {
1911
1925
  const data = taskData(object.data);
1912
1926
  if (!isOpenTask(data)) continue;
1927
+ if (home !== undefined) {
1928
+ const withdrawal = await withdrawIntegration(
1929
+ home,
1930
+ { name: data.repository, path: repositoryPath },
1931
+ idOfKey(object.id),
1932
+ );
1933
+ if (withdrawal.kind === "merged") {
1934
+ merged.push(object.id);
1935
+ continue;
1936
+ }
1937
+ }
1913
1938
  if (data.run !== null) runs.push({ run: data.run, flow: data.flowGraph });
1914
1939
  await writeTask(
1915
1940
  store,
@@ -1924,33 +1949,50 @@ async function cancelTasks(
1924
1949
  "dev:task-cancel",
1925
1950
  );
1926
1951
  }
1927
- return runs;
1952
+ return { runs, merged };
1928
1953
  }
1929
1954
 
1930
1955
  export interface CancelOptions {
1931
1956
  readonly runs?: DevRunControl | undefined;
1957
+ /**
1958
+ * The operad home, where the integration queue lives. Without it a cancel
1959
+ * does not look at the queue: only the action, which knows the home, passes it.
1960
+ */
1961
+ readonly home?: string | undefined;
1962
+ }
1963
+
1964
+ export interface CancelledTask {
1965
+ readonly task: StoredObject;
1966
+ readonly runs: readonly RunToCancel[];
1967
+ /** Set when a batch pushed the task first: it stays merged and is not cancelled. */
1968
+ readonly alreadyMerged?: string | undefined;
1932
1969
  }
1933
1970
 
1934
1971
  export async function cancelPlan(
1935
1972
  store: ObjectStore,
1936
1973
  id: string,
1937
1974
  options: CancelOptions = {},
1938
- ): Promise<{ readonly plan: StoredObject; readonly runs: readonly RunToCancel[] }> {
1975
+ ): Promise<{
1976
+ readonly plan: StoredObject;
1977
+ readonly runs: readonly RunToCancel[];
1978
+ readonly merged: readonly string[];
1979
+ }> {
1939
1980
  const initial = await getPlan(store, id);
1940
1981
  const initialData = planData(initial.data);
1982
+ const { home } = options;
1941
1983
  const cancelled = await withRepoLock(
1942
1984
  store,
1943
1985
  initialData.repository,
1944
- async () => {
1986
+ async (fresh) => {
1945
1987
  const plan = await getPlan(store, id);
1946
1988
  const data = planData(plan.data);
1947
- if (refusePlan("cancel", data, id)) return { plan, runs: [] };
1989
+ if (refusePlan("cancel", data, id)) return { plan, runs: [], merged: [] };
1948
1990
  const tasks = await tasksOfPlan(store, id);
1949
- const runs = await cancelTasks(store, tasks);
1991
+ const { runs, merged } = await cancelTasks(store, tasks, home, fresh.path);
1950
1992
  const next: PlanData = { ...data, status: "cancelled" };
1951
1993
  const written = await writePlan(store, id, next, "dev:plan-cancel");
1952
1994
  await refreshPlanCounts(store, written);
1953
- return { plan: written, runs };
1995
+ return { plan: written, runs, merged };
1954
1996
  },
1955
1997
  );
1956
1998
  await cancelRuns(options.runs, cancelled.runs);
@@ -1961,16 +2003,29 @@ export async function cancelTask(
1961
2003
  store: ObjectStore,
1962
2004
  id: string,
1963
2005
  options: CancelOptions = {},
1964
- ): Promise<{ readonly task: StoredObject; readonly runs: readonly RunToCancel[] }> {
2006
+ ): Promise<CancelledTask> {
1965
2007
  const initial = await getTask(store, id);
1966
2008
  const initialData = taskData(initial.data);
2009
+ const { home } = options;
1967
2010
  const cancelled = await withRepoLock(
1968
2011
  store,
1969
2012
  initialData.repository,
1970
- async () => {
2013
+ async (fresh) => {
1971
2014
  const task = await getTask(store, id);
1972
2015
  const data = taskData(task.data);
1973
- if (refuseTask("cancel", data, id)) return { task, runs: [] };
2016
+ if (refuseTask("cancel", data, id)) {
2017
+ return { task, runs: [], merged: data.phase === "merged" };
2018
+ }
2019
+ if (home !== undefined) {
2020
+ const withdrawal = await withdrawIntegration(
2021
+ home,
2022
+ { name: data.repository, path: fresh.path },
2023
+ idOfKey(id),
2024
+ );
2025
+ if (withdrawal.kind === "merged") {
2026
+ return { task, runs: [], merged: true };
2027
+ }
2028
+ }
1974
2029
  const runs: readonly RunToCancel[] =
1975
2030
  data.run === null ? [] : [{ run: data.run, flow: data.flowGraph }];
1976
2031
  const written = await writeTask(
@@ -1986,11 +2041,17 @@ export async function cancelTask(
1986
2041
  "dev:task-cancel",
1987
2042
  );
1988
2043
  await refreshPlanCountsOf(store, storeKey(data.repository, data.plan));
1989
- return { task: written, runs };
2044
+ return { task: written, runs, merged: false };
1990
2045
  },
1991
2046
  );
1992
2047
  await cancelRuns(options.runs, cancelled.runs);
1993
- return cancelled;
2048
+ return {
2049
+ task: cancelled.task,
2050
+ runs: cancelled.runs,
2051
+ ...(cancelled.merged
2052
+ ? { alreadyMerged: `${idOfKey(id)} was merged; nothing can be cancelled` }
2053
+ : {}),
2054
+ };
1994
2055
  }
1995
2056
 
1996
2057
  /**
@@ -2126,35 +2187,3 @@ export async function setConcurrency(
2126
2187
  );
2127
2188
  });
2128
2189
  }
2129
-
2130
- /* ---------------------------------------------------------------------------
2131
- * History
2132
- * ------------------------------------------------------------------------- */
2133
-
2134
- /** Rebuilds the objects a store's facts describe, in append order. */
2135
- export function rebuildObjects(
2136
- facts: readonly PluginFact[],
2137
- ): Map<string, Record<string, unknown>> {
2138
- const objects = new Map<string, Record<string, unknown>>();
2139
- for (const fact of facts) {
2140
- const object = fact.object;
2141
- if (object === undefined) continue;
2142
- const key = `${object.type}:${object.id}`;
2143
- const value = objectValueAfter(fact, objects.get(key) ?? {});
2144
- if (value !== undefined) objects.set(key, { ...value });
2145
- }
2146
- return objects;
2147
- }
2148
-
2149
- /** The live object data, keyed the way `rebuildObjects` keys it. */
2150
- export async function liveObjects(
2151
- store: ObjectStore,
2152
- ): Promise<Map<string, Record<string, unknown>>> {
2153
- const objects = new Map<string, Record<string, unknown>>();
2154
- for (const type of [REPOSITORY_TYPE, PLAN_TYPE, TASK_TYPE]) {
2155
- for (const object of await listAll(store, type)) {
2156
- objects.set(`${type}:${object.id}`, { ...object.data });
2157
- }
2158
- }
2159
- return objects;
2160
- }