@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/service.ts CHANGED
@@ -10,17 +10,18 @@ import {
10
10
  writeFileSync,
11
11
  } from "node:fs";
12
12
  import { homedir } from "node:os";
13
- import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
14
- import { objectValueAfter, ViewError } from "@operad-io/engine";
15
- import { isBusy } from "@operad-io/engine/platform";
16
- import type { FlowDefinition, ObjectStore, PluginFact, StoredObject } from "@operad-io/engine";
13
+ import { basename, isAbsolute, join, relative, resolve } from "node:path";
14
+ import { ViewError } from "@operad-io/engine";
15
+ import { isBusy, type GitFinderHost } from "@operad-io/engine/platform";
16
+ import type { FlowDefinition, ObjectStore, StoredObject } from "@operad-io/engine";
17
17
  import { git } from "./git.ts";
18
+ import { assertCanCreateTask, GitStateError, gitStateOf, type GitState } from "./git-state.ts";
18
19
  import { withdrawIntegration } from "./integration-queue.ts";
20
+ import { switchBackToStart } from "./mainclone.ts";
19
21
  import { withRepositoryLock } from "./lock.ts";
20
22
  import {
21
23
  appendChange,
22
- appendRework,
23
- bareId,
24
+ idOfKey,
24
25
  dependencyKey,
25
26
  dependencyLabel,
26
27
  DevError,
@@ -67,7 +68,7 @@ import { DEFAULT_DEV_SETTINGS, DEV_SETTINGS_SCHEMA } from "./settings.ts";
67
68
  /** An optional way for the dev plugin to ask the kernel to cancel a run. */
68
69
  export interface DevRunControl {
69
70
  /** `flow` is the run's own graph, when the task stores one the loaded plugins lack. */
70
- cancel(runId: string, flow?: FlowDefinition): Promise<void> | void;
71
+ cancel(runId: string, flow?: FlowDefinition): Promise<boolean | void> | boolean | void;
71
72
  }
72
73
 
73
74
  export interface ResolveRepositoryOptions {
@@ -79,6 +80,8 @@ export interface AddRepositoryOptions {
79
80
  readonly path: string;
80
81
  readonly name?: string | undefined;
81
82
  readonly cwd?: string | undefined;
83
+ /** The machine the git program is looked up on; a test injects one without git. */
84
+ readonly finder?: GitFinderHost | undefined;
82
85
  }
83
86
 
84
87
  const REPOSITORY_TYPE = "repo";
@@ -450,7 +453,7 @@ export async function resolveDevKey(
450
453
  }
451
454
  }
452
455
 
453
- function ensureExcludes(repositoryPath: string): void {
456
+ export function ensureExcludes(repositoryPath: string): void {
454
457
  const path = git(repositoryPath, ["rev-parse", "--git-path", "info/exclude"]);
455
458
  if (!path.ok) {
456
459
  throw new DevError("path", `is not a git work tree: ${path.err}`);
@@ -468,7 +471,12 @@ function ensureExcludes(repositoryPath: string): void {
468
471
  appendFileSync(excludePath, `${prefix}${missing.join("\n")}\n`, "utf8");
469
472
  }
470
473
 
471
- function writeSettings(repositoryPath: string, name: string): void {
474
+ export function writeSettings(
475
+ repositoryPath: string,
476
+ name: string,
477
+ hasRemote: boolean,
478
+ inPlace: boolean,
479
+ ): void {
472
480
  const directory = join(repositoryPath, ".operad");
473
481
  mkdirSync(directory, { recursive: true });
474
482
  const settings = join(directory, "dev.json");
@@ -479,11 +487,11 @@ function writeSettings(repositoryPath: string, name: string): void {
479
487
  {
480
488
  $schema: DEV_SETTINGS_SCHEMA,
481
489
  name,
482
- remote: DEFAULT_DEV_SETTINGS.remote,
490
+ ...(hasRemote ? { remote: DEFAULT_DEV_SETTINGS.remote } : {}),
491
+ ...(inPlace ? { workIn: "branch" } : {}),
483
492
  mainBranch: DEFAULT_DEV_SETTINGS.mainBranch,
484
493
  worktreeRoot: DEFAULT_DEV_SETTINGS.worktreeRoot,
485
494
  concurrency: DEFAULT_DEV_SETTINGS.concurrency,
486
- worker: DEFAULT_DEV_SETTINGS.worker,
487
495
  workerBrief: DEFAULT_DEV_SETTINGS.workerBrief,
488
496
  },
489
497
  null,
@@ -493,7 +501,32 @@ function writeSettings(repositoryPath: string, name: string): void {
493
501
  );
494
502
  }
495
503
 
496
- /** Registers a git work tree that has a remote. */
504
+ /**
505
+ * Whether a repository has a remote. `git remote` prints nothing both for a
506
+ * repository with no remote and, under heavy load, sometimes for one that has
507
+ * one: git exits 0 with empty output. An empty answer is therefore confirmed by
508
+ * a query whose exit status is the answer: `git config --get-regexp` exits 1
509
+ * when no remote is configured. Its output is not read. The pattern needs the
510
+ * second dot that makes the key a remote's own key (`remote.<name>.<key>`):
511
+ * `remote.pushDefault` is a key of the `remote` section, not a remote.
512
+ */
513
+ function repositoryHasRemote(
514
+ path: string,
515
+ ): { readonly present: boolean; readonly err: string } {
516
+ const remotes = git(path, ["remote"]);
517
+ if (remotes.out.length > 0) return { present: true, err: "" };
518
+ const configured = git(path, ["config", "--local", "--get-regexp", "^remote\\..*\\."]);
519
+ if (configured.ok) return { present: true, err: "" };
520
+ return {
521
+ present: false,
522
+ err: remotes.err.length > 0 ? remotes.err : configured.err,
523
+ };
524
+ }
525
+
526
+ /**
527
+ * Registers a folder. It may have no remote, no git repository, or no git
528
+ * program on the machine; a subfolder of a repository is refused, naming the root.
529
+ */
497
530
  export async function addRepository(
498
531
  store: ObjectStore,
499
532
  options: AddRepositoryOptions,
@@ -502,38 +535,41 @@ export async function addRepository(
502
535
  if (!existsSync(from) || !statSync(from).isDirectory()) {
503
536
  throw new DevError("path", `no directory "${from}"`);
504
537
  }
505
- const top = git(from, ["rev-parse", "--show-toplevel"]);
506
- if (!top.ok || top.out.length === 0) {
507
- throw new DevError(
508
- "path",
509
- `"${from}" is not a git work tree${top.err.length > 0 ? `: ${top.err}` : ""}`,
510
- );
538
+ // A folder needs git only to create a task (ADR 0039 D7): without the git
539
+ // program, or in no repository, it is registered as it is.
540
+ let state: GitState;
541
+ try {
542
+ state = gitStateOf(from, options.finder === undefined ? {} : { finder: options.finder });
543
+ } catch (error) {
544
+ if (error instanceof GitStateError) {
545
+ throw new DevError("path", `"${from}" is not a git work tree: ${error.reason}`);
546
+ }
547
+ throw error;
511
548
  }
512
- const path = realpathSync(top.out);
513
- if (path !== realpathSync(from)) {
549
+ if (state.state === "subfolder") {
514
550
  throw new DevError(
515
551
  "path",
516
- `"${from}" is not the root of a git work tree`,
552
+ `"${from}" is inside the git repository at "${state.root}"; add "${state.root}" instead`,
517
553
  );
518
554
  }
519
- const bare = git(path, ["rev-parse", "--is-bare-repository"]);
520
- if (bare.ok && bare.out === "true") {
555
+ const path = realpathSync(from);
556
+ const hasRepository = state.state === "no commit" || state.state === "ready";
557
+ const bare =
558
+ state.state === "no program" ? undefined : git(path, ["rev-parse", "--is-bare-repository"]);
559
+ if (bare !== undefined && bare.ok && bare.out === "true") {
521
560
  throw new DevError("path", `"${path}" is a bare repository`);
522
561
  }
523
- const remotes = git(path, ["remote"]);
524
- if (!remotes.ok || remotes.out.length === 0) {
525
- throw new DevError(
526
- "path",
527
- `"${path}" has no remote${remotes.err.length > 0 ? `: ${remotes.err}` : ""}`,
528
- );
529
- }
562
+ // A repository with no remote is allowed: its merges stay local.
563
+ const hasRemote = hasRepository && repositoryHasRemote(path).present;
530
564
 
531
565
  const name = validateRepositoryName(options.name ?? basename(path));
532
- const existing = await findRepository(store, name);
533
- if (existing !== undefined) {
566
+ const existing = await findRepository(store, name, { includeRemoved: true });
567
+ const previous =
568
+ existing === undefined ? undefined : repositoryData(existing.data);
569
+ if (previous !== undefined && !previous.removed) {
534
570
  throw new DevError(
535
571
  "name",
536
- `repository "${name}" is already registered at "${repositoryData(existing.data).path}"`,
572
+ `repository "${name}" is already registered at "${previous.path}"`,
537
573
  );
538
574
  }
539
575
  const samePath = (await listRepositories(store)).find(
@@ -546,17 +582,22 @@ export async function addRepository(
546
582
  );
547
583
  }
548
584
 
549
- const data: RepositoryData = {
550
- name,
551
- path,
552
- removed: false,
553
- openPlans: 0,
554
- openTasks: 0,
555
- activeTasks: 0,
556
- };
585
+ // A removed repository is registered again under its name: its counters and
586
+ // every plan and task under that name stay, and only its path changes.
587
+ const data: RepositoryData =
588
+ previous === undefined
589
+ ? {
590
+ name,
591
+ path,
592
+ removed: false,
593
+ openPlans: 0,
594
+ openTasks: 0,
595
+ activeTasks: 0,
596
+ }
597
+ : { ...previous, name, path, removed: false };
557
598
  await store.put(REPOSITORY_TYPE, name, data, "dev:repo-add");
558
- writeSettings(path, name);
559
- ensureExcludes(path);
599
+ writeSettings(path, name, hasRemote, !hasRepository);
600
+ if (hasRepository) ensureExcludes(path);
560
601
  return data;
561
602
  }
562
603
 
@@ -628,7 +669,7 @@ async function tasksOfPlan(
628
669
  planKey: string,
629
670
  ): Promise<readonly StoredObject[]> {
630
671
  const repository = keyRepository(planKey);
631
- const plan = bareId(planKey);
672
+ const plan = idOfKey(planKey);
632
673
  return (await allTasks(store)).filter((object) => {
633
674
  const task = taskData(object.data);
634
675
  return task.repository === repository && task.plan === plan;
@@ -649,14 +690,14 @@ function refuseTask(
649
690
  if (action === "confirm" && task.phase === "proposed" && plan?.state === "confirmed") {
650
691
  return false;
651
692
  }
652
- const said = taskLine(action, task, { id: bareId(key), plan });
693
+ const said = taskLine(action, task, { id: idOfKey(key), plan });
653
694
  if (said?.kind === "refuse") throw new DevRefusal(said.text);
654
695
  return said !== undefined;
655
696
  }
656
697
 
657
698
  /** As `refuseTask`, for a plan action. */
658
699
  function refusePlan(action: PlanActionName, plan: PlanData, key: string): boolean {
659
- const said = planLine(action, plan, { id: bareId(key) });
700
+ const said = planLine(action, plan, { id: idOfKey(key) });
660
701
  if (said?.kind === "refuse") throw new DevRefusal(said.text);
661
702
  return said !== undefined;
662
703
  }
@@ -667,7 +708,7 @@ export async function getPlan(
667
708
  ): Promise<StoredObject> {
668
709
  const object = await store.get(PLAN_TYPE, key);
669
710
  if (object === undefined) {
670
- throw new DevError("plan", `no plan "${bareId(key)}"`);
711
+ throw new DevError("plan", `no plan "${idOfKey(key)}"`);
671
712
  }
672
713
  return object;
673
714
  }
@@ -678,7 +719,7 @@ export async function getTask(
678
719
  ): Promise<StoredObject> {
679
720
  const object = await store.get(TASK_TYPE, key);
680
721
  if (object === undefined) {
681
- throw new DevError("task", `no task "${bareId(key)}"`);
722
+ throw new DevError("task", `no task "${idOfKey(key)}"`);
682
723
  }
683
724
  return object;
684
725
  }
@@ -773,9 +814,10 @@ function sameCostTotals(a: PlanCostTotals | undefined, b: PlanCostTotals): boole
773
814
  export async function refreshPlanCounts(
774
815
  store: ObjectStore,
775
816
  plan: StoredObject,
817
+ tasks?: readonly StoredObject[] | undefined,
776
818
  ): Promise<StoredObject> {
777
819
  try {
778
- return await recountPlan(store, plan);
820
+ return await recountPlan(store, plan, tasks);
779
821
  } catch (error) {
780
822
  if (isBusy(error)) return plan;
781
823
  throw error;
@@ -794,9 +836,10 @@ async function refreshPlanCountsOf(store: ObjectStore, key: string): Promise<voi
794
836
  async function recountPlan(
795
837
  store: ObjectStore,
796
838
  plan: StoredObject,
839
+ knownTasks?: readonly StoredObject[] | undefined,
797
840
  ): Promise<StoredObject> {
798
841
  const data = planData(plan.data);
799
- const tasks = await tasksOfPlan(store, plan.id);
842
+ const tasks = knownTasks ?? (await tasksOfPlan(store, plan.id));
800
843
  const taskCount = tasks.length;
801
844
  const mergedCount = tasks.filter(
802
845
  (object) => taskData(object.data).phase === "merged",
@@ -893,6 +936,7 @@ export async function addPlan(
893
936
  ? 1
894
937
  : validatePlanConcurrency(options.concurrency);
895
938
  return withRepoLock(store, options.repository.name, async (repository) => {
939
+ assertCanCreateTask(repository.path);
896
940
  const id = await nextId(store, "plan", repository.name, slug);
897
941
  const data: PlanData = {
898
942
  repository: repository.name,
@@ -1027,7 +1071,7 @@ export async function addTask(
1027
1071
  const plan = await getPlan(store, options.plan);
1028
1072
  const planObject = planData(plan.data);
1029
1073
  if (planObject.status === "cancelled") {
1030
- throw new DevError("plan", `plan "${bareId(plan.id)}" is cancelled`);
1074
+ throw new DevError("plan", `plan "${idOfKey(plan.id)}" is cancelled`);
1031
1075
  }
1032
1076
  await devTestHooks.beforeLock?.("task-add");
1033
1077
  const names = await afterLockNames(
@@ -1053,15 +1097,16 @@ export async function addTaskLocked(
1053
1097
  if (current.status === "cancelled") {
1054
1098
  throw new DevError(
1055
1099
  "plan",
1056
- `plan "${bareId(currentPlan.id)}" is cancelled`,
1100
+ `plan "${idOfKey(currentPlan.id)}" is cancelled`,
1057
1101
  );
1058
1102
  }
1059
1103
  if (current.repository !== repository.name) {
1060
1104
  throw new DevError(
1061
1105
  "plan",
1062
- `plan "${bareId(currentPlan.id)}" is not in repository "${repository.name}"`,
1106
+ `plan "${idOfKey(currentPlan.id)}" is not in repository "${repository.name}"`,
1063
1107
  );
1064
1108
  }
1109
+ assertCanCreateTask(repository.path);
1065
1110
  const id = await nextId(store, "task", repository.name, slug);
1066
1111
  const tasks = await allTasks(store);
1067
1112
  const after = validateAfter(
@@ -1076,7 +1121,7 @@ export async function addTaskLocked(
1076
1121
  options.area === undefined ? undefined : validateArea(options.area);
1077
1122
  const data: TaskData = {
1078
1123
  repository: repository.name,
1079
- plan: bareId(currentPlan.id),
1124
+ plan: idOfKey(currentPlan.id),
1080
1125
  title,
1081
1126
  brief,
1082
1127
  after,
@@ -1274,18 +1319,6 @@ export async function updateTask(
1274
1319
  return updated.object;
1275
1320
  }
1276
1321
 
1277
- /** The task after a run changed its phase. Used by later tasks and by tests. */
1278
- export async function setTaskPhase(
1279
- store: ObjectStore,
1280
- id: string,
1281
- phase: TaskPhase,
1282
- options: { readonly run?: string | null | undefined } = {},
1283
- ): Promise<StoredObject> {
1284
- const written = await changeTaskPhase(store, id, undefined, phase, options);
1285
- if (written === undefined) throw new DevError("task", `no task "${bareId(id)}"`);
1286
- return written;
1287
- }
1288
-
1289
1322
  /**
1290
1323
  * Moves a task to `to` only while it is still in phase `from`, checked under
1291
1324
  * the repository lock; undefined when another pass already moved it, so only
@@ -1301,7 +1334,7 @@ export async function moveTaskPhase(
1301
1334
  return changeTaskPhase(store, id, from, to, options);
1302
1335
  }
1303
1336
 
1304
- async function changeTaskPhase(
1337
+ export async function changeTaskPhase(
1305
1338
  store: ObjectStore,
1306
1339
  id: string,
1307
1340
  from: TaskPhase | undefined,
@@ -1374,12 +1407,11 @@ export async function claimTaskStart(
1374
1407
  const next: TaskData = {
1375
1408
  ...rest,
1376
1409
  ...(options.oldestPlanSlot === true ? { oldestPlanSlot: true } : {}),
1410
+ // The recorded graph follows the flow the start uses: a built-in flow
1411
+ // records none, so a refused graph an older dev wrote is not kept.
1377
1412
  ...(options.flow === undefined
1378
1413
  ? {}
1379
- : {
1380
- flowName: options.flow.name,
1381
- ...(options.flow.graph === undefined ? {} : { flowGraph: options.flow.graph }),
1382
- }),
1414
+ : { flowName: options.flow.name, flowGraph: options.flow.graph }),
1383
1415
  phase: "running",
1384
1416
  run: null,
1385
1417
  brief: appendChange(latest.brief, "running"),
@@ -1402,7 +1434,7 @@ export async function areaHolder(
1402
1434
  const task = taskData(object.data);
1403
1435
  if (task.repository !== repository || task.area !== area) continue;
1404
1436
  if (task.phase === "running" || task.phase === "review") {
1405
- return bareId(object.id);
1437
+ return idOfKey(object.id);
1406
1438
  }
1407
1439
  }
1408
1440
  return undefined;
@@ -1417,17 +1449,17 @@ export async function setAreaHold(
1417
1449
  id: string,
1418
1450
  holder: string | undefined,
1419
1451
  ahead = 0,
1420
- ): Promise<void> {
1452
+ known?: TaskData | undefined,
1453
+ ): Promise<boolean> {
1421
1454
  const same = (task: TaskData): boolean =>
1422
1455
  task.areaHeldBy === holder &&
1423
1456
  (holder === undefined || (task.areaAhead ?? 0) === ahead);
1424
- const initial = await getTask(store, id);
1425
- const data = taskData(initial.data);
1426
- if (same(data)) return;
1427
- await withRepoLock(store, data.repository, async () => {
1457
+ const initial = known ?? taskData((await getTask(store, id)).data);
1458
+ if (same(initial)) return false;
1459
+ return withRepoLock(store, initial.repository, async () => {
1428
1460
  const current = await getTask(store, id);
1429
1461
  const latest = taskData(current.data);
1430
- if (latest.phase !== "ready" || same(latest)) return;
1462
+ if (latest.phase !== "ready" || same(latest)) return false;
1431
1463
  const { areaHeldBy: _held, areaAhead: _ahead, ...rest } = latest;
1432
1464
  await writeTask(
1433
1465
  store,
@@ -1439,6 +1471,7 @@ export async function setAreaHold(
1439
1471
  },
1440
1472
  "dev:task-area-hold",
1441
1473
  );
1474
+ return true;
1442
1475
  });
1443
1476
  }
1444
1477
 
@@ -1451,15 +1484,18 @@ export async function setDependencyHold(
1451
1484
  id: string,
1452
1485
  held: boolean,
1453
1486
  waitingFor: readonly string[] = [],
1454
- ): Promise<void> {
1455
- const initial = await getTask(store, id);
1456
- const data = taskData(initial.data);
1487
+ known?: TaskData | undefined,
1488
+ ): Promise<boolean> {
1489
+ const initial = known ?? taskData((await getTask(store, id)).data);
1457
1490
  const same = (left: readonly string[] | undefined) =>
1458
1491
  (left ?? []).join("\n") === waitingFor.join("\n");
1459
- if ((data.dependencyHeld === true) === held && (!held || same(data.dependencyHeldFor))) {
1460
- return;
1492
+ if (
1493
+ (initial.dependencyHeld === true) === held &&
1494
+ (!held || same(initial.dependencyHeldFor))
1495
+ ) {
1496
+ return false;
1461
1497
  }
1462
- await withRepoLock(store, data.repository, async () => {
1498
+ return withRepoLock(store, initial.repository, async () => {
1463
1499
  const current = await getTask(store, id);
1464
1500
  const latest = taskData(current.data);
1465
1501
  if (
@@ -1467,7 +1503,7 @@ export async function setDependencyHold(
1467
1503
  ((latest.dependencyHeld === true) === held &&
1468
1504
  (!held || same(latest.dependencyHeldFor)))
1469
1505
  ) {
1470
- return;
1506
+ return false;
1471
1507
  }
1472
1508
  const { dependencyHeld: _waits, dependencyHeldFor: _for, ...rest } = latest;
1473
1509
  await writeTask(
@@ -1481,6 +1517,7 @@ export async function setDependencyHold(
1481
1517
  },
1482
1518
  "dev:task-dependency-hold",
1483
1519
  );
1520
+ return true;
1484
1521
  });
1485
1522
  }
1486
1523
 
@@ -1493,14 +1530,14 @@ export async function setSlotHold(
1493
1530
  store: ObjectStore,
1494
1531
  id: string,
1495
1532
  note: string | undefined,
1496
- ): Promise<void> {
1497
- const initial = await getTask(store, id);
1498
- const data = taskData(initial.data);
1499
- if (data.slotHeld === note) return;
1500
- await withRepoLock(store, data.repository, async () => {
1533
+ known?: TaskData | undefined,
1534
+ ): Promise<boolean> {
1535
+ const initial = known ?? taskData((await getTask(store, id)).data);
1536
+ if (initial.slotHeld === note) return false;
1537
+ return withRepoLock(store, initial.repository, async () => {
1501
1538
  const current = await getTask(store, id);
1502
1539
  const latest = taskData(current.data);
1503
- if (latest.phase !== "ready" || latest.slotHeld === note) return;
1540
+ if (latest.phase !== "ready" || latest.slotHeld === note) return false;
1504
1541
  const { slotHeld: _slot, ...rest } = latest;
1505
1542
  await writeTask(
1506
1543
  store,
@@ -1508,6 +1545,7 @@ export async function setSlotHold(
1508
1545
  { ...rest, ...(note === undefined ? {} : { slotHeld: note }) },
1509
1546
  "dev:task-slot-hold",
1510
1547
  );
1548
+ return true;
1511
1549
  });
1512
1550
  }
1513
1551
 
@@ -1519,15 +1557,16 @@ export async function setFlowNote(
1519
1557
  store: ObjectStore,
1520
1558
  id: string,
1521
1559
  note: { readonly shown?: string | undefined; readonly held?: string | undefined },
1522
- ): Promise<void> {
1523
- const initial = await getTask(store, id);
1560
+ known?: TaskData | undefined,
1561
+ ): Promise<boolean> {
1562
+ const initial = known ?? taskData((await getTask(store, id)).data);
1524
1563
  const same = (data: TaskData) =>
1525
1564
  data.flowShown === note.shown && data.flowHeld === note.held;
1526
- if (same(taskData(initial.data))) return;
1527
- await withRepoLock(store, taskData(initial.data).repository, async () => {
1565
+ if (same(initial)) return false;
1566
+ return withRepoLock(store, initial.repository, async () => {
1528
1567
  const current = await getTask(store, id);
1529
1568
  const latest = taskData(current.data);
1530
- if (same(latest)) return;
1569
+ if (same(latest)) return false;
1531
1570
  const { flowShown: _shown, flowHeld: _held, ...rest } = latest;
1532
1571
  await writeTask(
1533
1572
  store,
@@ -1539,6 +1578,7 @@ export async function setFlowNote(
1539
1578
  },
1540
1579
  "dev:task-flow-note",
1541
1580
  );
1581
+ return true;
1542
1582
  });
1543
1583
  }
1544
1584
 
@@ -1568,17 +1608,18 @@ export async function recordPlanStart(
1568
1608
  export async function clearOldestPlanSlot(
1569
1609
  store: ObjectStore,
1570
1610
  id: string,
1571
- ): Promise<void> {
1611
+ ): Promise<boolean> {
1572
1612
  const initial = await getTask(store, id);
1573
1613
  const data = taskData(initial.data);
1574
- if (data.oldestPlanSlot !== true) return;
1575
- await withRepoLock(store, data.repository, async () => {
1614
+ if (data.oldestPlanSlot !== true) return false;
1615
+ return withRepoLock(store, data.repository, async () => {
1576
1616
  const current = await getTask(store, id);
1577
1617
  const latest = taskData(current.data);
1578
- if (latest.oldestPlanSlot !== true) return;
1579
- if (latest.phase === "running" || latest.phase === "review") return;
1618
+ if (latest.oldestPlanSlot !== true) return false;
1619
+ if (latest.phase === "running" || latest.phase === "review") return false;
1580
1620
  const { oldestPlanSlot: _slot, ...rest } = latest;
1581
1621
  await writeTask(store, id, rest, "dev:task-slot-release");
1622
+ return true;
1582
1623
  });
1583
1624
  }
1584
1625
 
@@ -1700,7 +1741,7 @@ export async function requestTaskStart(
1700
1741
  ): Promise<StoredObject> {
1701
1742
  const initial = await getTask(store, id);
1702
1743
  const data = taskData(initial.data);
1703
- const at = `task "${bareId(id)}"`;
1744
+ const at = `task "${idOfKey(id)}"`;
1704
1745
  if (data.phase !== "ready") {
1705
1746
  throw new DevError(
1706
1747
  "phase",
@@ -1771,12 +1812,12 @@ export async function claimWaitingTask(
1771
1812
  const latest = taskData(current.data);
1772
1813
  // Where the task is now: the table's line for this action. A result that
1773
1814
  // is already true (another merge won) succeeds with its line.
1774
- const said = taskLine(action, latest, { id: bareId(id) });
1815
+ const said = taskLine(action, latest, { id: idOfKey(id) });
1775
1816
  if (said?.kind === "done") return { settled: said.text };
1776
1817
  refuseTask(action, latest, id);
1777
1818
  if (current.version !== seen) {
1778
1819
  throw new DevRefusal(
1779
- `${bareId(id)} changed since you looked; look again, then dev:${action}`,
1820
+ `${idOfKey(id)} changed since you looked; look again, then dev:${action}`,
1780
1821
  );
1781
1822
  }
1782
1823
  const claimed = await writeTask(
@@ -1804,27 +1845,6 @@ export async function releaseWaitingClaim(
1804
1845
  });
1805
1846
  }
1806
1847
 
1807
- /** Appends a rework section and records it. */
1808
- export async function addRework(
1809
- store: ObjectStore,
1810
- id: string,
1811
- source: string,
1812
- text: string,
1813
- ): Promise<StoredObject> {
1814
- const initial = await getTask(store, id);
1815
- const data = taskData(initial.data);
1816
- return withRepoLock(store, data.repository, async () => {
1817
- const current = await getTask(store, id);
1818
- const latest = taskData(current.data);
1819
- return writeTask(
1820
- store,
1821
- id,
1822
- { ...latest, brief: appendRework(latest.brief, source, text) },
1823
- "dev:task-rework",
1824
- );
1825
- });
1826
- }
1827
-
1828
1848
  export async function confirmPlan(
1829
1849
  store: ObjectStore,
1830
1850
  id: string,
@@ -1903,21 +1923,71 @@ async function cancelRuns(
1903
1923
  }
1904
1924
  }
1905
1925
 
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[];
1926
+ /** A task whose attempt put the main clone on the task's own branch (ADR 0039 D3). */
1927
+ function holdsClone(task: TaskData): boolean {
1928
+ return task.attempt?.inPlace === true && isOpenTask(task);
1910
1929
  }
1911
1930
 
1912
- /** Where a cancel finds the integration queue: the home the action runs in. */
1913
- function cancelHome(
1931
+ /**
1932
+ * The id of an open task that holds a repository's main clone on its own
1933
+ * branch, or undefined when none does (ADR 0039 D3).
1934
+ */
1935
+ export async function cloneHolder(
1914
1936
  store: ObjectStore,
1915
- options: CancelOptions,
1937
+ repositoryName: string,
1938
+ ): Promise<string | undefined> {
1939
+ for (const object of await allTasks(store)) {
1940
+ const task = taskData(object.data);
1941
+ if (task.repository === repositoryName && holdsClone(task)) return idOfKey(object.id);
1942
+ }
1943
+ return undefined;
1944
+ }
1945
+
1946
+ /**
1947
+ * Switches the main clone back to the branch an ended branch-mode task started
1948
+ * on and keeps the task's branch (ADR 0039 D5). A clone that is not clean, or
1949
+ * that has moved, stays as it is and the returned note says so.
1950
+ */
1951
+ function releaseClone(
1952
+ repositoryPath: string,
1953
+ key: string,
1954
+ task: TaskData,
1916
1955
  ): 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;
1956
+ const attempt = task.attempt;
1957
+ if (attempt?.inPlace !== true) return undefined;
1958
+ const start = attempt.startBranch;
1959
+ if (typeof start !== "string" || start.length === 0) return undefined;
1960
+ const branch =
1961
+ typeof attempt.branch === "string" && attempt.branch.length > 0
1962
+ ? attempt.branch
1963
+ : `work/${idOfKey(key)}`;
1964
+ const back = switchBackToStart(repositoryPath, start, branch);
1965
+ return back.ok ? undefined : `${idOfKey(key)} kept its branch "${branch}": ${back.note}`;
1966
+ }
1967
+
1968
+ /**
1969
+ * A branch-mode task's run works in the main clone itself, so it is stopped
1970
+ * before the clone is switched. Returns the runs it stopped.
1971
+ */
1972
+ async function stopCloneRuns(
1973
+ control: DevRunControl | undefined,
1974
+ tasks: readonly StoredObject[],
1975
+ ): Promise<ReadonlySet<string>> {
1976
+ const runs: RunToCancel[] = [];
1977
+ for (const object of tasks) {
1978
+ const data = taskData(object.data);
1979
+ if (holdsClone(data) && data.run !== null) runs.push({ run: data.run, flow: data.flowGraph });
1980
+ }
1981
+ await cancelRuns(control, runs);
1982
+ return new Set(runs.map((entry) => entry.run));
1983
+ }
1984
+
1985
+ interface CancelledTasks {
1986
+ readonly runs: readonly RunToCancel[];
1987
+ /** The tasks a batch had already pushed; they stay merged, not cancelled. */
1988
+ readonly merged: readonly string[];
1989
+ /** What the end of a branch-mode task left in the main clone when it could not switch back. */
1990
+ readonly notes: readonly string[];
1921
1991
  }
1922
1992
 
1923
1993
  async function cancelTasks(
@@ -1925,9 +1995,11 @@ async function cancelTasks(
1925
1995
  tasks: readonly StoredObject[],
1926
1996
  home: string | undefined,
1927
1997
  repositoryPath: string,
1998
+ stopped: ReadonlySet<string> = new Set(),
1928
1999
  ): Promise<CancelledTasks> {
1929
2000
  const runs: RunToCancel[] = [];
1930
2001
  const merged: string[] = [];
2002
+ const notes: string[] = [];
1931
2003
  for (const object of tasks) {
1932
2004
  const data = taskData(object.data);
1933
2005
  if (!isOpenTask(data)) continue;
@@ -1935,14 +2007,18 @@ async function cancelTasks(
1935
2007
  const withdrawal = await withdrawIntegration(
1936
2008
  home,
1937
2009
  { name: data.repository, path: repositoryPath },
1938
- bareId(object.id),
2010
+ idOfKey(object.id),
1939
2011
  );
1940
2012
  if (withdrawal.kind === "merged") {
1941
2013
  merged.push(object.id);
1942
2014
  continue;
1943
2015
  }
1944
2016
  }
1945
- if (data.run !== null) runs.push({ run: data.run, flow: data.flowGraph });
2017
+ if (data.run !== null && !stopped.has(data.run)) {
2018
+ runs.push({ run: data.run, flow: data.flowGraph });
2019
+ }
2020
+ const note = releaseClone(repositoryPath, object.id, data);
2021
+ if (note !== undefined) notes.push(note);
1946
2022
  await writeTask(
1947
2023
  store,
1948
2024
  object.id,
@@ -1951,17 +2027,20 @@ async function cancelTasks(
1951
2027
  phase: "cancelled",
1952
2028
  run: null,
1953
2029
  claim: null,
1954
- brief: appendChange(data.brief, "cancelled"),
2030
+ brief: appendChange(data.brief, "cancelled", note),
1955
2031
  },
1956
2032
  "dev:task-cancel",
1957
2033
  );
1958
2034
  }
1959
- return { runs, merged };
2035
+ return { runs, merged, notes };
1960
2036
  }
1961
2037
 
1962
2038
  export interface CancelOptions {
1963
2039
  readonly runs?: DevRunControl | undefined;
1964
- /** The operad home, where the integration queue lives. */
2040
+ /**
2041
+ * The operad home, where the integration queue lives. Without it a cancel
2042
+ * does not look at the queue: only the action, which knows the home, passes it.
2043
+ */
1965
2044
  readonly home?: string | undefined;
1966
2045
  }
1967
2046
 
@@ -1970,6 +2049,8 @@ export interface CancelledTask {
1970
2049
  readonly runs: readonly RunToCancel[];
1971
2050
  /** Set when a batch pushed the task first: it stays merged and is not cancelled. */
1972
2051
  readonly alreadyMerged?: string | undefined;
2052
+ /** Set when a branch-mode task's end could not switch the main clone back. */
2053
+ readonly note?: string | undefined;
1973
2054
  }
1974
2055
 
1975
2056
  export async function cancelPlan(
@@ -1980,23 +2061,25 @@ export async function cancelPlan(
1980
2061
  readonly plan: StoredObject;
1981
2062
  readonly runs: readonly RunToCancel[];
1982
2063
  readonly merged: readonly string[];
2064
+ readonly notes: readonly string[];
1983
2065
  }> {
1984
2066
  const initial = await getPlan(store, id);
1985
2067
  const initialData = planData(initial.data);
1986
- const home = cancelHome(store, options);
2068
+ const { home } = options;
2069
+ const stopped = await stopCloneRuns(options.runs, await tasksOfPlan(store, id));
1987
2070
  const cancelled = await withRepoLock(
1988
2071
  store,
1989
2072
  initialData.repository,
1990
2073
  async (fresh) => {
1991
2074
  const plan = await getPlan(store, id);
1992
2075
  const data = planData(plan.data);
1993
- if (refusePlan("cancel", data, id)) return { plan, runs: [], merged: [] };
2076
+ if (refusePlan("cancel", data, id)) return { plan, runs: [], merged: [], notes: [] };
1994
2077
  const tasks = await tasksOfPlan(store, id);
1995
- const { runs, merged } = await cancelTasks(store, tasks, home, fresh.path);
2078
+ const { runs, merged, notes } = await cancelTasks(store, tasks, home, fresh.path, stopped);
1996
2079
  const next: PlanData = { ...data, status: "cancelled" };
1997
2080
  const written = await writePlan(store, id, next, "dev:plan-cancel");
1998
2081
  await refreshPlanCounts(store, written);
1999
- return { plan: written, runs, merged };
2082
+ return { plan: written, runs, merged, notes };
2000
2083
  },
2001
2084
  );
2002
2085
  await cancelRuns(options.runs, cancelled.runs);
@@ -2010,7 +2093,8 @@ export async function cancelTask(
2010
2093
  ): Promise<CancelledTask> {
2011
2094
  const initial = await getTask(store, id);
2012
2095
  const initialData = taskData(initial.data);
2013
- const home = cancelHome(store, options);
2096
+ const { home } = options;
2097
+ const stopped = await stopCloneRuns(options.runs, [initial]);
2014
2098
  const cancelled = await withRepoLock(
2015
2099
  store,
2016
2100
  initialData.repository,
@@ -2018,20 +2102,23 @@ export async function cancelTask(
2018
2102
  const task = await getTask(store, id);
2019
2103
  const data = taskData(task.data);
2020
2104
  if (refuseTask("cancel", data, id)) {
2021
- return { task, runs: [], merged: data.phase === "merged" };
2105
+ return { task, runs: [], merged: data.phase === "merged", note: undefined };
2022
2106
  }
2023
2107
  if (home !== undefined) {
2024
2108
  const withdrawal = await withdrawIntegration(
2025
2109
  home,
2026
2110
  { name: data.repository, path: fresh.path },
2027
- bareId(id),
2111
+ idOfKey(id),
2028
2112
  );
2029
2113
  if (withdrawal.kind === "merged") {
2030
- return { task, runs: [], merged: true };
2114
+ return { task, runs: [], merged: true, note: undefined };
2031
2115
  }
2032
2116
  }
2033
2117
  const runs: readonly RunToCancel[] =
2034
- data.run === null ? [] : [{ run: data.run, flow: data.flowGraph }];
2118
+ data.run === null || stopped.has(data.run)
2119
+ ? []
2120
+ : [{ run: data.run, flow: data.flowGraph }];
2121
+ const note = releaseClone(fresh.path, id, data);
2035
2122
  const written = await writeTask(
2036
2123
  store,
2037
2124
  id,
@@ -2040,12 +2127,12 @@ export async function cancelTask(
2040
2127
  phase: "cancelled",
2041
2128
  run: null,
2042
2129
  claim: null,
2043
- brief: appendChange(data.brief, "cancelled"),
2130
+ brief: appendChange(data.brief, "cancelled", note),
2044
2131
  },
2045
2132
  "dev:task-cancel",
2046
2133
  );
2047
2134
  await refreshPlanCountsOf(store, storeKey(data.repository, data.plan));
2048
- return { task: written, runs, merged: false };
2135
+ return { task: written, runs, merged: false, note };
2049
2136
  },
2050
2137
  );
2051
2138
  await cancelRuns(options.runs, cancelled.runs);
@@ -2053,8 +2140,9 @@ export async function cancelTask(
2053
2140
  task: cancelled.task,
2054
2141
  runs: cancelled.runs,
2055
2142
  ...(cancelled.merged
2056
- ? { alreadyMerged: `${bareId(id)} was merged; nothing can be cancelled` }
2143
+ ? { alreadyMerged: `${idOfKey(id)} was merged; nothing can be cancelled` }
2057
2144
  : {}),
2145
+ ...(cancelled.note === undefined ? {} : { note: cancelled.note }),
2058
2146
  };
2059
2147
  }
2060
2148
 
@@ -2191,35 +2279,3 @@ export async function setConcurrency(
2191
2279
  );
2192
2280
  });
2193
2281
  }
2194
-
2195
- /* ---------------------------------------------------------------------------
2196
- * History
2197
- * ------------------------------------------------------------------------- */
2198
-
2199
- /** Rebuilds the objects a store's facts describe, in append order. */
2200
- export function rebuildObjects(
2201
- facts: readonly PluginFact[],
2202
- ): Map<string, Record<string, unknown>> {
2203
- const objects = new Map<string, Record<string, unknown>>();
2204
- for (const fact of facts) {
2205
- const object = fact.object;
2206
- if (object === undefined) continue;
2207
- const key = `${object.type}:${object.id}`;
2208
- const value = objectValueAfter(fact, objects.get(key) ?? {});
2209
- if (value !== undefined) objects.set(key, { ...value });
2210
- }
2211
- return objects;
2212
- }
2213
-
2214
- /** The live object data, keyed the way `rebuildObjects` keys it. */
2215
- export async function liveObjects(
2216
- store: ObjectStore,
2217
- ): Promise<Map<string, Record<string, unknown>>> {
2218
- const objects = new Map<string, Record<string, unknown>>();
2219
- for (const type of [REPOSITORY_TYPE, PLAN_TYPE, TASK_TYPE]) {
2220
- for (const object of await listAll(store, type)) {
2221
- objects.set(`${type}:${object.id}`, { ...object.data });
2222
- }
2223
- }
2224
- return objects;
2225
- }