@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/integrate.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  * never runs either itself.
5
5
  */
6
6
 
7
- import { isRecord, messageOf, type PluginStepResult, type StepContext, type StepRunOptions } from "@operad-io/engine";
7
+ import { guardOutward, personStarted } from "@operad-io/access-match";
8
+ import { isRecord, messageOf, type PluginStepResult, type StepContext } from "@operad-io/engine";
8
9
  import { appendChange, appendRework, storeKey, type CleanupFailure, type CleanupRecord, type IntegrationRecord, type TaskAttempt, type TaskData } from "./model.ts";
9
10
  import {
10
11
  branchHead,
@@ -12,6 +13,7 @@ import {
12
13
  recreateGateWorktree,
13
14
  } from "./gate.ts";
14
15
  import { mainCloneRunner, runPrepare, stepOptions } from "./prepare.ts";
16
+ import { checkEnvironment } from "./check-host.ts";
15
17
  import { checkPlaces } from "./places.ts";
16
18
  import {
17
19
  IntegrationQueue,
@@ -22,6 +24,7 @@ import {
22
24
  } from "./integration-queue.ts";
23
25
  import {
24
26
  mainCloneChange,
27
+ switchBackToStart,
25
28
  updateMainClone,
26
29
  type CommandRunner,
27
30
  type MainCloneOutcome,
@@ -32,12 +35,21 @@ import { runCheckCommands } from "./rerun.ts";
32
35
  import { reportFlakyTests } from "./flaky.ts";
33
36
  import { recordRerunPasses } from "./reruns.ts";
34
37
  import { getPlan, refreshPlanCounts } from "./service.ts";
38
+ import {
39
+ baseName,
40
+ baseRef,
41
+ commitOf,
42
+ fetchRemote,
43
+ git,
44
+ headOf,
45
+ isAncestor,
46
+ treeOf,
47
+ type GitResult,
48
+ } from "./git.ts";
35
49
  import {
36
50
  cancelledStep,
37
51
  claimAllows,
38
52
  conflictedFiles,
39
- git,
40
- headOf,
41
53
  mergeInProgress,
42
54
  saveTaskGuarded,
43
55
  taskContext,
@@ -81,6 +93,34 @@ export const integrateTestHooks: {
81
93
  wait?: ((ms: number) => Promise<void>) | undefined;
82
94
  } = {};
83
95
 
96
+ // The branch a work tree is on, or undefined when it is on none.
97
+ function currentBranchOf(path: string): string | undefined {
98
+ const current = git(path, ["symbolic-ref", "--short", "-q", "HEAD"]);
99
+ return current.ok && current.out.length > 0 ? current.out : undefined;
100
+ }
101
+
102
+ // Lands the commit the gate worktree holds on main. With a remote it is a push
103
+ // from the gate worktree. With none the local main branch moves: through the
104
+ // clone when it has main checked out (its files move with the branch, and a
105
+ // change that does not fast-forward is refused), else by updating the ref only
106
+ // from `base`, so a main that moved meanwhile is not overwritten.
107
+ function landOnMain(
108
+ repository: string,
109
+ gate: string,
110
+ settings: DevSettings,
111
+ base: string,
112
+ ): GitResult {
113
+ if (settings.remote !== undefined) {
114
+ return git(gate, ["push", settings.remote, `HEAD:refs/heads/${settings.mainBranch}`]);
115
+ }
116
+ const sha = headOf(gate);
117
+ if (sha === undefined) return { ok: false, out: "", err: "the gate has no commit" };
118
+ if (currentBranchOf(repository) === settings.mainBranch) {
119
+ return git(repository, ["merge", "--ff-only", sha]);
120
+ }
121
+ return git(repository, ["update-ref", baseRef(settings), sha, base]);
122
+ }
123
+
84
124
  export async function followMain(
85
125
  repository: { readonly name: string; readonly path: string },
86
126
  branch: string,
@@ -90,7 +130,14 @@ export async function followMain(
90
130
  run: async () => ({ ok: true, out: "" }),
91
131
  },
92
132
  marker?: PrepareMarker | undefined,
133
+ /** Branch mode: the clone is on the task's branch and goes back to `start` first. */
134
+ inPlace?: { readonly start: string; readonly taskBranch: string } | undefined,
93
135
  ): Promise<MainCloneOutcome> {
136
+ if (inPlace !== undefined) {
137
+ const back = switchBackToStart(repository.path, inPlace.start, inPlace.taskBranch);
138
+ integrateTestHooks.at?.("switched-back");
139
+ if (!back.ok) return { updated: false, note: back.note };
140
+ }
94
141
  return updateMainClone(
95
142
  repository.path,
96
143
  branch,
@@ -105,20 +152,6 @@ function shortSha(sha: string): string {
105
152
  return sha.slice(0, 7);
106
153
  }
107
154
 
108
- function revParse(cwd: string, ref: string): string | undefined {
109
- const result = git(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
110
- return result.ok && result.out.length > 0 ? result.out : undefined;
111
- }
112
-
113
- /** True when `ancestor` is reachable from `descendant`. */
114
- function contains(
115
- cwd: string,
116
- ancestor: string,
117
- descendant: string,
118
- ): boolean {
119
- return git(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]).ok;
120
- }
121
-
122
155
  interface Candidate {
123
156
  readonly kind: "ok" | "conflict" | "failed";
124
157
  readonly sha?: string | undefined;
@@ -263,12 +296,6 @@ function integrationData(
263
296
  };
264
297
  }
265
298
 
266
- /** Step `dev/integrate`: land the verified commit on main. */
267
- function treeOf(cwd: string, commit: string): string | undefined {
268
- const result = git(cwd, ["rev-parse", "--verify", "--quiet", `${commit}^{tree}`]);
269
- return result.ok && result.out.length > 0 ? result.out : undefined;
270
- }
271
-
272
299
  /** The patch id of a diff, which ignores line numbers and whitespace. */
273
300
  function patchIdOf(cwd: string, args: readonly string[]): string | undefined {
274
301
  const diff = git(cwd, args, { raw: true });
@@ -285,7 +312,7 @@ function patchIdOf(cwd: string, args: readonly string[]): string | undefined {
285
312
  function carrierOnMain(cwd: string, verified: string, main: string): string | undefined {
286
313
  // A verified commit that main contains arrived in the first commit of main's
287
314
  // own line that has it.
288
- if (git(cwd, ["merge-base", "--is-ancestor", verified, main]).ok) {
315
+ if (isAncestor(cwd, verified, main)) {
289
316
  const arrived = git(cwd, [
290
317
  "rev-list",
291
318
  "--first-parent",
@@ -308,6 +335,7 @@ function carrierOnMain(cwd: string, verified: string, main: string): string | un
308
335
  return undefined;
309
336
  }
310
337
 
338
+ /** Step `dev/integrate`: land the verified commit on main. */
311
339
  export async function runIntegrate(
312
340
  ctx: StepContext,
313
341
  ): Promise<PluginStepResult> {
@@ -333,9 +361,24 @@ export async function runIntegrate(
333
361
  context.taskId,
334
362
  );
335
363
  const head = branchHead(repository, settings, context.workName);
336
- const mainRef = `refs/remotes/${settings.remote}/${settings.mainBranch}`;
364
+ const mainRef = baseRef(settings);
365
+ const recordedStart = task.attempt?.startBranch;
366
+ const inPlace =
367
+ task.attempt?.inPlace === true &&
368
+ typeof recordedStart === "string" &&
369
+ recordedStart.length > 0
370
+ ? { start: recordedStart, taskBranch: `work/${context.workName}` }
371
+ : undefined;
337
372
  const keyCommands = settings.integration.keyCommands;
338
373
  const runStep = ctx.runStep;
374
+ // With no remote the merge moves the local main branch, and the clone that
375
+ // has it checked out moves with it before the clone's own update runs: the
376
+ // prepare lines are due, and the record says so before the move.
377
+ const cloneFollowsLocalMain =
378
+ settings.remote === undefined &&
379
+ settings.prepare.length > 0 &&
380
+ (currentBranchOf(repository) === settings.mainBranch ||
381
+ inPlace?.start === settings.mainBranch);
339
382
 
340
383
  const fail = async (
341
384
  message: string,
@@ -363,12 +406,40 @@ export async function runIntegrate(
363
406
  };
364
407
  };
365
408
 
409
+ /** Asks before a push in a background run; a person-started run and an allowlisted target do not ask. */
410
+ const pushAllowed = async (sha: string | undefined, what: string): Promise<boolean> =>
411
+ // With no remote the merge only moves the local main branch: nothing leaves the machine.
412
+ settings.remote === undefined ||
413
+ guardOutward(
414
+ {
415
+ access: ctx.access,
416
+ ask: (request) => ctx.ask(request),
417
+ personStarted: personStarted(ctx.trigger),
418
+ onTimeout: "reject_once" as const,
419
+ home: ctx.home,
420
+ ...(ctx.flow === undefined ? {} : { flow: ctx.flow }),
421
+ onLog: (message) => {
422
+ void ctx.logger.write(message);
423
+ },
424
+ },
425
+ {
426
+ kind: "repository",
427
+ target: baseName(settings),
428
+ content: `push ${sha ?? "HEAD"} to ${baseName(settings)} (${what})`,
429
+ },
430
+ );
431
+
366
432
  let flakyReason: string | undefined;
367
433
  /** The other tasks this task was merged with in one batch. */
368
434
  let batchWith: readonly string[] = [];
369
435
  /** Saves that this merge's prepare is due before the clone moves, and done after. */
436
+ // A killed run of this step may have left prepare due; a restart that cannot
437
+ // fetch builds fresh records and must not forget it.
438
+ const leftDue =
439
+ task.attempt?.integration?.run === ctx.runId &&
440
+ task.attempt.integration.prepareDue === true;
370
441
  const prepareMarker = (record: IntegrationRecord): PrepareMarker => ({
371
- due: record.prepareDue === true,
442
+ due: record.prepareDue === true || leftDue,
372
443
  save: async (due) => {
373
444
  const pending: IntegrationRecord = {
374
445
  ...record,
@@ -390,18 +461,21 @@ export async function runIntegrate(
390
461
  mergedLine: string = `merged as ${shortSha(sha)}`,
391
462
  ): Promise<PluginStepResult> => {
392
463
  const note = record.checkNote;
464
+ const marker = prepareMarker(record);
393
465
  const clone = await followMain(
394
466
  context.repository,
395
467
  settings.mainBranch,
396
468
  cloneSha,
397
469
  { lines: settings.prepare, run: mainCloneRunner(ctx, settings) },
398
- prepareMarker(record),
470
+ marker,
471
+ inPlace,
399
472
  );
400
473
  integrateTestHooks.at?.("clone-followed");
401
474
  const cloneChange = mainCloneChange(clone);
475
+ // A clone that did not move keeps the prepare the killed run left due.
402
476
  const withClone: IntegrationRecord = {
403
477
  ...record,
404
- prepareDue: false,
478
+ prepareDue: !clone.updated && marker.due,
405
479
  mainClone: { ...clone },
406
480
  };
407
481
  if (
@@ -447,12 +521,12 @@ export async function runIntegrate(
447
521
  typeof previous.candidate === "string" &&
448
522
  previous.candidate.length > 0
449
523
  ) {
450
- const fetched = git(repository, ["fetch", "--prune", settings.remote]);
451
- const remoteMain = revParse(repository, mainRef);
524
+ const fetched = fetchRemote(repository, settings);
525
+ const remoteMain = commitOf(repository, mainRef);
452
526
  if (
453
527
  fetched.ok &&
454
528
  remoteMain !== undefined &&
455
- contains(repository, previous.candidate, remoteMain)
529
+ isAncestor(repository, previous.candidate, remoteMain)
456
530
  ) {
457
531
  const record: IntegrationRecord = {
458
532
  ...previous,
@@ -470,17 +544,19 @@ export async function runIntegrate(
470
544
  const previousBatch = Array.isArray(previous.batch)
471
545
  ? previous.batch.filter((name): name is string => typeof name === "string")
472
546
  : [];
547
+ const marker = prepareMarker(record);
473
548
  const clone = await followMain(
474
549
  context.repository,
475
550
  settings.mainBranch,
476
551
  typeof previous.batchHead === "string" ? previous.batchHead : previous.candidate,
477
552
  { lines: settings.prepare, run: mainCloneRunner(ctx, settings) },
478
- prepareMarker(record),
553
+ marker,
554
+ inPlace,
479
555
  );
480
556
  const cloneChange = mainCloneChange(clone);
481
557
  const withClone: IntegrationRecord = {
482
558
  ...record,
483
- prepareDue: false,
559
+ prepareDue: !clone.updated && marker.due,
484
560
  mainClone: { ...clone },
485
561
  };
486
562
  if (
@@ -523,9 +599,9 @@ export async function runIntegrate(
523
599
  signal: ctx.signal,
524
600
  wait: integrateTestHooks.wait,
525
601
  landed: (result) => {
526
- if (!git(repository, ["fetch", "--prune", settings.remote]).ok) return false;
527
- const main = revParse(repository, mainRef);
528
- return main !== undefined && contains(repository, result.head, main);
602
+ if (!fetchRemote(repository, settings).ok) return false;
603
+ const main = commitOf(repository, mainRef);
604
+ return main !== undefined && isAncestor(repository, result.head, main);
529
605
  },
530
606
  say: async (line, holder) => {
531
607
  await ctx.logger.write(line);
@@ -550,8 +626,8 @@ export async function runIntegrate(
550
626
 
551
627
  /** This task's merge commit when main already has it, and the main that has it. */
552
628
  const alreadyOnMain = (): { sha: string; main: string } | undefined => {
553
- if (!git(repository, ["fetch", "--prune", settings.remote]).ok) return undefined;
554
- const main = revParse(repository, mainRef);
629
+ if (!fetchRemote(repository, settings).ok) return undefined;
630
+ const main = commitOf(repository, mainRef);
555
631
  if (main === undefined) return undefined;
556
632
  const found = git(repository, [
557
633
  "log",
@@ -582,9 +658,9 @@ export async function runIntegrate(
582
658
  })),
583
659
  ];
584
660
  for (let round = 0; round < MAX_INTEGRATION_ROUNDS; round += 1) {
585
- const fetched = git(repository, ["fetch", "--prune", settings.remote]);
661
+ const fetched = fetchRemote(repository, settings);
586
662
  if (!fetched.ok) return undefined;
587
- const base = revParse(repository, mainRef);
663
+ const base = commitOf(repository, mainRef);
588
664
  if (base === undefined) return undefined;
589
665
  if (recreateGateWorktree(repository, gate, base, settings) !== undefined) {
590
666
  return undefined;
@@ -622,6 +698,7 @@ export async function runIntegrate(
622
698
  ...(settings.gate.stallSecs === undefined
623
699
  ? {}
624
700
  : { stallSecs: settings.gate.stallSecs }),
701
+ env: checkEnvironment(ctx.settings),
625
702
  },
626
703
  keyCommands,
627
704
  stepOptions(ctx, gate),
@@ -638,6 +715,7 @@ export async function runIntegrate(
638
715
  flakyLimit: settings.check.flakyLoadLimit,
639
716
  signal: ctx.signal,
640
717
  log: (text) => ctx.logger.write(text),
718
+ logPath: ctx.logger.path,
641
719
  });
642
720
  if (steady.cancelled === true) return cancelledStep();
643
721
  const { checked } = steady;
@@ -716,6 +794,7 @@ export async function runIntegrate(
716
794
  head: head ?? null,
717
795
  headMoved,
718
796
  pushed: false,
797
+ ...(cloneFollowsLocalMain ? { prepareDue: true } : {}),
719
798
  batchHead,
720
799
  batch: members.filter((member) => member.task !== context.taskId).map((member) => member.task),
721
800
  ...(checkNote === undefined ? {} : { checkNote }),
@@ -742,22 +821,31 @@ export async function runIntegrate(
742
821
  // A claimed task that left (cancelled) is not merged: one by one instead.
743
822
  // The check and the push share the queue's land lock with a withdrawal,
744
823
  // so a cancel either comes before the check or after the push.
824
+ // A push that reports an error may still have landed: that is settled
825
+ // inside the lock, so a cancel waiting on it sees a pushed batch.
826
+ let landedDespiteError = false;
745
827
  const landed = await queue.landWhenStillQueued(followers, result, async () => {
746
828
  await integrateTestHooks.beforePush?.(batchHead);
747
- return git(gate, [
748
- "push",
749
- settings.remote,
750
- `HEAD:refs/heads/${settings.mainBranch}`,
751
- ]).ok;
829
+ if (!(await pushAllowed(batchHead, "the batch merge"))) return false;
830
+ const pushed = landOnMain(repository, gate, settings, base).ok;
831
+ if (pushed) return true;
832
+ fetchRemote(repository, settings);
833
+ const after = commitOf(repository, mainRef);
834
+ landedDespiteError = after !== undefined && isAncestor(repository, batchHead, after);
835
+ return landedDespiteError;
752
836
  });
753
837
  if (landed === "withdrawn") return undefined;
838
+ if (landed === "failed") {
839
+ return fail(`the person did not allow the push to "${baseName(settings)}"`);
840
+ }
754
841
  if (landed === "pushed") {
842
+ if (landedDespiteError) return land({ landed: true });
755
843
  integrateTestHooks.afterPush?.(batchHead);
756
844
  return land({});
757
845
  }
758
- git(repository, ["fetch", "--prune", settings.remote]);
759
- const now = revParse(repository, mainRef);
760
- if (now !== undefined && contains(repository, batchHead, now)) {
846
+ fetchRemote(repository, settings);
847
+ const now = commitOf(repository, mainRef);
848
+ if (now !== undefined && isAncestor(repository, batchHead, now)) {
761
849
  return land({ landed: true });
762
850
  }
763
851
  if (now !== undefined && now !== base) continue;
@@ -785,6 +873,9 @@ export async function runIntegrate(
785
873
  head: head ?? null,
786
874
  headMoved,
787
875
  pushed: true,
876
+ // What a replay needs to follow the batch's head and say the batch.
877
+ batchHead: leaderResult.head,
878
+ batch: batchWith,
788
879
  ...(leaderResult.note === undefined ? {} : { checkNote: leaderResult.note }),
789
880
  };
790
881
  return recordMerged(record, mine.sha, {}, leaderResult.head);
@@ -807,7 +898,7 @@ export async function runIntegrate(
807
898
  const landed = alreadyOnMain();
808
899
  if (landed !== undefined) {
809
900
  // The dead leader's note and batch are gone; main still has the base.
810
- const landedBase = revParse(repository, `${landed.sha}^1`);
901
+ const landedBase = commitOf(repository, `${landed.sha}^1`);
811
902
  return recordMerged(
812
903
  {
813
904
  result: "merged",
@@ -848,15 +939,19 @@ export async function runIntegrate(
848
939
 
849
940
  let lastError = "";
850
941
  for (let round = 0; round < MAX_INTEGRATION_ROUNDS; round += 1) {
851
- const fetched = git(repository, ["fetch", "--prune", settings.remote]);
942
+ const fetched = fetchRemote(repository, settings);
852
943
  if (!fetched.ok) {
853
944
  return fail(
854
945
  `cannot fetch "${settings.remote}": ${fetched.err || fetched.out || "git fetch failed"}`,
855
946
  );
856
947
  }
857
- const base = revParse(repository, mainRef);
948
+ const base = commitOf(repository, mainRef);
858
949
  if (base === undefined) {
859
- return fail(`"${settings.remote}/${settings.mainBranch}" does not exist after the fetch`);
950
+ return fail(
951
+ settings.remote === undefined
952
+ ? `the branch "${settings.mainBranch}" does not exist`
953
+ : `"${baseName(settings)}" does not exist after the fetch`,
954
+ );
860
955
  }
861
956
 
862
957
  const prepared = recreateGateWorktree(repository, gate, base, settings);
@@ -969,6 +1064,7 @@ export async function runIntegrate(
969
1064
  ...(settings.gate.stallSecs === undefined
970
1065
  ? {}
971
1066
  : { stallSecs: settings.gate.stallSecs }),
1067
+ env: checkEnvironment(ctx.settings),
972
1068
  },
973
1069
  keyCommands,
974
1070
  stepOptions(ctx, gate),
@@ -985,6 +1081,7 @@ export async function runIntegrate(
985
1081
  flakyLimit: settings.check.flakyLoadLimit,
986
1082
  signal: ctx.signal,
987
1083
  log: (text) => ctx.logger.write(text),
1084
+ logPath: ctx.logger.path,
988
1085
  });
989
1086
  if (steady.cancelled === true) return cancelledStep();
990
1087
  const { checked } = steady;
@@ -1108,6 +1205,7 @@ export async function runIntegrate(
1108
1205
  head: head ?? null,
1109
1206
  headMoved,
1110
1207
  pushed: false,
1208
+ ...(cloneFollowsLocalMain ? { prepareDue: true } : {}),
1111
1209
  ...(checkNote === undefined ? {} : { checkNote }),
1112
1210
  };
1113
1211
  if ((await writeIntegration(ctx, context, task, attempt, pending, {
@@ -1117,11 +1215,10 @@ export async function runIntegrate(
1117
1215
  }
1118
1216
  integrateTestHooks.at?.("pending-saved");
1119
1217
 
1120
- const push = git(gate, [
1121
- "push",
1122
- settings.remote,
1123
- `HEAD:refs/heads/${settings.mainBranch}`,
1124
- ]);
1218
+ if (!(await pushAllowed(sha, "the task merge"))) {
1219
+ return fail(`the person did not allow the push to "${baseName(settings)}"`);
1220
+ }
1221
+ const push = landOnMain(repository, gate, settings, base);
1125
1222
  if (push.ok) {
1126
1223
  integrateTestHooks.afterPush?.(sha);
1127
1224
  const record: IntegrationRecord = {
@@ -1132,13 +1229,16 @@ export async function runIntegrate(
1132
1229
  return recordMerged(record, sha);
1133
1230
  }
1134
1231
 
1135
- lastError = `cannot push "${settings.mainBranch}" to "${settings.remote}": ${push.err || push.out || "git push failed"}`;
1136
- git(repository, ["fetch", "--prune", settings.remote]);
1137
- const now = revParse(repository, mainRef);
1232
+ lastError =
1233
+ settings.remote === undefined
1234
+ ? `cannot move "${settings.mainBranch}": ${push.err || push.out || "git failed"}`
1235
+ : `cannot push "${settings.mainBranch}" to "${settings.remote}": ${push.err || push.out || "git push failed"}`;
1236
+ fetchRemote(repository, settings);
1237
+ const now = commitOf(repository, mainRef);
1138
1238
  // A push can land on the remote and still report an error (the client lost
1139
1239
  // the answer). The remote's main then contains the candidate: it is
1140
1240
  // merged, and building and pushing a second candidate would be wrong.
1141
- if (now !== undefined && contains(repository, sha, now)) {
1241
+ if (now !== undefined && isAncestor(repository, sha, now)) {
1142
1242
  const record: IntegrationRecord = {
1143
1243
  ...pending,
1144
1244
  result: "merged",
@@ -1181,7 +1281,7 @@ export async function runCleanup(
1181
1281
  const env: Record<string, string> = {
1182
1282
  OPERAD_TASK: context.taskId,
1183
1283
  OPERAD_WORKTREE: worktree,
1184
- OPERAD_REMOTE: settings.remote,
1284
+ OPERAD_REMOTE: settings.remote ?? "",
1185
1285
  };
1186
1286
  const failures: CleanupFailure[] = [];
1187
1287
  const runStep = ctx.runStep;
@@ -24,12 +24,23 @@ import {
24
24
  mkdirSync,
25
25
  readdirSync,
26
26
  readFileSync,
27
- renameSync,
28
27
  rmSync,
29
- writeFileSync,
30
28
  } from "node:fs";
31
29
  import { join } from "node:path";
32
- import { waitForChange, withLockFile } from "@operad-io/engine/platform";
30
+ import {
31
+ waitForChange,
32
+ withLockFile,
33
+ writeJsonAtomicSync,
34
+ } from "@operad-io/engine/platform";
35
+ import { isRecord } from "@operad-io/engine";
36
+ import { repositoryPathKey } from "./repository-key.ts";
37
+
38
+ /**
39
+ * How long a waiter accepts a live holder of the land lock. The holder is
40
+ * across a git push, which has no bound of its own, so the engine's 10 s
41
+ * default would fail every cancel and leave behind a slow push.
42
+ */
43
+ const LAND_LOCK_TIMEOUT_MS = 30 * 60 * 1000;
33
44
 
34
45
  /** How often a waiting integration looks again when nothing announced a change. */
35
46
  const RECHECK_MS = 500;
@@ -117,7 +128,7 @@ export function integrationQueueDirectory(
117
128
  home: string,
118
129
  repository: { readonly name: string; readonly path: string },
119
130
  ): string {
120
- const hash = new Bun.CryptoHasher("sha1").update(repository.path).digest("hex");
131
+ const hash = repositoryPathKey(repository.path);
121
132
  const name = repository.name.replace(/[^A-Za-z0-9._-]/g, "_");
122
133
  return join(home, "dev", "integration-queue", `${name}-${hash.slice(0, 8)}`);
123
134
  }
@@ -140,16 +151,14 @@ function landLockPath(directory: string): string {
140
151
  }
141
152
 
142
153
  function writeAtomic(path: string, value: unknown): void {
143
- const temporary = `${path}.${process.pid}.tmp`;
144
- writeFileSync(temporary, JSON.stringify(value));
145
- renameSync(temporary, path);
154
+ writeJsonAtomicSync(path, value, { newline: false });
146
155
  }
147
156
 
148
157
  function parseTicket(text: string): Ticket | undefined {
149
158
  try {
150
159
  const value: unknown = JSON.parse(text);
151
- if (typeof value !== "object" || value === null) return undefined;
152
- const record = value as Record<string, unknown>;
160
+ if (!isRecord(value)) return undefined;
161
+ const record = value;
153
162
  if (
154
163
  typeof record.seq !== "number" ||
155
164
  typeof record.task !== "string" ||
@@ -205,6 +214,7 @@ export class IntegrationQueue {
205
214
  return withLockFile(landLockPath(this.directory), work, {
206
215
  label: "integration queue",
207
216
  onLog: () => {},
217
+ timeoutMs: LAND_LOCK_TIMEOUT_MS,
208
218
  ...(wait === undefined ? {} : { wait }),
209
219
  });
210
220
  }
@@ -512,7 +522,10 @@ export class IntegrationQueue {
512
522
  /**
513
523
  * Takes a task out of the integration queue on behalf of a cancel, with the
514
524
  * 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.
525
+ * leader already pushed a batch that lists the task. The ticket goes at once,
526
+ * before the cancelled run has seen its abort: that run can no longer push
527
+ * (its last check finds no ticket), and the next task may start its turn while
528
+ * the cancelled run is still winding down.
516
529
  */
517
530
  export async function withdrawIntegration(
518
531
  home: string,
package/src/lock.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  /** The repository lock: one dev writer per repository, safe across processes. */
2
2
 
3
- import { join } from "node:path";
3
+ import { existsSync, readFileSync, realpathSync, statSync, unlinkSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { defaultOperadHome } from "@operad-io/engine";
4
6
  import {
5
7
  LOCK_TIMEOUT_MS,
6
8
  LockTimeoutError,
@@ -9,8 +11,100 @@ import {
9
11
  } from "@operad-io/engine/platform";
10
12
  import { DevError } from "./model.ts";
11
13
 
12
- /** What a waiter may inject: the clock, how it waits, and where a log goes. */
13
- export type RepositoryLockOptions = Omit<LockFileOptions, "label">;
14
+ /**
15
+ * What a waiter may inject: the clock, how it waits, where a log goes, and the
16
+ * operad home that holds the lock file.
17
+ */
18
+ export type RepositoryLockOptions = Omit<LockFileOptions, "label"> & {
19
+ /** The home whose `dev/repository-locks` holds the file; defaults to `$OPERAD_HOME`. */
20
+ readonly home?: string | undefined;
21
+ };
22
+
23
+ /** Where an older dev kept its lock, inside the working tree. */
24
+ const LEGACY_LOCK_FILE = join(".operad", "dev.lock");
25
+
26
+ function realpathOr(path: string): string {
27
+ try {
28
+ return realpathSync.native(path);
29
+ } catch {
30
+ return path;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * The git directory a repository shares with its worktrees. A normal checkout
36
+ * has `.git` as a directory; a linked worktree has a `.git` file naming its git
37
+ * directory, whose `commondir` file names the shared one. Reading both keeps
38
+ * the lock path off a git process and off the working tree.
39
+ */
40
+ function commonGitDirectory(repositoryPath: string): string {
41
+ const dotGit = join(repositoryPath, ".git");
42
+ try {
43
+ if (statSync(dotGit).isDirectory()) return realpathOr(dotGit);
44
+ const line = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotGit, "utf8"));
45
+ const named = line?.[1];
46
+ if (named !== undefined) {
47
+ const gitDirectory = resolve(repositoryPath, named);
48
+ const commonFile = join(gitDirectory, "commondir");
49
+ if (existsSync(commonFile)) {
50
+ const common = readFileSync(commonFile, "utf8").trim();
51
+ if (common.length > 0) return realpathOr(resolve(gitDirectory, common));
52
+ }
53
+ return realpathOr(gitDirectory);
54
+ }
55
+ } catch {
56
+ // Not a readable git checkout; its own path is the best identity left.
57
+ }
58
+ return realpathOr(resolve(repositoryPath));
59
+ }
60
+
61
+ /**
62
+ * The identity of a repository, shared by every worktree, so a lock taken
63
+ * through one holds through all.
64
+ */
65
+ function repositoryKey(repositoryPath: string): string {
66
+ return new Bun.CryptoHasher("sha1")
67
+ .update(commonGitDirectory(repositoryPath))
68
+ .digest("hex");
69
+ }
70
+
71
+ /**
72
+ * The lock file of one repository. It lives in the operad home, never in the
73
+ * working tree: a held lock must not make the main clone look dirty to a merge.
74
+ */
75
+ export function repositoryLockPath(
76
+ repositoryPath: string,
77
+ home: string = defaultOperadHome(),
78
+ ): string {
79
+ return join(home, "dev", "repository-locks", `${repositoryKey(repositoryPath)}.lock`);
80
+ }
81
+
82
+ /**
83
+ * Removes the lock older versions left in the working tree, but only when
84
+ * nobody holds it. An old holder keeps it until it ends; that lock is not ours
85
+ * and its process still relies on it.
86
+ */
87
+ async function removeLegacyLock(repositoryPath: string): Promise<void> {
88
+ const legacy = join(repositoryPath, LEGACY_LOCK_FILE);
89
+ if (!existsSync(legacy)) return;
90
+ const held = new Error("the legacy dev lock is held");
91
+ try {
92
+ await withLockFile(
93
+ legacy,
94
+ () => {
95
+ unlinkSync(legacy);
96
+ },
97
+ {
98
+ label: "dev lock",
99
+ onLog: () => {},
100
+ timeoutMs: 0,
101
+ wait: () => Promise.reject(held),
102
+ },
103
+ );
104
+ } catch {
105
+ // A held or unreadable old lock is left as it is; the new lock is elsewhere.
106
+ }
107
+ }
14
108
 
15
109
  /**
16
110
  * Holds one repository's lock while ids and counts change. The lock file makes
@@ -21,9 +115,11 @@ export async function withRepositoryLock<T>(
21
115
  work: () => Promise<T> | T,
22
116
  options: RepositoryLockOptions = {},
23
117
  ): Promise<T> {
24
- const lockPath = join(repositoryPath, ".operad", "dev.lock");
118
+ await removeLegacyLock(repositoryPath);
119
+ const { home, ...lockOptions } = options;
120
+ const lockPath = repositoryLockPath(repositoryPath, home);
25
121
  try {
26
- return await withLockFile(lockPath, work, { ...options, label: "dev lock" });
122
+ return await withLockFile(lockPath, work, { ...lockOptions, label: "dev lock" });
27
123
  } catch (error) {
28
124
  if (error instanceof LockTimeoutError) {
29
125
  throw new DevError(