@operad-io/dev 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dev.schema.json +53 -31
- package/package.json +9 -6
- package/skills/git/SKILL.md +70 -0
- package/skills/setup/SKILL.md +74 -0
- package/src/access-grants.ts +59 -0
- package/src/actions.ts +81 -17
- package/src/announce.ts +134 -17
- package/src/chat.ts +586 -36
- package/src/check-host.ts +111 -0
- package/src/check-load.ts +67 -0
- package/src/check.ts +45 -22
- package/src/clock.ts +29 -0
- package/src/clone-chat.ts +32 -0
- package/src/commands.ts +103 -34
- package/src/create-actions.ts +210 -0
- package/src/flaky.ts +45 -29
- package/src/flow-compiler.ts +156 -69
- package/src/followups.ts +20 -22
- package/src/gate.ts +254 -88
- package/src/git-state.ts +155 -0
- package/src/git.ts +92 -4
- package/src/index.ts +52 -6
- package/src/integrate.ts +162 -62
- package/src/integration-queue.ts +23 -10
- package/src/lock.ts +101 -5
- package/src/mainclone.ts +61 -5
- package/src/model-error.ts +70 -0
- package/src/model.ts +61 -35
- package/src/notcode.ts +51 -15
- package/src/places.ts +2 -2
- package/src/prepare.ts +7 -2
- package/src/project-flows.ts +135 -4
- package/src/project-settings.ts +110 -3
- package/src/register-requests.ts +121 -0
- package/src/repository-key.ts +4 -0
- package/src/rerun.ts +23 -7
- package/src/retry.ts +2 -12
- package/src/rework.ts +8 -0
- package/src/schedule.ts +342 -93
- package/src/service.ts +241 -185
- package/src/settings.ts +409 -65
- package/src/setup-git.ts +366 -0
- package/src/standing.ts +23 -6
- package/src/step-edge.ts +22 -0
- package/src/steps.ts +945 -179
- package/src/throughput.ts +4 -21
- package/src/timeouts.ts +10 -2
- package/src/views.ts +325 -86
- package/src/waits.ts +59 -0
package/src/steps.ts
CHANGED
|
@@ -5,9 +5,19 @@
|
|
|
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
|
+
appendFileSync,
|
|
10
|
+
existsSync,
|
|
11
|
+
mkdirSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
realpathSync,
|
|
14
|
+
rmSync,
|
|
15
|
+
statSync,
|
|
16
|
+
writeFileSync,
|
|
17
|
+
} from "node:fs";
|
|
18
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
19
|
+
import {
|
|
20
|
+
isRecord,
|
|
11
21
|
messageOf,
|
|
12
22
|
readUsage,
|
|
13
23
|
type CostQuality,
|
|
@@ -18,7 +28,7 @@ import {
|
|
|
18
28
|
} from "@operad-io/engine";
|
|
19
29
|
import {
|
|
20
30
|
appendChange,
|
|
21
|
-
|
|
31
|
+
idOfKey,
|
|
22
32
|
DevError,
|
|
23
33
|
listAll,
|
|
24
34
|
repositoryData,
|
|
@@ -37,8 +47,22 @@ import {
|
|
|
37
47
|
WAITING_EVENT,
|
|
38
48
|
type WorkerDefinition,
|
|
39
49
|
} from "@operad-io/pool";
|
|
40
|
-
import {
|
|
41
|
-
import {
|
|
50
|
+
import { writingChat } from "./clone-chat.ts";
|
|
51
|
+
import { now as devNow } from "./clock.ts";
|
|
52
|
+
import { modelErrorIn, modelWaitsForPerson } from "./model-error.ts";
|
|
53
|
+
import {
|
|
54
|
+
baseName,
|
|
55
|
+
baseRef,
|
|
56
|
+
branchExists,
|
|
57
|
+
fetchRemote,
|
|
58
|
+
git,
|
|
59
|
+
headOf,
|
|
60
|
+
isAncestor,
|
|
61
|
+
type BaseSettings,
|
|
62
|
+
type GitResult,
|
|
63
|
+
} from "./git.ts";
|
|
64
|
+
import { taskGitRefusal } from "./git-state.ts";
|
|
65
|
+
import { runPrepare, taskStepAccess } from "./prepare.ts";
|
|
42
66
|
import { classifyStop, isConnectionError, STOP_REASONS } from "./stops.ts";
|
|
43
67
|
import { findRepository, putTaskKeepingPlanCost, withRepoLock } from "./service.ts";
|
|
44
68
|
import {
|
|
@@ -54,13 +78,14 @@ import {
|
|
|
54
78
|
import { MAX_WORK_WAITS, STEP_TIMEOUT_SECS } from "./timeouts.ts";
|
|
55
79
|
import {
|
|
56
80
|
assertInsideRepository,
|
|
81
|
+
DEV_SETTINGS_FILE,
|
|
82
|
+
devSettingsFromText,
|
|
57
83
|
readDevSettings,
|
|
84
|
+
readDevSettingsText,
|
|
58
85
|
readWorkerBrief,
|
|
59
86
|
type DevSettings,
|
|
60
87
|
} from "./settings.ts";
|
|
61
88
|
|
|
62
|
-
export { git, type GitResult };
|
|
63
|
-
|
|
64
89
|
function resolvePath(path: string): string {
|
|
65
90
|
try {
|
|
66
91
|
return realpathSync(path);
|
|
@@ -82,6 +107,20 @@ export function worktreePath(
|
|
|
82
107
|
return path;
|
|
83
108
|
}
|
|
84
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
|
+
|
|
85
124
|
/** The branch a task's worktree is on. */
|
|
86
125
|
export function workBranch(taskId: string): string {
|
|
87
126
|
return `work/${taskId}`;
|
|
@@ -89,10 +128,9 @@ export function workBranch(taskId: string): string {
|
|
|
89
128
|
|
|
90
129
|
/** The step a host error says was not loaded; undefined for any other error. */
|
|
91
130
|
function notLoadedStep(error: unknown): string | undefined {
|
|
92
|
-
if (
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
? record.use
|
|
131
|
+
if (!isRecord(error)) return undefined;
|
|
132
|
+
return error.kind === "step_not_loaded" && typeof error.use === "string"
|
|
133
|
+
? error.use
|
|
96
134
|
: undefined;
|
|
97
135
|
}
|
|
98
136
|
|
|
@@ -104,15 +142,56 @@ export interface TaskContext {
|
|
|
104
142
|
/** The name of the task's worktree and branch: the task id, or the chat worktree it was opened on. */
|
|
105
143
|
readonly workName: string;
|
|
106
144
|
readonly settings: DevSettings;
|
|
145
|
+
/** The dev.json text `settings` came from; empty when the file does not exist. */
|
|
146
|
+
readonly settingsText?: string;
|
|
107
147
|
}
|
|
108
148
|
|
|
109
|
-
|
|
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> {
|
|
110
158
|
const parts = await taskParts(ctx);
|
|
111
|
-
const
|
|
112
|
-
|
|
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 };
|
|
179
|
+
}
|
|
180
|
+
|
|
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
|
+
}
|
|
113
192
|
}
|
|
114
193
|
|
|
115
|
-
/** A task context whose settings may be missing:
|
|
194
|
+
/** A task context whose settings may be missing:a step that can retry reads it. */
|
|
116
195
|
export type LooseTaskContext = Omit<TaskContext, "settings"> & {
|
|
117
196
|
readonly settings?: DevSettings | undefined;
|
|
118
197
|
/** Why the settings could not be read, when `settings` is absent. */
|
|
@@ -127,6 +206,11 @@ export async function looseTaskContext(
|
|
|
127
206
|
ctx: StepContext,
|
|
128
207
|
): Promise<LooseTaskContext> {
|
|
129
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
|
+
}
|
|
130
214
|
try {
|
|
131
215
|
return { ...parts, settings: await readDevSettings(parts.repository.path) };
|
|
132
216
|
} catch (error) {
|
|
@@ -147,7 +231,7 @@ async function taskParts(
|
|
|
147
231
|
let stored = await ctx.store.get("task", object.id);
|
|
148
232
|
if (stored === undefined && !object.id.includes("/")) {
|
|
149
233
|
const matches = (await listAll(ctx.store, "task")).filter(
|
|
150
|
-
(candidate) =>
|
|
234
|
+
(candidate) => idOfKey(candidate.id) === object.id,
|
|
151
235
|
);
|
|
152
236
|
if (matches.length === 1) stored = matches[0];
|
|
153
237
|
}
|
|
@@ -160,7 +244,7 @@ async function taskParts(
|
|
|
160
244
|
);
|
|
161
245
|
}
|
|
162
246
|
const repository = repositoryData(found.data);
|
|
163
|
-
const taskId =
|
|
247
|
+
const taskId = idOfKey(stored?.id ?? object.id);
|
|
164
248
|
let taskKey = stored?.id ?? object.id;
|
|
165
249
|
if ((await ctx.store.get("task", taskKey)) === undefined) {
|
|
166
250
|
taskKey = storeKey(repository.name, taskId);
|
|
@@ -208,6 +292,12 @@ function attemptFor(ctx: StepContext, task: TaskData): AttemptState {
|
|
|
208
292
|
};
|
|
209
293
|
}
|
|
210
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
|
+
|
|
211
301
|
function listWorktrees(repositoryPath: string): readonly string[] {
|
|
212
302
|
const result = git(repositoryPath, ["worktree", "list", "--porcelain"]);
|
|
213
303
|
if (!result.ok) return [];
|
|
@@ -236,42 +326,6 @@ function currentBranch(path: string): string | undefined {
|
|
|
236
326
|
return result.ok && result.out.length > 0 ? result.out : undefined;
|
|
237
327
|
}
|
|
238
328
|
|
|
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
329
|
function gitDirOf(worktree: string): string | undefined {
|
|
276
330
|
const result = git(worktree, ["rev-parse", "--git-dir"]);
|
|
277
331
|
if (!result.ok || result.out.length === 0) return undefined;
|
|
@@ -299,25 +353,179 @@ export function conflictedFiles(worktree: string): readonly string[] {
|
|
|
299
353
|
.sort();
|
|
300
354
|
}
|
|
301
355
|
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
356
|
+
// One `git status --porcelain` entry: its two status letters and its path.
|
|
357
|
+
interface CheckoutEntry {
|
|
358
|
+
readonly code: string;
|
|
359
|
+
readonly path: string;
|
|
360
|
+
/** What the path held when it was read, when it is a readable file. */
|
|
361
|
+
readonly content?: string | undefined;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// The status entries of a checkout, read from `--porcelain -z`: names are not
|
|
365
|
+
// quoted or trimmed, a name may hold spaces or newlines, and a rename or copy
|
|
366
|
+
// is followed by its old path, which is skipped. `--no-optional-locks` stops git
|
|
367
|
+
// from refreshing the index, so reading the checkout writes no metadata.
|
|
368
|
+
function checkoutEntries(checkout: string): readonly CheckoutEntry[] {
|
|
369
|
+
const result = git(checkout, ["--no-optional-locks", "status", "--porcelain", "-z"], true);
|
|
310
370
|
if (!result.ok || result.out.length === 0) return [];
|
|
311
371
|
const entries = result.out.split("\0");
|
|
312
|
-
const
|
|
372
|
+
const status: CheckoutEntry[] = [];
|
|
313
373
|
for (let index = 0; index < entries.length; index += 1) {
|
|
314
374
|
const entry = entries[index] ?? "";
|
|
315
375
|
if (entry.length < 4) continue;
|
|
316
|
-
files.push(entry.slice(3));
|
|
317
376
|
const code = entry.slice(0, 2);
|
|
377
|
+
status.push({ code, path: entry.slice(3) });
|
|
318
378
|
if (code.includes("R") || code.includes("C")) index += 1;
|
|
319
379
|
}
|
|
320
|
-
return
|
|
380
|
+
return status;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function checkoutEntryKey(entry: CheckoutEntry): string {
|
|
384
|
+
return `${entry.code}\0${entry.path}`;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* What a status path holds, so a further edit to a file that was already
|
|
389
|
+
* changed before the step is a change too: its status letters and path stay the
|
|
390
|
+
* same when it is edited again. A deleted file, a collapsed untracked directory
|
|
391
|
+
* and any other unreadable path have none, and their status letters are all
|
|
392
|
+
* they compare by. Only a checkout that is already dirty is read, so a clean
|
|
393
|
+
* main checkout costs nothing.
|
|
394
|
+
*/
|
|
395
|
+
function checkoutContent(checkout: string, path: string): string | undefined {
|
|
396
|
+
const file = join(checkout, path);
|
|
397
|
+
try {
|
|
398
|
+
if (!statSync(file).isFile()) return undefined;
|
|
399
|
+
return Bun.hash(readFileSync(file)).toString(16);
|
|
400
|
+
} catch {
|
|
401
|
+
return undefined;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
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
|
+
|
|
475
|
+
/** The status entries of a checkout, with what each readable file holds. */
|
|
476
|
+
function checkoutSnapshot(checkout: string): readonly CheckoutEntry[] {
|
|
477
|
+
return checkoutEntries(checkout).map((entry) => {
|
|
478
|
+
const content = checkoutContent(checkout, entry.path);
|
|
479
|
+
return content === undefined ? entry : { ...entry, content };
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// True when a status path is the task's worktree or lies inside it.
|
|
484
|
+
function insideWorktree(checkout: string, worktree: string, path: string): boolean {
|
|
485
|
+
const root = relative(checkout, worktree).replace(/\\/g, "/");
|
|
486
|
+
if (root.length === 0) return true;
|
|
487
|
+
if (root.startsWith("..")) return false;
|
|
488
|
+
const candidate = path.replace(/\\/g, "/");
|
|
489
|
+
return candidate === root || candidate.startsWith(`${root}/`);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// The paths whose status in the main checkout is new since `before`, or whose
|
|
493
|
+
// file was edited again since then, leaving out the task's own worktree, whose
|
|
494
|
+
// presence there the worktree explains.
|
|
495
|
+
function newCheckoutChanges(
|
|
496
|
+
checkout: string,
|
|
497
|
+
worktree: string,
|
|
498
|
+
before: CheckoutBefore,
|
|
499
|
+
reach: MainReach,
|
|
500
|
+
): readonly 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];
|
|
504
|
+
for (const entry of checkoutEntries(checkout)) {
|
|
505
|
+
const was = seen.get(checkoutEntryKey(entry));
|
|
506
|
+
// The same status letters and path: only a further edit to the file itself
|
|
507
|
+
// is a change. A path that was unreadable then has no content to compare.
|
|
508
|
+
if (was !== undefined) {
|
|
509
|
+
if (was.content === undefined) continue;
|
|
510
|
+
if (checkoutContent(checkout, entry.path) === was.content) continue;
|
|
511
|
+
}
|
|
512
|
+
if (!insideWorktree(checkout, worktree, entry.path)) changed.push(entry.path);
|
|
513
|
+
}
|
|
514
|
+
return [...new Set(changed)].sort();
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// The files `git status` calls changed, untracked included. Read from
|
|
518
|
+
// `--porcelain -z`: names are not quoted or trimmed, a name may hold spaces, and
|
|
519
|
+
// a rename or copy is followed by its old path, which is skipped (the new path
|
|
520
|
+
// is the changed file).
|
|
521
|
+
export function changedFiles(worktree: string): readonly string[] {
|
|
522
|
+
return [
|
|
523
|
+
...new Set(
|
|
524
|
+
checkoutEntries(worktree)
|
|
525
|
+
.map((entry) => entry.path)
|
|
526
|
+
.filter((file) => file !== PROGRESS_FILE),
|
|
527
|
+
),
|
|
528
|
+
].sort();
|
|
321
529
|
}
|
|
322
530
|
|
|
323
531
|
export interface Prepared {
|
|
@@ -330,6 +538,10 @@ export interface Prepared {
|
|
|
330
538
|
/** Set when the prepare commands failed. */
|
|
331
539
|
readonly reason?: string | undefined;
|
|
332
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;
|
|
333
545
|
}
|
|
334
546
|
|
|
335
547
|
/** Runs the prepare commands in a ready worktree; a failure turns it into a failed visit. */
|
|
@@ -362,14 +574,190 @@ function failed(message: string, files?: readonly string[]): Prepared {
|
|
|
362
574
|
return { kind: "failed", message, ...(files === undefined ? {} : { files }) };
|
|
363
575
|
}
|
|
364
576
|
|
|
577
|
+
/** True for the root and package files whose rows are appended, never moved. */
|
|
578
|
+
function isMutationFile(path: string): boolean {
|
|
579
|
+
const parts = path.split("/");
|
|
580
|
+
return (
|
|
581
|
+
path === "MUTATIONS.md" ||
|
|
582
|
+
(parts.length >= 3 &&
|
|
583
|
+
parts[0] === "packages" &&
|
|
584
|
+
parts[parts.length - 1] === "MUTATIONS.md")
|
|
585
|
+
);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** The lines of a file; a final newline does not add an empty last line. */
|
|
589
|
+
function linesOf(text: string): readonly string[] {
|
|
590
|
+
if (text === "") return [];
|
|
591
|
+
return (text.endsWith("\n") ? text.slice(0, -1) : text).split("\n");
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** The lines `after` has beyond a longest common subsequence with `before`. */
|
|
595
|
+
function linesOnlyIn(before: readonly string[], after: readonly string[]): readonly string[] {
|
|
596
|
+
const table: Uint32Array[] = Array.from(
|
|
597
|
+
{ length: before.length + 1 },
|
|
598
|
+
() => new Uint32Array(after.length + 1),
|
|
599
|
+
);
|
|
600
|
+
for (let row = before.length - 1; row >= 0; row -= 1) {
|
|
601
|
+
const line = table[row];
|
|
602
|
+
const next = table[row + 1];
|
|
603
|
+
if (line === undefined || next === undefined) continue;
|
|
604
|
+
for (let column = after.length - 1; column >= 0; column -= 1) {
|
|
605
|
+
line[column] =
|
|
606
|
+
before[row] === after[column]
|
|
607
|
+
? (next[column + 1] ?? 0) + 1
|
|
608
|
+
: Math.max(next[column] ?? 0, line[column + 1] ?? 0);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
const added: string[] = [];
|
|
612
|
+
let row = 0;
|
|
613
|
+
let column = 0;
|
|
614
|
+
while (row < before.length && column < after.length) {
|
|
615
|
+
if (before[row] === after[column]) {
|
|
616
|
+
row += 1;
|
|
617
|
+
column += 1;
|
|
618
|
+
} else if ((table[row + 1]?.[column] ?? 0) >= (table[row]?.[column + 1] ?? 0)) {
|
|
619
|
+
row += 1;
|
|
620
|
+
} else {
|
|
621
|
+
const line = after[column];
|
|
622
|
+
if (line !== undefined) added.push(line);
|
|
623
|
+
column += 1;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
while (column < after.length) {
|
|
627
|
+
const line = after[column];
|
|
628
|
+
if (line !== undefined) added.push(line);
|
|
629
|
+
column += 1;
|
|
630
|
+
}
|
|
631
|
+
return added;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** The lines `after` has in addition to the counts of the same lines in `before`. */
|
|
635
|
+
function linesBeyond(before: readonly string[], after: readonly string[]): readonly string[] {
|
|
636
|
+
const left = new Map<string, number>();
|
|
637
|
+
for (const line of before) left.set(line, (left.get(line) ?? 0) + 1);
|
|
638
|
+
const added: string[] = [];
|
|
639
|
+
for (const line of after) {
|
|
640
|
+
const count = left.get(line) ?? 0;
|
|
641
|
+
if (count === 0) added.push(line);
|
|
642
|
+
else left.set(line, count - 1);
|
|
643
|
+
}
|
|
644
|
+
return added;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** The lines a task appended to a file since the merge base. */
|
|
648
|
+
function taskAddition(baseText: string, taskText: string): readonly string[] {
|
|
649
|
+
if (taskText.startsWith(baseText)) return linesOf(taskText.slice(baseText.length));
|
|
650
|
+
return linesOnlyIn(linesOf(baseText), linesOf(taskText));
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Main's file unchanged, then the task's appended lines, then anything else the
|
|
655
|
+
* merged file has. A union merge puts the task's rows before main's, so the
|
|
656
|
+
* task's lines would otherwise sit inside main's file instead of after it. The
|
|
657
|
+
* task's own version says exactly which lines it appended, so a blank line or
|
|
658
|
+
* table header that is also in main's file is kept.
|
|
659
|
+
*/
|
|
660
|
+
function mainFirst(
|
|
661
|
+
mainText: string,
|
|
662
|
+
taskText: string,
|
|
663
|
+
baseText: string,
|
|
664
|
+
mergedText: string,
|
|
665
|
+
): string {
|
|
666
|
+
const taskLines = taskAddition(baseText, taskText);
|
|
667
|
+
const extra = linesBeyond([...linesOf(mainText), ...taskLines], linesOf(mergedText));
|
|
668
|
+
const added = [...taskLines, ...extra];
|
|
669
|
+
while (added[0]?.trim() === "") added.shift();
|
|
670
|
+
while (added[added.length - 1]?.trim() === "") added.pop();
|
|
671
|
+
if (added.length === 0) return mainText;
|
|
672
|
+
let text = mainText;
|
|
673
|
+
if (text.length > 0 && !text.endsWith("\n")) text += "\n";
|
|
674
|
+
if (text.length > 0 && !text.endsWith("\n\n")) text += "\n";
|
|
675
|
+
return `${text}${added.join("\n")}\n`;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** A MUTATIONS.md main changed since a branch tip, and the merge base it changed from. */
|
|
679
|
+
type MutationChange = {
|
|
680
|
+
readonly file: string;
|
|
681
|
+
readonly base: string;
|
|
682
|
+
};
|
|
683
|
+
|
|
684
|
+
/** The MUTATIONS.md files main changed since a branch tip. */
|
|
685
|
+
function mainChangedMutations(
|
|
686
|
+
path: string,
|
|
687
|
+
before: string,
|
|
688
|
+
mainRef: string,
|
|
689
|
+
): readonly MutationChange[] {
|
|
690
|
+
const base = git(path, ["merge-base", before, mainRef]);
|
|
691
|
+
if (!base.ok || base.out.length === 0) return [];
|
|
692
|
+
const diff = git(path, ["diff", "--name-only", base.out, mainRef]);
|
|
693
|
+
if (!diff.ok) return [];
|
|
694
|
+
return diff.out
|
|
695
|
+
.split("\n")
|
|
696
|
+
.filter((file) => isMutationFile(file))
|
|
697
|
+
.map((file) => ({ file, base: base.out }));
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** Rewrites the merged MUTATIONS.md files with main's rows first; returns those it changed. */
|
|
701
|
+
function mainFirstMutations(
|
|
702
|
+
path: string,
|
|
703
|
+
mainRef: string,
|
|
704
|
+
taskRef: string,
|
|
705
|
+
files: readonly MutationChange[],
|
|
706
|
+
): readonly string[] {
|
|
707
|
+
const conflicted = new Set(conflictedFiles(path));
|
|
708
|
+
const changed: string[] = [];
|
|
709
|
+
for (const { file, base } of files) {
|
|
710
|
+
if (conflicted.has(file)) continue;
|
|
711
|
+
const main = git(path, ["show", `${mainRef}:${file}`], true);
|
|
712
|
+
const task = git(path, ["show", `${taskRef}:${file}`], true);
|
|
713
|
+
const fromBase = git(path, ["show", `${base}:${file}`], true);
|
|
714
|
+
const merged = join(path, file);
|
|
715
|
+
if (!main.ok || !task.ok || !fromBase.ok || !existsSync(merged)) continue;
|
|
716
|
+
const current = readFileSync(merged, "utf8");
|
|
717
|
+
const next = mainFirst(main.out, task.out, fromBase.out, current);
|
|
718
|
+
if (next === current) continue;
|
|
719
|
+
writeFileSync(merged, next);
|
|
720
|
+
changed.push(file);
|
|
721
|
+
}
|
|
722
|
+
return changed;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/** Amends the merge, or commits after an extra worker commit, with the rewritten files. */
|
|
726
|
+
function commitMainFirstMutations(
|
|
727
|
+
path: string,
|
|
728
|
+
files: readonly string[],
|
|
729
|
+
mergeHead?: string | undefined,
|
|
730
|
+
): boolean {
|
|
731
|
+
if (files.length === 0) return true;
|
|
732
|
+
const added = git(path, ["add", "--", ...files]);
|
|
733
|
+
if (!added.ok) return false;
|
|
734
|
+
const second = git(path, ["rev-parse", "--verify", "--quiet", "HEAD^2"]);
|
|
735
|
+
const amend =
|
|
736
|
+
second.ok && (mergeHead === undefined || second.out === mergeHead);
|
|
737
|
+
return git(path, [
|
|
738
|
+
"commit",
|
|
739
|
+
...(amend ? ["--amend", "--no-edit"] : ["-m", "mutations: keep main's rows first"]),
|
|
740
|
+
"--no-verify",
|
|
741
|
+
]).ok;
|
|
742
|
+
}
|
|
743
|
+
|
|
365
744
|
/** Merges the fetched main into a reused branch and reports a conflict. */
|
|
366
745
|
function mergeLatest(path: string, mainRef: string): Prepared {
|
|
367
746
|
const before = headOf(path);
|
|
368
747
|
const commit = git(path, ["rev-parse", "--short", mainRef]).out;
|
|
748
|
+
const mutationFiles =
|
|
749
|
+
before === undefined ? [] : mainChangedMutations(path, before, mainRef);
|
|
369
750
|
const merge = git(path, ["merge", "--no-edit", "--no-ff", mainRef]);
|
|
370
751
|
if (!merge.ok) {
|
|
371
752
|
const files = conflictedFiles(path);
|
|
372
753
|
if (files.length > 0 || mergeInProgress(path)) {
|
|
754
|
+
// The worker will commit the merge after resolving the other files; put
|
|
755
|
+
// main's rows first now so that commit already has the right order.
|
|
756
|
+
const changed =
|
|
757
|
+
before === undefined
|
|
758
|
+
? []
|
|
759
|
+
: mainFirstMutations(path, mainRef, before, mutationFiles);
|
|
760
|
+
if (changed.length > 0) git(path, ["add", "--", ...changed]);
|
|
373
761
|
return {
|
|
374
762
|
kind: "conflict",
|
|
375
763
|
base: headOf(path),
|
|
@@ -381,6 +769,13 @@ function mergeLatest(path: string, mainRef: string): Prepared {
|
|
|
381
769
|
`cannot merge "${mainRef}" into the worktree: ${merge.err || merge.out}`,
|
|
382
770
|
);
|
|
383
771
|
}
|
|
772
|
+
const changed =
|
|
773
|
+
before === undefined
|
|
774
|
+
? []
|
|
775
|
+
: mainFirstMutations(path, mainRef, before, mutationFiles);
|
|
776
|
+
if (changed.length > 0 && !commitMainFirstMutations(path, changed)) {
|
|
777
|
+
return failed(`cannot keep main's rows first in ${changed.join(", ")}`);
|
|
778
|
+
}
|
|
384
779
|
const after = headOf(path);
|
|
385
780
|
return {
|
|
386
781
|
kind: "ready",
|
|
@@ -398,15 +793,21 @@ export function prepareWorktree(
|
|
|
398
793
|
taskId: string,
|
|
399
794
|
mergeMain = true,
|
|
400
795
|
): Prepared {
|
|
401
|
-
const
|
|
796
|
+
const refusal = taskGitRefusal(repository.path);
|
|
797
|
+
if (refusal !== undefined) return failed(refusal);
|
|
798
|
+
const fetch = fetchRemote(repository.path, settings);
|
|
402
799
|
if (!fetch.ok) {
|
|
403
800
|
return failed(
|
|
404
801
|
`cannot fetch "${settings.remote}": ${fetch.err || fetch.out || "git fetch failed"}`,
|
|
405
802
|
);
|
|
406
803
|
}
|
|
407
|
-
const mainRef =
|
|
408
|
-
if (!git(repository.path, ["show-ref", "--verify", "--quiet",
|
|
409
|
-
return failed(
|
|
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
|
+
);
|
|
410
811
|
}
|
|
411
812
|
|
|
412
813
|
const path = worktreePath(repository.path, settings, taskId);
|
|
@@ -450,7 +851,7 @@ export function prepareWorktree(
|
|
|
450
851
|
if (branchExists(repository.path, branch)) {
|
|
451
852
|
add = git(repository.path, ["worktree", "add", path, branch]);
|
|
452
853
|
reused = true;
|
|
453
|
-
} else if (
|
|
854
|
+
} else if (settings.remote !== undefined && branchExists(repository.path, branch, settings.remote)) {
|
|
454
855
|
add = git(repository.path, [
|
|
455
856
|
"worktree",
|
|
456
857
|
"add",
|
|
@@ -481,6 +882,149 @@ export function prepareWorktree(
|
|
|
481
882
|
return { kind: "ready", base: headOf(path) };
|
|
482
883
|
}
|
|
483
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
|
+
|
|
484
1028
|
export async function saveTask(
|
|
485
1029
|
ctx: StepContext,
|
|
486
1030
|
key: string,
|
|
@@ -493,10 +1037,8 @@ export async function saveTask(
|
|
|
493
1037
|
/** The claim token the scheduler put in the run's start parameters. */
|
|
494
1038
|
export function runToken(ctx: StepContext): string | undefined {
|
|
495
1039
|
const params = ctx.params;
|
|
496
|
-
if (
|
|
497
|
-
|
|
498
|
-
}
|
|
499
|
-
const token = (params as Record<string, unknown>).token;
|
|
1040
|
+
if (!isRecord(params)) return undefined;
|
|
1041
|
+
const token = params.token;
|
|
500
1042
|
return typeof token === "string" && token.length > 0 ? token : undefined;
|
|
501
1043
|
}
|
|
502
1044
|
|
|
@@ -522,17 +1064,6 @@ export function claimAllows(ctx: StepContext, task: TaskData): boolean {
|
|
|
522
1064
|
return true;
|
|
523
1065
|
}
|
|
524
1066
|
|
|
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
1067
|
/**
|
|
537
1068
|
* Test-only hook, run by a guarded write after its caller built the new data
|
|
538
1069
|
* and before the write takes the repository lock. A test uses it to cancel the
|
|
@@ -546,6 +1077,14 @@ export const stepTestHooks: {
|
|
|
546
1077
|
workClock?: WorkClock | undefined;
|
|
547
1078
|
/** Replaces the timer that says a worker with a place has not started. */
|
|
548
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;
|
|
549
1088
|
/** Called once the task has recorded what the work step waits for (null: nothing). */
|
|
550
1089
|
afterWorkerWait?: ((text: string | null) => void) | undefined;
|
|
551
1090
|
} = {};
|
|
@@ -614,16 +1153,20 @@ function commitWip(worktree: string): boolean {
|
|
|
614
1153
|
return git(worktree, ["commit", "-q", "--no-verify", "-m", WIP_MESSAGE]).ok;
|
|
615
1154
|
}
|
|
616
1155
|
|
|
617
|
-
/**
|
|
618
|
-
|
|
619
|
-
|
|
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(", ")}`;
|
|
620
1163
|
const added = git(worktree, ["add", "-A", "--", "."]);
|
|
621
|
-
if (!added.ok) return
|
|
622
|
-
const committed = git(worktree, ["commit", "-q", "--no-verify", "-m", message])
|
|
1164
|
+
if (!added.ok) return `git add failed: ${(added.err || added.out).trim()}`;
|
|
1165
|
+
const committed = git(worktree, ["commit", "-q", "--no-verify", "-m", message]);
|
|
623
1166
|
// The note is the worker's report, not part of the change: take it out of the
|
|
624
1167
|
// branch again, leaving the file for the step to read.
|
|
625
1168
|
untrackNote(worktree);
|
|
626
|
-
return committed
|
|
1169
|
+
return committed.ok ? undefined : `git commit failed: ${(committed.err || committed.out).trim()}`;
|
|
627
1170
|
}
|
|
628
1171
|
|
|
629
1172
|
/**
|
|
@@ -655,19 +1198,15 @@ export function cancelledStep(): PluginStepResult {
|
|
|
655
1198
|
|
|
656
1199
|
/** The step a repair run says stopped, when the scheduler asked for one. */
|
|
657
1200
|
function runStoppedAt(params: unknown): string | undefined {
|
|
658
|
-
if (
|
|
659
|
-
|
|
660
|
-
}
|
|
661
|
-
const value = (params as Record<string, unknown>).runStoppedAt;
|
|
1201
|
+
if (!isRecord(params)) return undefined;
|
|
1202
|
+
const value = params.runStoppedAt;
|
|
662
1203
|
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
663
1204
|
}
|
|
664
1205
|
|
|
665
1206
|
/** The cancelled dependency a blocked start names, when the flow carries one. */
|
|
666
1207
|
function blockedDependency(params: unknown): string | undefined {
|
|
667
|
-
if (
|
|
668
|
-
|
|
669
|
-
}
|
|
670
|
-
const value = (params as Record<string, unknown>).blockedBy;
|
|
1208
|
+
if (!isRecord(params)) return undefined;
|
|
1209
|
+
const value = params.blockedBy;
|
|
671
1210
|
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
672
1211
|
}
|
|
673
1212
|
|
|
@@ -675,7 +1214,7 @@ function blockedDependency(params: unknown): string | undefined {
|
|
|
675
1214
|
export async function runWorktree(
|
|
676
1215
|
ctx: StepContext,
|
|
677
1216
|
): Promise<PluginStepResult> {
|
|
678
|
-
const context = await taskContext(ctx);
|
|
1217
|
+
const context = await taskContext(ctx, true);
|
|
679
1218
|
if (!claimAllows(ctx, context.task)) return cancelledStep();
|
|
680
1219
|
const stoppedAt = runStoppedAt(ctx.params);
|
|
681
1220
|
if (stoppedAt !== undefined && context.task.run === null) {
|
|
@@ -740,27 +1279,75 @@ export async function runWorktree(
|
|
|
740
1279
|
};
|
|
741
1280
|
}
|
|
742
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;
|
|
743
1298
|
const prepared = await withPrepare(
|
|
744
1299
|
ctx,
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
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),
|
|
753
1336
|
);
|
|
1337
|
+
if (prepared.cancelled === true) return cancelledStep();
|
|
1338
|
+
if (inPlace) stepTestHooks.branchStep?.("before-save");
|
|
754
1339
|
const base = prepared.base ?? attempt.base ?? null;
|
|
1340
|
+
const startBranch = prepared.startBranch ?? startBranchOf(replay ? attempt : undefined);
|
|
755
1341
|
const nextAttempt: TaskAttempt = {
|
|
756
1342
|
...attempt,
|
|
757
1343
|
run: ctx.runId,
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
context.settings,
|
|
761
|
-
context.workName,
|
|
762
|
-
),
|
|
1344
|
+
settingsText,
|
|
1345
|
+
worktree: where,
|
|
763
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
|
+
: {}),
|
|
764
1351
|
base,
|
|
765
1352
|
result: prepared.kind,
|
|
766
1353
|
// The answer of an earlier attempt belongs to that attempt.
|
|
@@ -839,18 +1426,24 @@ export async function runReverify(
|
|
|
839
1426
|
run: ctx.runId,
|
|
840
1427
|
};
|
|
841
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";
|
|
842
1435
|
const prepared = await withPrepare(
|
|
843
1436
|
ctx,
|
|
844
1437
|
context.settings,
|
|
845
|
-
|
|
846
|
-
|
|
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),
|
|
847
1445
|
);
|
|
848
1446
|
const base = prepared.base ?? attempt.base ?? null;
|
|
849
|
-
const worktree = worktreePath(
|
|
850
|
-
context.repository.path,
|
|
851
|
-
context.settings,
|
|
852
|
-
context.workName,
|
|
853
|
-
);
|
|
854
1447
|
const message =
|
|
855
1448
|
prepared.kind === "conflict"
|
|
856
1449
|
? "reverify: main conflicts, sending to work"
|
|
@@ -864,6 +1457,12 @@ export async function runReverify(
|
|
|
864
1457
|
run: ctx.runId,
|
|
865
1458
|
worktree,
|
|
866
1459
|
branch: workBranch(context.workName),
|
|
1460
|
+
...(inPlace
|
|
1461
|
+
? {
|
|
1462
|
+
inPlace: true,
|
|
1463
|
+
...(prepared.startBranch === undefined ? {} : { startBranch: prepared.startBranch }),
|
|
1464
|
+
}
|
|
1465
|
+
: {}),
|
|
867
1466
|
base,
|
|
868
1467
|
result: prepared.kind,
|
|
869
1468
|
// A conflict is worked on again; a clean merge goes straight to the gate.
|
|
@@ -1055,7 +1654,7 @@ function poolParams(
|
|
|
1055
1654
|
};
|
|
1056
1655
|
}
|
|
1057
1656
|
|
|
1058
|
-
/** The harness overrides a
|
|
1657
|
+
/** The harness overrides a code stage wrote in its params. */
|
|
1059
1658
|
function stageParamsOf(params: unknown): {
|
|
1060
1659
|
readonly use?: string | undefined;
|
|
1061
1660
|
readonly args?: readonly string[] | undefined;
|
|
@@ -1080,7 +1679,7 @@ function stageParamsOf(params: unknown): {
|
|
|
1080
1679
|
};
|
|
1081
1680
|
}
|
|
1082
1681
|
|
|
1083
|
-
/** The preparation a
|
|
1682
|
+
/** The preparation a code stage asks for before its attempt. */
|
|
1084
1683
|
type BeforeAttempt = "merge-main" | "none";
|
|
1085
1684
|
|
|
1086
1685
|
function beforeAttemptOf(params: unknown): BeforeAttempt | undefined {
|
|
@@ -1099,15 +1698,6 @@ function workLine(attempt: TaskAttempt): string {
|
|
|
1099
1698
|
].join("");
|
|
1100
1699
|
}
|
|
1101
1700
|
|
|
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
1701
|
/** The lines of a step's `stderr` data, which may be a string or a list. */
|
|
1112
1702
|
function stderrLines(value: unknown): readonly string[] {
|
|
1113
1703
|
if (typeof value === "string") return [value];
|
|
@@ -1132,15 +1722,22 @@ function hasUncheckedWork(
|
|
|
1132
1722
|
path: string,
|
|
1133
1723
|
head: string,
|
|
1134
1724
|
attempt: TaskAttempt,
|
|
1135
|
-
context: { readonly settings:
|
|
1725
|
+
context: { readonly settings: BaseSettings },
|
|
1136
1726
|
): boolean {
|
|
1137
1727
|
if (attempt.verified === head && attempt.verify?.result === "pass") return false;
|
|
1138
|
-
const mainRef =
|
|
1728
|
+
const mainRef = baseName(context.settings);
|
|
1139
1729
|
const ahead = git(path, ["rev-list", "--count", "--no-merges", `${mainRef}..${head}`]);
|
|
1140
1730
|
return ahead.ok && Number(ahead.out) > 0;
|
|
1141
1731
|
}
|
|
1142
1732
|
|
|
1143
|
-
|
|
1733
|
+
/** Step `dev/work`: run the configured harness step and decide what it left. */
|
|
1734
|
+
export async function runWork(ctx: StepContext, stepParams?: unknown): Promise<PluginStepResult> {
|
|
1735
|
+
// The step's own params (a flow stage writes them) and the run's start params
|
|
1736
|
+
// (a direct call writes them) both reach this step; the step's own win.
|
|
1737
|
+
const stage: Record<string, unknown> = {
|
|
1738
|
+
...(isRecord(ctx.params) ? ctx.params : {}),
|
|
1739
|
+
...(isRecord(stepParams) ? stepParams : {}),
|
|
1740
|
+
};
|
|
1144
1741
|
const loose = await looseTaskContext(ctx);
|
|
1145
1742
|
if (!claimAllows(ctx, loose.task)) return cancelledStep();
|
|
1146
1743
|
if (loose.settings === undefined) {
|
|
@@ -1169,7 +1766,7 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1169
1766
|
const task = context.task;
|
|
1170
1767
|
const path =
|
|
1171
1768
|
task.attempt?.worktree ??
|
|
1172
|
-
|
|
1769
|
+
workPath(context.repository, context.settings, context.workName);
|
|
1173
1770
|
const branch = task.attempt?.branch ?? workBranch(context.workName);
|
|
1174
1771
|
const attempt: TaskAttempt = task.attempt ?? {
|
|
1175
1772
|
number: Math.max(task.attempts, 0) + 1,
|
|
@@ -1178,7 +1775,11 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1178
1775
|
const attempts = Math.max(task.attempts, attempt.number);
|
|
1179
1776
|
const base = attempt.base ?? headOf(path) ?? null;
|
|
1180
1777
|
|
|
1181
|
-
|
|
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) {
|
|
1182
1783
|
const nextAttempt: TaskAttempt = {
|
|
1183
1784
|
...attempt,
|
|
1184
1785
|
run: ctx.runId,
|
|
@@ -1187,6 +1788,7 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1187
1788
|
base,
|
|
1188
1789
|
result: "failed",
|
|
1189
1790
|
worked: true,
|
|
1791
|
+
workDone: false,
|
|
1190
1792
|
};
|
|
1191
1793
|
const written = await saveTaskGuarded(
|
|
1192
1794
|
ctx,
|
|
@@ -1205,14 +1807,16 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1205
1807
|
result: "failed",
|
|
1206
1808
|
data: resultData(nextAttempt, harnessReading({}), {
|
|
1207
1809
|
reason: "no_worktree",
|
|
1208
|
-
message:
|
|
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`,
|
|
1209
1813
|
}),
|
|
1210
1814
|
};
|
|
1211
1815
|
}
|
|
1212
1816
|
|
|
1213
|
-
if (beforeAttemptOf(
|
|
1817
|
+
if (beforeAttemptOf(stage) === "merge-main") {
|
|
1214
1818
|
const remote = context.settings.remote;
|
|
1215
|
-
const mainRef =
|
|
1819
|
+
const mainRef = baseName(context.settings);
|
|
1216
1820
|
const failBefore = async (message: string): Promise<PluginStepResult> => {
|
|
1217
1821
|
const nextAttempt: TaskAttempt = {
|
|
1218
1822
|
...attempt,
|
|
@@ -1222,6 +1826,7 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1222
1826
|
base,
|
|
1223
1827
|
result: "failed",
|
|
1224
1828
|
worked: true,
|
|
1829
|
+
workDone: false,
|
|
1225
1830
|
};
|
|
1226
1831
|
const written = await saveTaskGuarded(
|
|
1227
1832
|
ctx,
|
|
@@ -1244,7 +1849,7 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1244
1849
|
}),
|
|
1245
1850
|
};
|
|
1246
1851
|
};
|
|
1247
|
-
const fetch =
|
|
1852
|
+
const fetch = fetchRemote(context.repository.path, context.settings);
|
|
1248
1853
|
if (!fetch.ok) {
|
|
1249
1854
|
return failBefore(
|
|
1250
1855
|
`cannot fetch "${remote}": ${fetch.err || fetch.out || "git fetch failed"}`,
|
|
@@ -1256,7 +1861,22 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1256
1861
|
}
|
|
1257
1862
|
}
|
|
1258
1863
|
|
|
1259
|
-
|
|
1864
|
+
// A conflict is left for the worker to resolve and commit. Keep the main it
|
|
1865
|
+
// merged so the commit is checked again after the worker is done.
|
|
1866
|
+
const mergeHead = mergeInProgress(path)
|
|
1867
|
+
? git(path, ["rev-parse", "MERGE_HEAD"]).out
|
|
1868
|
+
: undefined;
|
|
1869
|
+
let mergeTaskRef: string | undefined;
|
|
1870
|
+
let mergeMutationFiles: readonly MutationChange[] = [];
|
|
1871
|
+
if (mergeHead !== undefined && mergeHead.length > 0) {
|
|
1872
|
+
const mergeBefore = headOf(path);
|
|
1873
|
+
if (mergeBefore !== undefined) {
|
|
1874
|
+
mergeTaskRef = mergeBefore;
|
|
1875
|
+
mergeMutationFiles = mainChangedMutations(path, mergeBefore, mergeHead);
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
const stageParams = stage as {
|
|
1260
1880
|
readonly flowWorkerBrief?: unknown;
|
|
1261
1881
|
readonly flowCommit?: unknown;
|
|
1262
1882
|
};
|
|
@@ -1272,7 +1892,7 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1272
1892
|
progressOf(attempt.previousProgress),
|
|
1273
1893
|
);
|
|
1274
1894
|
const stageBrief = (() => {
|
|
1275
|
-
const given = (
|
|
1895
|
+
const given = (stage as { readonly flowBrief?: unknown }).flowBrief;
|
|
1276
1896
|
return typeof given === "string" && given.trim().length > 0 ? given.trim() : undefined;
|
|
1277
1897
|
})();
|
|
1278
1898
|
const finalPrompt =
|
|
@@ -1290,6 +1910,7 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1290
1910
|
base,
|
|
1291
1911
|
result: "failed",
|
|
1292
1912
|
worked: true,
|
|
1913
|
+
workDone: false,
|
|
1293
1914
|
};
|
|
1294
1915
|
const written = await saveTaskGuarded(
|
|
1295
1916
|
ctx,
|
|
@@ -1324,14 +1945,20 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1324
1945
|
cwd: path,
|
|
1325
1946
|
...(ctx.object === undefined ? {} : { object: ctx.object }),
|
|
1326
1947
|
params: ctx.params,
|
|
1327
|
-
access: ctx.access,
|
|
1948
|
+
access: taskStepAccess(ctx.access),
|
|
1328
1949
|
...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
|
|
1329
1950
|
signal: stopper.signal,
|
|
1330
1951
|
};
|
|
1331
1952
|
// A rework or reject goes back to the worker that ran the attempt before,
|
|
1332
1953
|
// and resumes its session when the harness can. When that worker is no
|
|
1333
1954
|
// longer in the pool, any free worker takes it and the change is recorded.
|
|
1334
|
-
const stagePool = stageParamsOf(
|
|
1955
|
+
const stagePool = stageParamsOf(stage).pool ?? DEFAULT_POOL;
|
|
1956
|
+
const resumedSession =
|
|
1957
|
+
typeof stage.resumeSession === "string" ? stage.resumeSession : undefined;
|
|
1958
|
+
const askAnswer = isRecord(stage.askAnswer) ? stage.askAnswer : undefined;
|
|
1959
|
+
// An answer to the worker's own question comes back to this step; it resumes
|
|
1960
|
+
// the same worker, never a fallback.
|
|
1961
|
+
const resumed = resumedSession !== undefined || askAnswer !== undefined;
|
|
1335
1962
|
const before =
|
|
1336
1963
|
typeof attempt.previousWorker === "string" && attempt.previousWorker.length > 0
|
|
1337
1964
|
? attempt.previousWorker
|
|
@@ -1348,8 +1975,15 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1348
1975
|
return false;
|
|
1349
1976
|
}
|
|
1350
1977
|
})();
|
|
1351
|
-
const asked =
|
|
1352
|
-
|
|
1978
|
+
const asked = resumed
|
|
1979
|
+
? (typeof attempt.worker === "string" ? attempt.worker : before)
|
|
1980
|
+
: stillThere
|
|
1981
|
+
? before
|
|
1982
|
+
: undefined;
|
|
1983
|
+
const workerChangedFrom = !resumed && before !== undefined && !stillThere ? before : undefined;
|
|
1984
|
+
const resumeSession =
|
|
1985
|
+
resumedSession ??
|
|
1986
|
+
(typeof attempt.previousSession === "string" ? attempt.previousSession : undefined);
|
|
1353
1987
|
const clock = stepTestHooks.workClock ?? realWorkClock;
|
|
1354
1988
|
let timedOut = false;
|
|
1355
1989
|
const timeOut = (): void => {
|
|
@@ -1386,11 +2020,14 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1386
2020
|
// holds it, in the row and in the step log. A rework waits for the worker it
|
|
1387
2021
|
// asked for; any other attempt waits for the workers of the pool.
|
|
1388
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;
|
|
1389
2026
|
const setWorkerWait = async (text: string | null): Promise<void> => {
|
|
1390
2027
|
await saveTaskGuarded(
|
|
1391
2028
|
ctx,
|
|
1392
2029
|
context.taskKey,
|
|
1393
|
-
{ ...task, attempt: { ...attempt, workerWait: text } },
|
|
2030
|
+
{ ...task, attempt: { ...attempt, ...placedWorker, workerWait: text } },
|
|
1394
2031
|
"dev:work-wait",
|
|
1395
2032
|
);
|
|
1396
2033
|
stepTestHooks.afterWorkerWait?.(text);
|
|
@@ -1403,9 +2040,8 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1403
2040
|
: [];
|
|
1404
2041
|
const mine = entries.filter(
|
|
1405
2042
|
(entry): entry is { worker?: unknown; holders?: unknown } =>
|
|
1406
|
-
|
|
1407
|
-
entry
|
|
1408
|
-
(asked === undefined || (entry as { worker?: unknown }).worker === asked),
|
|
2043
|
+
isRecord(entry) &&
|
|
2044
|
+
(asked === undefined || entry.worker === asked),
|
|
1409
2045
|
);
|
|
1410
2046
|
const names = mine.flatMap((entry) =>
|
|
1411
2047
|
typeof entry.worker === "string" ? [entry.worker] : [],
|
|
@@ -1457,6 +2093,29 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1457
2093
|
}).catch(() => undefined);
|
|
1458
2094
|
};
|
|
1459
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
|
+
}
|
|
1460
2119
|
if (started) return;
|
|
1461
2120
|
startTimer = startClock.setTimeout(() => {
|
|
1462
2121
|
if (started) return;
|
|
@@ -1474,23 +2133,29 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1474
2133
|
say("the worker started", null);
|
|
1475
2134
|
}
|
|
1476
2135
|
};
|
|
2136
|
+
const poolCall: Record<string, unknown> = poolParams(
|
|
2137
|
+
finalPrompt,
|
|
2138
|
+
path,
|
|
2139
|
+
context.repository,
|
|
2140
|
+
context.settings,
|
|
2141
|
+
asked,
|
|
2142
|
+
resumeSession,
|
|
2143
|
+
outbox.inbox,
|
|
2144
|
+
context.taskId,
|
|
2145
|
+
stageParamsOf(stage),
|
|
2146
|
+
);
|
|
2147
|
+
if (askAnswer !== undefined) poolCall.askAnswer = askAnswer;
|
|
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);
|
|
2151
|
+
let mainChanges: readonly string[] = [];
|
|
1477
2152
|
try {
|
|
1478
2153
|
outcome = await withWorkerReports(
|
|
1479
2154
|
{ placed: workerPlaced, started: workerStarted },
|
|
1480
2155
|
() =>
|
|
1481
2156
|
runStep(
|
|
1482
2157
|
"pool/agent",
|
|
1483
|
-
|
|
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
|
-
),
|
|
2158
|
+
poolCall,
|
|
1494
2159
|
{ ...options, observe: onPoolEvent },
|
|
1495
2160
|
),
|
|
1496
2161
|
);
|
|
@@ -1498,6 +2163,15 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1498
2163
|
hostError = messageOf(error);
|
|
1499
2164
|
notLoaded = notLoadedStep(error);
|
|
1500
2165
|
} finally {
|
|
2166
|
+
// Reading the main checkout is part of ending the step, so a worker call
|
|
2167
|
+
// that throws still reports what the step left there.
|
|
2168
|
+
mainChanges = inPlace
|
|
2169
|
+
? []
|
|
2170
|
+
: newCheckoutChanges(context.repository.path, path, mainCheckoutBefore, {
|
|
2171
|
+
remote: context.settings.remote,
|
|
2172
|
+
mainRef: baseName(context.settings),
|
|
2173
|
+
base,
|
|
2174
|
+
});
|
|
1501
2175
|
if (startTimer !== undefined) startClock.clearTimeout(startTimer);
|
|
1502
2176
|
sayClosed = true;
|
|
1503
2177
|
await sayChain;
|
|
@@ -1509,11 +2183,7 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1509
2183
|
ctx.signal.removeEventListener("abort", forwardAbort);
|
|
1510
2184
|
}
|
|
1511
2185
|
const outcomeData =
|
|
1512
|
-
outcome !== undefined &&
|
|
1513
|
-
typeof outcome.data === "object" &&
|
|
1514
|
-
outcome.data !== null
|
|
1515
|
-
? (outcome.data as Record<string, unknown>)
|
|
1516
|
-
: {};
|
|
2186
|
+
outcome !== undefined && isRecord(outcome.data) ? outcome.data : {};
|
|
1517
2187
|
const reading = harnessReading(outcomeData, (problem) => {
|
|
1518
2188
|
// A usage the harness got wrong is the harness's bug; say which run.
|
|
1519
2189
|
void ctx.logger
|
|
@@ -1555,6 +2225,23 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1555
2225
|
extra: Readonly<Record<string, unknown>>,
|
|
1556
2226
|
waitsForModel = false,
|
|
1557
2227
|
): Promise<PluginStepResult> => {
|
|
2228
|
+
const mainLine =
|
|
2229
|
+
mainChanges.length === 0
|
|
2230
|
+
? undefined
|
|
2231
|
+
: `changed the main checkout: ${mainChanges.join(", ")}`;
|
|
2232
|
+
const said = (message: string | undefined): string | undefined => {
|
|
2233
|
+
if (mainLine === undefined) return message;
|
|
2234
|
+
return message === undefined || message.length === 0
|
|
2235
|
+
? mainLine
|
|
2236
|
+
: `${message}; ${mainLine}`;
|
|
2237
|
+
};
|
|
2238
|
+
const mainMessage = said(
|
|
2239
|
+
typeof extra.message === "string" ? extra.message : undefined,
|
|
2240
|
+
);
|
|
2241
|
+
const data: Readonly<Record<string, unknown>> = {
|
|
2242
|
+
...extra,
|
|
2243
|
+
...(mainMessage === undefined ? {} : { message: mainMessage }),
|
|
2244
|
+
};
|
|
1558
2245
|
const note = readNote(path);
|
|
1559
2246
|
const progress: Progress | undefined =
|
|
1560
2247
|
note === null && !timedOutRun
|
|
@@ -1563,8 +2250,20 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1563
2250
|
nextAttempt = {
|
|
1564
2251
|
...nextAttempt,
|
|
1565
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",
|
|
2256
|
+
...(mainLine === undefined
|
|
2257
|
+
? {}
|
|
2258
|
+
: {
|
|
2259
|
+
finalMessage:
|
|
2260
|
+
typeof nextAttempt.finalMessage === "string" &&
|
|
2261
|
+
nextAttempt.finalMessage.trim().length > 0
|
|
2262
|
+
? `${nextAttempt.finalMessage}\n\n${mainLine}`
|
|
2263
|
+
: mainLine,
|
|
2264
|
+
}),
|
|
1566
2265
|
workNote:
|
|
1567
|
-
result !== "done" && typeof
|
|
2266
|
+
result !== "done" && typeof data.message === "string" ? data.message : null,
|
|
1568
2267
|
...(waitsForModel ? {} : { workRetryAt: null }),
|
|
1569
2268
|
// An attempt that left no note keeps the one before it for later attempts.
|
|
1570
2269
|
progress: progress ?? progressOf(attempt.previousProgress) ?? null,
|
|
@@ -1601,9 +2300,13 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1601
2300
|
// unavailable is not a person's business: the work step runs again.
|
|
1602
2301
|
phase:
|
|
1603
2302
|
result === "done" || waitsForModel || retried ? "running" : "waiting",
|
|
2303
|
+
waitKind: result === "waiting" ? "work-question" : undefined,
|
|
1604
2304
|
run: ctx.runId,
|
|
1605
2305
|
attempts,
|
|
1606
2306
|
attempt: nextAttempt,
|
|
2307
|
+
...(mainLine === undefined
|
|
2308
|
+
? {}
|
|
2309
|
+
: { brief: appendChange(task.brief, mainLine) }),
|
|
1607
2310
|
...(reading.cost === null
|
|
1608
2311
|
? {}
|
|
1609
2312
|
: { cost: reading.cost, costQuality: reading.costQuality }),
|
|
@@ -1631,12 +2334,18 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1631
2334
|
? { fallbackFrom: nextAttempt.fallbackFrom }
|
|
1632
2335
|
: {}),
|
|
1633
2336
|
}),
|
|
1634
|
-
...
|
|
2337
|
+
...data,
|
|
1635
2338
|
}),
|
|
1636
2339
|
};
|
|
1637
2340
|
};
|
|
1638
2341
|
|
|
1639
2342
|
untrackNote(path);
|
|
2343
|
+
// The worker asked a person and the grace passed. The pool already gave the
|
|
2344
|
+
// worker's place back; the flow's wait carries the question, and the answer
|
|
2345
|
+
// returns here to resume the same worker's session.
|
|
2346
|
+
if (outcome?.result === "waiting") {
|
|
2347
|
+
return finish("waiting", { ...outcomeData });
|
|
2348
|
+
}
|
|
1640
2349
|
if (timedOutRun) {
|
|
1641
2350
|
const committed = commitWip(path);
|
|
1642
2351
|
const left = changedFiles(path);
|
|
@@ -1658,15 +2367,42 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1658
2367
|
// it left uncommitted, and a success must still fail on a dirty tree.
|
|
1659
2368
|
let dirty = changedFiles(path);
|
|
1660
2369
|
|
|
2370
|
+
// The worker resolved and committed the merge; put main's rows first in that
|
|
2371
|
+
// commit, or in one commit after the worker's own. An aborted merge changed
|
|
2372
|
+
// nothing, so it is left alone.
|
|
2373
|
+
const afterMerge = headOf(path);
|
|
2374
|
+
if (
|
|
2375
|
+
mergeHead !== undefined &&
|
|
2376
|
+
mergeHead.length > 0 &&
|
|
2377
|
+
afterMerge !== undefined &&
|
|
2378
|
+
!mergeInProgress(path) &&
|
|
2379
|
+
isAncestor(path, mergeHead, afterMerge)
|
|
2380
|
+
) {
|
|
2381
|
+
const changed =
|
|
2382
|
+
mergeTaskRef === undefined
|
|
2383
|
+
? []
|
|
2384
|
+
: mainFirstMutations(path, mergeHead, mergeTaskRef, mergeMutationFiles);
|
|
2385
|
+
if (changed.length > 0 && !commitMainFirstMutations(path, changed, mergeHead)) {
|
|
2386
|
+
return finish("failed", {
|
|
2387
|
+
reason: "mutations",
|
|
2388
|
+
message: `cannot keep main's rows first in ${changed.join(", ")}`,
|
|
2389
|
+
});
|
|
2390
|
+
}
|
|
2391
|
+
dirty = changedFiles(path);
|
|
2392
|
+
}
|
|
2393
|
+
|
|
2394
|
+
let commitError: string | undefined;
|
|
1661
2395
|
// A worker whose sandbox cannot write .git leaves its work uncommitted; the
|
|
1662
2396
|
// stage asks dev to commit it, before verify so the check sees the commit.
|
|
1663
2397
|
if (
|
|
1664
|
-
|
|
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)) &&
|
|
1665
2401
|
hostError === undefined &&
|
|
1666
2402
|
outcome?.result === "done" &&
|
|
1667
2403
|
dirty.length > 0
|
|
1668
2404
|
) {
|
|
1669
|
-
commitLeft(path, `${context.taskId}: ${task.title}`);
|
|
2405
|
+
commitError = commitLeft(path, `${context.taskId}: ${task.title}`);
|
|
1670
2406
|
dirty = changedFiles(path);
|
|
1671
2407
|
}
|
|
1672
2408
|
|
|
@@ -1686,8 +2422,36 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1686
2422
|
|
|
1687
2423
|
if (outcome !== undefined && outcome.result !== "done") {
|
|
1688
2424
|
const waits = typeof attempt.workWaits === "number" ? attempt.workWaits : 0;
|
|
1689
|
-
|
|
1690
|
-
|
|
2425
|
+
const modelError = modelErrorIn(outcomeData);
|
|
2426
|
+
if (modelError !== undefined && modelWaitsForPerson(modelError)) {
|
|
2427
|
+
// A usage limit, or a wait past the bound, is not an outage dev can wait
|
|
2428
|
+
// out: the work fails to a person who can change the worker or wait.
|
|
2429
|
+
const reported =
|
|
2430
|
+
modelError.message ??
|
|
2431
|
+
(typeof outcomeData.message === "string"
|
|
2432
|
+
? outcomeData.message
|
|
2433
|
+
: "the worker's model cannot serve");
|
|
2434
|
+
const reset =
|
|
2435
|
+
modelError.retryAfterSecs === undefined
|
|
2436
|
+
? ""
|
|
2437
|
+
: `; the model can serve again at ${new Date(
|
|
2438
|
+
(modelError.reportedAt ?? devNow()) +
|
|
2439
|
+
modelError.retryAfterSecs * 1000,
|
|
2440
|
+
).toISOString()}`;
|
|
2441
|
+
return finish("failed", {
|
|
2442
|
+
reason: "model_unavailable",
|
|
2443
|
+
message: `${reported}${reset}`,
|
|
2444
|
+
...(dirty.length === 0 ? {} : { files: dirty }),
|
|
2445
|
+
});
|
|
2446
|
+
}
|
|
2447
|
+
if (modelError !== undefined && waits < MAX_WORK_WAITS) {
|
|
2448
|
+
const waitSecs =
|
|
2449
|
+
modelError.retryAfterSecs ?? context.settings.reviewer.retrySecs;
|
|
2450
|
+
const retryAt =
|
|
2451
|
+
(modelError.retryAfterSecs === undefined
|
|
2452
|
+
? devNow()
|
|
2453
|
+
: modelError.reportedAt ?? devNow()) +
|
|
2454
|
+
waitSecs * 1000;
|
|
1691
2455
|
nextAttempt = { ...nextAttempt, workWaits: waits + 1, workRetryAt: retryAt };
|
|
1692
2456
|
return finish(
|
|
1693
2457
|
"unavailable",
|
|
@@ -1733,7 +2497,9 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1733
2497
|
return finish("failed", {
|
|
1734
2498
|
reason: "changes",
|
|
1735
2499
|
files: dirty,
|
|
1736
|
-
message:
|
|
2500
|
+
message:
|
|
2501
|
+
`uncommitted changes: ${dirty.join(", ")}` +
|
|
2502
|
+
(commitError === undefined ? "" : `; the commit the stage asked for failed: ${commitError}`),
|
|
1737
2503
|
});
|
|
1738
2504
|
}
|
|
1739
2505
|
|
|
@@ -1755,12 +2521,12 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1755
2521
|
}
|
|
1756
2522
|
}
|
|
1757
2523
|
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
context.settings.remote
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
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) {
|
|
1764
2530
|
return finish("failed", {
|
|
1765
2531
|
reason: "push",
|
|
1766
2532
|
head,
|
|
@@ -1769,7 +2535,7 @@ export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
|
1769
2535
|
}
|
|
1770
2536
|
return finish("done", {
|
|
1771
2537
|
head,
|
|
1772
|
-
pushed:
|
|
2538
|
+
pushed: push !== undefined,
|
|
1773
2539
|
...(note === undefined ? {} : { message: note }),
|
|
1774
2540
|
});
|
|
1775
2541
|
}
|