@operad-io/dev 0.1.1 → 0.2.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/steps.ts CHANGED
@@ -5,9 +5,18 @@
5
5
  */
6
6
 
7
7
  import { withWorkerReports } from "@operad-io/engine/platform";
8
- import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from "node:fs";
9
- import { dirname, join, resolve } from "node:path";
10
8
  import {
9
+ existsSync,
10
+ mkdirSync,
11
+ readFileSync,
12
+ realpathSync,
13
+ rmSync,
14
+ statSync,
15
+ writeFileSync,
16
+ } from "node:fs";
17
+ import { dirname, join, relative, resolve } from "node:path";
18
+ import {
19
+ isRecord,
11
20
  messageOf,
12
21
  readUsage,
13
22
  type CostQuality,
@@ -18,7 +27,7 @@ import {
18
27
  } from "@operad-io/engine";
19
28
  import {
20
29
  appendChange,
21
- bareId,
30
+ idOfKey,
22
31
  DevError,
23
32
  listAll,
24
33
  repositoryData,
@@ -37,8 +46,16 @@ import {
37
46
  WAITING_EVENT,
38
47
  type WorkerDefinition,
39
48
  } from "@operad-io/pool";
40
- import { git, type GitResult } from "./git.ts";
41
- import { runPrepare } from "./prepare.ts";
49
+ import { now as devNow } from "./clock.ts";
50
+ import { modelErrorIn, modelWaitsForPerson } from "./model-error.ts";
51
+ import {
52
+ branchExists,
53
+ git,
54
+ headOf,
55
+ isAncestor,
56
+ type GitResult,
57
+ } from "./git.ts";
58
+ import { runPrepare, taskStepAccess } from "./prepare.ts";
42
59
  import { classifyStop, isConnectionError, STOP_REASONS } from "./stops.ts";
43
60
  import { findRepository, putTaskKeepingPlanCost, withRepoLock } from "./service.ts";
44
61
  import {
@@ -59,8 +76,6 @@ import {
59
76
  type DevSettings,
60
77
  } from "./settings.ts";
61
78
 
62
- export { git, type GitResult };
63
-
64
79
  function resolvePath(path: string): string {
65
80
  try {
66
81
  return realpathSync(path);
@@ -89,10 +104,9 @@ export function workBranch(taskId: string): string {
89
104
 
90
105
  /** The step a host error says was not loaded; undefined for any other error. */
91
106
  function notLoadedStep(error: unknown): string | undefined {
92
- if (typeof error !== "object" || error === null) return undefined;
93
- const record = error as { readonly kind?: unknown; readonly use?: unknown };
94
- return record.kind === "step_not_loaded" && typeof record.use === "string"
95
- ? record.use
107
+ if (!isRecord(error)) return undefined;
108
+ return error.kind === "step_not_loaded" && typeof error.use === "string"
109
+ ? error.use
96
110
  : undefined;
97
111
  }
98
112
 
@@ -147,7 +161,7 @@ async function taskParts(
147
161
  let stored = await ctx.store.get("task", object.id);
148
162
  if (stored === undefined && !object.id.includes("/")) {
149
163
  const matches = (await listAll(ctx.store, "task")).filter(
150
- (candidate) => bareId(candidate.id) === object.id,
164
+ (candidate) => idOfKey(candidate.id) === object.id,
151
165
  );
152
166
  if (matches.length === 1) stored = matches[0];
153
167
  }
@@ -160,7 +174,7 @@ async function taskParts(
160
174
  );
161
175
  }
162
176
  const repository = repositoryData(found.data);
163
- const taskId = bareId(stored?.id ?? object.id);
177
+ const taskId = idOfKey(stored?.id ?? object.id);
164
178
  let taskKey = stored?.id ?? object.id;
165
179
  if ((await ctx.store.get("task", taskKey)) === undefined) {
166
180
  taskKey = storeKey(repository.name, taskId);
@@ -236,42 +250,6 @@ function currentBranch(path: string): string | undefined {
236
250
  return result.ok && result.out.length > 0 ? result.out : undefined;
237
251
  }
238
252
 
239
- export function headOf(path: string): string | undefined {
240
- const result = git(path, ["rev-parse", "HEAD"]);
241
- return result.ok && result.out.length > 0 ? result.out : undefined;
242
- }
243
-
244
- /** True when `ancestor` is reachable from `descendant`, so it is not new work. */
245
- function isAncestor(
246
- path: string,
247
- ancestor: string,
248
- descendant: string,
249
- ): boolean {
250
- return git(path, ["merge-base", "--is-ancestor", ancestor, descendant]).ok;
251
- }
252
-
253
- function branchExists(repositoryPath: string, branch: string): boolean {
254
- return git(repositoryPath, [
255
- "show-ref",
256
- "--verify",
257
- "--quiet",
258
- `refs/heads/${branch}`,
259
- ]).ok;
260
- }
261
-
262
- function remoteBranchExists(
263
- repositoryPath: string,
264
- remote: string,
265
- branch: string,
266
- ): boolean {
267
- return git(repositoryPath, [
268
- "show-ref",
269
- "--verify",
270
- "--quiet",
271
- `refs/remotes/${remote}/${branch}`,
272
- ]).ok;
273
- }
274
-
275
253
  function gitDirOf(worktree: string): string | undefined {
276
254
  const result = git(worktree, ["rev-parse", "--git-dir"]);
277
255
  if (!result.ok || result.out.length === 0) return undefined;
@@ -299,25 +277,107 @@ export function conflictedFiles(worktree: string): readonly string[] {
299
277
  .sort();
300
278
  }
301
279
 
302
- /**
303
- * The files `git status` calls changed, untracked included. Read from
304
- * `--porcelain -z`: names are not quoted or trimmed, a name may hold spaces, and
305
- * a rename or copy is followed by its old path, which is skipped (the new path
306
- * is the changed file).
307
- */
308
- export function changedFiles(worktree: string): readonly string[] {
309
- const result = git(worktree, ["status", "--porcelain", "-z"], true);
280
+ // One `git status --porcelain` entry: its two status letters and its path.
281
+ interface CheckoutEntry {
282
+ readonly code: string;
283
+ readonly path: string;
284
+ /** What the path held when it was read, when it is a readable file. */
285
+ readonly content?: string | undefined;
286
+ }
287
+
288
+ // The status entries of a checkout, read from `--porcelain -z`: names are not
289
+ // quoted or trimmed, a name may hold spaces or newlines, and a rename or copy
290
+ // is followed by its old path, which is skipped. `--no-optional-locks` stops git
291
+ // from refreshing the index, so reading the checkout writes no metadata.
292
+ function checkoutEntries(checkout: string): readonly CheckoutEntry[] {
293
+ const result = git(checkout, ["--no-optional-locks", "status", "--porcelain", "-z"], true);
310
294
  if (!result.ok || result.out.length === 0) return [];
311
295
  const entries = result.out.split("\0");
312
- const files: string[] = [];
296
+ const status: CheckoutEntry[] = [];
313
297
  for (let index = 0; index < entries.length; index += 1) {
314
298
  const entry = entries[index] ?? "";
315
299
  if (entry.length < 4) continue;
316
- files.push(entry.slice(3));
317
300
  const code = entry.slice(0, 2);
301
+ status.push({ code, path: entry.slice(3) });
318
302
  if (code.includes("R") || code.includes("C")) index += 1;
319
303
  }
320
- return [...new Set(files)].filter((file) => file !== PROGRESS_FILE).sort();
304
+ return status;
305
+ }
306
+
307
+ function checkoutEntryKey(entry: CheckoutEntry): string {
308
+ return `${entry.code}\0${entry.path}`;
309
+ }
310
+
311
+ /**
312
+ * What a status path holds, so a further edit to a file that was already
313
+ * changed before the step is a change too: its status letters and path stay the
314
+ * same when it is edited again. A deleted file, a collapsed untracked directory
315
+ * and any other unreadable path have none, and their status letters are all
316
+ * they compare by. Only a checkout that is already dirty is read, so a clean
317
+ * main checkout costs nothing.
318
+ */
319
+ function checkoutContent(checkout: string, path: string): string | undefined {
320
+ const file = join(checkout, path);
321
+ try {
322
+ if (!statSync(file).isFile()) return undefined;
323
+ return Bun.hash(readFileSync(file)).toString(16);
324
+ } catch {
325
+ return undefined;
326
+ }
327
+ }
328
+
329
+ /** The status entries of a checkout, with what each readable file holds. */
330
+ function checkoutSnapshot(checkout: string): readonly CheckoutEntry[] {
331
+ return checkoutEntries(checkout).map((entry) => {
332
+ const content = checkoutContent(checkout, entry.path);
333
+ return content === undefined ? entry : { ...entry, content };
334
+ });
335
+ }
336
+
337
+ // True when a status path is the task's worktree or lies inside it.
338
+ function insideWorktree(checkout: string, worktree: string, path: string): boolean {
339
+ const root = relative(checkout, worktree).replace(/\\/g, "/");
340
+ if (root.length === 0) return true;
341
+ if (root.startsWith("..")) return false;
342
+ const candidate = path.replace(/\\/g, "/");
343
+ return candidate === root || candidate.startsWith(`${root}/`);
344
+ }
345
+
346
+ // The paths whose status in the main checkout is new since `before`, or whose
347
+ // file was edited again since then, leaving out the task's own worktree, whose
348
+ // presence there the worktree explains.
349
+ function newCheckoutChanges(
350
+ checkout: string,
351
+ worktree: string,
352
+ before: readonly CheckoutEntry[],
353
+ ): readonly string[] {
354
+ const seen = new Map(before.map((entry) => [checkoutEntryKey(entry), entry]));
355
+ const changed: string[] = [];
356
+ for (const entry of checkoutEntries(checkout)) {
357
+ const was = seen.get(checkoutEntryKey(entry));
358
+ // The same status letters and path: only a further edit to the file itself
359
+ // is a change. A path that was unreadable then has no content to compare.
360
+ if (was !== undefined) {
361
+ if (was.content === undefined) continue;
362
+ if (checkoutContent(checkout, entry.path) === was.content) continue;
363
+ }
364
+ if (!insideWorktree(checkout, worktree, entry.path)) changed.push(entry.path);
365
+ }
366
+ return [...new Set(changed)].sort();
367
+ }
368
+
369
+ // The files `git status` calls changed, untracked included. Read from
370
+ // `--porcelain -z`: names are not quoted or trimmed, a name may hold spaces, and
371
+ // a rename or copy is followed by its old path, which is skipped (the new path
372
+ // is the changed file).
373
+ export function changedFiles(worktree: string): readonly string[] {
374
+ return [
375
+ ...new Set(
376
+ checkoutEntries(worktree)
377
+ .map((entry) => entry.path)
378
+ .filter((file) => file !== PROGRESS_FILE),
379
+ ),
380
+ ].sort();
321
381
  }
322
382
 
323
383
  export interface Prepared {
@@ -362,14 +422,190 @@ function failed(message: string, files?: readonly string[]): Prepared {
362
422
  return { kind: "failed", message, ...(files === undefined ? {} : { files }) };
363
423
  }
364
424
 
425
+ /** True for the root and package files whose rows are appended, never moved. */
426
+ function isMutationFile(path: string): boolean {
427
+ const parts = path.split("/");
428
+ return (
429
+ path === "MUTATIONS.md" ||
430
+ (parts.length >= 3 &&
431
+ parts[0] === "packages" &&
432
+ parts[parts.length - 1] === "MUTATIONS.md")
433
+ );
434
+ }
435
+
436
+ /** The lines of a file; a final newline does not add an empty last line. */
437
+ function linesOf(text: string): readonly string[] {
438
+ if (text === "") return [];
439
+ return (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n");
440
+ }
441
+
442
+ /** The lines `after` has beyond a longest common subsequence with `before`. */
443
+ function linesOnlyIn(before: readonly string[], after: readonly string[]): readonly string[] {
444
+ const table: Uint32Array[] = Array.from(
445
+ { length: before.length + 1 },
446
+ () => new Uint32Array(after.length + 1),
447
+ );
448
+ for (let row = before.length - 1; row >= 0; row -= 1) {
449
+ const line = table[row];
450
+ const next = table[row + 1];
451
+ if (line === undefined || next === undefined) continue;
452
+ for (let column = after.length - 1; column >= 0; column -= 1) {
453
+ line[column] =
454
+ before[row] === after[column]
455
+ ? (next[column + 1] ?? 0) + 1
456
+ : Math.max(next[column] ?? 0, line[column + 1] ?? 0);
457
+ }
458
+ }
459
+ const added: string[] = [];
460
+ let row = 0;
461
+ let column = 0;
462
+ while (row < before.length && column < after.length) {
463
+ if (before[row] === after[column]) {
464
+ row += 1;
465
+ column += 1;
466
+ } else if ((table[row + 1]?.[column] ?? 0) >= (table[row]?.[column + 1] ?? 0)) {
467
+ row += 1;
468
+ } else {
469
+ const line = after[column];
470
+ if (line !== undefined) added.push(line);
471
+ column += 1;
472
+ }
473
+ }
474
+ while (column < after.length) {
475
+ const line = after[column];
476
+ if (line !== undefined) added.push(line);
477
+ column += 1;
478
+ }
479
+ return added;
480
+ }
481
+
482
+ /** The lines `after` has in addition to the counts of the same lines in `before`. */
483
+ function linesBeyond(before: readonly string[], after: readonly string[]): readonly string[] {
484
+ const left = new Map<string, number>();
485
+ for (const line of before) left.set(line, (left.get(line) ?? 0) + 1);
486
+ const added: string[] = [];
487
+ for (const line of after) {
488
+ const count = left.get(line) ?? 0;
489
+ if (count === 0) added.push(line);
490
+ else left.set(line, count - 1);
491
+ }
492
+ return added;
493
+ }
494
+
495
+ /** The lines a task appended to a file since the merge base. */
496
+ function taskAddition(baseText: string, taskText: string): readonly string[] {
497
+ if (taskText.startsWith(baseText)) return linesOf(taskText.slice(baseText.length));
498
+ return linesOnlyIn(linesOf(baseText), linesOf(taskText));
499
+ }
500
+
501
+ /**
502
+ * Main's file unchanged, then the task's appended lines, then anything else the
503
+ * merged file has. A union merge puts the task's rows before main's, so the
504
+ * task's lines would otherwise sit inside main's file instead of after it. The
505
+ * task's own version says exactly which lines it appended, so a blank line or
506
+ * table header that is also in main's file is kept.
507
+ */
508
+ function mainFirst(
509
+ mainText: string,
510
+ taskText: string,
511
+ baseText: string,
512
+ mergedText: string,
513
+ ): string {
514
+ const taskLines = taskAddition(baseText, taskText);
515
+ const extra = linesBeyond([...linesOf(mainText), ...taskLines], linesOf(mergedText));
516
+ const added = [...taskLines, ...extra];
517
+ while (added[0]?.trim() === "") added.shift();
518
+ while (added[added.length - 1]?.trim() === "") added.pop();
519
+ if (added.length === 0) return mainText;
520
+ let text = mainText;
521
+ if (text.length > 0 && !text.endsWith("\n")) text += "\n";
522
+ if (text.length > 0 && !text.endsWith("\n\n")) text += "\n";
523
+ return `${text}${added.join("\n")}\n`;
524
+ }
525
+
526
+ /** A MUTATIONS.md main changed since a branch tip, and the merge base it changed from. */
527
+ type MutationChange = {
528
+ readonly file: string;
529
+ readonly base: string;
530
+ };
531
+
532
+ /** The MUTATIONS.md files main changed since a branch tip. */
533
+ function mainChangedMutations(
534
+ path: string,
535
+ before: string,
536
+ mainRef: string,
537
+ ): readonly MutationChange[] {
538
+ const base = git(path, ["merge-base", before, mainRef]);
539
+ if (!base.ok || base.out.length === 0) return [];
540
+ const diff = git(path, ["diff", "--name-only", base.out, mainRef]);
541
+ if (!diff.ok) return [];
542
+ return diff.out
543
+ .split("\n")
544
+ .filter((file) => isMutationFile(file))
545
+ .map((file) => ({ file, base: base.out }));
546
+ }
547
+
548
+ /** Rewrites the merged MUTATIONS.md files with main's rows first; returns those it changed. */
549
+ function mainFirstMutations(
550
+ path: string,
551
+ mainRef: string,
552
+ taskRef: string,
553
+ files: readonly MutationChange[],
554
+ ): readonly string[] {
555
+ const conflicted = new Set(conflictedFiles(path));
556
+ const changed: string[] = [];
557
+ for (const { file, base } of files) {
558
+ if (conflicted.has(file)) continue;
559
+ const main = git(path, ["show", `${mainRef}:${file}`], true);
560
+ const task = git(path, ["show", `${taskRef}:${file}`], true);
561
+ const fromBase = git(path, ["show", `${base}:${file}`], true);
562
+ const merged = join(path, file);
563
+ if (!main.ok || !task.ok || !fromBase.ok || !existsSync(merged)) continue;
564
+ const current = readFileSync(merged, "utf8");
565
+ const next = mainFirst(main.out, task.out, fromBase.out, current);
566
+ if (next === current) continue;
567
+ writeFileSync(merged, next);
568
+ changed.push(file);
569
+ }
570
+ return changed;
571
+ }
572
+
573
+ /** Amends the merge, or commits after an extra worker commit, with the rewritten files. */
574
+ function commitMainFirstMutations(
575
+ path: string,
576
+ files: readonly string[],
577
+ mergeHead?: string | undefined,
578
+ ): boolean {
579
+ if (files.length === 0) return true;
580
+ const added = git(path, ["add", "--", ...files]);
581
+ if (!added.ok) return false;
582
+ const second = git(path, ["rev-parse", "--verify", "--quiet", "HEAD^2"]);
583
+ const amend =
584
+ second.ok && (mergeHead === undefined || second.out === mergeHead);
585
+ return git(path, [
586
+ "commit",
587
+ ...(amend ? ["--amend", "--no-edit"] : ["-m", "mutations: keep main's rows first"]),
588
+ "--no-verify",
589
+ ]).ok;
590
+ }
591
+
365
592
  /** Merges the fetched main into a reused branch and reports a conflict. */
366
593
  function mergeLatest(path: string, mainRef: string): Prepared {
367
594
  const before = headOf(path);
368
595
  const commit = git(path, ["rev-parse", "--short", mainRef]).out;
596
+ const mutationFiles =
597
+ before === undefined ? [] : mainChangedMutations(path, before, mainRef);
369
598
  const merge = git(path, ["merge", "--no-edit", "--no-ff", mainRef]);
370
599
  if (!merge.ok) {
371
600
  const files = conflictedFiles(path);
372
601
  if (files.length > 0 || mergeInProgress(path)) {
602
+ // The worker will commit the merge after resolving the other files; put
603
+ // main's rows first now so that commit already has the right order.
604
+ const changed =
605
+ before === undefined
606
+ ? []
607
+ : mainFirstMutations(path, mainRef, before, mutationFiles);
608
+ if (changed.length > 0) git(path, ["add", "--", ...changed]);
373
609
  return {
374
610
  kind: "conflict",
375
611
  base: headOf(path),
@@ -381,6 +617,13 @@ function mergeLatest(path: string, mainRef: string): Prepared {
381
617
  `cannot merge "${mainRef}" into the worktree: ${merge.err || merge.out}`,
382
618
  );
383
619
  }
620
+ const changed =
621
+ before === undefined
622
+ ? []
623
+ : mainFirstMutations(path, mainRef, before, mutationFiles);
624
+ if (changed.length > 0 && !commitMainFirstMutations(path, changed)) {
625
+ return failed(`cannot keep main's rows first in ${changed.join(", ")}`);
626
+ }
384
627
  const after = headOf(path);
385
628
  return {
386
629
  kind: "ready",
@@ -450,7 +693,7 @@ export function prepareWorktree(
450
693
  if (branchExists(repository.path, branch)) {
451
694
  add = git(repository.path, ["worktree", "add", path, branch]);
452
695
  reused = true;
453
- } else if (remoteBranchExists(repository.path, settings.remote, branch)) {
696
+ } else if (branchExists(repository.path, branch, settings.remote)) {
454
697
  add = git(repository.path, [
455
698
  "worktree",
456
699
  "add",
@@ -493,10 +736,8 @@ export async function saveTask(
493
736
  /** The claim token the scheduler put in the run's start parameters. */
494
737
  export function runToken(ctx: StepContext): string | undefined {
495
738
  const params = ctx.params;
496
- if (typeof params !== "object" || params === null || Array.isArray(params)) {
497
- return undefined;
498
- }
499
- const token = (params as Record<string, unknown>).token;
739
+ if (!isRecord(params)) return undefined;
740
+ const token = params.token;
500
741
  return typeof token === "string" && token.length > 0 ? token : undefined;
501
742
  }
502
743
 
@@ -522,17 +763,6 @@ export function claimAllows(ctx: StepContext, task: TaskData): boolean {
522
763
  return true;
523
764
  }
524
765
 
525
- /** The task as it is now, when the current step may still write it. */
526
- export async function guardTask(
527
- ctx: StepContext,
528
- key: string,
529
- ): Promise<TaskData | undefined> {
530
- const object = await ctx.store.get("task", key);
531
- if (object === undefined) return undefined;
532
- const task = taskData(object.data);
533
- return claimAllows(ctx, task) ? task : undefined;
534
- }
535
-
536
766
  /**
537
767
  * Test-only hook, run by a guarded write after its caller built the new data
538
768
  * and before the write takes the repository lock. A test uses it to cancel the
@@ -655,19 +885,15 @@ export function cancelledStep(): PluginStepResult {
655
885
 
656
886
  /** The step a repair run says stopped, when the scheduler asked for one. */
657
887
  function runStoppedAt(params: unknown): string | undefined {
658
- if (typeof params !== "object" || params === null || Array.isArray(params)) {
659
- return undefined;
660
- }
661
- const value = (params as Record<string, unknown>).runStoppedAt;
888
+ if (!isRecord(params)) return undefined;
889
+ const value = params.runStoppedAt;
662
890
  return typeof value === "string" && value.length > 0 ? value : undefined;
663
891
  }
664
892
 
665
893
  /** The cancelled dependency a blocked start names, when the flow carries one. */
666
894
  function blockedDependency(params: unknown): string | undefined {
667
- if (typeof params !== "object" || params === null || Array.isArray(params)) {
668
- return undefined;
669
- }
670
- const value = (params as Record<string, unknown>).blockedBy;
895
+ if (!isRecord(params)) return undefined;
896
+ const value = params.blockedBy;
671
897
  return typeof value === "string" && value.length > 0 ? value : undefined;
672
898
  }
673
899
 
@@ -1055,7 +1281,7 @@ function poolParams(
1055
1281
  };
1056
1282
  }
1057
1283
 
1058
- /** The harness overrides a work stage wrote in its params. */
1284
+ /** The harness overrides a code stage wrote in its params. */
1059
1285
  function stageParamsOf(params: unknown): {
1060
1286
  readonly use?: string | undefined;
1061
1287
  readonly args?: readonly string[] | undefined;
@@ -1080,7 +1306,7 @@ function stageParamsOf(params: unknown): {
1080
1306
  };
1081
1307
  }
1082
1308
 
1083
- /** The preparation a work stage asks for before its attempt. */
1309
+ /** The preparation a code stage asks for before its attempt. */
1084
1310
  type BeforeAttempt = "merge-main" | "none";
1085
1311
 
1086
1312
  function beforeAttemptOf(params: unknown): BeforeAttempt | undefined {
@@ -1099,15 +1325,6 @@ function workLine(attempt: TaskAttempt): string {
1099
1325
  ].join("");
1100
1326
  }
1101
1327
 
1102
- /** Step `dev/work`: run the configured harness step and decide what it left. */
1103
- /** True when the harness reported that its model is unavailable or at its usage limit. */
1104
- function modelUnavailable(data: Record<string, unknown>): boolean {
1105
- const error = data.modelError;
1106
- if (typeof error !== "object" || error === null) return false;
1107
- const kind = (error as { readonly kind?: unknown }).kind;
1108
- return kind === "unavailable" || kind === "usage_limit";
1109
- }
1110
-
1111
1328
  /** The lines of a step's `stderr` data, which may be a string or a list. */
1112
1329
  function stderrLines(value: unknown): readonly string[] {
1113
1330
  if (typeof value === "string") return [value];
@@ -1140,7 +1357,14 @@ function hasUncheckedWork(
1140
1357
  return ahead.ok && Number(ahead.out) > 0;
1141
1358
  }
1142
1359
 
1143
- export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1360
+ /** Step `dev/work`: run the configured harness step and decide what it left. */
1361
+ export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<PluginStepResult> {
1362
+ // The step's own params (a flow stage writes them) and the run's start params
1363
+ // (a direct call writes them) both reach this step; the step's own win.
1364
+ const stage: Record<string, unknown> = {
1365
+ ...(isRecord(ctx.params) ? ctx.params : {}),
1366
+ ...(isRecord(stepParams) ? stepParams : {}),
1367
+ };
1144
1368
  const loose = await looseTaskContext(ctx);
1145
1369
  if (!claimAllows(ctx, loose.task)) return cancelledStep();
1146
1370
  if (loose.settings === undefined) {
@@ -1256,6 +1480,21 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1256
1480
  }
1257
1481
  }
1258
1482
 
1483
+ // A conflict is left for the worker to resolve and commit. Keep the main it
1484
+ // merged so the commit is checked again after the worker is done.
1485
+ const mergeHead = mergeInProgress(path)
1486
+ ? git(path, ["rev-parse", "MERGE_HEAD"]).out
1487
+ : undefined;
1488
+ let mergeTaskRef: string | undefined;
1489
+ let mergeMutationFiles: readonly MutationChange[] = [];
1490
+ if (mergeHead !== undefined && mergeHead.length > 0) {
1491
+ const mergeBefore = headOf(path);
1492
+ if (mergeBefore !== undefined) {
1493
+ mergeTaskRef = mergeBefore;
1494
+ mergeMutationFiles = mainChangedMutations(path, mergeBefore, mergeHead);
1495
+ }
1496
+ }
1497
+
1259
1498
  const stageParams = (ctx.params ?? {}) as {
1260
1499
  readonly flowWorkerBrief?: unknown;
1261
1500
  readonly flowCommit?: unknown;
@@ -1324,14 +1563,20 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1324
1563
  cwd: path,
1325
1564
  ...(ctx.object === undefined ? {} : { object: ctx.object }),
1326
1565
  params: ctx.params,
1327
- access: ctx.access,
1566
+ access: taskStepAccess(ctx.access),
1328
1567
  ...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
1329
1568
  signal: stopper.signal,
1330
1569
  };
1331
1570
  // A rework or reject goes back to the worker that ran the attempt before,
1332
1571
  // and resumes its session when the harness can. When that worker is no
1333
1572
  // longer in the pool, any free worker takes it and the change is recorded.
1334
- const stagePool = stageParamsOf(ctx.params).pool ?? DEFAULT_POOL;
1573
+ const stagePool = stageParamsOf(stage).pool ?? DEFAULT_POOL;
1574
+ const resumedSession =
1575
+ typeof stage.resumeSession === "string" ? stage.resumeSession : undefined;
1576
+ const askAnswer = isRecord(stage.askAnswer) ? stage.askAnswer : undefined;
1577
+ // An answer to the worker's own question comes back to this step; it resumes
1578
+ // the same worker, never a fallback.
1579
+ const resumed = resumedSession !== undefined || askAnswer !== undefined;
1335
1580
  const before =
1336
1581
  typeof attempt.previousWorker === "string" && attempt.previousWorker.length > 0
1337
1582
  ? attempt.previousWorker
@@ -1348,8 +1593,15 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1348
1593
  return false;
1349
1594
  }
1350
1595
  })();
1351
- const asked = stillThere ? before : undefined;
1352
- const workerChangedFrom = before !== undefined && !stillThere ? before : undefined;
1596
+ const asked = resumed
1597
+ ? (typeof attempt.worker === "string" ? attempt.worker : before)
1598
+ : stillThere
1599
+ ? before
1600
+ : undefined;
1601
+ const workerChangedFrom = !resumed && before !== undefined && !stillThere ? before : undefined;
1602
+ const resumeSession =
1603
+ resumedSession ??
1604
+ (typeof attempt.previousSession === "string" ? attempt.previousSession : undefined);
1353
1605
  const clock = stepTestHooks.workClock ?? realWorkClock;
1354
1606
  let timedOut = false;
1355
1607
  const timeOut = (): void => {
@@ -1403,9 +1655,8 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1403
1655
  : [];
1404
1656
  const mine = entries.filter(
1405
1657
  (entry): entry is { worker?: unknown; holders?: unknown } =>
1406
- typeof entry === "object" &&
1407
- entry !== null &&
1408
- (asked === undefined || (entry as { worker?: unknown }).worker === asked),
1658
+ isRecord(entry) &&
1659
+ (asked === undefined || entry.worker === asked),
1409
1660
  );
1410
1661
  const names = mine.flatMap((entry) =>
1411
1662
  typeof entry.worker === "string" ? [entry.worker] : [],
@@ -1474,23 +1725,27 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1474
1725
  say("the worker started", null);
1475
1726
  }
1476
1727
  };
1728
+ const poolCall: Record<string, unknown> = poolParams(
1729
+ finalPrompt,
1730
+ path,
1731
+ context.repository,
1732
+ context.settings,
1733
+ asked,
1734
+ resumeSession,
1735
+ outbox.inbox,
1736
+ context.taskId,
1737
+ stageParamsOf(stage),
1738
+ );
1739
+ if (askAnswer !== undefined) poolCall.askAnswer = askAnswer;
1740
+ const mainCheckoutBefore = checkoutSnapshot(context.repository.path);
1741
+ let mainChanges: readonly string[] = [];
1477
1742
  try {
1478
1743
  outcome = await withWorkerReports(
1479
1744
  { placed: workerPlaced, started: workerStarted },
1480
1745
  () =>
1481
1746
  runStep(
1482
1747
  "pool/agent",
1483
- poolParams(
1484
- finalPrompt,
1485
- path,
1486
- context.repository,
1487
- context.settings,
1488
- asked,
1489
- typeof attempt.previousSession === "string" ? attempt.previousSession : undefined,
1490
- outbox.inbox,
1491
- context.taskId,
1492
- stageParamsOf(ctx.params),
1493
- ),
1748
+ poolCall,
1494
1749
  { ...options, observe: onPoolEvent },
1495
1750
  ),
1496
1751
  );
@@ -1498,6 +1753,13 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1498
1753
  hostError = messageOf(error);
1499
1754
  notLoaded = notLoadedStep(error);
1500
1755
  } finally {
1756
+ // Reading the main checkout is part of ending the step, so a worker call
1757
+ // that throws still reports what the step left there.
1758
+ mainChanges = newCheckoutChanges(
1759
+ context.repository.path,
1760
+ path,
1761
+ mainCheckoutBefore,
1762
+ );
1501
1763
  if (startTimer !== undefined) startClock.clearTimeout(startTimer);
1502
1764
  sayClosed = true;
1503
1765
  await sayChain;
@@ -1509,11 +1771,7 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1509
1771
  ctx.signal.removeEventListener("abort", forwardAbort);
1510
1772
  }
1511
1773
  const outcomeData =
1512
- outcome !== undefined &&
1513
- typeof outcome.data === "object" &&
1514
- outcome.data !== null
1515
- ? (outcome.data as Record<string, unknown>)
1516
- : {};
1774
+ outcome !== undefined && isRecord(outcome.data) ? outcome.data : {};
1517
1775
  const reading = harnessReading(outcomeData, (problem) => {
1518
1776
  // A usage the harness got wrong is the harness's bug; say which run.
1519
1777
  void ctx.logger
@@ -1555,6 +1813,23 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1555
1813
  extra: Readonly<Record<string, unknown>>,
1556
1814
  waitsForModel = false,
1557
1815
  ): Promise<PluginStepResult> => {
1816
+ const mainLine =
1817
+ mainChanges.length === 0
1818
+ ? undefined
1819
+ : `changed the main checkout: ${mainChanges.join(", ")}`;
1820
+ const said = (message: string | undefined): string | undefined => {
1821
+ if (mainLine === undefined) return message;
1822
+ return message === undefined || message.length === 0
1823
+ ? mainLine
1824
+ : `${message}; ${mainLine}`;
1825
+ };
1826
+ const mainMessage = said(
1827
+ typeof extra.message === "string" ? extra.message : undefined,
1828
+ );
1829
+ const data: Readonly<Record<string, unknown>> = {
1830
+ ...extra,
1831
+ ...(mainMessage === undefined ? {} : { message: mainMessage }),
1832
+ };
1558
1833
  const note = readNote(path);
1559
1834
  const progress: Progress | undefined =
1560
1835
  note === null && !timedOutRun
@@ -1563,8 +1838,17 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1563
1838
  nextAttempt = {
1564
1839
  ...nextAttempt,
1565
1840
  result,
1841
+ ...(mainLine === undefined
1842
+ ? {}
1843
+ : {
1844
+ finalMessage:
1845
+ typeof nextAttempt.finalMessage === "string" &&
1846
+ nextAttempt.finalMessage.trim().length > 0
1847
+ ? `${nextAttempt.finalMessage}\n\n${mainLine}`
1848
+ : mainLine,
1849
+ }),
1566
1850
  workNote:
1567
- result !== "done" && typeof extra.message === "string" ? extra.message : null,
1851
+ result !== "done" && typeof data.message === "string" ? data.message : null,
1568
1852
  ...(waitsForModel ? {} : { workRetryAt: null }),
1569
1853
  // An attempt that left no note keeps the one before it for later attempts.
1570
1854
  progress: progress ?? progressOf(attempt.previousProgress) ?? null,
@@ -1601,9 +1885,13 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1601
1885
  // unavailable is not a person's business: the work step runs again.
1602
1886
  phase:
1603
1887
  result === "done" || waitsForModel || retried ? "running" : "waiting",
1888
+ waitKind: result === "waiting" ? "work-question" : undefined,
1604
1889
  run: ctx.runId,
1605
1890
  attempts,
1606
1891
  attempt: nextAttempt,
1892
+ ...(mainLine === undefined
1893
+ ? {}
1894
+ : { brief: appendChange(task.brief, mainLine) }),
1607
1895
  ...(reading.cost === null
1608
1896
  ? {}
1609
1897
  : { cost: reading.cost, costQuality: reading.costQuality }),
@@ -1631,12 +1919,18 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1631
1919
  ? { fallbackFrom: nextAttempt.fallbackFrom }
1632
1920
  : {}),
1633
1921
  }),
1634
- ...extra,
1922
+ ...data,
1635
1923
  }),
1636
1924
  };
1637
1925
  };
1638
1926
 
1639
1927
  untrackNote(path);
1928
+ // The worker asked a person and the grace passed. The pool already gave the
1929
+ // worker's place back; the flow's wait carries the question, and the answer
1930
+ // returns here to resume the same worker's session.
1931
+ if (outcome?.result === "waiting") {
1932
+ return finish("waiting", { ...outcomeData });
1933
+ }
1640
1934
  if (timedOutRun) {
1641
1935
  const committed = commitWip(path);
1642
1936
  const left = changedFiles(path);
@@ -1658,6 +1952,30 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1658
1952
  // it left uncommitted, and a success must still fail on a dirty tree.
1659
1953
  let dirty = changedFiles(path);
1660
1954
 
1955
+ // The worker resolved and committed the merge; put main's rows first in that
1956
+ // commit, or in one commit after the worker's own. An aborted merge changed
1957
+ // nothing, so it is left alone.
1958
+ const afterMerge = headOf(path);
1959
+ if (
1960
+ mergeHead !== undefined &&
1961
+ mergeHead.length > 0 &&
1962
+ afterMerge !== undefined &&
1963
+ !mergeInProgress(path) &&
1964
+ isAncestor(path, mergeHead, afterMerge)
1965
+ ) {
1966
+ const changed =
1967
+ mergeTaskRef === undefined
1968
+ ? []
1969
+ : mainFirstMutations(path, mergeHead, mergeTaskRef, mergeMutationFiles);
1970
+ if (changed.length > 0 && !commitMainFirstMutations(path, changed, mergeHead)) {
1971
+ return finish("failed", {
1972
+ reason: "mutations",
1973
+ message: `cannot keep main's rows first in ${changed.join(", ")}`,
1974
+ });
1975
+ }
1976
+ dirty = changedFiles(path);
1977
+ }
1978
+
1661
1979
  // A worker whose sandbox cannot write .git leaves its work uncommitted; the
1662
1980
  // stage asks dev to commit it, before verify so the check sees the commit.
1663
1981
  if (
@@ -1686,8 +2004,36 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
1686
2004
 
1687
2005
  if (outcome !== undefined && outcome.result !== "done") {
1688
2006
  const waits = typeof attempt.workWaits === "number" ? attempt.workWaits : 0;
1689
- if (modelUnavailable(outcomeData) && waits < MAX_WORK_WAITS) {
1690
- const retryAt = Date.now() + context.settings.reviewer.retrySecs * 1000;
2007
+ const modelError = modelErrorIn(outcomeData);
2008
+ if (modelError !== undefined && modelWaitsForPerson(modelError)) {
2009
+ // A usage limit, or a wait past the bound, is not an outage dev can wait
2010
+ // out: the work fails to a person who can change the worker or wait.
2011
+ const reported =
2012
+ modelError.message ??
2013
+ (typeof outcomeData.message === "string"
2014
+ ? outcomeData.message
2015
+ : "the worker's model cannot serve");
2016
+ const reset =
2017
+ modelError.retryAfterSecs === undefined
2018
+ ? ""
2019
+ : `; the model can serve again at ${new Date(
2020
+ (modelError.reportedAt ?? devNow()) +
2021
+ modelError.retryAfterSecs * 1000,
2022
+ ).toISOString()}`;
2023
+ return finish("failed", {
2024
+ reason: "model_unavailable",
2025
+ message: `${reported}${reset}`,
2026
+ ...(dirty.length === 0 ? {} : { files: dirty }),
2027
+ });
2028
+ }
2029
+ if (modelError !== undefined && waits < MAX_WORK_WAITS) {
2030
+ const waitSecs =
2031
+ modelError.retryAfterSecs ?? context.settings.reviewer.retrySecs;
2032
+ const retryAt =
2033
+ (modelError.retryAfterSecs === undefined
2034
+ ? devNow()
2035
+ : modelError.reportedAt ?? devNow()) +
2036
+ waitSecs * 1000;
1691
2037
  nextAttempt = { ...nextAttempt, workWaits: waits + 1, workRetryAt: retryAt };
1692
2038
  return finish(
1693
2039
  "unavailable",