@operad-io/dev 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/steps.ts CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  import { withWorkerReports } from "@operad-io/engine/platform";
8
8
  import {
9
+ appendFileSync,
9
10
  existsSync,
10
11
  mkdirSync,
11
12
  readFileSync,
@@ -46,15 +47,21 @@ import {
46
47
  WAITING_EVENT,
47
48
  type WorkerDefinition,
48
49
  } from "@operad-io/pool";
50
+ import { writingChat } from "./clone-chat.ts";
49
51
  import { now as devNow } from "./clock.ts";
50
52
  import { modelErrorIn, modelWaitsForPerson } from "./model-error.ts";
51
53
  import {
54
+ baseName,
55
+ baseRef,
52
56
  branchExists,
57
+ fetchRemote,
53
58
  git,
54
59
  headOf,
55
60
  isAncestor,
61
+ type BaseSettings,
56
62
  type GitResult,
57
63
  } from "./git.ts";
64
+ import { taskGitRefusal } from "./git-state.ts";
58
65
  import { runPrepare, taskStepAccess } from "./prepare.ts";
59
66
  import { classifyStop, isConnectionError, STOP_REASONS } from "./stops.ts";
60
67
  import { findRepository, putTaskKeepingPlanCost, withRepoLock } from "./service.ts";
@@ -71,7 +78,10 @@ import {
71
78
  import { MAX_WORK_WAITS, STEP_TIMEOUT_SECS } from "./timeouts.ts";
72
79
  import {
73
80
  assertInsideRepository,
81
+ DEV_SETTINGS_FILE,
82
+ devSettingsFromText,
74
83
  readDevSettings,
84
+ readDevSettingsText,
75
85
  readWorkerBrief,
76
86
  type DevSettings,
77
87
  } from "./settings.ts";
@@ -97,6 +107,20 @@ export function worktreePath(
97
107
  return path;
98
108
  }
99
109
 
110
+ /**
111
+ * Where a task's work is done: its own worktree, or the main clone itself when
112
+ * the repository works in a branch of its folder (ADR 0039 D1).
113
+ */
114
+ export function workPath(
115
+ repository: RepositoryData,
116
+ settings: DevSettings,
117
+ taskId: string,
118
+ ): string {
119
+ return settings.workIn === "branch"
120
+ ? repository.path
121
+ : worktreePath(repository.path, settings, taskId);
122
+ }
123
+
100
124
  /** The branch a task's worktree is on. */
101
125
  export function workBranch(taskId: string): string {
102
126
  return `work/${taskId}`;
@@ -118,15 +142,56 @@ export interface TaskContext {
118
142
  /** The name of the task's worktree and branch: the task id, or the chat worktree it was opened on. */
119
143
  readonly workName: string;
120
144
  readonly settings: DevSettings;
145
+ /** The dev.json text `settings` came from; empty when the file does not exist. */
146
+ readonly settingsText?: string;
121
147
  }
122
148
 
123
- export async function taskContext(ctx: StepContext): Promise<TaskContext> {
149
+ /**
150
+ * The task's context. The settings are the ones the task's attempt recorded
151
+ * when it started (ADR 0039 D6); `fresh` reads the file instead, for the step
152
+ * that starts an attempt.
153
+ */
154
+ export async function taskContext(
155
+ ctx: StepContext,
156
+ fresh: boolean = false,
157
+ ): Promise<TaskContext> {
124
158
  const parts = await taskParts(ctx);
125
- const settings = await readDevSettings(parts.repository.path);
126
- return { ...parts, settings };
159
+ const recorded = parts.task.attempt?.settingsText;
160
+ if (!fresh && typeof recorded === "string") {
161
+ const settings = recordedSettings(parts.repository.path, recorded);
162
+ if (settings !== undefined) return { ...parts, settings, settingsText: recorded };
163
+ }
164
+ const start = startBranchOf(parts.task.attempt);
165
+ if (fresh && parts.task.attempt?.inPlace === true && start !== undefined) {
166
+ // The clone is on the task's branch, which may have edited the file; the
167
+ // settings are the ones the person controls, on the branch it started from.
168
+ const committed = git(parts.repository.path, ["show", `${start}:${DEV_SETTINGS_FILE}`], true);
169
+ if (committed.ok) {
170
+ return {
171
+ ...parts,
172
+ settings: devSettingsFromText(parts.repository.path, committed.out),
173
+ settingsText: committed.out,
174
+ };
175
+ }
176
+ }
177
+ const read = readDevSettingsText(parts.repository.path);
178
+ return { ...parts, settings: read.settings, settingsText: read.text };
127
179
  }
128
180
 
129
- /** A task context whose settings may be missing: a step that can retry reads it. */
181
+ /**
182
+ * The settings an attempt recorded. A text that this build no longer accepts
183
+ * gives undefined, and the caller reads the file instead.
184
+ */
185
+ function recordedSettings(repositoryPath: string, text: string): DevSettings | undefined {
186
+ try {
187
+ return devSettingsFromText(repositoryPath, text);
188
+ } catch (error) {
189
+ if (error instanceof DevError) return undefined;
190
+ throw error;
191
+ }
192
+ }
193
+
194
+ /** A task context whose settings may be missing:a step that can retry reads it. */
130
195
  export type LooseTaskContext = Omit<TaskContext, "settings"> & {
131
196
  readonly settings?: DevSettings | undefined;
132
197
  /** Why the settings could not be read, when `settings` is absent. */
@@ -141,6 +206,11 @@ export async function looseTaskContext(
141
206
  ctx: StepContext,
142
207
  ): Promise<LooseTaskContext> {
143
208
  const parts = await taskParts(ctx);
209
+ const recorded = parts.task.attempt?.settingsText;
210
+ if (typeof recorded === "string") {
211
+ const settings = recordedSettings(parts.repository.path, recorded);
212
+ if (settings !== undefined) return { ...parts, settings, settingsText: recorded };
213
+ }
144
214
  try {
145
215
  return { ...parts, settings: await readDevSettings(parts.repository.path) };
146
216
  } catch (error) {
@@ -222,6 +292,12 @@ function attemptFor(ctx: StepContext, task: TaskData): AttemptState {
222
292
  };
223
293
  }
224
294
 
295
+ /** The branch an attempt recorded the main clone as being on before the task's. */
296
+ function startBranchOf(attempt: TaskAttempt | undefined): string | undefined {
297
+ const value = attempt?.startBranch;
298
+ return typeof value === "string" && value.length > 0 ? value : undefined;
299
+ }
300
+
225
301
  function listWorktrees(repositoryPath: string): readonly string[] {
226
302
  const result = git(repositoryPath, ["worktree", "list", "--porcelain"]);
227
303
  if (!result.ok) return [];
@@ -326,6 +402,76 @@ function checkoutContent(checkout: string, path: string): string | undefined {
326
402
  }
327
403
  }
328
404
 
405
+ // Where a checkout's HEAD stood: the commit and the branch it was on.
406
+ interface CheckoutPosition {
407
+ readonly head: string;
408
+ readonly branch: string | undefined;
409
+ }
410
+
411
+ function checkoutPosition(checkout: string): CheckoutPosition | undefined {
412
+ const head = headOf(checkout);
413
+ if (head === undefined) return undefined;
414
+ const branch = git(checkout, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
415
+ return { head, branch: branch.ok && branch.out.length > 0 ? branch.out : undefined };
416
+ }
417
+
418
+ // What the main checkout holds before the worker runs: its status entries and
419
+ // where its HEAD is, so a commit made there with a clean tree afterwards is
420
+ // seen too.
421
+ interface CheckoutBefore {
422
+ readonly entries: readonly CheckoutEntry[];
423
+ readonly position: CheckoutPosition | undefined;
424
+ }
425
+
426
+ function checkoutBefore(checkout: string): CheckoutBefore {
427
+ return { entries: checkoutSnapshot(checkout), position: checkoutPosition(checkout) };
428
+ }
429
+
430
+ const NO_CHECKOUT_BEFORE: CheckoutBefore = { entries: [], position: undefined };
431
+
432
+ // A moved or switched HEAD, in words that end with `(moved a..b)` or
433
+ // `(switched a..b)`; the review reads that ending as a commit, not a file.
434
+ // A move counts only for commits the clone gained that are not on the remote's
435
+ // main: dev's own fast-forward after a merge and a commit a person pushed are
436
+ // on it. A repository without that remote ref compares with the attempt's
437
+ // recorded base instead, which is the main the worktree started from. A branch
438
+ // switch counts only when the clone was left on another branch than it began on.
439
+ interface MainReach {
440
+ /** Undefined when the repository has no remote: there is nothing to fetch. */
441
+ readonly remote: string | undefined;
442
+ readonly mainRef: string;
443
+ readonly base: string | null;
444
+ }
445
+
446
+ function movedHead(
447
+ checkout: string,
448
+ before: CheckoutPosition | undefined,
449
+ after: CheckoutPosition | undefined,
450
+ reach: MainReach,
451
+ ): string | undefined {
452
+ if (before === undefined || after === undefined) return undefined;
453
+ const name = after.branch ?? "HEAD";
454
+ const short = (sha: string): string => sha.slice(0, 7);
455
+ if (before.head !== after.head) {
456
+ // Reads the remote's current main; a failed fetch leaves the ref as it was.
457
+ if (reach.remote !== undefined) git(checkout, ["fetch", "--quiet", reach.remote]);
458
+ const known = git(checkout, ["rev-parse", "--verify", "--quiet", `${reach.mainRef}^{commit}`]);
459
+ const floor = known.ok && known.out.length > 0 ? reach.mainRef : reach.base;
460
+ const gained = git(checkout, [
461
+ "rev-list",
462
+ `${before.head}..${after.head}`,
463
+ ...(floor === null ? [] : ["--not", floor]),
464
+ ]);
465
+ if (gained.ok && gained.out.trim().length > 0) {
466
+ return `${name} (moved ${short(before.head)}..${short(after.head)})`;
467
+ }
468
+ }
469
+ if (before.branch !== after.branch) {
470
+ return `${name} (switched ${before.branch ?? "HEAD"}..${name})`;
471
+ }
472
+ return undefined;
473
+ }
474
+
329
475
  /** The status entries of a checkout, with what each readable file holds. */
330
476
  function checkoutSnapshot(checkout: string): readonly CheckoutEntry[] {
331
477
  return checkoutEntries(checkout).map((entry) => {
@@ -349,10 +495,12 @@ function insideWorktree(checkout: string, worktree: string, path: string): boole
349
495
  function newCheckoutChanges(
350
496
  checkout: string,
351
497
  worktree: string,
352
- before: readonly CheckoutEntry[],
498
+ before: CheckoutBefore,
499
+ reach: MainReach,
353
500
  ): readonly string[] {
354
- const seen = new Map(before.map((entry) => [checkoutEntryKey(entry), entry]));
355
- const changed: string[] = [];
501
+ const seen = new Map(before.entries.map((entry) => [checkoutEntryKey(entry), entry]));
502
+ const moved = movedHead(checkout, before.position, checkoutPosition(checkout), reach);
503
+ const changed: string[] = moved === undefined ? [] : [moved];
356
504
  for (const entry of checkoutEntries(checkout)) {
357
505
  const was = seen.get(checkoutEntryKey(entry));
358
506
  // The same status letters and path: only a further edit to the file itself
@@ -390,6 +538,10 @@ export interface Prepared {
390
538
  /** Set when the prepare commands failed. */
391
539
  readonly reason?: string | undefined;
392
540
  readonly log?: string | undefined;
541
+ /** In branch mode: the branch the main clone was on before the task's. */
542
+ readonly startBranch?: string | undefined;
543
+ /** In branch mode: the task was cancelled while the step was preparing. */
544
+ readonly cancelled?: boolean | undefined;
393
545
  }
394
546
 
395
547
  /** Runs the prepare commands in a ready worktree; a failure turns it into a failed visit. */
@@ -641,15 +793,21 @@ export function prepareWorktree(
641
793
  taskId: string,
642
794
  mergeMain = true,
643
795
  ): Prepared {
644
- const fetch = git(repository.path, ["fetch", "--prune", settings.remote]);
796
+ const refusal = taskGitRefusal(repository.path);
797
+ if (refusal !== undefined) return failed(refusal);
798
+ const fetch = fetchRemote(repository.path, settings);
645
799
  if (!fetch.ok) {
646
800
  return failed(
647
801
  `cannot fetch "${settings.remote}": ${fetch.err || fetch.out || "git fetch failed"}`,
648
802
  );
649
803
  }
650
- const mainRef = `${settings.remote}/${settings.mainBranch}`;
651
- if (!git(repository.path, ["show-ref", "--verify", "--quiet", `refs/remotes/${mainRef}`]).ok) {
652
- return failed(`"${mainRef}" does not exist after the fetch`);
804
+ const mainRef = baseName(settings);
805
+ if (!git(repository.path, ["show-ref", "--verify", "--quiet", baseRef(settings)]).ok) {
806
+ return failed(
807
+ settings.remote === undefined
808
+ ? `the branch "${mainRef}" does not exist`
809
+ : `"${mainRef}" does not exist after the fetch`,
810
+ );
653
811
  }
654
812
 
655
813
  const path = worktreePath(repository.path, settings, taskId);
@@ -693,7 +851,7 @@ export function prepareWorktree(
693
851
  if (branchExists(repository.path, branch)) {
694
852
  add = git(repository.path, ["worktree", "add", path, branch]);
695
853
  reused = true;
696
- } else if (branchExists(repository.path, branch, settings.remote)) {
854
+ } else if (settings.remote !== undefined && branchExists(repository.path, branch, settings.remote)) {
697
855
  add = git(repository.path, [
698
856
  "worktree",
699
857
  "add",
@@ -724,6 +882,149 @@ export function prepareWorktree(
724
882
  return { kind: "ready", base: headOf(path) };
725
883
  }
726
884
 
885
+ /** Adds a line to the repository's own ignore list, so git status never shows it. */
886
+ function excludeFromStatus(repositoryPath: string, entry: string): void {
887
+ const path = git(repositoryPath, ["rev-parse", "--git-path", "info/exclude"]);
888
+ if (!path.ok) return;
889
+ const excludePath = resolve(repositoryPath, path.out);
890
+ try {
891
+ mkdirSync(dirname(excludePath), { recursive: true });
892
+ const current = existsSync(excludePath) ? readFileSync(excludePath, "utf8") : "";
893
+ const lines = current.replace(/\r\n/g, "\n").split("\n");
894
+ if (lines.some((line) => line.trim() === entry)) return;
895
+ const prefix = current.length === 0 || current.endsWith("\n") ? "" : "\n";
896
+ appendFileSync(excludePath, `${prefix}${entry}\n`, "utf8");
897
+ } catch {
898
+ // Without the entry the note shows as an untracked file; the step goes on.
899
+ }
900
+ }
901
+
902
+ export interface BranchOptions {
903
+ /** The start branch this attempt already recorded (a replay of the step). */
904
+ readonly recorded?: string | undefined;
905
+ /** The start branch an earlier attempt recorded; used only while the clone is on the task's branch. */
906
+ readonly carried?: string | undefined;
907
+ readonly mergeMain: boolean;
908
+ /**
909
+ * Called once, with the branch the clone is on, before the clone is switched,
910
+ * so a crash after the switch still knows where to switch back to. False
911
+ * says the task was cancelled.
912
+ */
913
+ readonly beforeSwitch?: ((start: string) => Promise<boolean>) | undefined;
914
+ }
915
+
916
+ /** A message names at most this many files of a dirty clone. */
917
+ const NAMED_FILES = 20;
918
+
919
+ function namedFiles(files: readonly string[]): string {
920
+ const shown = files.slice(0, NAMED_FILES).join(", ");
921
+ return files.length > NAMED_FILES
922
+ ? `${shown} and ${String(files.length - NAMED_FILES)} more`
923
+ : shown;
924
+ }
925
+
926
+ /**
927
+ * The branch mode of `prepareWorktree` (ADR 0039 D1, D4): the task works on
928
+ * `work/<id>` in the main clone itself. The clone is in one of three states
929
+ * when the step runs, told apart by the branch it is on:
930
+ *
931
+ * - on `work/<id>`: the step goes on from an earlier visit (a rework, or a
932
+ * crash after the switch). Edits in the tree are the worker's own, so main
933
+ * is not merged into a dirty tree.
934
+ * - on the branch the task started on, or on any branch the first time: the
935
+ * clone must be clean, then it is switched.
936
+ * - on another branch than the recorded start: the person moved it; the step
937
+ * stops and says so instead of switching under them.
938
+ */
939
+ export async function prepareBranch(
940
+ repository: RepositoryData,
941
+ settings: DevSettings,
942
+ taskId: string,
943
+ options: BranchOptions,
944
+ ): Promise<Prepared> {
945
+ const refusal = taskGitRefusal(repository.path);
946
+ if (refusal !== undefined) return failed(refusal);
947
+ const fetch = fetchRemote(repository.path, settings);
948
+ if (!fetch.ok) {
949
+ return failed(
950
+ `cannot fetch "${settings.remote}": ${fetch.err || fetch.out || "git fetch failed"}`,
951
+ );
952
+ }
953
+ const mainRef = baseName(settings);
954
+ if (!git(repository.path, ["show-ref", "--verify", "--quiet", baseRef(settings)]).ok) {
955
+ return failed(
956
+ settings.remote === undefined
957
+ ? `the branch "${mainRef}" does not exist`
958
+ : `"${mainRef}" does not exist after the fetch`,
959
+ );
960
+ }
961
+ const path = repository.path;
962
+ const branch = workBranch(taskId);
963
+ const current = currentBranch(path);
964
+ excludeFromStatus(path, PROGRESS_FILE);
965
+
966
+ if (current === branch) {
967
+ const startBranch = options.recorded ?? options.carried ?? settings.mainBranch;
968
+ if (mergeInProgress(path)) {
969
+ return { kind: "conflict", base: headOf(path), files: conflictedFiles(path), startBranch };
970
+ }
971
+ if (!options.mergeMain || changedFiles(path).length > 0) {
972
+ return { kind: "ready", base: headOf(path), startBranch };
973
+ }
974
+ return { ...mergeLatest(path, mainRef), startBranch };
975
+ }
976
+
977
+ if (current === undefined) {
978
+ return failed(
979
+ "the main clone is not on a branch; switch it to a branch, then run the task again",
980
+ );
981
+ }
982
+ if (options.recorded !== undefined && current !== options.recorded) {
983
+ return failed(
984
+ `the main clone is on "${current}", but the task started on "${options.recorded}"; switch it back to "${options.recorded}", then run the task again`,
985
+ );
986
+ }
987
+ const dirty = changedFiles(path);
988
+ if (dirty.length > 0) {
989
+ return failed(
990
+ `the main clone has uncommitted changes: ${namedFiles(dirty)}; commit or set them aside, then run the task again`,
991
+ dirty,
992
+ );
993
+ }
994
+ const startBranch = options.recorded ?? current;
995
+ if (options.beforeSwitch !== undefined && options.recorded === undefined) {
996
+ if (!(await options.beforeSwitch(startBranch))) {
997
+ return { kind: "failed", cancelled: true };
998
+ }
999
+ }
1000
+
1001
+ stepTestHooks.branchStep?.("before-switch");
1002
+ let reused = false;
1003
+ let switched: GitResult;
1004
+ if (branchExists(path, branch)) {
1005
+ switched = git(path, ["switch", "--quiet", branch]);
1006
+ reused = true;
1007
+ } else if (settings.remote !== undefined && branchExists(path, branch, settings.remote)) {
1008
+ switched = git(path, [
1009
+ "switch",
1010
+ "--quiet",
1011
+ "--no-track",
1012
+ "-c",
1013
+ branch,
1014
+ `${settings.remote}/${branch}`,
1015
+ ]);
1016
+ reused = true;
1017
+ } else {
1018
+ switched = git(path, ["switch", "--quiet", "--no-track", "-c", branch, mainRef]);
1019
+ }
1020
+ if (!switched.ok) {
1021
+ return failed(`cannot switch the main clone to "${branch}": ${switched.err || switched.out}`);
1022
+ }
1023
+ stepTestHooks.branchStep?.("after-switch");
1024
+ if (reused && options.mergeMain) return { ...mergeLatest(path, mainRef), startBranch };
1025
+ return { kind: "ready", base: headOf(path), startBranch };
1026
+ }
1027
+
727
1028
  export async function saveTask(
728
1029
  ctx: StepContext,
729
1030
  key: string,
@@ -776,6 +1077,14 @@ export const stepTestHooks: {
776
1077
  workClock?: WorkClock | undefined;
777
1078
  /** Replaces the timer that says a worker with a place has not started. */
778
1079
  workerStartClock?: WorkClock | undefined;
1080
+ /**
1081
+ * Called at each point of the branch mode's worktree step where a crash
1082
+ * leaves the main clone in a different state. A test kills its own process
1083
+ * there.
1084
+ */
1085
+ branchStep?:
1086
+ | ((point: "before-switch" | "after-switch" | "before-save") => void)
1087
+ | undefined;
779
1088
  /** Called once the task has recorded what the work step waits for (null: nothing). */
780
1089
  afterWorkerWait?: ((text: string | null) => void) | undefined;
781
1090
  } = {};
@@ -844,16 +1153,20 @@ function commitWip(worktree: string): boolean {
844
1153
  return git(worktree, ["commit", "-q", "--no-verify", "-m", WIP_MESSAGE]).ok;
845
1154
  }
846
1155
 
847
- /** Commits everything left in the worktree (honouring .gitignore) with the given message. */
848
- function commitLeft(worktree: string, message: string): boolean {
849
- if (conflictedFiles(worktree).length > 0) return false;
1156
+ /**
1157
+ * Commits everything left in the worktree (honouring .gitignore) with the given
1158
+ * message. Returns what went wrong when it could not, so the step can report it.
1159
+ */
1160
+ function commitLeft(worktree: string, message: string): string | undefined {
1161
+ const conflicted = conflictedFiles(worktree);
1162
+ if (conflicted.length > 0) return `unresolved conflicts in ${conflicted.join(", ")}`;
850
1163
  const added = git(worktree, ["add", "-A", "--", "."]);
851
- if (!added.ok) return false;
852
- const committed = git(worktree, ["commit", "-q", "--no-verify", "-m", message]).ok;
1164
+ if (!added.ok) return `git add failed: ${(added.err || added.out).trim()}`;
1165
+ const committed = git(worktree, ["commit", "-q", "--no-verify", "-m", message]);
853
1166
  // The note is the worker's report, not part of the change: take it out of the
854
1167
  // branch again, leaving the file for the step to read.
855
1168
  untrackNote(worktree);
856
- return committed;
1169
+ return committed.ok ? undefined : `git commit failed: ${(committed.err || committed.out).trim()}`;
857
1170
  }
858
1171
 
859
1172
  /**
@@ -901,7 +1214,7 @@ function blockedDependency(params: unknown): string | undefined {
901
1214
  export async function runWorktree(
902
1215
  ctx: StepContext,
903
1216
  ): Promise<PluginStepResult> {
904
- const context = await taskContext(ctx);
1217
+ const context = await taskContext(ctx, true);
905
1218
  if (!claimAllows(ctx, context.task)) return cancelledStep();
906
1219
  const stoppedAt = runStoppedAt(ctx.params);
907
1220
  if (stoppedAt !== undefined && context.task.run === null) {
@@ -966,27 +1279,75 @@ export async function runWorktree(
966
1279
  };
967
1280
  }
968
1281
  const { attempt, attempts, replay } = attemptFor(ctx, context.task);
1282
+ // A replay of an attempt keeps what its first visit recorded.
1283
+ const recordedText = replay ? attempt.settingsText : undefined;
1284
+ const settingsText = recordedText ?? context.settingsText ?? "";
1285
+ const settings =
1286
+ recordedText === undefined
1287
+ ? context.settings
1288
+ : devSettingsFromText(context.repository.path, recordedText);
1289
+ const inPlace = settings.workIn === "branch";
1290
+ const mergeMain = beforeAttemptOf(ctx.params) !== "none";
1291
+ const where = workPath(context.repository, settings, context.workName);
1292
+ // A task that holds the clone already was refused any chat writer when it
1293
+ // started; a new start waits for a reply that can write there to end.
1294
+ const writer =
1295
+ inPlace && startBranchOf(context.task.attempt) === undefined
1296
+ ? await writingChat(ctx.store, context.repository.name, ctx.runs)
1297
+ : undefined;
969
1298
  const prepared = await withPrepare(
970
1299
  ctx,
971
- context.settings,
972
- worktreePath(context.repository.path, context.settings, context.workName),
973
- prepareWorktree(
974
- context.repository,
975
- context.settings,
976
- context.workName,
977
- beforeAttemptOf(ctx.params) !== "none",
978
- ),
1300
+ settings,
1301
+ where,
1302
+ writer !== undefined
1303
+ ? failed(
1304
+ `chat ${writer} is writing a reply in the main clone and can change files there; wait for it to end or stop it, then run the task again`,
1305
+ )
1306
+ : inPlace
1307
+ ? await prepareBranch(context.repository, settings, context.workName, {
1308
+ recorded: replay ? startBranchOf(attempt) : undefined,
1309
+ carried: startBranchOf(context.task.attempt),
1310
+ mergeMain,
1311
+ // Record where the clone started before it is switched, so a crash
1312
+ // between the two still knows which branch to switch back to.
1313
+ beforeSwitch: (start) =>
1314
+ saveTaskGuarded(
1315
+ ctx,
1316
+ context.taskKey,
1317
+ {
1318
+ ...context.task,
1319
+ phase: "running",
1320
+ waitKind: undefined,
1321
+ run: ctx.runId,
1322
+ startRequested: false,
1323
+ attempts,
1324
+ attempt: {
1325
+ ...attempt,
1326
+ run: ctx.runId,
1327
+ settingsText,
1328
+ inPlace: true,
1329
+ startBranch: start,
1330
+ },
1331
+ },
1332
+ "dev:worktree-start",
1333
+ ),
1334
+ })
1335
+ : prepareWorktree(context.repository, settings, context.workName, mergeMain),
979
1336
  );
1337
+ if (prepared.cancelled === true) return cancelledStep();
1338
+ if (inPlace) stepTestHooks.branchStep?.("before-save");
980
1339
  const base = prepared.base ?? attempt.base ?? null;
1340
+ const startBranch = prepared.startBranch ?? startBranchOf(replay ? attempt : undefined);
981
1341
  const nextAttempt: TaskAttempt = {
982
1342
  ...attempt,
983
1343
  run: ctx.runId,
984
- worktree: worktreePath(
985
- context.repository.path,
986
- context.settings,
987
- context.workName,
988
- ),
1344
+ settingsText,
1345
+ worktree: where,
989
1346
  branch: workBranch(context.workName),
1347
+ // A start that was refused before the clone moved holds nothing.
1348
+ ...(inPlace && (startBranch !== undefined || prepared.kind !== "failed")
1349
+ ? { inPlace: true, ...(startBranch === undefined ? {} : { startBranch }) }
1350
+ : {}),
990
1351
  base,
991
1352
  result: prepared.kind,
992
1353
  // The answer of an earlier attempt belongs to that attempt.
@@ -1065,18 +1426,24 @@ export async function runReverify(
1065
1426
  run: ctx.runId,
1066
1427
  };
1067
1428
  const attempts = Math.max(context.task.attempts, attempt.number);
1429
+ const worktree = workPath(
1430
+ context.repository,
1431
+ context.settings,
1432
+ context.workName,
1433
+ );
1434
+ const inPlace = context.settings.workIn === "branch";
1068
1435
  const prepared = await withPrepare(
1069
1436
  ctx,
1070
1437
  context.settings,
1071
- worktreePath(context.repository.path, context.settings, context.workName),
1072
- prepareWorktree(context.repository, context.settings, context.workName),
1438
+ worktree,
1439
+ inPlace
1440
+ ? await prepareBranch(context.repository, context.settings, context.workName, {
1441
+ recorded: startBranchOf(attempt),
1442
+ mergeMain: true,
1443
+ })
1444
+ : prepareWorktree(context.repository, context.settings, context.workName),
1073
1445
  );
1074
1446
  const base = prepared.base ?? attempt.base ?? null;
1075
- const worktree = worktreePath(
1076
- context.repository.path,
1077
- context.settings,
1078
- context.workName,
1079
- );
1080
1447
  const message =
1081
1448
  prepared.kind === "conflict"
1082
1449
  ? "reverify: main conflicts, sending to work"
@@ -1090,6 +1457,12 @@ export async function runReverify(
1090
1457
  run: ctx.runId,
1091
1458
  worktree,
1092
1459
  branch: workBranch(context.workName),
1460
+ ...(inPlace
1461
+ ? {
1462
+ inPlace: true,
1463
+ ...(prepared.startBranch === undefined ? {} : { startBranch: prepared.startBranch }),
1464
+ }
1465
+ : {}),
1093
1466
  base,
1094
1467
  result: prepared.kind,
1095
1468
  // A conflict is worked on again; a clean merge goes straight to the gate.
@@ -1349,10 +1722,10 @@ function hasUncheckedWork(
1349
1722
  path: string,
1350
1723
  head: string,
1351
1724
  attempt: TaskAttempt,
1352
- context: { readonly settings: { readonly remote: string; readonly mainBranch: string } },
1725
+ context: { readonly settings: BaseSettings },
1353
1726
  ): boolean {
1354
1727
  if (attempt.verified === head && attempt.verify?.result === "pass") return false;
1355
- const mainRef = `${context.settings.remote}/${context.settings.mainBranch}`;
1728
+ const mainRef = baseName(context.settings);
1356
1729
  const ahead = git(path, ["rev-list", "--count", "--no-merges", `${mainRef}..${head}`]);
1357
1730
  return ahead.ok && Number(ahead.out) > 0;
1358
1731
  }
@@ -1393,7 +1766,7 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1393
1766
  const task = context.task;
1394
1767
  const path =
1395
1768
  task.attempt?.worktree ??
1396
- worktreePath(context.repository.path, context.settings, context.workName);
1769
+ workPath(context.repository, context.settings, context.workName);
1397
1770
  const branch = task.attempt?.branch ?? workBranch(context.workName);
1398
1771
  const attempt: TaskAttempt = task.attempt ?? {
1399
1772
  number: Math.max(task.attempts, 0) + 1,
@@ -1402,7 +1775,11 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1402
1775
  const attempts = Math.max(task.attempts, attempt.number);
1403
1776
  const base = attempt.base ?? headOf(path) ?? null;
1404
1777
 
1405
- if (!existsSync(path) || !isWorktree(path)) {
1778
+ // The attempt's own record says where it works; the settings may have
1779
+ // changed since (a task switched from one mode to the other keeps its way).
1780
+ const inPlace = task.attempt?.inPlace === true;
1781
+ const wrongBranch = inPlace ? currentBranch(path) !== branch : false;
1782
+ if (!existsSync(path) || !isWorktree(path) || wrongBranch) {
1406
1783
  const nextAttempt: TaskAttempt = {
1407
1784
  ...attempt,
1408
1785
  run: ctx.runId,
@@ -1411,6 +1788,7 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1411
1788
  base,
1412
1789
  result: "failed",
1413
1790
  worked: true,
1791
+ workDone: false,
1414
1792
  };
1415
1793
  const written = await saveTaskGuarded(
1416
1794
  ctx,
@@ -1429,14 +1807,16 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1429
1807
  result: "failed",
1430
1808
  data: resultData(nextAttempt, harnessReading({}), {
1431
1809
  reason: "no_worktree",
1432
- message: `no worktree at ${path}; run the worktree step first`,
1810
+ message: inPlace
1811
+ ? `the main clone is on "${currentBranch(path) ?? "no branch"}", not "${branch}"; run the worktree step first`
1812
+ : `no worktree at ${path}; run the worktree step first`,
1433
1813
  }),
1434
1814
  };
1435
1815
  }
1436
1816
 
1437
- if (beforeAttemptOf(ctx.params) === "merge-main") {
1817
+ if (beforeAttemptOf(stage) === "merge-main") {
1438
1818
  const remote = context.settings.remote;
1439
- const mainRef = `${remote}/${context.settings.mainBranch}`;
1819
+ const mainRef = baseName(context.settings);
1440
1820
  const failBefore = async (message: string): Promise<PluginStepResult> => {
1441
1821
  const nextAttempt: TaskAttempt = {
1442
1822
  ...attempt,
@@ -1446,6 +1826,7 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1446
1826
  base,
1447
1827
  result: "failed",
1448
1828
  worked: true,
1829
+ workDone: false,
1449
1830
  };
1450
1831
  const written = await saveTaskGuarded(
1451
1832
  ctx,
@@ -1468,7 +1849,7 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1468
1849
  }),
1469
1850
  };
1470
1851
  };
1471
- const fetch = git(context.repository.path, ["fetch", "--prune", remote]);
1852
+ const fetch = fetchRemote(context.repository.path, context.settings);
1472
1853
  if (!fetch.ok) {
1473
1854
  return failBefore(
1474
1855
  `cannot fetch "${remote}": ${fetch.err || fetch.out || "git fetch failed"}`,
@@ -1495,7 +1876,7 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1495
1876
  }
1496
1877
  }
1497
1878
 
1498
- const stageParams = (ctx.params ?? {}) as {
1879
+ const stageParams = stage as {
1499
1880
  readonly flowWorkerBrief?: unknown;
1500
1881
  readonly flowCommit?: unknown;
1501
1882
  };
@@ -1511,7 +1892,7 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1511
1892
  progressOf(attempt.previousProgress),
1512
1893
  );
1513
1894
  const stageBrief = (() => {
1514
- const given = ((ctx.params ?? {}) as { readonly flowBrief?: unknown }).flowBrief;
1895
+ const given = (stage as { readonly flowBrief?: unknown }).flowBrief;
1515
1896
  return typeof given === "string" && given.trim().length > 0 ? given.trim() : undefined;
1516
1897
  })();
1517
1898
  const finalPrompt =
@@ -1529,6 +1910,7 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1529
1910
  base,
1530
1911
  result: "failed",
1531
1912
  worked: true,
1913
+ workDone: false,
1532
1914
  };
1533
1915
  const written = await saveTaskGuarded(
1534
1916
  ctx,
@@ -1638,11 +2020,14 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1638
2020
  // holds it, in the row and in the step log. A rework waits for the worker it
1639
2021
  // asked for; any other attempt waits for the workers of the pool.
1640
2022
  let waitingFor: string | undefined;
2023
+ // The worker the pool placed and its harness step, kept on the attempt while
2024
+ // the work runs so the log view finds the right log before the outcome.
2025
+ let placedWorker: { readonly workerRunning: string; readonly workerUse: string } | undefined;
1641
2026
  const setWorkerWait = async (text: string | null): Promise<void> => {
1642
2027
  await saveTaskGuarded(
1643
2028
  ctx,
1644
2029
  context.taskKey,
1645
- { ...task, attempt: { ...attempt, workerWait: text } },
2030
+ { ...task, attempt: { ...attempt, ...placedWorker, workerWait: text } },
1646
2031
  "dev:work-wait",
1647
2032
  );
1648
2033
  stepTestHooks.afterWorkerWait?.(text);
@@ -1708,6 +2093,29 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1708
2093
  }).catch(() => undefined);
1709
2094
  };
1710
2095
  const workerPlaced = (name: string): void => {
2096
+ let use = stageParamsOf(stage).use;
2097
+ if (use === undefined) {
2098
+ try {
2099
+ const resolved = resolvePool(context.settings.workers, stagePool);
2100
+ use = [...resolved.workers, ...resolved.fallbacks].find((item) => item.name === name)?.use;
2101
+ } catch {
2102
+ use = undefined;
2103
+ }
2104
+ }
2105
+ if (use !== undefined) {
2106
+ placedWorker = { workerRunning: name, workerUse: use };
2107
+ sayChain = sayChain
2108
+ .then(async () => {
2109
+ if (sayClosed) return;
2110
+ await saveTaskGuarded(
2111
+ ctx,
2112
+ context.taskKey,
2113
+ { ...task, attempt: { ...attempt, ...placedWorker, workerWait: null } },
2114
+ "dev:work-placed",
2115
+ );
2116
+ })
2117
+ .catch(() => undefined);
2118
+ }
1711
2119
  if (started) return;
1712
2120
  startTimer = startClock.setTimeout(() => {
1713
2121
  if (started) return;
@@ -1737,7 +2145,9 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1737
2145
  stageParamsOf(stage),
1738
2146
  );
1739
2147
  if (askAnswer !== undefined) poolCall.askAnswer = askAnswer;
1740
- const mainCheckoutBefore = checkoutSnapshot(context.repository.path);
2148
+ // Working in the main clone changes it by design, so there is nothing to
2149
+ // report about it (ADR 0039 D1).
2150
+ const mainCheckoutBefore = inPlace ? NO_CHECKOUT_BEFORE : checkoutBefore(context.repository.path);
1741
2151
  let mainChanges: readonly string[] = [];
1742
2152
  try {
1743
2153
  outcome = await withWorkerReports(
@@ -1755,11 +2165,13 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1755
2165
  } finally {
1756
2166
  // Reading the main checkout is part of ending the step, so a worker call
1757
2167
  // that throws still reports what the step left there.
1758
- mainChanges = newCheckoutChanges(
1759
- context.repository.path,
1760
- path,
1761
- mainCheckoutBefore,
1762
- );
2168
+ mainChanges = inPlace
2169
+ ? []
2170
+ : newCheckoutChanges(context.repository.path, path, mainCheckoutBefore, {
2171
+ remote: context.settings.remote,
2172
+ mainRef: baseName(context.settings),
2173
+ base,
2174
+ });
1763
2175
  if (startTimer !== undefined) startClock.clearTimeout(startTimer);
1764
2176
  sayClosed = true;
1765
2177
  await sayChain;
@@ -1838,6 +2250,9 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1838
2250
  nextAttempt = {
1839
2251
  ...nextAttempt,
1840
2252
  result,
2253
+ // Whether the work reported done; reverify keeps it, so the gate can
2254
+ // tell a branch whose work never finished from one that changed nothing.
2255
+ workDone: result === "done",
1841
2256
  ...(mainLine === undefined
1842
2257
  ? {}
1843
2258
  : {
@@ -1976,15 +2391,18 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
1976
2391
  dirty = changedFiles(path);
1977
2392
  }
1978
2393
 
2394
+ let commitError: string | undefined;
1979
2395
  // A worker whose sandbox cannot write .git leaves its work uncommitted; the
1980
2396
  // stage asks dev to commit it, before verify so the check sees the commit.
1981
2397
  if (
1982
- stageParams.flowCommit === true &&
2398
+ // In the main clone dev commits what the worker left unless the stage says
2399
+ // the worker commits itself: the checks run on a commit (ADR 0020 D3).
2400
+ (stageParams.flowCommit === true || (inPlace && stageParams.flowCommit !== false)) &&
1983
2401
  hostError === undefined &&
1984
2402
  outcome?.result === "done" &&
1985
2403
  dirty.length > 0
1986
2404
  ) {
1987
- commitLeft(path, `${context.taskId}: ${task.title}`);
2405
+ commitError = commitLeft(path, `${context.taskId}: ${task.title}`);
1988
2406
  dirty = changedFiles(path);
1989
2407
  }
1990
2408
 
@@ -2079,7 +2497,9 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
2079
2497
  return finish("failed", {
2080
2498
  reason: "changes",
2081
2499
  files: dirty,
2082
- message: `uncommitted changes: ${dirty.join(", ")}`,
2500
+ message:
2501
+ `uncommitted changes: ${dirty.join(", ")}` +
2502
+ (commitError === undefined ? "" : `; the commit the stage asked for failed: ${commitError}`),
2083
2503
  });
2084
2504
  }
2085
2505
 
@@ -2101,12 +2521,12 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
2101
2521
  }
2102
2522
  }
2103
2523
 
2104
- const push = git(path, [
2105
- "push",
2106
- context.settings.remote,
2107
- `HEAD:refs/heads/${branch}`,
2108
- ]);
2109
- if (!push.ok) {
2524
+ // With no remote the branch stays local; verify reads it from here.
2525
+ const push =
2526
+ context.settings.remote === undefined
2527
+ ? undefined
2528
+ : git(path, ["push", context.settings.remote, `HEAD:refs/heads/${branch}`]);
2529
+ if (push !== undefined && !push.ok) {
2110
2530
  return finish("failed", {
2111
2531
  reason: "push",
2112
2532
  head,
@@ -2115,7 +2535,7 @@ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<P
2115
2535
  }
2116
2536
  return finish("done", {
2117
2537
  head,
2118
- pushed: true,
2538
+ pushed: push !== undefined,
2119
2539
  ...(note === undefined ? {} : { message: note }),
2120
2540
  });
2121
2541
  }