@operad-io/dev 0.1.0 → 0.1.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.
package/package.json CHANGED
@@ -1,18 +1,18 @@
1
1
  {
2
2
  "name": "@operad-io/dev",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./src/index.ts"
7
7
  },
8
8
  "dependencies": {
9
- "@operad-io/chat": "0.1.0",
10
- "@operad-io/engine": "0.1.0",
11
- "@operad-io/pool": "0.1.0",
12
- "@operad-io/review-grading": "0.1.0"
9
+ "@operad-io/chat": "0.1.1",
10
+ "@operad-io/engine": "0.1.1",
11
+ "@operad-io/pool": "0.1.1",
12
+ "@operad-io/review-grading": "0.1.1"
13
13
  },
14
14
  "devDependencies": {
15
- "@operad-io/shell": "0.1.0"
15
+ "@operad-io/shell": "0.1.1"
16
16
  },
17
17
  "description": "operad: the dev plugin, plans and tasks on a repository",
18
18
  "repository": {
package/src/actions.ts CHANGED
@@ -443,7 +443,10 @@ export const actions: readonly ActionTypeDefinition[] = [
443
443
  why: planWhy("cancel"),
444
444
  settled: planSettled("cancel"),
445
445
  async run(ctx) {
446
- await cancelPlan(ctx.store, ctx.object.id, { runs: ctx.runs });
446
+ await cancelPlan(ctx.store, ctx.object.id, {
447
+ runs: ctx.runs,
448
+ home: ctx.home,
449
+ });
447
450
  },
448
451
  },
449
452
  {
@@ -459,7 +462,11 @@ export const actions: readonly ActionTypeDefinition[] = [
459
462
  why: taskWhy("cancel"),
460
463
  settled: taskSettled("cancel"),
461
464
  async run(ctx) {
462
- await cancelTask(ctx.store, ctx.object.id, { runs: ctx.runs });
465
+ const cancelled = await cancelTask(ctx.store, ctx.object.id, {
466
+ runs: ctx.runs,
467
+ home: ctx.home,
468
+ });
469
+ return cancelled.alreadyMerged;
463
470
  },
464
471
  },
465
472
  {
package/src/integrate.ts CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  updateMainClone,
26
26
  type CommandRunner,
27
27
  type MainCloneOutcome,
28
+ type PrepareMarker,
28
29
  } from "./mainclone.ts";
29
30
  import { runCheckSteadily } from "./notcode.ts";
30
31
  import { runCheckCommands } from "./rerun.ts";
@@ -71,6 +72,11 @@ export const integrateTestHooks: {
71
72
  turnTaken?: ((task: string) => Promise<void> | void) | undefined;
72
73
  /** Awaited by a batch's leader once it has claimed the tasks queued behind it. */
73
74
  claimed?: ((followers: readonly string[]) => Promise<void> | void) | undefined;
75
+ /**
76
+ * Awaited under the queue's land lock between the leader's last check and
77
+ * its push. A test holds the push to make a cancel race it.
78
+ */
79
+ beforePush?: ((candidate: string) => Promise<void> | void) | undefined;
74
80
  /** How a task waits for its turn before it looks again. */
75
81
  wait?: ((ms: number) => Promise<void>) | undefined;
76
82
  } = {};
@@ -83,6 +89,7 @@ export async function followMain(
83
89
  lines: [],
84
90
  run: async () => ({ ok: true, out: "" }),
85
91
  },
92
+ marker?: PrepareMarker | undefined,
86
93
  ): Promise<MainCloneOutcome> {
87
94
  return updateMainClone(
88
95
  repository.path,
@@ -90,6 +97,7 @@ export async function followMain(
90
97
  sha,
91
98
  prepare.lines,
92
99
  integrateTestHooks.runCommand ?? prepare.run,
100
+ marker,
93
101
  );
94
102
  }
95
103
 
@@ -358,6 +366,22 @@ export async function runIntegrate(
358
366
  let flakyReason: string | undefined;
359
367
  /** The other tasks this task was merged with in one batch. */
360
368
  let batchWith: readonly string[] = [];
369
+ /** Saves that this merge's prepare is due before the clone moves, and done after. */
370
+ const prepareMarker = (record: IntegrationRecord): PrepareMarker => ({
371
+ due: record.prepareDue === true,
372
+ save: async (due) => {
373
+ const pending: IntegrationRecord = {
374
+ ...record,
375
+ result: "pending",
376
+ prepareDue: due,
377
+ };
378
+ return (
379
+ (await writeIntegration(ctx, context, task, attempt, pending, {
380
+ integrating: true,
381
+ })) !== undefined
382
+ );
383
+ },
384
+ });
361
385
  const recordMerged = async (
362
386
  record: IntegrationRecord,
363
387
  sha: string,
@@ -371,10 +395,15 @@ export async function runIntegrate(
371
395
  settings.mainBranch,
372
396
  cloneSha,
373
397
  { lines: settings.prepare, run: mainCloneRunner(ctx, settings) },
398
+ prepareMarker(record),
374
399
  );
375
400
  integrateTestHooks.at?.("clone-followed");
376
401
  const cloneChange = mainCloneChange(clone);
377
- const withClone: IntegrationRecord = { ...record, mainClone: { ...clone } };
402
+ const withClone: IntegrationRecord = {
403
+ ...record,
404
+ prepareDue: false,
405
+ mainClone: { ...clone },
406
+ };
378
407
  if (
379
408
  (await writeIntegration(ctx, context, task, attempt, withClone, {
380
409
  phase: "merged",
@@ -446,10 +475,12 @@ export async function runIntegrate(
446
475
  settings.mainBranch,
447
476
  typeof previous.batchHead === "string" ? previous.batchHead : previous.candidate,
448
477
  { lines: settings.prepare, run: mainCloneRunner(ctx, settings) },
478
+ prepareMarker(record),
449
479
  );
450
480
  const cloneChange = mainCloneChange(clone);
451
481
  const withClone: IntegrationRecord = {
452
482
  ...record,
483
+ prepareDue: false,
453
484
  mainClone: { ...clone },
454
485
  };
455
486
  if (
@@ -709,11 +740,18 @@ export async function runIntegrate(
709
740
  return merged;
710
741
  };
711
742
  // A claimed task that left (cancelled) is not merged: one by one instead.
712
- // Checked last, so the window between this and the push is as short as it can be.
713
- if (queue.stillQueued(followers).length !== followers.length) return undefined;
714
- queue.publish(result);
715
- const push = git(gate, ["push", settings.remote, `HEAD:refs/heads/${settings.mainBranch}`]);
716
- if (push.ok) {
743
+ // The check and the push share the queue's land lock with a withdrawal,
744
+ // so a cancel either comes before the check or after the push.
745
+ const landed = await queue.landWhenStillQueued(followers, result, async () => {
746
+ await integrateTestHooks.beforePush?.(batchHead);
747
+ return git(gate, [
748
+ "push",
749
+ settings.remote,
750
+ `HEAD:refs/heads/${settings.mainBranch}`,
751
+ ]).ok;
752
+ });
753
+ if (landed === "withdrawn") return undefined;
754
+ if (landed === "pushed") {
717
755
  integrateTestHooks.afterPush?.(batchHead);
718
756
  return land({});
719
757
  }
@@ -1118,7 +1156,7 @@ export async function runIntegrate(
1118
1156
  `main moved ${MAX_INTEGRATION_ROUNDS} times while the candidate was built; ${lastError}`,
1119
1157
  );
1120
1158
  } finally {
1121
- queue.leave();
1159
+ await queue.leave();
1122
1160
  }
1123
1161
  }
1124
1162
 
@@ -12,6 +12,11 @@
12
12
  * A ticket is written only by its own task. Claims and "integrate alone" marks
13
13
  * are separate files the leader owns (`c-<leader>.json`, `s-<task>.json`), so a
14
14
  * task that leaves while it is claimed is never written back.
15
+ *
16
+ * Withdrawing a ticket and a leader's last check-and-push take the same lock
17
+ * (`land.lock`): either the withdrawal comes first, so the leader sees it and
18
+ * lands without that task, or the push comes first, so the task stays in the
19
+ * batch. The lock is held across the push, and nothing slower.
15
20
  */
16
21
 
17
22
  import {
@@ -50,11 +55,12 @@ export interface BatchResult {
50
55
  readonly head: string;
51
56
  readonly note?: string | undefined;
52
57
  /**
53
- * `pending` from before the leader pushes until it has recorded the merge. A
54
- * pending result whose leader is gone is settled by whether `head` landed.
55
- * A result without a state is done.
58
+ * `pending` from before the leader pushes until the push succeeds, `pushed`
59
+ * once it has, and `done` after the leader recorded the merge. A pending
60
+ * result whose leader is gone is settled by whether `head` landed. A result
61
+ * without a state is done.
56
62
  */
57
- readonly state?: "pending" | "done" | undefined;
63
+ readonly state?: "pending" | "pushed" | "done" | undefined;
58
64
  readonly members: readonly { readonly task: string; readonly sha: string }[];
59
65
  }
60
66
 
@@ -71,6 +77,24 @@ export type Turn =
71
77
  | { readonly kind: "turn" }
72
78
  | { readonly kind: "batched"; readonly leader: string; readonly result: BatchResult };
73
79
 
80
+ /** What withdrawing a ticket found: it went, or the leader had already pushed it. */
81
+ export type Withdrawal =
82
+ | { readonly kind: "withdrawn" }
83
+ | { readonly kind: "merged"; readonly leader: string; readonly result: BatchResult };
84
+
85
+ /** What a leader's last check, publish and push did. */
86
+ export type Landing = "withdrawn" | "pushed" | "failed";
87
+
88
+ /**
89
+ * Test-only hooks. Production code never sets them. `lockWait` replaces the
90
+ * wait of the land lock so a test can see a withdrawal wait behind a push;
91
+ * `withdrawn` reports what that withdrawal found.
92
+ */
93
+ export const integrationQueueTestHooks: {
94
+ lockWait?: ((ms: number) => Promise<void>) | undefined;
95
+ withdrawn?: ((task: string, kind: Withdrawal["kind"]) => void) | undefined;
96
+ } = {};
97
+
74
98
  export interface QueueOptions {
75
99
  readonly home: string;
76
100
  readonly repository: { readonly name: string; readonly path: string };
@@ -111,6 +135,10 @@ function safeName(task: string): string {
111
135
  return task.replace(/[^A-Za-z0-9._-]/g, "_");
112
136
  }
113
137
 
138
+ function landLockPath(directory: string): string {
139
+ return join(directory, "land.lock");
140
+ }
141
+
114
142
  function writeAtomic(path: string, value: unknown): void {
115
143
  const temporary = `${path}.${process.pid}.tmp`;
116
144
  writeFileSync(temporary, JSON.stringify(value));
@@ -171,6 +199,26 @@ export class IntegrationQueue {
171
199
  return join(this.directory, `r-${safeName(leader)}.json`);
172
200
  }
173
201
 
202
+ /** The lock a withdrawal and a leader's last check-and-push share. */
203
+ private withLandLock<T>(work: () => Promise<T> | T): Promise<T> {
204
+ const wait = integrationQueueTestHooks.lockWait;
205
+ return withLockFile(landLockPath(this.directory), work, {
206
+ label: "integration queue",
207
+ onLog: () => {},
208
+ ...(wait === undefined ? {} : { wait }),
209
+ });
210
+ }
211
+
212
+ /** Removes this task's ticket and its "integrate alone" mark. */
213
+ private removeTicket(): void {
214
+ this.joined = false;
215
+ rmSync(this.ticketPath(this.options.task), { force: true });
216
+ rmSync(this.soloPath(this.options.task), { force: true });
217
+ // Looking prunes what no one needs now: a leader's claim and result stay
218
+ // while a task it claimed is still queued.
219
+ this.tickets();
220
+ }
221
+
174
222
  /** The live tickets in queue order; tickets of dead processes are dropped. */
175
223
  tickets(): readonly Ticket[] {
176
224
  let names: string[];
@@ -272,14 +320,65 @@ export class IntegrationQueue {
272
320
  }
273
321
 
274
322
  /** Gives the turn back, and the ticket with it. */
275
- leave(): void {
323
+ async leave(): Promise<void> {
276
324
  if (!this.joined) return;
277
- this.joined = false;
278
- rmSync(this.ticketPath(this.options.task), { force: true });
279
- rmSync(this.soloPath(this.options.task), { force: true });
280
- // Looking prunes what no one needs now: a leader's claim and result stay
281
- // while a task it claimed is still queued.
282
- this.tickets();
325
+ await this.withLandLock(() => this.removeTicket());
326
+ }
327
+
328
+ /**
329
+ * A withdrawal takes the land lock, so it cannot slip between a leader's last
330
+ * check and its push. It removes the ticket unless the leader already pushed
331
+ * a batch that lists this task; then it says so and leaves the task to record
332
+ * its merge.
333
+ */
334
+ async withdraw(): Promise<Withdrawal> {
335
+ const withdrawal = await this.withLandLock(() => {
336
+ const me = this.options.task;
337
+ const mine = this.tickets().find((ticket) => ticket.task === me);
338
+ // A follower reads its leader's result; the leader reads its own. The
339
+ // leader's ticket is still here while it pushes, so it must be asked too.
340
+ const leader = mine === undefined ? undefined : (mine.claimedBy ?? me);
341
+ if (leader !== undefined) {
342
+ const result = this.readResult(leader);
343
+ if (
344
+ result !== undefined &&
345
+ result.state !== "pending" &&
346
+ result.members.some((member) => member.task === me)
347
+ ) {
348
+ return { kind: "merged" as const, leader, result };
349
+ }
350
+ }
351
+ this.removeTicket();
352
+ return { kind: "withdrawn" as const };
353
+ });
354
+ integrationQueueTestHooks.withdrawn?.(this.options.task, withdrawal.kind);
355
+ return withdrawal;
356
+ }
357
+
358
+ /**
359
+ * The leader's last check, its result and the push, under the land lock. A
360
+ * ticket that left first makes this land without its batch; a push that
361
+ * lands first leaves a result a waiting withdrawal reads as merged.
362
+ */
363
+ async landWhenStillQueued(
364
+ followers: readonly Ticket[],
365
+ result: BatchResult,
366
+ push: () => Promise<boolean> | boolean,
367
+ ): Promise<Landing> {
368
+ return this.withLandLock(async () => {
369
+ const queued = new Set(this.tickets().map((ticket) => ticket.task));
370
+ if (
371
+ !queued.has(this.options.task) ||
372
+ this.stillQueued(followers).length !== followers.length
373
+ ) {
374
+ return "withdrawn" as const;
375
+ }
376
+ this.publish(result);
377
+ const pushed = await push();
378
+ if (!pushed) return "failed" as const;
379
+ this.markPushed();
380
+ return "pushed" as const;
381
+ });
283
382
  }
284
383
 
285
384
  private readResult(leader: string): BatchResult | undefined {
@@ -321,8 +420,19 @@ export class IntegrationQueue {
321
420
  }
322
421
  holder = claimed;
323
422
  }
324
- if (this.options.signal?.aborted === true) throw new IntegrationQueueCancelled();
325
- if (mine === undefined) throw new Error("the integration ticket is gone");
423
+ if (this.options.signal?.aborted === true) {
424
+ const withdrawal = await this.withdraw();
425
+ if (withdrawal.kind === "merged") {
426
+ return {
427
+ kind: "batched",
428
+ leader: withdrawal.leader,
429
+ result: withdrawal.result,
430
+ };
431
+ }
432
+ throw new IntegrationQueueCancelled();
433
+ }
434
+ // Only a withdrawal removes a live task's ticket; its run is cancelled.
435
+ if (mine === undefined) throw new IntegrationQueueCancelled();
326
436
  if (holder === undefined) {
327
437
  const head = tickets.find((ticket) => ticket.claimedBy === undefined);
328
438
  if (head !== undefined && head.task === me) return { kind: "turn" };
@@ -379,7 +489,14 @@ export class IntegrationQueue {
379
489
  writeAtomic(this.resultPath(this.options.task), { ...result, state: "pending" });
380
490
  }
381
491
 
382
- /** The push landed and the leader has recorded it: the result is final. */
492
+ /** The push landed: a waiting withdrawal now reads the batch as merged. */
493
+ private markPushed(): void {
494
+ const result = this.readResult(this.options.task);
495
+ if (result === undefined) return;
496
+ writeAtomic(this.resultPath(this.options.task), { ...result, state: "pushed" });
497
+ }
498
+
499
+ /** The leader has recorded the merge: the result is final. */
383
500
  finish(): void {
384
501
  const result = this.readResult(this.options.task);
385
502
  if (result === undefined) return;
@@ -387,7 +504,28 @@ export class IntegrationQueue {
387
504
  }
388
505
 
389
506
  /** A claimed task is done with the result. */
390
- done(): void {
391
- this.leave();
507
+ async done(): Promise<void> {
508
+ await this.leave();
392
509
  }
393
510
  }
511
+
512
+ /**
513
+ * Takes a task out of the integration queue on behalf of a cancel, with the
514
+ * land lock a leader's last check-and-push takes. It answers `merged` when the
515
+ * leader already pushed a batch that lists the task.
516
+ */
517
+ export async function withdrawIntegration(
518
+ home: string,
519
+ repository: { readonly name: string; readonly path: string },
520
+ task: string,
521
+ ): Promise<Withdrawal> {
522
+ return new IntegrationQueue({
523
+ home,
524
+ repository,
525
+ task,
526
+ run: "",
527
+ verified: "",
528
+ message: "",
529
+ say: () => {},
530
+ }).withdraw();
531
+ }
package/src/mainclone.ts CHANGED
@@ -23,6 +23,18 @@ export type CommandRunner = (
23
23
  line: string,
24
24
  ) => Promise<CommandResult>;
25
25
 
26
+ /**
27
+ * The task's durable record of whether this merge's prepare still has to run.
28
+ * It is saved before the fast-forward, so a restart after the clone moved runs
29
+ * the lines even when the clone already holds the commit.
30
+ */
31
+ export interface PrepareMarker {
32
+ /** True when the record says this merge moved the clone and prepare is not done. */
33
+ readonly due: boolean;
34
+ /** Saves whether prepare is due; false when the record could not be written. */
35
+ readonly save: (due: boolean) => Promise<boolean>;
36
+ }
37
+
26
38
  /** What happened to the main clone. */
27
39
  export interface MainCloneOutcome {
28
40
  readonly updated: boolean;
@@ -57,6 +69,18 @@ async function prepare(
57
69
  return { updated: true, prepared: true, note: "prepare done" };
58
70
  }
59
71
 
72
+ /** Runs prepare and records that it is no longer due, even when a line failed. */
73
+ async function prepareAndClear(
74
+ repository: string,
75
+ lines: readonly string[],
76
+ run: CommandRunner,
77
+ marker: PrepareMarker | undefined,
78
+ ): Promise<MainCloneOutcome> {
79
+ const outcome = await prepare(repository, lines, run);
80
+ await marker?.save(false);
81
+ return outcome;
82
+ }
83
+
60
84
  /** The text a task's Changes shows, or undefined when there is nothing to say. */
61
85
  export function mainCloneChange(outcome: MainCloneOutcome): string | undefined {
62
86
  if (!outcome.updated) return `main clone not updated: ${outcome.note ?? "unknown"}`;
@@ -65,7 +89,9 @@ export function mainCloneChange(outcome: MainCloneOutcome): string | undefined {
65
89
 
66
90
  /**
67
91
  * Fast-forwards the main clone to `sha` when it is on `branch` and clean, then
68
- * runs the prepare lines there when the clone moved.
92
+ * runs the prepare lines there when the clone moved. A marker left by an
93
+ * interrupted merge makes a replay run prepare even when the clone already
94
+ * holds the commit.
69
95
  */
70
96
  export async function updateMainClone(
71
97
  repository: string,
@@ -73,6 +99,7 @@ export async function updateMainClone(
73
99
  sha: string,
74
100
  lines: readonly string[],
75
101
  run: CommandRunner,
102
+ marker?: PrepareMarker | undefined,
76
103
  ): Promise<MainCloneOutcome> {
77
104
  const current = git(repository, ["symbolic-ref", "--short", "-q", "HEAD"]);
78
105
  if (!current.ok || current.out !== branch) {
@@ -88,15 +115,27 @@ export async function updateMainClone(
88
115
  if (status.out.length > 0) {
89
116
  return { updated: false, note: "uncommitted changes" };
90
117
  }
91
- if (git(repository, ["merge-base", "--is-ancestor", sha, "HEAD"]).ok) {
92
- return { updated: true };
118
+ const already = git(repository, ["merge-base", "--is-ancestor", sha, "HEAD"]).ok;
119
+ if (already) {
120
+ if (marker?.due !== true) return { updated: true };
121
+ if (lines.length === 0) {
122
+ await marker.save(false);
123
+ return { updated: true };
124
+ }
125
+ return prepareAndClear(repository, lines, run, marker);
126
+ }
127
+ if (lines.length > 0 && marker !== undefined) {
128
+ if (!(await marker.save(true))) {
129
+ return { updated: false, note: "cannot record that prepare is due" };
130
+ }
93
131
  }
94
132
  const merge = git(repository, ["merge", "--ff-only", sha]);
95
133
  if (!merge.ok) {
134
+ if (lines.length > 0 && marker !== undefined) await marker.save(false);
96
135
  return {
97
136
  updated: false,
98
137
  note: `cannot fast-forward: ${lastLine(merge.err || merge.out) || "git merge failed"}`,
99
138
  };
100
139
  }
101
- return prepare(repository, lines, run);
140
+ return prepareAndClear(repository, lines, run, marker);
102
141
  }
package/src/model.ts CHANGED
@@ -317,6 +317,8 @@ export interface IntegrationRecord {
317
317
  /** True when the branch head was no longer the verified commit. */
318
318
  readonly headMoved?: boolean | null;
319
319
  readonly pushed?: boolean | null;
320
+ /** True when this merge moved the clone and its prepare lines have not finished. */
321
+ readonly prepareDue?: boolean | null;
320
322
  readonly message?: string | null;
321
323
  readonly command?: string | null;
322
324
  readonly log?: string | null;
package/src/service.ts CHANGED
@@ -10,11 +10,12 @@ import {
10
10
  writeFileSync,
11
11
  } from "node:fs";
12
12
  import { homedir } from "node:os";
13
- import { basename, isAbsolute, join, relative, resolve } from "node:path";
13
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
14
14
  import { objectValueAfter, ViewError } from "@operad-io/engine";
15
15
  import { isBusy } from "@operad-io/engine/platform";
16
16
  import type { FlowDefinition, ObjectStore, PluginFact, 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,
@@ -289,7 +290,7 @@ function noRepositoryHere(
289
290
  if (registered.length === 0) {
290
291
  return new DevError(
291
292
  "repo",
292
- `no registered repository contains ${cwd}, and none is registered; register one with \`operad repo add <path>\``,
293
+ `no registered repository contains ${cwd}, and none is registered; register one with \`operad dev repo add <path>\``,
293
294
  );
294
295
  }
295
296
  return new DevError(
@@ -308,7 +309,7 @@ function unknownRepository(
308
309
  if (registered.length === 0) {
309
310
  return new DevError(
310
311
  "repo",
311
- `no registered repository "${name}", and none is registered; register one with \`operad repo add <path>\``,
312
+ `no registered repository "${name}", and none is registered; register one with \`operad dev repo add <path>\``,
312
313
  );
313
314
  }
314
315
  return new DevError(
@@ -1902,14 +1903,45 @@ async function cancelRuns(
1902
1903
  }
1903
1904
  }
1904
1905
 
1906
+ interface CancelledTasks {
1907
+ readonly runs: readonly RunToCancel[];
1908
+ /** The tasks a batch had already pushed; they stay merged, not cancelled. */
1909
+ readonly merged: readonly string[];
1910
+ }
1911
+
1912
+ /** Where a cancel finds the integration queue: the home the action runs in. */
1913
+ function cancelHome(
1914
+ store: ObjectStore,
1915
+ options: CancelOptions,
1916
+ ): string | undefined {
1917
+ if (options.home !== undefined) return options.home;
1918
+ // Before this option, a cancel called the service directly: the default
1919
+ // store sits at `<home>/store`, so that home still finds the queue.
1920
+ return basename(store.root) === "store" ? dirname(store.root) : undefined;
1921
+ }
1922
+
1905
1923
  async function cancelTasks(
1906
1924
  store: ObjectStore,
1907
1925
  tasks: readonly StoredObject[],
1908
- ): Promise<readonly RunToCancel[]> {
1926
+ home: string | undefined,
1927
+ repositoryPath: string,
1928
+ ): Promise<CancelledTasks> {
1909
1929
  const runs: RunToCancel[] = [];
1930
+ const merged: string[] = [];
1910
1931
  for (const object of tasks) {
1911
1932
  const data = taskData(object.data);
1912
1933
  if (!isOpenTask(data)) continue;
1934
+ if (home !== undefined) {
1935
+ const withdrawal = await withdrawIntegration(
1936
+ home,
1937
+ { name: data.repository, path: repositoryPath },
1938
+ bareId(object.id),
1939
+ );
1940
+ if (withdrawal.kind === "merged") {
1941
+ merged.push(object.id);
1942
+ continue;
1943
+ }
1944
+ }
1913
1945
  if (data.run !== null) runs.push({ run: data.run, flow: data.flowGraph });
1914
1946
  await writeTask(
1915
1947
  store,
@@ -1924,33 +1956,47 @@ async function cancelTasks(
1924
1956
  "dev:task-cancel",
1925
1957
  );
1926
1958
  }
1927
- return runs;
1959
+ return { runs, merged };
1928
1960
  }
1929
1961
 
1930
1962
  export interface CancelOptions {
1931
1963
  readonly runs?: DevRunControl | undefined;
1964
+ /** The operad home, where the integration queue lives. */
1965
+ readonly home?: string | undefined;
1966
+ }
1967
+
1968
+ export interface CancelledTask {
1969
+ readonly task: StoredObject;
1970
+ readonly runs: readonly RunToCancel[];
1971
+ /** Set when a batch pushed the task first: it stays merged and is not cancelled. */
1972
+ readonly alreadyMerged?: string | undefined;
1932
1973
  }
1933
1974
 
1934
1975
  export async function cancelPlan(
1935
1976
  store: ObjectStore,
1936
1977
  id: string,
1937
1978
  options: CancelOptions = {},
1938
- ): Promise<{ readonly plan: StoredObject; readonly runs: readonly RunToCancel[] }> {
1979
+ ): Promise<{
1980
+ readonly plan: StoredObject;
1981
+ readonly runs: readonly RunToCancel[];
1982
+ readonly merged: readonly string[];
1983
+ }> {
1939
1984
  const initial = await getPlan(store, id);
1940
1985
  const initialData = planData(initial.data);
1986
+ const home = cancelHome(store, options);
1941
1987
  const cancelled = await withRepoLock(
1942
1988
  store,
1943
1989
  initialData.repository,
1944
- async () => {
1990
+ async (fresh) => {
1945
1991
  const plan = await getPlan(store, id);
1946
1992
  const data = planData(plan.data);
1947
- if (refusePlan("cancel", data, id)) return { plan, runs: [] };
1993
+ if (refusePlan("cancel", data, id)) return { plan, runs: [], merged: [] };
1948
1994
  const tasks = await tasksOfPlan(store, id);
1949
- const runs = await cancelTasks(store, tasks);
1995
+ const { runs, merged } = await cancelTasks(store, tasks, home, fresh.path);
1950
1996
  const next: PlanData = { ...data, status: "cancelled" };
1951
1997
  const written = await writePlan(store, id, next, "dev:plan-cancel");
1952
1998
  await refreshPlanCounts(store, written);
1953
- return { plan: written, runs };
1999
+ return { plan: written, runs, merged };
1954
2000
  },
1955
2001
  );
1956
2002
  await cancelRuns(options.runs, cancelled.runs);
@@ -1961,16 +2007,29 @@ export async function cancelTask(
1961
2007
  store: ObjectStore,
1962
2008
  id: string,
1963
2009
  options: CancelOptions = {},
1964
- ): Promise<{ readonly task: StoredObject; readonly runs: readonly RunToCancel[] }> {
2010
+ ): Promise<CancelledTask> {
1965
2011
  const initial = await getTask(store, id);
1966
2012
  const initialData = taskData(initial.data);
2013
+ const home = cancelHome(store, options);
1967
2014
  const cancelled = await withRepoLock(
1968
2015
  store,
1969
2016
  initialData.repository,
1970
- async () => {
2017
+ async (fresh) => {
1971
2018
  const task = await getTask(store, id);
1972
2019
  const data = taskData(task.data);
1973
- if (refuseTask("cancel", data, id)) return { task, runs: [] };
2020
+ if (refuseTask("cancel", data, id)) {
2021
+ return { task, runs: [], merged: data.phase === "merged" };
2022
+ }
2023
+ if (home !== undefined) {
2024
+ const withdrawal = await withdrawIntegration(
2025
+ home,
2026
+ { name: data.repository, path: fresh.path },
2027
+ bareId(id),
2028
+ );
2029
+ if (withdrawal.kind === "merged") {
2030
+ return { task, runs: [], merged: true };
2031
+ }
2032
+ }
1974
2033
  const runs: readonly RunToCancel[] =
1975
2034
  data.run === null ? [] : [{ run: data.run, flow: data.flowGraph }];
1976
2035
  const written = await writeTask(
@@ -1986,11 +2045,17 @@ export async function cancelTask(
1986
2045
  "dev:task-cancel",
1987
2046
  );
1988
2047
  await refreshPlanCountsOf(store, storeKey(data.repository, data.plan));
1989
- return { task: written, runs };
2048
+ return { task: written, runs, merged: false };
1990
2049
  },
1991
2050
  );
1992
2051
  await cancelRuns(options.runs, cancelled.runs);
1993
- return cancelled;
2052
+ return {
2053
+ task: cancelled.task,
2054
+ runs: cancelled.runs,
2055
+ ...(cancelled.merged
2056
+ ? { alreadyMerged: `${bareId(id)} was merged; nothing can be cancelled` }
2057
+ : {}),
2058
+ };
1994
2059
  }
1995
2060
 
1996
2061
  /**