@operad-io/dev 0.2.0 → 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.
package/src/integrate.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  } from "./integration-queue.ts";
25
25
  import {
26
26
  mainCloneChange,
27
+ switchBackToStart,
27
28
  updateMainClone,
28
29
  type CommandRunner,
29
30
  type MainCloneOutcome,
@@ -35,11 +36,15 @@ import { reportFlakyTests } from "./flaky.ts";
35
36
  import { recordRerunPasses } from "./reruns.ts";
36
37
  import { getPlan, refreshPlanCounts } from "./service.ts";
37
38
  import {
39
+ baseName,
40
+ baseRef,
38
41
  commitOf,
42
+ fetchRemote,
39
43
  git,
40
44
  headOf,
41
45
  isAncestor,
42
46
  treeOf,
47
+ type GitResult,
43
48
  } from "./git.ts";
44
49
  import {
45
50
  cancelledStep,
@@ -88,6 +93,34 @@ export const integrateTestHooks: {
88
93
  wait?: ((ms: number) => Promise<void>) | undefined;
89
94
  } = {};
90
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
+
91
124
  export async function followMain(
92
125
  repository: { readonly name: string; readonly path: string },
93
126
  branch: string,
@@ -97,7 +130,14 @@ export async function followMain(
97
130
  run: async () => ({ ok: true, out: "" }),
98
131
  },
99
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,
100
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
+ }
101
141
  return updateMainClone(
102
142
  repository.path,
103
143
  branch,
@@ -321,9 +361,24 @@ export async function runIntegrate(
321
361
  context.taskId,
322
362
  );
323
363
  const head = branchHead(repository, settings, context.workName);
324
- 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;
325
372
  const keyCommands = settings.integration.keyCommands;
326
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);
327
382
 
328
383
  const fail = async (
329
384
  message: string,
@@ -353,6 +408,8 @@ export async function runIntegrate(
353
408
 
354
409
  /** Asks before a push in a background run; a person-started run and an allowlisted target do not ask. */
355
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 ||
356
413
  guardOutward(
357
414
  {
358
415
  access: ctx.access,
@@ -367,8 +424,8 @@ export async function runIntegrate(
367
424
  },
368
425
  {
369
426
  kind: "repository",
370
- target: `${settings.remote}/${settings.mainBranch}`,
371
- content: `push ${sha ?? "HEAD"} to ${settings.remote}/${settings.mainBranch} (${what})`,
427
+ target: baseName(settings),
428
+ content: `push ${sha ?? "HEAD"} to ${baseName(settings)} (${what})`,
372
429
  },
373
430
  );
374
431
 
@@ -411,6 +468,7 @@ export async function runIntegrate(
411
468
  cloneSha,
412
469
  { lines: settings.prepare, run: mainCloneRunner(ctx, settings) },
413
470
  marker,
471
+ inPlace,
414
472
  );
415
473
  integrateTestHooks.at?.("clone-followed");
416
474
  const cloneChange = mainCloneChange(clone);
@@ -463,7 +521,7 @@ export async function runIntegrate(
463
521
  typeof previous.candidate === "string" &&
464
522
  previous.candidate.length > 0
465
523
  ) {
466
- const fetched = git(repository, ["fetch", "--prune", settings.remote]);
524
+ const fetched = fetchRemote(repository, settings);
467
525
  const remoteMain = commitOf(repository, mainRef);
468
526
  if (
469
527
  fetched.ok &&
@@ -493,6 +551,7 @@ export async function runIntegrate(
493
551
  typeof previous.batchHead === "string" ? previous.batchHead : previous.candidate,
494
552
  { lines: settings.prepare, run: mainCloneRunner(ctx, settings) },
495
553
  marker,
554
+ inPlace,
496
555
  );
497
556
  const cloneChange = mainCloneChange(clone);
498
557
  const withClone: IntegrationRecord = {
@@ -540,7 +599,7 @@ export async function runIntegrate(
540
599
  signal: ctx.signal,
541
600
  wait: integrateTestHooks.wait,
542
601
  landed: (result) => {
543
- if (!git(repository, ["fetch", "--prune", settings.remote]).ok) return false;
602
+ if (!fetchRemote(repository, settings).ok) return false;
544
603
  const main = commitOf(repository, mainRef);
545
604
  return main !== undefined && isAncestor(repository, result.head, main);
546
605
  },
@@ -567,7 +626,7 @@ export async function runIntegrate(
567
626
 
568
627
  /** This task's merge commit when main already has it, and the main that has it. */
569
628
  const alreadyOnMain = (): { sha: string; main: string } | undefined => {
570
- if (!git(repository, ["fetch", "--prune", settings.remote]).ok) return undefined;
629
+ if (!fetchRemote(repository, settings).ok) return undefined;
571
630
  const main = commitOf(repository, mainRef);
572
631
  if (main === undefined) return undefined;
573
632
  const found = git(repository, [
@@ -599,7 +658,7 @@ export async function runIntegrate(
599
658
  })),
600
659
  ];
601
660
  for (let round = 0; round < MAX_INTEGRATION_ROUNDS; round += 1) {
602
- const fetched = git(repository, ["fetch", "--prune", settings.remote]);
661
+ const fetched = fetchRemote(repository, settings);
603
662
  if (!fetched.ok) return undefined;
604
663
  const base = commitOf(repository, mainRef);
605
664
  if (base === undefined) return undefined;
@@ -735,6 +794,7 @@ export async function runIntegrate(
735
794
  head: head ?? null,
736
795
  headMoved,
737
796
  pushed: false,
797
+ ...(cloneFollowsLocalMain ? { prepareDue: true } : {}),
738
798
  batchHead,
739
799
  batch: members.filter((member) => member.task !== context.taskId).map((member) => member.task),
740
800
  ...(checkNote === undefined ? {} : { checkNote }),
@@ -767,27 +827,23 @@ export async function runIntegrate(
767
827
  const landed = await queue.landWhenStillQueued(followers, result, async () => {
768
828
  await integrateTestHooks.beforePush?.(batchHead);
769
829
  if (!(await pushAllowed(batchHead, "the batch merge"))) return false;
770
- const pushed = git(gate, [
771
- "push",
772
- settings.remote,
773
- `HEAD:refs/heads/${settings.mainBranch}`,
774
- ]).ok;
830
+ const pushed = landOnMain(repository, gate, settings, base).ok;
775
831
  if (pushed) return true;
776
- git(repository, ["fetch", "--prune", settings.remote]);
832
+ fetchRemote(repository, settings);
777
833
  const after = commitOf(repository, mainRef);
778
834
  landedDespiteError = after !== undefined && isAncestor(repository, batchHead, after);
779
835
  return landedDespiteError;
780
836
  });
781
837
  if (landed === "withdrawn") return undefined;
782
838
  if (landed === "failed") {
783
- return fail(`the person did not allow the push to "${settings.remote}/${settings.mainBranch}"`);
839
+ return fail(`the person did not allow the push to "${baseName(settings)}"`);
784
840
  }
785
841
  if (landed === "pushed") {
786
842
  if (landedDespiteError) return land({ landed: true });
787
843
  integrateTestHooks.afterPush?.(batchHead);
788
844
  return land({});
789
845
  }
790
- git(repository, ["fetch", "--prune", settings.remote]);
846
+ fetchRemote(repository, settings);
791
847
  const now = commitOf(repository, mainRef);
792
848
  if (now !== undefined && isAncestor(repository, batchHead, now)) {
793
849
  return land({ landed: true });
@@ -883,7 +939,7 @@ export async function runIntegrate(
883
939
 
884
940
  let lastError = "";
885
941
  for (let round = 0; round < MAX_INTEGRATION_ROUNDS; round += 1) {
886
- const fetched = git(repository, ["fetch", "--prune", settings.remote]);
942
+ const fetched = fetchRemote(repository, settings);
887
943
  if (!fetched.ok) {
888
944
  return fail(
889
945
  `cannot fetch "${settings.remote}": ${fetched.err || fetched.out || "git fetch failed"}`,
@@ -891,7 +947,11 @@ export async function runIntegrate(
891
947
  }
892
948
  const base = commitOf(repository, mainRef);
893
949
  if (base === undefined) {
894
- 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
+ );
895
955
  }
896
956
 
897
957
  const prepared = recreateGateWorktree(repository, gate, base, settings);
@@ -1145,6 +1205,7 @@ export async function runIntegrate(
1145
1205
  head: head ?? null,
1146
1206
  headMoved,
1147
1207
  pushed: false,
1208
+ ...(cloneFollowsLocalMain ? { prepareDue: true } : {}),
1148
1209
  ...(checkNote === undefined ? {} : { checkNote }),
1149
1210
  };
1150
1211
  if ((await writeIntegration(ctx, context, task, attempt, pending, {
@@ -1155,13 +1216,9 @@ export async function runIntegrate(
1155
1216
  integrateTestHooks.at?.("pending-saved");
1156
1217
 
1157
1218
  if (!(await pushAllowed(sha, "the task merge"))) {
1158
- return fail(`the person did not allow the push to "${settings.remote}/${settings.mainBranch}"`);
1219
+ return fail(`the person did not allow the push to "${baseName(settings)}"`);
1159
1220
  }
1160
- const push = git(gate, [
1161
- "push",
1162
- settings.remote,
1163
- `HEAD:refs/heads/${settings.mainBranch}`,
1164
- ]);
1221
+ const push = landOnMain(repository, gate, settings, base);
1165
1222
  if (push.ok) {
1166
1223
  integrateTestHooks.afterPush?.(sha);
1167
1224
  const record: IntegrationRecord = {
@@ -1172,8 +1229,11 @@ export async function runIntegrate(
1172
1229
  return recordMerged(record, sha);
1173
1230
  }
1174
1231
 
1175
- lastError = `cannot push "${settings.mainBranch}" to "${settings.remote}": ${push.err || push.out || "git push failed"}`;
1176
- git(repository, ["fetch", "--prune", settings.remote]);
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);
1177
1237
  const now = commitOf(repository, mainRef);
1178
1238
  // A push can land on the remote and still report an error (the client lost
1179
1239
  // the answer). The remote's main then contains the candidate: it is
@@ -1221,7 +1281,7 @@ export async function runCleanup(
1221
1281
  const env: Record<string, string> = {
1222
1282
  OPERAD_TASK: context.taskId,
1223
1283
  OPERAD_WORKTREE: worktree,
1224
- OPERAD_REMOTE: settings.remote,
1284
+ OPERAD_REMOTE: settings.remote ?? "",
1225
1285
  };
1226
1286
  const failures: CleanupFailure[] = [];
1227
1287
  const runStep = ctx.runStep;
package/src/mainclone.ts CHANGED
@@ -44,6 +44,23 @@ export interface MainCloneOutcome {
44
44
  readonly prepared?: boolean | undefined;
45
45
  }
46
46
 
47
+ /**
48
+ * Why a fast-forward refused. When untracked files are in the way, git lists
49
+ * them before "Aborting"; say which.
50
+ */
51
+ function mergeReason(text: string): string {
52
+ const lines = text.split("\n");
53
+ const at = lines.findIndex((line) => line.includes("untracked working tree files would be overwritten"));
54
+ if (at >= 0) {
55
+ const files = lines
56
+ .slice(at + 1)
57
+ .filter((line) => line.startsWith("\t") || line.startsWith(" "))
58
+ .map((line) => line.trim());
59
+ if (files.length > 0) return `untracked files in the way: ${files.join(", ")}`;
60
+ }
61
+ return lastLine(text);
62
+ }
63
+
47
64
  function lastLine(text: string): string {
48
65
  const lines = text.split("\n").filter((line) => line.trim().length > 0);
49
66
  return lines[lines.length - 1] ?? "";
@@ -87,6 +104,45 @@ export function mainCloneChange(outcome: MainCloneOutcome): string | undefined {
87
104
  return outcome.note === undefined ? undefined : `main clone: ${outcome.note}`;
88
105
  }
89
106
 
107
+ /**
108
+ * In branch mode the clone is on the task's branch when the merge lands. Put it
109
+ * back on the branch it started on so the fast-forward can follow. A clone the
110
+ * person moved, or left with uncommitted changes, stays as it is and the note
111
+ * says where it is.
112
+ */
113
+ export function switchBackToStart(
114
+ repository: string,
115
+ start: string,
116
+ taskBranch: string,
117
+ ): { readonly ok: true } | { readonly ok: false; readonly note: string } {
118
+ const current = git(repository, ["symbolic-ref", "--short", "-q", "HEAD"]);
119
+ if (current.ok && current.out === start) return { ok: true };
120
+ if (!current.ok || current.out !== taskBranch) {
121
+ return {
122
+ ok: false,
123
+ note: `the main clone is on ${current.ok ? `"${current.out}"` : "no branch"}, not on the task's branch "${taskBranch}" or "${start}"; it was left as it is`,
124
+ };
125
+ }
126
+ const status = git(repository, ["status", "--porcelain", "--untracked-files=normal"]);
127
+ if (!status.ok) {
128
+ return { ok: false, note: `cannot read its status: ${status.err}; the main clone stays on "${taskBranch}"` };
129
+ }
130
+ if (status.out.length > 0) {
131
+ return {
132
+ ok: false,
133
+ note: `uncommitted changes; the main clone stays on "${taskBranch}", not "${start}"`,
134
+ };
135
+ }
136
+ const moved = git(repository, ["switch", "-q", start]);
137
+ if (!moved.ok) {
138
+ return {
139
+ ok: false,
140
+ note: `cannot switch back to "${start}": ${lastLine(moved.err || moved.out) || "git switch failed"}; the main clone stays on "${taskBranch}"`,
141
+ };
142
+ }
143
+ return { ok: true };
144
+ }
145
+
90
146
  /**
91
147
  * Fast-forwards the main clone to `sha` when it is on `branch` and clean, then
92
148
  * runs the prepare lines there when the clone moved. A marker left by an
@@ -108,7 +164,7 @@ export async function updateMainClone(
108
164
  note: `the main clone is on ${current.ok ? `"${current.out}"` : "no branch"}, not "${branch}"`,
109
165
  };
110
166
  }
111
- const status = git(repository, ["status", "--porcelain", "--untracked-files=normal"]);
167
+ const status = git(repository, ["status", "--porcelain", "--untracked-files=no"]);
112
168
  if (!status.ok) {
113
169
  return { updated: false, note: `cannot read its status: ${status.err}` };
114
170
  }
@@ -134,7 +190,7 @@ export async function updateMainClone(
134
190
  if (lines.length > 0 && marker !== undefined) await marker.save(marker.due);
135
191
  return {
136
192
  updated: false,
137
- note: `cannot fast-forward: ${lastLine(merge.err || merge.out) || "git merge failed"}`,
193
+ note: `cannot fast-forward: ${mergeReason(merge.err || merge.out) || "git merge failed"}`,
138
194
  };
139
195
  }
140
196
  return prepareAndClear(repository, lines, run, marker);
package/src/model.ts CHANGED
@@ -310,6 +310,8 @@ export interface ReviewRecord {
310
310
  readonly model?: string | null;
311
311
  /** Which round (first or rework) ran and which block each setting came from. */
312
312
  readonly reviewSettings?: ReviewSettingsUsed | null;
313
+ /** The fix level in force when the round ran. */
314
+ readonly fixLevel?: string | null;
313
315
  /** When an unavailable round may run again, in epoch milliseconds. */
314
316
  readonly retryAt?: number | null;
315
317
  /** Every run of this round, in order. */
@@ -391,6 +393,12 @@ export type TaskAttempt = {
391
393
  readonly worktree?: string | null;
392
394
  readonly branch?: string | null;
393
395
  readonly base?: string | null;
396
+ /**
397
+ * The text of `.operad/dev.json` as the attempt's first step read it (empty
398
+ * when the file did not exist). The attempt's steps use it and do not read
399
+ * the file again (ADR 0039 D6).
400
+ */
401
+ readonly settingsText?: string;
394
402
  readonly sessionId?: string | null;
395
403
  /** The cost in dollars, when the harness reported one. */
396
404
  readonly cost?: number | null;
@@ -409,6 +417,8 @@ export type TaskAttempt = {
409
417
  readonly workerChanged?: string | null;
410
418
  /** Whether the work step consumed this attempt; a later worktree visit is new work. */
411
419
  readonly worked?: boolean;
420
+ /** Whether the work reported done; false when it failed, waited or never ran to its end. */
421
+ readonly workDone?: boolean;
412
422
  /** The file the worker's own log was written to. */
413
423
  readonly workLog?: string | null;
414
424
  /** The worker's last message of this attempt's work, in full, as the harness reported it. */
@@ -442,6 +452,9 @@ export type TaskAttempt = {
442
452
  readonly integrating?: string | null;
443
453
  /** While the work step waits for its named worker: what it waits for and who holds it. */
444
454
  readonly workerWait?: string | null;
455
+ /** While the work runs: the worker the pool placed and its harness step, for the log. */
456
+ readonly workerRunning?: string | null;
457
+ readonly workerUse?: string | null;
445
458
  /** While a step waits for a check place: the place group, since when, and how many wait ahead. */
446
459
  readonly placeWait?: { readonly key: string; readonly since: number; readonly ahead: number } | null;
447
460
  /** While the integrate step waits for its turn: who is integrating. */
@@ -8,15 +8,22 @@
8
8
  */
9
9
 
10
10
  import { messageOf } from "@operad-io/engine";
11
- import type { ProjectSettingsDeclaration } from "@operad-io/engine";
11
+ import type { ObjectStore, ProjectSettingsDeclaration, SettingsRepository } from "@operad-io/engine";
12
12
  import { flowClash, listRepositoryFlows } from "./project-flows.ts";
13
13
  import { defaultDevSettings, readDevSettings, settingsProblem, settingsValueProblem, useNewStageNames } from "./settings.ts";
14
- import { listRepositories } from "./service.ts";
14
+ import { cloneHolder, listRepositories } from "./service.ts";
15
15
  import type { JsonValue } from "@operad-io/engine";
16
16
 
17
+ /** The store each listed repository came from: a settings save looks for the task holding its clone there. */
18
+ const storeOf = new WeakMap<SettingsRepository, ObjectStore>();
19
+
17
20
  export const DEV_PROJECT_SETTINGS: ProjectSettingsDeclaration = {
18
21
  repositories: async ({ store }) =>
19
- (await listRepositories(store)).map(({ name, path }) => ({ name, path })),
22
+ (await listRepositories(store)).map(({ name, path }) => {
23
+ const repository = { name, path };
24
+ storeOf.set(repository, store);
25
+ return repository;
26
+ }),
20
27
  files: [
21
28
  {
22
29
  name: "dev",
@@ -25,7 +32,15 @@ export const DEV_PROJECT_SETTINGS: ProjectSettingsDeclaration = {
25
32
  // (ADR 0020 D4), then the name clash with a TypeScript flow (D6). It runs
26
33
  // for a flow change only, so an invalid flow already in the file does not
27
34
  // block an unrelated setting.
28
- check: ({ repository, value, name }) => {
35
+ check: async ({ repository, value, name }) => {
36
+ // dev reads dev.json once when an attempt starts (ADR 0039 D6): a save
37
+ // while a branch-mode task holds the clone would change what the next
38
+ // attempt reads from the branch it started on, so none is made.
39
+ const store = storeOf.get(repository);
40
+ const holder = store === undefined ? undefined : await cloneHolder(store, repository.name);
41
+ if (holder !== undefined) {
42
+ return `dev.json cannot be saved while ${holder} holds the main clone on its own branch: merge or cancel ${holder} first`;
43
+ }
29
44
  if (name !== "dev.flows" && !name.startsWith("dev.flows.")) return undefined;
30
45
  const problem =
31
46
  settingsValueProblem(repository.path, value) ??
@@ -102,6 +117,17 @@ export const DEV_PROJECT_SETTINGS: ProjectSettingsDeclaration = {
102
117
  description:
103
118
  "The most of this repository's tasks that run at the same time, on top of the worker counts. Unset means the workers' own counts decide.",
104
119
  },
120
+ workIn: {
121
+ title: "Work in",
122
+ oneOf: [
123
+ { const: "branch", title: "A branch in this folder" },
124
+ { const: "worktree", title: "A separate worktree" },
125
+ ],
126
+ default: "worktree",
127
+ editable: true,
128
+ description:
129
+ "Where a task's changes are made. branch (A branch in this folder): dev makes the task's branch in the main clone and the task works there, one task at a time; it cannot be combined with a concurrency above 1 or workers that add up to more than 1. worktree (A separate worktree): each task has its own worktree.",
130
+ },
105
131
  autoDefault: {
106
132
  type: "string",
107
133
  title: "Auto for new plans",
@@ -6,12 +6,18 @@
6
6
  * add` does and removes the file. A request that cannot be registered stays,
7
7
  * with the reason written into it, and is shown as a pending item until it is
8
8
  * fixed or removed.
9
+ *
10
+ * A request with `"kind": "setup-git"` (ADR 0039 D8) asks for git to be set up in
11
+ * a folder instead: it carries the `.gitignore` text, the approved paths and,
12
+ * when git has none, the name and email (see `setup-git.ts`). It is run the
13
+ * same way and a failure stays in the file the same way.
9
14
  */
10
15
 
11
16
  import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12
17
  import { join } from "node:path";
13
18
  import { isRecord, messageOf, type ObjectStore, type StandingItem } from "@operad-io/engine";
14
19
  import { addRepository } from "./service.ts";
20
+ import { applySetupGit, type SetupGitRequest } from "./setup-git.ts";
15
21
 
16
22
  /** The directory under the home that holds the requests. */
17
23
  export function registerRequestsDirectory(home: string): string {
@@ -22,6 +28,24 @@ interface Request {
22
28
  readonly file: string;
23
29
  readonly path: string;
24
30
  readonly error: string | undefined;
31
+ /** The whole file, kept when a failure is written back. */
32
+ readonly body: Record<string, unknown>;
33
+ /** Set for a request to set up git. */
34
+ readonly setupGit: SetupGitRequest | undefined;
35
+ }
36
+
37
+ function setupGitOf(body: Record<string, unknown>, path: string): SetupGitRequest | undefined {
38
+ if (body.kind !== "setup-git") return undefined;
39
+ const paths = Array.isArray(body.paths) ? body.paths.filter((p): p is string => typeof p === "string") : [];
40
+ const identity = isRecord(body.identity) ? body.identity : undefined;
41
+ return {
42
+ path,
43
+ gitignore: typeof body.gitignore === "string" ? body.gitignore : "",
44
+ paths,
45
+ ...(identity !== undefined && typeof identity.name === "string" && typeof identity.email === "string"
46
+ ? { identity: { name: identity.name, email: identity.email } }
47
+ : {}),
48
+ };
25
49
  }
26
50
 
27
51
  function readRequests(home: string): Request[] {
@@ -45,6 +69,8 @@ function readRequests(home: string): Request[] {
45
69
  file,
46
70
  path: parsed.path,
47
71
  error: typeof parsed.error === "string" ? parsed.error : undefined,
72
+ body: parsed,
73
+ setupGit: setupGitOf(parsed, parsed.path),
48
74
  });
49
75
  } catch {
50
76
  // A file that is not written yet or is not a request is left alone.
@@ -61,7 +87,11 @@ export async function registerRequested(ctx: {
61
87
  }): Promise<void> {
62
88
  for (const request of readRequests(ctx.home)) {
63
89
  try {
64
- await addRepository(ctx.store, { path: request.path, cwd: ctx.cwd });
90
+ if (request.setupGit !== undefined) {
91
+ await applySetupGit(request.setupGit, { lock: { home: ctx.home } });
92
+ } else {
93
+ await addRepository(ctx.store, { path: request.path, cwd: ctx.cwd });
94
+ }
65
95
  rmSync(request.file, { force: true });
66
96
  } catch (error) {
67
97
  const message = messageOf(error);
@@ -70,7 +100,8 @@ export async function registerRequested(ctx: {
70
100
  continue;
71
101
  }
72
102
  if (message !== request.error) {
73
- writeFileSync(request.file, `${JSON.stringify({ path: request.path, error: message })}\n`);
103
+ const body = request.setupGit === undefined ? { path: request.path } : request.body;
104
+ writeFileSync(request.file, `${JSON.stringify({ ...body, error: message })}\n`);
74
105
  }
75
106
  }
76
107
  }
@@ -81,7 +112,10 @@ export function registerStanding(home: string): readonly StandingItem[] {
81
112
  return readRequests(home)
82
113
  .filter((request) => request.error !== undefined)
83
114
  .map((request) => ({
84
- id: `register:${request.path}`,
85
- prompt: `the repository ${request.path} could not be registered: ${request.error ?? ""}; fix it and it is registered on its own, or remove ${request.file}`,
115
+ id: `${request.setupGit === undefined ? "register" : "setup-git"}:${request.path}`,
116
+ prompt:
117
+ request.setupGit === undefined
118
+ ? `the repository ${request.path} could not be registered: ${request.error ?? ""}; fix it and it is registered on its own, or remove ${request.file}`
119
+ : `git could not be set up in ${request.path}: ${request.error ?? ""}; fix it and it is tried again on its own, or remove ${request.file}`,
86
120
  }));
87
121
  }
package/src/schedule.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  } from "@operad-io/engine";
19
19
  import {
20
20
  idOfKey,
21
+ isOpenTask,
21
22
  changeClock,
22
23
  dependencyKey,
23
24
  dependencyLabel,
@@ -79,8 +80,17 @@ export function writeSchedulerLine(line: string): void {
79
80
  write(line);
80
81
  }
81
82
 
83
+ /**
84
+ * A task holds a slot while it runs or is reviewed. A branch-mode task also
85
+ * holds the main clone until it is merged or cancelled, whatever it waits for:
86
+ * a person, the merge, a pause, or its next start (ADR 0039 D3).
87
+ */
82
88
  function isActive(task: TaskData): boolean {
83
- return task.phase === "running" || task.phase === "review";
89
+ return (
90
+ task.phase === "running" ||
91
+ task.phase === "review" ||
92
+ (task.attempt?.inPlace === true && isOpenTask(task))
93
+ );
84
94
  }
85
95
 
86
96
  function planOf(task: TaskData): string {
@@ -917,11 +927,16 @@ async function scheduleRepository(
917
927
  if (task.phase !== "ready") return false;
918
928
  if (!dependencyState(task, tasksById).ready) return false;
919
929
  if (!canStartWork) return false;
920
- if (task.area !== undefined && areaActive.has(task.area)) return false;
921
- if (planConcurrency(plan) - (planActive.get(planId) ?? 0) <= 0) return false;
922
- if (repositoryActive >= repositoryConcurrency(settings)) return false;
930
+ // A ready task that already holds the clone (it was paused, or its claim
931
+ // was released) does not count against itself.
932
+ const own = isActive(task) ? 1 : 0;
933
+ if (task.area !== undefined && areaActive.has(task.area) && areaActive.get(task.area) !== idOfKey(object.id)) {
934
+ return false;
935
+ }
936
+ if (planConcurrency(plan) - ((planActive.get(planId) ?? 0) - own) <= 0) return false;
937
+ if (repositoryActive - own >= repositoryConcurrency(settings)) return false;
923
938
  const pool = poolOf(task);
924
- return (poolActive.get(pool) ?? 0) < repositoryConcurrency(settings, pool);
939
+ return (poolActive.get(pool) ?? 0) - own < repositoryConcurrency(settings, pool);
925
940
  };
926
941
 
927
942
  /**
@@ -1136,8 +1151,10 @@ async function scheduleRepository(
1136
1151
  note = "waiting for the plan to resume";
1137
1152
  } else if (queuedIds.has(object.id)) {
1138
1153
  const plan = plansById.get(task.plan);
1139
- const holders = activeIds(task.plan);
1140
- const all = activeIds(undefined);
1154
+ // A ready task that holds the clone itself is not held by itself.
1155
+ const self = idOfKey(object.id);
1156
+ const holders = activeIds(task.plan).filter((held) => held !== self);
1157
+ const all = activeIds(undefined).filter((held) => held !== self);
1141
1158
  if (missing.length > 0) {
1142
1159
  note = `waiting for plugin ${missing.join(", ")}`;
1143
1160
  } else if (task.area !== undefined && areaActive.has(task.area)) {
@@ -1152,6 +1169,7 @@ async function scheduleRepository(
1152
1169
  return (isActive(otherTask) || started.has(other.id)) && poolOf(otherTask) === pool;
1153
1170
  })
1154
1171
  .map((other) => idOfKey(other.id))
1172
+ .filter((held) => held !== self)
1155
1173
  .sort();
1156
1174
  if (
1157
1175
  Object.keys(settings.workers.pools).length > 1 &&