@operad-io/dev 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +12 -2
- package/dev.schema.json +631 -0
- package/flows/chat-worktree.flow.ts +18 -0
- package/flows/dev.flow.ts +7 -0
- package/package.json +29 -4
- package/src/actions.ts +591 -0
- package/src/announce.ts +225 -0
- package/src/chat.ts +234 -0
- package/src/check.ts +80 -0
- package/src/commands.ts +417 -0
- package/src/editor.ts +55 -0
- package/src/flaky.ts +716 -0
- package/src/flow-compiler.ts +858 -0
- package/src/followups.ts +223 -0
- package/src/gate.ts +2950 -0
- package/src/git.ts +138 -0
- package/src/index.ts +227 -0
- package/src/integrate.ts +1213 -0
- package/src/integration-queue.ts +393 -0
- package/src/lock.ts +36 -0
- package/src/mainclone.ts +102 -0
- package/src/marks.ts +126 -0
- package/src/model.ts +1171 -0
- package/src/notcode.ts +305 -0
- package/src/place-order.ts +161 -0
- package/src/place-wait.ts +64 -0
- package/src/places.ts +368 -0
- package/src/prepare.ts +106 -0
- package/src/progress.ts +115 -0
- package/src/project-flows.ts +160 -0
- package/src/project-settings.ts +192 -0
- package/src/refusals.ts +336 -0
- package/src/rerun.ts +390 -0
- package/src/reruns.ts +62 -0
- package/src/retry.ts +212 -0
- package/src/rework.ts +366 -0
- package/src/schedule.ts +1052 -0
- package/src/service.ts +2160 -0
- package/src/settings.ts +1495 -0
- package/src/standing.ts +87 -0
- package/src/stdin.ts +105 -0
- package/src/steps.ts +1775 -0
- package/src/stops.ts +103 -0
- package/src/throughput.ts +347 -0
- package/src/timeouts.ts +60 -0
- package/src/views.ts +1167 -0
- package/src/waits.ts +105 -0
package/src/steps.ts
ADDED
|
@@ -0,0 +1,1775 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two steps a task runs before a check: `worktree` gives it a branch and a
|
|
3
|
+
* worktree, `work` asks a harness step to do the task and reads the result.
|
|
4
|
+
* The kernel never runs git or a harness itself; both live here in `dev`.
|
|
5
|
+
*/
|
|
6
|
+
|
|
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
|
+
import {
|
|
11
|
+
messageOf,
|
|
12
|
+
readUsage,
|
|
13
|
+
type CostQuality,
|
|
14
|
+
type PluginStepResult,
|
|
15
|
+
type StepContext,
|
|
16
|
+
type StepEvent,
|
|
17
|
+
type StepRunOptions,
|
|
18
|
+
} from "@operad-io/engine";
|
|
19
|
+
import {
|
|
20
|
+
appendChange,
|
|
21
|
+
bareId,
|
|
22
|
+
DevError,
|
|
23
|
+
listAll,
|
|
24
|
+
repositoryData,
|
|
25
|
+
splitBrief,
|
|
26
|
+
storeKey,
|
|
27
|
+
taskData,
|
|
28
|
+
type RepositoryData,
|
|
29
|
+
type StopRecord,
|
|
30
|
+
type TaskAttempt,
|
|
31
|
+
type TaskData,
|
|
32
|
+
} from "./model.ts";
|
|
33
|
+
import {
|
|
34
|
+
ACQUIRED_EVENT,
|
|
35
|
+
DEFAULT_POOL,
|
|
36
|
+
resolvePool,
|
|
37
|
+
WAITING_EVENT,
|
|
38
|
+
type WorkerDefinition,
|
|
39
|
+
} from "@operad-io/pool";
|
|
40
|
+
import { git, type GitResult } from "./git.ts";
|
|
41
|
+
import { runPrepare } from "./prepare.ts";
|
|
42
|
+
import { classifyStop, isConnectionError, STOP_REASONS } from "./stops.ts";
|
|
43
|
+
import { findRepository, putTaskKeepingPlanCost, withRepoLock } from "./service.ts";
|
|
44
|
+
import {
|
|
45
|
+
createOutbox,
|
|
46
|
+
NOTE_REMOVED_MESSAGE,
|
|
47
|
+
previousAttemptText,
|
|
48
|
+
progressOf,
|
|
49
|
+
PROGRESS_FILE,
|
|
50
|
+
WIP_MESSAGE,
|
|
51
|
+
wrapUpMessage,
|
|
52
|
+
type Progress,
|
|
53
|
+
} from "./progress.ts";
|
|
54
|
+
import { MAX_WORK_WAITS, STEP_TIMEOUT_SECS } from "./timeouts.ts";
|
|
55
|
+
import {
|
|
56
|
+
assertInsideRepository,
|
|
57
|
+
readDevSettings,
|
|
58
|
+
readWorkerBrief,
|
|
59
|
+
type DevSettings,
|
|
60
|
+
} from "./settings.ts";
|
|
61
|
+
|
|
62
|
+
export { git, type GitResult };
|
|
63
|
+
|
|
64
|
+
function resolvePath(path: string): string {
|
|
65
|
+
try {
|
|
66
|
+
return realpathSync(path);
|
|
67
|
+
} catch {
|
|
68
|
+
return resolve(path);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The path a task's worktree occupies, refused when it lands outside the repository. */
|
|
73
|
+
export function worktreePath(
|
|
74
|
+
repositoryPath: string,
|
|
75
|
+
settings: DevSettings,
|
|
76
|
+
taskId: string,
|
|
77
|
+
): string {
|
|
78
|
+
const path = resolve(repositoryPath, settings.worktreeRoot, taskId);
|
|
79
|
+
// Settings were checked when they were read, but a link can appear before the
|
|
80
|
+
// step runs; the worktree must still stay inside the repository.
|
|
81
|
+
assertInsideRepository(repositoryPath, path, "worktreeRoot");
|
|
82
|
+
return path;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The branch a task's worktree is on. */
|
|
86
|
+
export function workBranch(taskId: string): string {
|
|
87
|
+
return `work/${taskId}`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The step a host error says was not loaded; undefined for any other error. */
|
|
91
|
+
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
|
|
96
|
+
: undefined;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface TaskContext {
|
|
100
|
+
readonly task: TaskData;
|
|
101
|
+
readonly repository: RepositoryData;
|
|
102
|
+
readonly taskKey: string;
|
|
103
|
+
readonly taskId: string;
|
|
104
|
+
/** The name of the task's worktree and branch: the task id, or the chat worktree it was opened on. */
|
|
105
|
+
readonly workName: string;
|
|
106
|
+
readonly settings: DevSettings;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function taskContext(ctx: StepContext): Promise<TaskContext> {
|
|
110
|
+
const parts = await taskParts(ctx);
|
|
111
|
+
const settings = await readDevSettings(parts.repository.path);
|
|
112
|
+
return { ...parts, settings };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A task context whose settings may be missing: a step that can retry reads it. */
|
|
116
|
+
export type LooseTaskContext = Omit<TaskContext, "settings"> & {
|
|
117
|
+
readonly settings?: DevSettings | undefined;
|
|
118
|
+
/** Why the settings could not be read, when `settings` is absent. */
|
|
119
|
+
readonly settingsError?: string | undefined;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Like `taskContext`, but a repository whose settings cannot be read comes
|
|
124
|
+
* back with `settingsError` instead of throwing, so the step can say so.
|
|
125
|
+
*/
|
|
126
|
+
export async function looseTaskContext(
|
|
127
|
+
ctx: StepContext,
|
|
128
|
+
): Promise<LooseTaskContext> {
|
|
129
|
+
const parts = await taskParts(ctx);
|
|
130
|
+
try {
|
|
131
|
+
return { ...parts, settings: await readDevSettings(parts.repository.path) };
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (error instanceof DevError && error.field === "dev.json") {
|
|
134
|
+
return { ...parts, settingsError: error.message };
|
|
135
|
+
}
|
|
136
|
+
throw error;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function taskParts(
|
|
141
|
+
ctx: StepContext,
|
|
142
|
+
): Promise<Omit<TaskContext, "settings">> {
|
|
143
|
+
const object = ctx.object;
|
|
144
|
+
if (object === undefined || object.type !== "task") {
|
|
145
|
+
throw new DevError("object", "this step runs on a task");
|
|
146
|
+
}
|
|
147
|
+
let stored = await ctx.store.get("task", object.id);
|
|
148
|
+
if (stored === undefined && !object.id.includes("/")) {
|
|
149
|
+
const matches = (await listAll(ctx.store, "task")).filter(
|
|
150
|
+
(candidate) => bareId(candidate.id) === object.id,
|
|
151
|
+
);
|
|
152
|
+
if (matches.length === 1) stored = matches[0];
|
|
153
|
+
}
|
|
154
|
+
const task = taskData(stored?.data ?? object.data);
|
|
155
|
+
const found = await findRepository(ctx.store, task.repository);
|
|
156
|
+
if (found === undefined) {
|
|
157
|
+
throw new DevError(
|
|
158
|
+
"repository",
|
|
159
|
+
`no registered repository "${task.repository}"`,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
const repository = repositoryData(found.data);
|
|
163
|
+
const taskId = bareId(stored?.id ?? object.id);
|
|
164
|
+
let taskKey = stored?.id ?? object.id;
|
|
165
|
+
if ((await ctx.store.get("task", taskKey)) === undefined) {
|
|
166
|
+
taskKey = storeKey(repository.name, taskId);
|
|
167
|
+
}
|
|
168
|
+
return { task, repository, taskKey, taskId, workName: task.worktree ?? taskId };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
interface AttemptState {
|
|
172
|
+
readonly attempt: TaskAttempt;
|
|
173
|
+
readonly attempts: number;
|
|
174
|
+
readonly replay: boolean;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function attemptFor(ctx: StepContext, task: TaskData): AttemptState {
|
|
178
|
+
const previous = task.attempt;
|
|
179
|
+
const replay =
|
|
180
|
+
task.phase === "running" &&
|
|
181
|
+
task.run === ctx.runId &&
|
|
182
|
+
previous?.run === ctx.runId &&
|
|
183
|
+
// A worktree visit that follows a `work` in the same run is a retry, not a
|
|
184
|
+
// replay: the attempt has already been used and the next one must count.
|
|
185
|
+
previous.worked !== true;
|
|
186
|
+
if (replay && previous !== undefined) {
|
|
187
|
+
return { attempt: previous, attempts: task.attempts, replay: true };
|
|
188
|
+
}
|
|
189
|
+
const number = Math.max(task.attempts, previous?.number ?? 0) + 1;
|
|
190
|
+
// The worker of the attempt before this one, so the work goes back to it.
|
|
191
|
+
const previousWorker =
|
|
192
|
+
typeof previous?.worker === "string" ? previous.worker : previous?.previousWorker;
|
|
193
|
+
const ran = typeof previous?.worker === "string";
|
|
194
|
+
const previousSession = ran ? previous?.sessionId : previous?.previousSession;
|
|
195
|
+
// What the attempt before left to continue from; only an attempt that left
|
|
196
|
+
// a note or ran out of time has any.
|
|
197
|
+
const left = progressOf(previous?.progress);
|
|
198
|
+
return {
|
|
199
|
+
attempt: {
|
|
200
|
+
number,
|
|
201
|
+
run: ctx.runId,
|
|
202
|
+
...(left === undefined ? {} : { previousProgress: left }),
|
|
203
|
+
...(typeof previousWorker === "string" ? { previousWorker } : {}),
|
|
204
|
+
...(typeof previousSession === "string" ? { previousSession } : {}),
|
|
205
|
+
},
|
|
206
|
+
attempts: number,
|
|
207
|
+
replay: false,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function listWorktrees(repositoryPath: string): readonly string[] {
|
|
212
|
+
const result = git(repositoryPath, ["worktree", "list", "--porcelain"]);
|
|
213
|
+
if (!result.ok) return [];
|
|
214
|
+
const paths: string[] = [];
|
|
215
|
+
for (const line of result.out.split("\n")) {
|
|
216
|
+
if (line.startsWith("worktree ")) paths.push(line.slice("worktree ".length));
|
|
217
|
+
}
|
|
218
|
+
return paths;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function isRegistered(repositoryPath: string, path: string): boolean {
|
|
222
|
+
const wanted = resolvePath(path);
|
|
223
|
+
return listWorktrees(repositoryPath).some(
|
|
224
|
+
(candidate) => resolvePath(candidate) === wanted,
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function isWorktree(path: string): boolean {
|
|
229
|
+
if (!existsSync(path)) return false;
|
|
230
|
+
const result = git(path, ["rev-parse", "--is-inside-work-tree"]);
|
|
231
|
+
return result.ok && result.out === "true";
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function currentBranch(path: string): string | undefined {
|
|
235
|
+
const result = git(path, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
236
|
+
return result.ok && result.out.length > 0 ? result.out : undefined;
|
|
237
|
+
}
|
|
238
|
+
|
|
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
|
+
function gitDirOf(worktree: string): string | undefined {
|
|
276
|
+
const result = git(worktree, ["rev-parse", "--git-dir"]);
|
|
277
|
+
if (!result.ok || result.out.length === 0) return undefined;
|
|
278
|
+
return resolve(worktree, result.out);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** True while a merge left conflicts for the worker to resolve. */
|
|
282
|
+
export function mergeInProgress(worktree: string): boolean {
|
|
283
|
+
const directory = gitDirOf(worktree);
|
|
284
|
+
return directory !== undefined && existsSync(join(directory, "MERGE_HEAD"));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** The files git recorded as conflicted, in path order. */
|
|
288
|
+
export function conflictedFiles(worktree: string): readonly string[] {
|
|
289
|
+
const result = git(worktree, [
|
|
290
|
+
"diff",
|
|
291
|
+
"--name-only",
|
|
292
|
+
"--diff-filter=U",
|
|
293
|
+
]);
|
|
294
|
+
if (!result.ok || result.out.length === 0) return [];
|
|
295
|
+
return result.out
|
|
296
|
+
.split("\n")
|
|
297
|
+
.map((line) => line.trim())
|
|
298
|
+
.filter((line) => line.length > 0)
|
|
299
|
+
.sort();
|
|
300
|
+
}
|
|
301
|
+
|
|
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);
|
|
310
|
+
if (!result.ok || result.out.length === 0) return [];
|
|
311
|
+
const entries = result.out.split("\0");
|
|
312
|
+
const files: string[] = [];
|
|
313
|
+
for (let index = 0; index < entries.length; index += 1) {
|
|
314
|
+
const entry = entries[index] ?? "";
|
|
315
|
+
if (entry.length < 4) continue;
|
|
316
|
+
files.push(entry.slice(3));
|
|
317
|
+
const code = entry.slice(0, 2);
|
|
318
|
+
if (code.includes("R") || code.includes("C")) index += 1;
|
|
319
|
+
}
|
|
320
|
+
return [...new Set(files)].filter((file) => file !== PROGRESS_FILE).sort();
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export interface Prepared {
|
|
324
|
+
readonly kind: "ready" | "conflict" | "failed";
|
|
325
|
+
readonly base?: string | undefined;
|
|
326
|
+
readonly message?: string | undefined;
|
|
327
|
+
readonly files?: readonly string[] | undefined;
|
|
328
|
+
/** The main this visit merged into the branch, when it merged one. */
|
|
329
|
+
readonly merged?: MergedMain | undefined;
|
|
330
|
+
/** Set when the prepare commands failed. */
|
|
331
|
+
readonly reason?: string | undefined;
|
|
332
|
+
readonly log?: string | undefined;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Runs the prepare commands in a ready worktree; a failure turns it into a failed visit. */
|
|
336
|
+
async function withPrepare(
|
|
337
|
+
ctx: StepContext,
|
|
338
|
+
settings: DevSettings,
|
|
339
|
+
path: string,
|
|
340
|
+
prepared: Prepared,
|
|
341
|
+
): Promise<Prepared> {
|
|
342
|
+
if (prepared.kind !== "ready") return prepared;
|
|
343
|
+
const failure = await runPrepare(ctx, settings, path);
|
|
344
|
+
if (failure === undefined) return prepared;
|
|
345
|
+
return {
|
|
346
|
+
...prepared,
|
|
347
|
+
kind: "failed",
|
|
348
|
+
message: failure.message,
|
|
349
|
+
reason: failure.reason,
|
|
350
|
+
log: failure.log,
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** What the worktree step merged: the remote main's commit, and whether it conflicted. */
|
|
355
|
+
export type MergedMain = {
|
|
356
|
+
readonly ref: string;
|
|
357
|
+
readonly commit: string;
|
|
358
|
+
readonly conflict: boolean;
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
function failed(message: string, files?: readonly string[]): Prepared {
|
|
362
|
+
return { kind: "failed", message, ...(files === undefined ? {} : { files }) };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Merges the fetched main into a reused branch and reports a conflict. */
|
|
366
|
+
function mergeLatest(path: string, mainRef: string): Prepared {
|
|
367
|
+
const before = headOf(path);
|
|
368
|
+
const commit = git(path, ["rev-parse", "--short", mainRef]).out;
|
|
369
|
+
const merge = git(path, ["merge", "--no-edit", "--no-ff", mainRef]);
|
|
370
|
+
if (!merge.ok) {
|
|
371
|
+
const files = conflictedFiles(path);
|
|
372
|
+
if (files.length > 0 || mergeInProgress(path)) {
|
|
373
|
+
return {
|
|
374
|
+
kind: "conflict",
|
|
375
|
+
base: headOf(path),
|
|
376
|
+
files,
|
|
377
|
+
merged: { ref: mainRef, commit, conflict: true },
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
return failed(
|
|
381
|
+
`cannot merge "${mainRef}" into the worktree: ${merge.err || merge.out}`,
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
const after = headOf(path);
|
|
385
|
+
return {
|
|
386
|
+
kind: "ready",
|
|
387
|
+
base: after,
|
|
388
|
+
...(after === before
|
|
389
|
+
? {}
|
|
390
|
+
: { merged: { ref: mainRef, commit, conflict: false } }),
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Fetches, creates the worktree when needed, and merges main into a reused one. */
|
|
395
|
+
export function prepareWorktree(
|
|
396
|
+
repository: RepositoryData,
|
|
397
|
+
settings: DevSettings,
|
|
398
|
+
taskId: string,
|
|
399
|
+
mergeMain = true,
|
|
400
|
+
): Prepared {
|
|
401
|
+
const fetch = git(repository.path, ["fetch", "--prune", settings.remote]);
|
|
402
|
+
if (!fetch.ok) {
|
|
403
|
+
return failed(
|
|
404
|
+
`cannot fetch "${settings.remote}": ${fetch.err || fetch.out || "git fetch failed"}`,
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
const mainRef = `${settings.remote}/${settings.mainBranch}`;
|
|
408
|
+
if (!git(repository.path, ["show-ref", "--verify", "--quiet", `refs/remotes/${mainRef}`]).ok) {
|
|
409
|
+
return failed(`"${mainRef}" does not exist after the fetch`);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const path = worktreePath(repository.path, settings, taskId);
|
|
413
|
+
const branch = workBranch(taskId);
|
|
414
|
+
const registered = isRegistered(repository.path, path);
|
|
415
|
+
|
|
416
|
+
if (existsSync(path) && !registered) {
|
|
417
|
+
return failed(
|
|
418
|
+
`${path} exists but is not a git worktree of this repository`,
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
if (!existsSync(path) && registered) {
|
|
422
|
+
git(repository.path, ["worktree", "prune"]);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
if (existsSync(path)) {
|
|
426
|
+
if (!isWorktree(path)) {
|
|
427
|
+
return failed(`${path} is not a git worktree`);
|
|
428
|
+
}
|
|
429
|
+
if (currentBranch(path) !== branch) {
|
|
430
|
+
return failed(
|
|
431
|
+
`${path} is on "${currentBranch(path) ?? "no branch"}", not "${branch}"`,
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
if (!mergeMain) {
|
|
435
|
+
return { kind: "ready", base: headOf(path) };
|
|
436
|
+
}
|
|
437
|
+
if (mergeInProgress(path)) {
|
|
438
|
+
return {
|
|
439
|
+
kind: "conflict",
|
|
440
|
+
base: headOf(path),
|
|
441
|
+
files: conflictedFiles(path),
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
return mergeLatest(path, mainRef);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
448
|
+
let add: GitResult;
|
|
449
|
+
let reused = false;
|
|
450
|
+
if (branchExists(repository.path, branch)) {
|
|
451
|
+
add = git(repository.path, ["worktree", "add", path, branch]);
|
|
452
|
+
reused = true;
|
|
453
|
+
} else if (remoteBranchExists(repository.path, settings.remote, branch)) {
|
|
454
|
+
add = git(repository.path, [
|
|
455
|
+
"worktree",
|
|
456
|
+
"add",
|
|
457
|
+
"--no-track",
|
|
458
|
+
"-b",
|
|
459
|
+
branch,
|
|
460
|
+
path,
|
|
461
|
+
`${settings.remote}/${branch}`,
|
|
462
|
+
]);
|
|
463
|
+
reused = true;
|
|
464
|
+
} else {
|
|
465
|
+
add = git(repository.path, [
|
|
466
|
+
"worktree",
|
|
467
|
+
"add",
|
|
468
|
+
"--no-track",
|
|
469
|
+
"-b",
|
|
470
|
+
branch,
|
|
471
|
+
path,
|
|
472
|
+
mainRef,
|
|
473
|
+
]);
|
|
474
|
+
}
|
|
475
|
+
if (!add.ok) {
|
|
476
|
+
return failed(`cannot create worktree at ${path}: ${add.err || add.out}`);
|
|
477
|
+
}
|
|
478
|
+
// A branch kept from an earlier attempt continues from its old base, so the
|
|
479
|
+
// freshly fetched main is merged before the worker sees it.
|
|
480
|
+
if (reused && mergeMain) return mergeLatest(path, mainRef);
|
|
481
|
+
return { kind: "ready", base: headOf(path) };
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
export async function saveTask(
|
|
485
|
+
ctx: StepContext,
|
|
486
|
+
key: string,
|
|
487
|
+
data: TaskData,
|
|
488
|
+
cause: string,
|
|
489
|
+
): Promise<void> {
|
|
490
|
+
await putTaskKeepingPlanCost(ctx.store, key, data, cause);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** The claim token the scheduler put in the run's start parameters. */
|
|
494
|
+
export function runToken(ctx: StepContext): string | undefined {
|
|
495
|
+
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;
|
|
500
|
+
return typeof token === "string" && token.length > 0 ? token : undefined;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* True while a step may write its task: the task is not cancelled, the run
|
|
505
|
+
* carries the claim's token, and a step that runs before the run recorded
|
|
506
|
+
* itself still finds the phase the claim wrote. A task without a claim was not
|
|
507
|
+
* started by the scheduler (a step test or a direct call), so it is allowed.
|
|
508
|
+
*/
|
|
509
|
+
export function claimAllows(ctx: StepContext, task: TaskData): boolean {
|
|
510
|
+
if (task.phase === "cancelled" || task.phase === "paused") return false;
|
|
511
|
+
const claim = task.claim;
|
|
512
|
+
if (claim === undefined || claim === null) {
|
|
513
|
+
// A scheduler-started step that finds the task ready with no run and no
|
|
514
|
+
// claim belongs to a run that was paused and resumed: its task is back in
|
|
515
|
+
// the queue, so its late write would overwrite the resumed task.
|
|
516
|
+
return !(
|
|
517
|
+
runToken(ctx) !== undefined && task.run === null && task.phase === "ready"
|
|
518
|
+
);
|
|
519
|
+
}
|
|
520
|
+
if (runToken(ctx) !== claim.token) return false;
|
|
521
|
+
if (task.run === null && task.phase !== claim.phase) return false;
|
|
522
|
+
return true;
|
|
523
|
+
}
|
|
524
|
+
|
|
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
|
+
/**
|
|
537
|
+
* Test-only hook, run by a guarded write after its caller built the new data
|
|
538
|
+
* and before the write takes the repository lock. A test uses it to cancel the
|
|
539
|
+
* task from another process in that window.
|
|
540
|
+
*/
|
|
541
|
+
export const stepTestHooks: {
|
|
542
|
+
beforeGuardedWrite?:
|
|
543
|
+
| ((ctx: StepContext, key: string) => Promise<void> | void)
|
|
544
|
+
| undefined;
|
|
545
|
+
/** Replaces the timers of a work step's wrap-up and time limit. */
|
|
546
|
+
workClock?: WorkClock | undefined;
|
|
547
|
+
/** Replaces the timer that says a worker with a place has not started. */
|
|
548
|
+
workerStartClock?: WorkClock | undefined;
|
|
549
|
+
/** Called once the task has recorded what the work step waits for (null: nothing). */
|
|
550
|
+
afterWorkerWait?: ((text: string | null) => void) | undefined;
|
|
551
|
+
} = {};
|
|
552
|
+
|
|
553
|
+
/** The timers a work step uses for its wrap-up message and its time limit. */
|
|
554
|
+
export interface WorkClock {
|
|
555
|
+
setTimeout(handler: () => void, ms: number): unknown;
|
|
556
|
+
clearTimeout(handle: unknown): void;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
const realWorkClock: WorkClock = {
|
|
560
|
+
setTimeout: (handler, ms) => setTimeout(handler, ms),
|
|
561
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* How long a worker may hold its place without its program running before the
|
|
566
|
+
* task says so. Starting a worker takes seconds; two minutes is a worker that
|
|
567
|
+
* is not starting.
|
|
568
|
+
*/
|
|
569
|
+
export const WORKER_START_GRACE_MS = 120_000;
|
|
570
|
+
|
|
571
|
+
/** How long before the limit the step stops the worker itself, so it can still commit. */
|
|
572
|
+
function limitMarginMs(limitMs: number): number {
|
|
573
|
+
return Math.min(30_000, Math.floor(limitMs / 100));
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** The commits the branch has beyond `base`, newest first. */
|
|
577
|
+
function commitsSince(
|
|
578
|
+
worktree: string,
|
|
579
|
+
base: string | null,
|
|
580
|
+
): Progress["commits"] {
|
|
581
|
+
if (base === null) return [];
|
|
582
|
+
const result = git(worktree, ["log", "--format=%h %s", "-n", "50", `${base}..HEAD`]);
|
|
583
|
+
if (!result.ok || result.out.length === 0) return [];
|
|
584
|
+
return result.out.split("\n").map((line) => {
|
|
585
|
+
const space = line.indexOf(" ");
|
|
586
|
+
return space === -1
|
|
587
|
+
? { sha: line, subject: "" }
|
|
588
|
+
: { sha: line.slice(0, space), subject: line.slice(space + 1) };
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function readNote(worktree: string): string | null {
|
|
593
|
+
try {
|
|
594
|
+
const text = readFileSync(join(worktree, PROGRESS_FILE), "utf8");
|
|
595
|
+
return text.trim().length === 0 ? null : text;
|
|
596
|
+
} catch {
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Takes the note out of the branch when the worker committed it anyway. */
|
|
602
|
+
function untrackNote(worktree: string): void {
|
|
603
|
+
if (!git(worktree, ["ls-files", "--error-unmatch", PROGRESS_FILE]).ok) return;
|
|
604
|
+
const removed = git(worktree, ["rm", "--cached", "-q", PROGRESS_FILE]);
|
|
605
|
+
if (removed.ok) git(worktree, ["commit", "-q", "-m", NOTE_REMOVED_MESSAGE]);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** Commits what a timed-out step left, except the note. False when nothing was committed. */
|
|
609
|
+
function commitWip(worktree: string): boolean {
|
|
610
|
+
if (conflictedFiles(worktree).length > 0) return false;
|
|
611
|
+
if (changedFiles(worktree).length === 0) return false;
|
|
612
|
+
const added = git(worktree, ["add", "-A", "--", ".", `:(exclude)${PROGRESS_FILE}`]);
|
|
613
|
+
if (!added.ok) return false;
|
|
614
|
+
return git(worktree, ["commit", "-q", "--no-verify", "-m", WIP_MESSAGE]).ok;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** Commits everything left in the worktree (honouring .gitignore) with the given message. */
|
|
618
|
+
function commitLeft(worktree: string, message: string): boolean {
|
|
619
|
+
if (conflictedFiles(worktree).length > 0) return false;
|
|
620
|
+
const added = git(worktree, ["add", "-A", "--", "."]);
|
|
621
|
+
if (!added.ok) return false;
|
|
622
|
+
const committed = git(worktree, ["commit", "-q", "--no-verify", "-m", message]).ok;
|
|
623
|
+
// The note is the worker's report, not part of the change: take it out of the
|
|
624
|
+
// branch again, leaving the file for the step to read.
|
|
625
|
+
untrackNote(worktree);
|
|
626
|
+
return committed;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Writes the task only while the step still owns its claim. The check reads the
|
|
631
|
+
* task again under the repository lock, so a `cancel` that landed after the
|
|
632
|
+
* caller's own guard cannot be overwritten by the data built from stale task
|
|
633
|
+
* state.
|
|
634
|
+
*/
|
|
635
|
+
export async function saveTaskGuarded(
|
|
636
|
+
ctx: StepContext,
|
|
637
|
+
key: string,
|
|
638
|
+
data: TaskData,
|
|
639
|
+
cause: string,
|
|
640
|
+
): Promise<boolean> {
|
|
641
|
+
await stepTestHooks.beforeGuardedWrite?.(ctx, key);
|
|
642
|
+
return withRepoLock(ctx.store, data.repository, async () => {
|
|
643
|
+
const object = await ctx.store.get("task", key);
|
|
644
|
+
if (object === undefined) return false;
|
|
645
|
+
if (!claimAllows(ctx, taskData(object.data))) return false;
|
|
646
|
+
await saveTask(ctx, key, data, cause);
|
|
647
|
+
return true;
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/** The result a step returns when its task was cancelled under it. */
|
|
652
|
+
export function cancelledStep(): PluginStepResult {
|
|
653
|
+
return { result: "cancelled", data: { reason: "cancelled" } };
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** The step a repair run says stopped, when the scheduler asked for one. */
|
|
657
|
+
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;
|
|
662
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** The cancelled dependency a blocked start names, when the flow carries one. */
|
|
666
|
+
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;
|
|
671
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/** Step `dev/worktree`: make the task's worktree ready or report a conflict. */
|
|
675
|
+
export async function runWorktree(
|
|
676
|
+
ctx: StepContext,
|
|
677
|
+
): Promise<PluginStepResult> {
|
|
678
|
+
const context = await taskContext(ctx);
|
|
679
|
+
if (!claimAllows(ctx, context.task)) return cancelledStep();
|
|
680
|
+
const stoppedAt = runStoppedAt(ctx.params);
|
|
681
|
+
if (stoppedAt !== undefined && context.task.run === null) {
|
|
682
|
+
// A run stopped without reaching an edge; the scheduler starts this run
|
|
683
|
+
// only to put the task in front of a person again.
|
|
684
|
+
const written = await saveTaskGuarded(
|
|
685
|
+
ctx,
|
|
686
|
+
context.taskKey,
|
|
687
|
+
{
|
|
688
|
+
...context.task,
|
|
689
|
+
phase: "waiting",
|
|
690
|
+
run: ctx.runId,
|
|
691
|
+
startRequested: false,
|
|
692
|
+
// The run that stopped is over: this one only asks a person, so the
|
|
693
|
+
// retry step must not run anything again.
|
|
694
|
+
stop: {
|
|
695
|
+
step: "worktree",
|
|
696
|
+
result: "interrupted",
|
|
697
|
+
reason: STOP_REASONS.runEnded,
|
|
698
|
+
},
|
|
699
|
+
brief: appendChange(
|
|
700
|
+
context.task.brief,
|
|
701
|
+
`waiting: ${stoppedAt} stopped`,
|
|
702
|
+
),
|
|
703
|
+
},
|
|
704
|
+
"dev:task-run-stopped",
|
|
705
|
+
);
|
|
706
|
+
if (!written) return cancelledStep();
|
|
707
|
+
return {
|
|
708
|
+
result: "interrupted",
|
|
709
|
+
data: {
|
|
710
|
+
reason: "run_stopped",
|
|
711
|
+
step: stoppedAt,
|
|
712
|
+
message: `the run stopped during ${stoppedAt}; reject to run it again`,
|
|
713
|
+
},
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
const blockedBy = blockedDependency(ctx.params);
|
|
717
|
+
if (blockedBy !== undefined && context.task.run === null) {
|
|
718
|
+
// A cancelled dependency made the scheduler start this run only to log a
|
|
719
|
+
// real person wait. The claim has no run yet; this step records the wait
|
|
720
|
+
// so the kernel's pending view and the task's normal actions both see it.
|
|
721
|
+
const written = await saveTaskGuarded(
|
|
722
|
+
ctx,
|
|
723
|
+
context.taskKey,
|
|
724
|
+
{
|
|
725
|
+
...context.task,
|
|
726
|
+
phase: "waiting",
|
|
727
|
+
run: ctx.runId,
|
|
728
|
+
startRequested: false,
|
|
729
|
+
brief: appendChange(
|
|
730
|
+
context.task.brief,
|
|
731
|
+
`waiting: ${blockedBy} cancelled`,
|
|
732
|
+
),
|
|
733
|
+
},
|
|
734
|
+
"dev:task-wait-dependency",
|
|
735
|
+
);
|
|
736
|
+
if (!written) return cancelledStep();
|
|
737
|
+
return {
|
|
738
|
+
result: "blocked",
|
|
739
|
+
data: { reason: "cancelled_dependency", dependency: blockedBy },
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
const { attempt, attempts, replay } = attemptFor(ctx, context.task);
|
|
743
|
+
const prepared = await withPrepare(
|
|
744
|
+
ctx,
|
|
745
|
+
context.settings,
|
|
746
|
+
worktreePath(context.repository.path, context.settings, context.workName),
|
|
747
|
+
prepareWorktree(
|
|
748
|
+
context.repository,
|
|
749
|
+
context.settings,
|
|
750
|
+
context.workName,
|
|
751
|
+
beforeAttemptOf(ctx.params) !== "none",
|
|
752
|
+
),
|
|
753
|
+
);
|
|
754
|
+
const base = prepared.base ?? attempt.base ?? null;
|
|
755
|
+
const nextAttempt: TaskAttempt = {
|
|
756
|
+
...attempt,
|
|
757
|
+
run: ctx.runId,
|
|
758
|
+
worktree: worktreePath(
|
|
759
|
+
context.repository.path,
|
|
760
|
+
context.settings,
|
|
761
|
+
context.workName,
|
|
762
|
+
),
|
|
763
|
+
branch: workBranch(context.workName),
|
|
764
|
+
base,
|
|
765
|
+
result: prepared.kind,
|
|
766
|
+
// The answer of an earlier attempt belongs to that attempt.
|
|
767
|
+
finalMessage: null,
|
|
768
|
+
workWaits: 0,
|
|
769
|
+
workRetryAt: null,
|
|
770
|
+
// A new attempt starts with no gate results; the branch may have moved.
|
|
771
|
+
// A passing verify of the very commit the branch is at still stands.
|
|
772
|
+
...(passedAt(context.task.attempt, prepared.base ?? null)
|
|
773
|
+
? {
|
|
774
|
+
verified: context.task.attempt?.verified ?? null,
|
|
775
|
+
verify: context.task.attempt?.verify ?? null,
|
|
776
|
+
}
|
|
777
|
+
: { verified: null, verify: null }),
|
|
778
|
+
review: null,
|
|
779
|
+
reviewRuns: [],
|
|
780
|
+
reviews: 0,
|
|
781
|
+
// The next gate failure appends a fresh rework even in the same flow run.
|
|
782
|
+
rework: null,
|
|
783
|
+
// A replay finds main already merged and keeps what the first visit said.
|
|
784
|
+
merged: prepared.merged ?? (replay ? (attempt.merged ?? null) : null),
|
|
785
|
+
};
|
|
786
|
+
const mergedNote =
|
|
787
|
+
prepared.merged === undefined
|
|
788
|
+
? undefined
|
|
789
|
+
: prepared.merged.conflict
|
|
790
|
+
? `merged ${prepared.merged.ref} ${prepared.merged.commit} into the branch (conflict)`
|
|
791
|
+
: `merged ${prepared.merged.ref} ${prepared.merged.commit} into the branch (clean)`;
|
|
792
|
+
const next: TaskData = {
|
|
793
|
+
...context.task,
|
|
794
|
+
phase: "running",
|
|
795
|
+
waitKind: undefined,
|
|
796
|
+
run: ctx.runId,
|
|
797
|
+
// The run now names the task, so the manual start request has been met.
|
|
798
|
+
startRequested: false,
|
|
799
|
+
attempts,
|
|
800
|
+
attempt: nextAttempt,
|
|
801
|
+
// A merge conflict between two review failures resets the count.
|
|
802
|
+
...(prepared.kind === "conflict" ? { reviewFailed: undefined } : {}),
|
|
803
|
+
...(mergedNote === undefined
|
|
804
|
+
? {}
|
|
805
|
+
: { brief: appendChange(context.task.brief, mergedNote) }),
|
|
806
|
+
};
|
|
807
|
+
if (!(await saveTaskGuarded(ctx, context.taskKey, next, "dev:worktree"))) {
|
|
808
|
+
return cancelledStep();
|
|
809
|
+
}
|
|
810
|
+
const data = {
|
|
811
|
+
attempt: attempts,
|
|
812
|
+
worktree: nextAttempt.worktree,
|
|
813
|
+
path: nextAttempt.worktree,
|
|
814
|
+
branch: nextAttempt.branch,
|
|
815
|
+
base,
|
|
816
|
+
...(prepared.message === undefined ? {} : { message: prepared.message }),
|
|
817
|
+
...(prepared.reason === undefined ? {} : { reason: prepared.reason }),
|
|
818
|
+
...(prepared.log === undefined ? {} : { log: prepared.log }),
|
|
819
|
+
...(prepared.files === undefined ? {} : { files: prepared.files }),
|
|
820
|
+
...(prepared.merged === undefined ? {} : { merged: prepared.merged }),
|
|
821
|
+
};
|
|
822
|
+
return { result: prepared.kind, data };
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* Step `dev/reverify`: bring the branch up to date with main before a reverify
|
|
827
|
+
* gates it. It keeps the attempt, since the work is the same: a clean merge (or
|
|
828
|
+
* a main already contained) goes to verify, a conflict goes to the worker with
|
|
829
|
+
* the merge left open.
|
|
830
|
+
*/
|
|
831
|
+
export async function runReverify(
|
|
832
|
+
ctx: StepContext,
|
|
833
|
+
): Promise<PluginStepResult> {
|
|
834
|
+
const context = await taskContext(ctx);
|
|
835
|
+
if (!claimAllows(ctx, context.task)) return cancelledStep();
|
|
836
|
+
const previous = context.task.attempt;
|
|
837
|
+
const attempt: TaskAttempt = previous ?? {
|
|
838
|
+
number: Math.max(context.task.attempts, 0) + 1,
|
|
839
|
+
run: ctx.runId,
|
|
840
|
+
};
|
|
841
|
+
const attempts = Math.max(context.task.attempts, attempt.number);
|
|
842
|
+
const prepared = await withPrepare(
|
|
843
|
+
ctx,
|
|
844
|
+
context.settings,
|
|
845
|
+
worktreePath(context.repository.path, context.settings, context.workName),
|
|
846
|
+
prepareWorktree(context.repository, context.settings, context.workName),
|
|
847
|
+
);
|
|
848
|
+
const base = prepared.base ?? attempt.base ?? null;
|
|
849
|
+
const worktree = worktreePath(
|
|
850
|
+
context.repository.path,
|
|
851
|
+
context.settings,
|
|
852
|
+
context.workName,
|
|
853
|
+
);
|
|
854
|
+
const message =
|
|
855
|
+
prepared.kind === "conflict"
|
|
856
|
+
? "reverify: main conflicts, sending to work"
|
|
857
|
+
: prepared.kind === "ready"
|
|
858
|
+
? prepared.merged === undefined
|
|
859
|
+
? "reverify: main already contained, checking again"
|
|
860
|
+
: `reverify: merged main ${prepared.merged.commit}, checking again`
|
|
861
|
+
: undefined;
|
|
862
|
+
const nextAttempt: TaskAttempt = {
|
|
863
|
+
...attempt,
|
|
864
|
+
run: ctx.runId,
|
|
865
|
+
worktree,
|
|
866
|
+
branch: workBranch(context.workName),
|
|
867
|
+
base,
|
|
868
|
+
result: prepared.kind,
|
|
869
|
+
// A conflict is worked on again; a clean merge goes straight to the gate.
|
|
870
|
+
...(prepared.kind === "conflict" ? { worked: false } : {}),
|
|
871
|
+
workWaits: 0,
|
|
872
|
+
workRetryAt: null,
|
|
873
|
+
merged: prepared.merged ?? attempt.merged ?? null,
|
|
874
|
+
};
|
|
875
|
+
const next: TaskData = {
|
|
876
|
+
...context.task,
|
|
877
|
+
phase: "running",
|
|
878
|
+
waitKind: undefined,
|
|
879
|
+
run: ctx.runId,
|
|
880
|
+
attempts,
|
|
881
|
+
attempt: nextAttempt,
|
|
882
|
+
// A merge conflict between two review failures resets the count.
|
|
883
|
+
...(prepared.kind === "conflict" ? { reviewFailed: undefined } : {}),
|
|
884
|
+
...(message === undefined
|
|
885
|
+
? {}
|
|
886
|
+
: { brief: appendChange(context.task.brief, message) }),
|
|
887
|
+
};
|
|
888
|
+
if (!(await saveTaskGuarded(ctx, context.taskKey, next, "dev:reverify"))) {
|
|
889
|
+
return cancelledStep();
|
|
890
|
+
}
|
|
891
|
+
return {
|
|
892
|
+
result: prepared.kind,
|
|
893
|
+
data: {
|
|
894
|
+
attempt: attempts,
|
|
895
|
+
worktree,
|
|
896
|
+
path: worktree,
|
|
897
|
+
branch: nextAttempt.branch,
|
|
898
|
+
base,
|
|
899
|
+
...(message === undefined ? {} : { message }),
|
|
900
|
+
...(prepared.message === undefined ? {} : { failure: prepared.message }),
|
|
901
|
+
...(prepared.reason === undefined ? {} : { reason: prepared.reason }),
|
|
902
|
+
...(prepared.log === undefined ? {} : { log: prepared.log }),
|
|
903
|
+
...(prepared.files === undefined ? {} : { files: prepared.files }),
|
|
904
|
+
...(prepared.merged === undefined ? {} : { merged: prepared.merged }),
|
|
905
|
+
},
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
export function briefText(task: TaskData): string {
|
|
910
|
+
const parts = splitBrief(task.brief);
|
|
911
|
+
const pieces = [parts.body, parts.reworks].filter(
|
|
912
|
+
(piece) => piece.trim().length > 0,
|
|
913
|
+
);
|
|
914
|
+
return pieces.join("\n\n");
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/** The conflict instruction a worker sees first when a merge is left open. */
|
|
918
|
+
export function conflictPrompt(files: readonly string[]): string {
|
|
919
|
+
const named =
|
|
920
|
+
files.length === 0
|
|
921
|
+
? "The worktree has an unresolved merge conflict."
|
|
922
|
+
: [
|
|
923
|
+
"The worktree has an unresolved merge conflict in these files:",
|
|
924
|
+
...files.map((file) => `- ${file}`),
|
|
925
|
+
].join("\n");
|
|
926
|
+
return [
|
|
927
|
+
named,
|
|
928
|
+
"The branch has a merge of the latest main in progress, and resolving it is part of this attempt. Start by resolving every conflict, then commit the merge and continue with the task.",
|
|
929
|
+
].join("\n\n");
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/** Builds the prompt a worker reads: conflict note, worker brief, task brief. */
|
|
933
|
+
export function buildWorkerPrompt(
|
|
934
|
+
worktree: string,
|
|
935
|
+
workerBrief: string,
|
|
936
|
+
task: TaskData,
|
|
937
|
+
previous?: Progress,
|
|
938
|
+
): string {
|
|
939
|
+
const pieces: string[] = [];
|
|
940
|
+
if (previous !== undefined) pieces.push(previousAttemptText(previous));
|
|
941
|
+
if (mergeInProgress(worktree)) {
|
|
942
|
+
pieces.push(conflictPrompt(conflictedFiles(worktree)));
|
|
943
|
+
}
|
|
944
|
+
pieces.push(workerBrief.trim());
|
|
945
|
+
const taskText = briefText(task).trim();
|
|
946
|
+
if (taskText.length > 0) pieces.push(taskText);
|
|
947
|
+
return pieces.join("\n\n");
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
interface HarnessReading {
|
|
951
|
+
readonly sessionId: string | null;
|
|
952
|
+
readonly costMicros: number | null;
|
|
953
|
+
readonly costQuality: CostQuality | null;
|
|
954
|
+
readonly cost: number | null;
|
|
955
|
+
readonly log: string | null;
|
|
956
|
+
readonly tokens: { readonly input: number; readonly output: number } | null;
|
|
957
|
+
readonly durationMs: number | null;
|
|
958
|
+
readonly finalMessage: string | null;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
function harnessReading(
|
|
962
|
+
data: Record<string, unknown>,
|
|
963
|
+
onProblem?: (message: string) => void,
|
|
964
|
+
): HarnessReading {
|
|
965
|
+
const sessionId =
|
|
966
|
+
typeof data.sessionId === "string" ? data.sessionId : null;
|
|
967
|
+
// The one reader of a step's usage: it takes the standard field and, for
|
|
968
|
+
// a fact written before it existed, the old fields.
|
|
969
|
+
const usage = readUsage(data, onProblem);
|
|
970
|
+
const micros = usage?.costMicros ?? null;
|
|
971
|
+
return {
|
|
972
|
+
sessionId,
|
|
973
|
+
costMicros: micros,
|
|
974
|
+
costQuality: usage?.costQuality ?? null,
|
|
975
|
+
cost: micros === null ? null : micros / 1_000_000,
|
|
976
|
+
log: typeof data.log === "string" && data.log.length > 0 ? data.log : null,
|
|
977
|
+
tokens:
|
|
978
|
+
// A run that reported no tokens at all has none to show.
|
|
979
|
+
usage === undefined || (usage.tokens.input === 0 && usage.tokens.output === 0)
|
|
980
|
+
? null
|
|
981
|
+
: { input: usage.tokens.input, output: usage.tokens.output },
|
|
982
|
+
finalMessage:
|
|
983
|
+
typeof data.finalMessage === "string" && data.finalMessage.trim().length > 0
|
|
984
|
+
? data.finalMessage
|
|
985
|
+
: null,
|
|
986
|
+
durationMs:
|
|
987
|
+
typeof data.durationMs === "number" && Number.isFinite(data.durationMs)
|
|
988
|
+
? data.durationMs
|
|
989
|
+
: null,
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
function resultData(
|
|
994
|
+
attempt: TaskAttempt,
|
|
995
|
+
reading: HarnessReading,
|
|
996
|
+
extra: Readonly<Record<string, unknown>>,
|
|
997
|
+
): Record<string, unknown> {
|
|
998
|
+
return {
|
|
999
|
+
attempt: attempt.number,
|
|
1000
|
+
sessionId: reading.sessionId,
|
|
1001
|
+
cost: reading.cost,
|
|
1002
|
+
costMicros: reading.costMicros,
|
|
1003
|
+
costQuality: reading.costQuality,
|
|
1004
|
+
...extra,
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/**
|
|
1009
|
+
* The params of the `pool/agent` call: the stage's pool's definitions (`default`
|
|
1010
|
+
* when the stage names none), the key prefix `<repository>/<pool>`, and the worker a rework goes back to.
|
|
1011
|
+
*/
|
|
1012
|
+
function poolParams(
|
|
1013
|
+
prompt: string,
|
|
1014
|
+
worktree: string,
|
|
1015
|
+
repository: RepositoryData,
|
|
1016
|
+
settings: DevSettings,
|
|
1017
|
+
worker: string | undefined,
|
|
1018
|
+
resumeSession: string | undefined,
|
|
1019
|
+
inbox: unknown,
|
|
1020
|
+
holder: string,
|
|
1021
|
+
stage?: {
|
|
1022
|
+
readonly use?: string | undefined;
|
|
1023
|
+
readonly args?: readonly string[] | undefined;
|
|
1024
|
+
readonly pool?: string | undefined;
|
|
1025
|
+
},
|
|
1026
|
+
): Record<string, unknown> {
|
|
1027
|
+
const pool = stage?.pool ?? DEFAULT_POOL;
|
|
1028
|
+
const resolved = resolvePool(settings.workers, pool);
|
|
1029
|
+
// A stage may name its own harness step or arguments. A named step runs as
|
|
1030
|
+
// one worker; arguments alone replace the pool's.
|
|
1031
|
+
const workers: readonly WorkerDefinition[] =
|
|
1032
|
+
stage?.use === undefined
|
|
1033
|
+
? stage?.args === undefined
|
|
1034
|
+
? resolved.workers
|
|
1035
|
+
: resolved.workers.map((item) => ({ ...item, args: stage.args as readonly string[] }))
|
|
1036
|
+
: [{ name: "flow", use: stage.use, args: stage.args ?? [], count: 1 }];
|
|
1037
|
+
// A fallback worker that ran is not a member of the pool; hand it over as
|
|
1038
|
+
// one so pool/agent can be asked for it by name.
|
|
1039
|
+
const fallback =
|
|
1040
|
+
worker === undefined || workers.some((item) => item.name === worker)
|
|
1041
|
+
? undefined
|
|
1042
|
+
: resolved.fallbacks.find((item) => item.name === worker);
|
|
1043
|
+
return {
|
|
1044
|
+
prompt,
|
|
1045
|
+
cwd: worktree,
|
|
1046
|
+
inbox,
|
|
1047
|
+
prefix: `${repository.name}/${pool}`,
|
|
1048
|
+
// A worker shared by two pools has one count: the claim ignores the pool.
|
|
1049
|
+
countPrefix: repository.name,
|
|
1050
|
+
holder,
|
|
1051
|
+
workers: fallback === undefined ? workers : [...workers, fallback],
|
|
1052
|
+
fallbacks: resolved.fallbacks,
|
|
1053
|
+
...(worker === undefined ? {} : { worker }),
|
|
1054
|
+
...(worker !== undefined && resumeSession !== undefined ? { resumeSession } : {}),
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/** The harness overrides a work stage wrote in its params. */
|
|
1059
|
+
function stageParamsOf(params: unknown): {
|
|
1060
|
+
readonly use?: string | undefined;
|
|
1061
|
+
readonly args?: readonly string[] | undefined;
|
|
1062
|
+
readonly pool?: string | undefined;
|
|
1063
|
+
} {
|
|
1064
|
+
const given = (params ?? {}) as {
|
|
1065
|
+
readonly flowUse?: unknown;
|
|
1066
|
+
readonly flowArgs?: unknown;
|
|
1067
|
+
readonly flowPool?: unknown;
|
|
1068
|
+
};
|
|
1069
|
+
const pool = typeof given.flowPool === "string" ? given.flowPool : undefined;
|
|
1070
|
+
const use = typeof given.flowUse === "string" ? given.flowUse : undefined;
|
|
1071
|
+
const args =
|
|
1072
|
+
Array.isArray(given.flowArgs) &&
|
|
1073
|
+
given.flowArgs.every((item): item is string => typeof item === "string")
|
|
1074
|
+
? given.flowArgs
|
|
1075
|
+
: undefined;
|
|
1076
|
+
return {
|
|
1077
|
+
...(use === undefined ? {} : { use }),
|
|
1078
|
+
...(args === undefined ? {} : { args }),
|
|
1079
|
+
...(pool === undefined ? {} : { pool }),
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
/** The preparation a work stage asks for before its attempt. */
|
|
1084
|
+
type BeforeAttempt = "merge-main" | "none";
|
|
1085
|
+
|
|
1086
|
+
function beforeAttemptOf(params: unknown): BeforeAttempt | undefined {
|
|
1087
|
+
const given = ((params ?? {}) as { readonly beforeAttempt?: unknown }).beforeAttempt;
|
|
1088
|
+
return given === "merge-main" || given === "none" ? given : undefined;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
/** The history line of a work run: `claude`, or `pi (fallback from claude)`. */
|
|
1092
|
+
function workLine(attempt: TaskAttempt): string {
|
|
1093
|
+
const base = `work: ${String(attempt.worker)}`;
|
|
1094
|
+
const from = attempt.fallbackFrom;
|
|
1095
|
+
const changed = attempt.workerChanged;
|
|
1096
|
+
return [
|
|
1097
|
+
typeof from === "string" ? `${base} (fallback from ${from})` : base,
|
|
1098
|
+
typeof changed === "string" ? `; ${changed} is no longer in the pool` : "",
|
|
1099
|
+
].join("");
|
|
1100
|
+
}
|
|
1101
|
+
|
|
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
|
+
/** The lines of a step's `stderr` data, which may be a string or a list. */
|
|
1112
|
+
function stderrLines(value: unknown): readonly string[] {
|
|
1113
|
+
if (typeof value === "string") return [value];
|
|
1114
|
+
return Array.isArray(value)
|
|
1115
|
+
? value.filter((line): line is string => typeof line === "string")
|
|
1116
|
+
: [];
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/** True when the attempt's verify passed on exactly `head`. */
|
|
1120
|
+
function passedAt(attempt: TaskAttempt | undefined, head: string | null): boolean {
|
|
1121
|
+
return (
|
|
1122
|
+
head !== null &&
|
|
1123
|
+
attempt?.verified === head &&
|
|
1124
|
+
attempt.verify?.result === "pass"
|
|
1125
|
+
);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
const UNCHECKED_WORK_NOTE = "the branch already has unchecked work; checking it";
|
|
1129
|
+
|
|
1130
|
+
/** True when the branch holds commits of its own (not a merge of main) that main lacks and `head` never passed verify. */
|
|
1131
|
+
function hasUncheckedWork(
|
|
1132
|
+
path: string,
|
|
1133
|
+
head: string,
|
|
1134
|
+
attempt: TaskAttempt,
|
|
1135
|
+
context: { readonly settings: { readonly remote: string; readonly mainBranch: string } },
|
|
1136
|
+
): boolean {
|
|
1137
|
+
if (attempt.verified === head && attempt.verify?.result === "pass") return false;
|
|
1138
|
+
const mainRef = `${context.settings.remote}/${context.settings.mainBranch}`;
|
|
1139
|
+
const ahead = git(path, ["rev-list", "--count", "--no-merges", `${mainRef}..${head}`]);
|
|
1140
|
+
return ahead.ok && Number(ahead.out) > 0;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
export async function runWork(ctx: StepContext): Promise<PluginStepResult> {
|
|
1144
|
+
const loose = await looseTaskContext(ctx);
|
|
1145
|
+
if (!claimAllows(ctx, loose.task)) return cancelledStep();
|
|
1146
|
+
if (loose.settings === undefined) {
|
|
1147
|
+
// Not the task's fault: record why, and the flow retries once.
|
|
1148
|
+
const message = loose.settingsError ?? "the settings could not be read";
|
|
1149
|
+
const written = await saveTaskGuarded(
|
|
1150
|
+
ctx,
|
|
1151
|
+
loose.taskKey,
|
|
1152
|
+
{
|
|
1153
|
+
...loose.task,
|
|
1154
|
+
stop: {
|
|
1155
|
+
step: "work",
|
|
1156
|
+
result: "failed",
|
|
1157
|
+
reason: STOP_REASONS.settingsUnreadable,
|
|
1158
|
+
},
|
|
1159
|
+
},
|
|
1160
|
+
"dev:work",
|
|
1161
|
+
);
|
|
1162
|
+
if (!written) return cancelledStep();
|
|
1163
|
+
return {
|
|
1164
|
+
result: "failed",
|
|
1165
|
+
data: { reason: STOP_REASONS.settingsUnreadable, message },
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
const context: TaskContext = { ...loose, settings: loose.settings };
|
|
1169
|
+
const task = context.task;
|
|
1170
|
+
const path =
|
|
1171
|
+
task.attempt?.worktree ??
|
|
1172
|
+
worktreePath(context.repository.path, context.settings, context.workName);
|
|
1173
|
+
const branch = task.attempt?.branch ?? workBranch(context.workName);
|
|
1174
|
+
const attempt: TaskAttempt = task.attempt ?? {
|
|
1175
|
+
number: Math.max(task.attempts, 0) + 1,
|
|
1176
|
+
run: ctx.runId,
|
|
1177
|
+
};
|
|
1178
|
+
const attempts = Math.max(task.attempts, attempt.number);
|
|
1179
|
+
const base = attempt.base ?? headOf(path) ?? null;
|
|
1180
|
+
|
|
1181
|
+
if (!existsSync(path) || !isWorktree(path)) {
|
|
1182
|
+
const nextAttempt: TaskAttempt = {
|
|
1183
|
+
...attempt,
|
|
1184
|
+
run: ctx.runId,
|
|
1185
|
+
worktree: path,
|
|
1186
|
+
branch,
|
|
1187
|
+
base,
|
|
1188
|
+
result: "failed",
|
|
1189
|
+
worked: true,
|
|
1190
|
+
};
|
|
1191
|
+
const written = await saveTaskGuarded(
|
|
1192
|
+
ctx,
|
|
1193
|
+
context.taskKey,
|
|
1194
|
+
{
|
|
1195
|
+
...task,
|
|
1196
|
+
phase: "waiting",
|
|
1197
|
+
run: ctx.runId,
|
|
1198
|
+
attempts,
|
|
1199
|
+
attempt: nextAttempt,
|
|
1200
|
+
},
|
|
1201
|
+
"dev:work",
|
|
1202
|
+
);
|
|
1203
|
+
if (!written) return cancelledStep();
|
|
1204
|
+
return {
|
|
1205
|
+
result: "failed",
|
|
1206
|
+
data: resultData(nextAttempt, harnessReading({}), {
|
|
1207
|
+
reason: "no_worktree",
|
|
1208
|
+
message: `no worktree at ${path}; run the worktree step first`,
|
|
1209
|
+
}),
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
if (beforeAttemptOf(ctx.params) === "merge-main") {
|
|
1214
|
+
const remote = context.settings.remote;
|
|
1215
|
+
const mainRef = `${remote}/${context.settings.mainBranch}`;
|
|
1216
|
+
const failBefore = async (message: string): Promise<PluginStepResult> => {
|
|
1217
|
+
const nextAttempt: TaskAttempt = {
|
|
1218
|
+
...attempt,
|
|
1219
|
+
run: ctx.runId,
|
|
1220
|
+
worktree: path,
|
|
1221
|
+
branch,
|
|
1222
|
+
base,
|
|
1223
|
+
result: "failed",
|
|
1224
|
+
worked: true,
|
|
1225
|
+
};
|
|
1226
|
+
const written = await saveTaskGuarded(
|
|
1227
|
+
ctx,
|
|
1228
|
+
context.taskKey,
|
|
1229
|
+
{
|
|
1230
|
+
...task,
|
|
1231
|
+
phase: "waiting",
|
|
1232
|
+
run: ctx.runId,
|
|
1233
|
+
attempts,
|
|
1234
|
+
attempt: nextAttempt,
|
|
1235
|
+
},
|
|
1236
|
+
"dev:work",
|
|
1237
|
+
);
|
|
1238
|
+
if (!written) return cancelledStep();
|
|
1239
|
+
return {
|
|
1240
|
+
result: "failed",
|
|
1241
|
+
data: resultData(nextAttempt, harnessReading({}), {
|
|
1242
|
+
reason: "before_attempt",
|
|
1243
|
+
message,
|
|
1244
|
+
}),
|
|
1245
|
+
};
|
|
1246
|
+
};
|
|
1247
|
+
const fetch = git(context.repository.path, ["fetch", "--prune", remote]);
|
|
1248
|
+
if (!fetch.ok) {
|
|
1249
|
+
return failBefore(
|
|
1250
|
+
`cannot fetch "${remote}": ${fetch.err || fetch.out || "git fetch failed"}`,
|
|
1251
|
+
);
|
|
1252
|
+
}
|
|
1253
|
+
const prepared = mergeLatest(path, mainRef);
|
|
1254
|
+
if (prepared.kind === "failed") {
|
|
1255
|
+
return failBefore(prepared.message ?? `cannot merge "${mainRef}"`);
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
const stageParams = (ctx.params ?? {}) as {
|
|
1260
|
+
readonly flowWorkerBrief?: unknown;
|
|
1261
|
+
readonly flowCommit?: unknown;
|
|
1262
|
+
};
|
|
1263
|
+
const workerBrief = await readWorkerBrief(
|
|
1264
|
+
context.repository.path,
|
|
1265
|
+
context.settings,
|
|
1266
|
+
typeof stageParams.flowWorkerBrief === "string" ? stageParams.flowWorkerBrief : undefined,
|
|
1267
|
+
);
|
|
1268
|
+
const prompt = buildWorkerPrompt(
|
|
1269
|
+
path,
|
|
1270
|
+
workerBrief,
|
|
1271
|
+
task,
|
|
1272
|
+
progressOf(attempt.previousProgress),
|
|
1273
|
+
);
|
|
1274
|
+
const stageBrief = (() => {
|
|
1275
|
+
const given = ((ctx.params ?? {}) as { readonly flowBrief?: unknown }).flowBrief;
|
|
1276
|
+
return typeof given === "string" && given.trim().length > 0 ? given.trim() : undefined;
|
|
1277
|
+
})();
|
|
1278
|
+
const finalPrompt =
|
|
1279
|
+
stageBrief === undefined ? prompt : `${prompt}\n\n${stageBrief}`;
|
|
1280
|
+
// A note from an earlier visit is in the task's data by now; the worker
|
|
1281
|
+
// writes a fresh one.
|
|
1282
|
+
rmSync(join(path, PROGRESS_FILE), { force: true });
|
|
1283
|
+
const runStep = ctx.runStep;
|
|
1284
|
+
if (runStep === undefined) {
|
|
1285
|
+
const nextAttempt: TaskAttempt = {
|
|
1286
|
+
...attempt,
|
|
1287
|
+
run: ctx.runId,
|
|
1288
|
+
worktree: path,
|
|
1289
|
+
branch,
|
|
1290
|
+
base,
|
|
1291
|
+
result: "failed",
|
|
1292
|
+
worked: true,
|
|
1293
|
+
};
|
|
1294
|
+
const written = await saveTaskGuarded(
|
|
1295
|
+
ctx,
|
|
1296
|
+
context.taskKey,
|
|
1297
|
+
{
|
|
1298
|
+
...task,
|
|
1299
|
+
phase: "waiting",
|
|
1300
|
+
run: ctx.runId,
|
|
1301
|
+
attempts,
|
|
1302
|
+
attempt: nextAttempt,
|
|
1303
|
+
},
|
|
1304
|
+
"dev:work",
|
|
1305
|
+
);
|
|
1306
|
+
if (!written) return cancelledStep();
|
|
1307
|
+
return {
|
|
1308
|
+
result: "failed",
|
|
1309
|
+
data: resultData(nextAttempt, harnessReading({}), {
|
|
1310
|
+
reason: "no_host",
|
|
1311
|
+
message: "the kernel did not offer a way to run the configured harness step",
|
|
1312
|
+
}),
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
// The step stops the worker itself a little before its time limit, so it
|
|
1317
|
+
// can still commit what is left; the kernel's own timeout stays behind it.
|
|
1318
|
+
const stopper = new AbortController();
|
|
1319
|
+
const forwardAbort = (): void => stopper.abort();
|
|
1320
|
+
if (ctx.signal.aborted) stopper.abort();
|
|
1321
|
+
else ctx.signal.addEventListener("abort", forwardAbort, { once: true });
|
|
1322
|
+
const options: StepRunOptions = {
|
|
1323
|
+
runId: ctx.runId,
|
|
1324
|
+
cwd: path,
|
|
1325
|
+
...(ctx.object === undefined ? {} : { object: ctx.object }),
|
|
1326
|
+
params: ctx.params,
|
|
1327
|
+
access: ctx.access,
|
|
1328
|
+
...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
|
|
1329
|
+
signal: stopper.signal,
|
|
1330
|
+
};
|
|
1331
|
+
// A rework or reject goes back to the worker that ran the attempt before,
|
|
1332
|
+
// and resumes its session when the harness can. When that worker is no
|
|
1333
|
+
// longer in the pool, any free worker takes it and the change is recorded.
|
|
1334
|
+
const stagePool = stageParamsOf(ctx.params).pool ?? DEFAULT_POOL;
|
|
1335
|
+
const before =
|
|
1336
|
+
typeof attempt.previousWorker === "string" && attempt.previousWorker.length > 0
|
|
1337
|
+
? attempt.previousWorker
|
|
1338
|
+
: undefined;
|
|
1339
|
+
const stillThere =
|
|
1340
|
+
before !== undefined &&
|
|
1341
|
+
(() => {
|
|
1342
|
+
try {
|
|
1343
|
+
const resolved = resolvePool(context.settings.workers, stagePool);
|
|
1344
|
+
return [...resolved.workers, ...resolved.fallbacks].some(
|
|
1345
|
+
(worker) => worker.name === before,
|
|
1346
|
+
);
|
|
1347
|
+
} catch {
|
|
1348
|
+
return false;
|
|
1349
|
+
}
|
|
1350
|
+
})();
|
|
1351
|
+
const asked = stillThere ? before : undefined;
|
|
1352
|
+
const workerChangedFrom = before !== undefined && !stillThere ? before : undefined;
|
|
1353
|
+
const clock = stepTestHooks.workClock ?? realWorkClock;
|
|
1354
|
+
let timedOut = false;
|
|
1355
|
+
const timeOut = (): void => {
|
|
1356
|
+
timedOut = true;
|
|
1357
|
+
stopper.abort();
|
|
1358
|
+
};
|
|
1359
|
+
// The step's own limit is the backstop, counted from the step's start. A
|
|
1360
|
+
// harness that can take a message says when its run begins and how long it
|
|
1361
|
+
// may run (its wall time, which starts after the pool gave it a place), and
|
|
1362
|
+
// the wrap-up and the stop are timed from then.
|
|
1363
|
+
let limitMs = STEP_TIMEOUT_SECS * 1000;
|
|
1364
|
+
const timers: unknown[] = [
|
|
1365
|
+
clock.setTimeout(timeOut, limitMs - limitMarginMs(limitMs)),
|
|
1366
|
+
];
|
|
1367
|
+
let runTimers: unknown[] = [];
|
|
1368
|
+
const outbox = createOutbox((runMs) => {
|
|
1369
|
+
workerStarted();
|
|
1370
|
+
for (const timer of runTimers) clock.clearTimeout(timer);
|
|
1371
|
+
limitMs = runMs;
|
|
1372
|
+
const hardMs = runMs - limitMarginMs(runMs);
|
|
1373
|
+
const wrapMs = Math.min(
|
|
1374
|
+
Math.floor(runMs * context.settings.work.wrapUpAt),
|
|
1375
|
+
hardMs,
|
|
1376
|
+
);
|
|
1377
|
+
runTimers = [
|
|
1378
|
+
clock.setTimeout(() => outbox.send(wrapUpMessage()), wrapMs),
|
|
1379
|
+
clock.setTimeout(timeOut, hardMs),
|
|
1380
|
+
];
|
|
1381
|
+
});
|
|
1382
|
+
let outcome: PluginStepResult | undefined;
|
|
1383
|
+
let hostError: string | undefined;
|
|
1384
|
+
let notLoaded: string | undefined;
|
|
1385
|
+
// While the step waits for a worker, the task says what it waits for and who
|
|
1386
|
+
// holds it, in the row and in the step log. A rework waits for the worker it
|
|
1387
|
+
// asked for; any other attempt waits for the workers of the pool.
|
|
1388
|
+
let waitingFor: string | undefined;
|
|
1389
|
+
const setWorkerWait = async (text: string | null): Promise<void> => {
|
|
1390
|
+
await saveTaskGuarded(
|
|
1391
|
+
ctx,
|
|
1392
|
+
context.taskKey,
|
|
1393
|
+
{ ...task, attempt: { ...attempt, workerWait: text } },
|
|
1394
|
+
"dev:work-wait",
|
|
1395
|
+
);
|
|
1396
|
+
stepTestHooks.afterWorkerWait?.(text);
|
|
1397
|
+
};
|
|
1398
|
+
const onPoolEvent = async (_plugin: string, event: StepEvent): Promise<void> => {
|
|
1399
|
+
const data: unknown = event.data;
|
|
1400
|
+
if (event.type === WAITING_EVENT) {
|
|
1401
|
+
const entries = Array.isArray((data as { workers?: unknown } | undefined)?.workers)
|
|
1402
|
+
? ((data as { workers: unknown[] }).workers)
|
|
1403
|
+
: [];
|
|
1404
|
+
const mine = entries.filter(
|
|
1405
|
+
(entry): entry is { worker?: unknown; holders?: unknown } =>
|
|
1406
|
+
typeof entry === "object" &&
|
|
1407
|
+
entry !== null &&
|
|
1408
|
+
(asked === undefined || (entry as { worker?: unknown }).worker === asked),
|
|
1409
|
+
);
|
|
1410
|
+
const names = mine.flatMap((entry) =>
|
|
1411
|
+
typeof entry.worker === "string" ? [entry.worker] : [],
|
|
1412
|
+
);
|
|
1413
|
+
const holders = [
|
|
1414
|
+
...new Set(
|
|
1415
|
+
mine.flatMap((entry) =>
|
|
1416
|
+
Array.isArray(entry.holders)
|
|
1417
|
+
? entry.holders.filter((item): item is string => typeof item === "string")
|
|
1418
|
+
: [],
|
|
1419
|
+
),
|
|
1420
|
+
),
|
|
1421
|
+
];
|
|
1422
|
+
const line = `waiting for worker ${asked ?? names.join(" or ")}${
|
|
1423
|
+
stagePool === DEFAULT_POOL ? "" : ` in pool ${stagePool}`
|
|
1424
|
+
}${
|
|
1425
|
+
holders.length === 0 ? "" : `: held by ${holders.join(", ")}`
|
|
1426
|
+
}`;
|
|
1427
|
+
waitingFor = line;
|
|
1428
|
+
await ctx.logger.write(line);
|
|
1429
|
+
await setWorkerWait(line);
|
|
1430
|
+
} else if (event.type === ACQUIRED_EVENT && waitingFor !== undefined) {
|
|
1431
|
+
waitingFor = undefined;
|
|
1432
|
+
const worker = (data as { worker?: unknown } | undefined)?.worker;
|
|
1433
|
+
const name = asked ?? (typeof worker === "string" ? worker : undefined);
|
|
1434
|
+
await ctx.logger.write(
|
|
1435
|
+
`${name === undefined ? "a worker" : `worker ${name}`} is free; the work starts`,
|
|
1436
|
+
);
|
|
1437
|
+
await setWorkerWait(null);
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
// A worker that has its place holds it against every other task that needs
|
|
1441
|
+
// that worker. When its program is not running a little after the place was
|
|
1442
|
+
// given, the task says so rather than looking like it works.
|
|
1443
|
+
const startClock = stepTestHooks.workerStartClock ?? realWorkClock;
|
|
1444
|
+
let startTimer: unknown;
|
|
1445
|
+
let started = false;
|
|
1446
|
+
let notStarted: string | undefined;
|
|
1447
|
+
// The notes are written one after another, and none after the step is over:
|
|
1448
|
+
// the step's own final save must be the last write to the task.
|
|
1449
|
+
let sayClosed = false;
|
|
1450
|
+
let sayChain: Promise<void> = Promise.resolve();
|
|
1451
|
+
const say = (line: string, wait: string | null): void => {
|
|
1452
|
+
sayChain = sayChain.then(async () => {
|
|
1453
|
+
if (sayClosed) return;
|
|
1454
|
+
await ctx.logger.write(line);
|
|
1455
|
+
if (sayClosed) return;
|
|
1456
|
+
await setWorkerWait(wait);
|
|
1457
|
+
}).catch(() => undefined);
|
|
1458
|
+
};
|
|
1459
|
+
const workerPlaced = (name: string): void => {
|
|
1460
|
+
if (started) return;
|
|
1461
|
+
startTimer = startClock.setTimeout(() => {
|
|
1462
|
+
if (started) return;
|
|
1463
|
+
const line = `worker ${name} has had its place for ${Math.round(WORKER_START_GRACE_MS / 60_000)} minutes and has not started`;
|
|
1464
|
+
notStarted = line;
|
|
1465
|
+
say(line, line);
|
|
1466
|
+
}, WORKER_START_GRACE_MS);
|
|
1467
|
+
};
|
|
1468
|
+
const workerStarted = (): void => {
|
|
1469
|
+
if (started) return;
|
|
1470
|
+
started = true;
|
|
1471
|
+
if (startTimer !== undefined) startClock.clearTimeout(startTimer);
|
|
1472
|
+
if (notStarted !== undefined) {
|
|
1473
|
+
notStarted = undefined;
|
|
1474
|
+
say("the worker started", null);
|
|
1475
|
+
}
|
|
1476
|
+
};
|
|
1477
|
+
try {
|
|
1478
|
+
outcome = await withWorkerReports(
|
|
1479
|
+
{ placed: workerPlaced, started: workerStarted },
|
|
1480
|
+
() =>
|
|
1481
|
+
runStep(
|
|
1482
|
+
"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
|
+
),
|
|
1494
|
+
{ ...options, observe: onPoolEvent },
|
|
1495
|
+
),
|
|
1496
|
+
);
|
|
1497
|
+
} catch (error) {
|
|
1498
|
+
hostError = messageOf(error);
|
|
1499
|
+
notLoaded = notLoadedStep(error);
|
|
1500
|
+
} finally {
|
|
1501
|
+
if (startTimer !== undefined) startClock.clearTimeout(startTimer);
|
|
1502
|
+
sayClosed = true;
|
|
1503
|
+
await sayChain;
|
|
1504
|
+
if (waitingFor !== undefined) {
|
|
1505
|
+
waitingFor = undefined;
|
|
1506
|
+
await ctx.logger.write(`stopped waiting for ${asked === undefined ? "a worker" : `worker ${asked}`}`).catch(() => undefined);
|
|
1507
|
+
}
|
|
1508
|
+
for (const timer of [...timers, ...runTimers]) clock.clearTimeout(timer);
|
|
1509
|
+
ctx.signal.removeEventListener("abort", forwardAbort);
|
|
1510
|
+
}
|
|
1511
|
+
const outcomeData =
|
|
1512
|
+
outcome !== undefined &&
|
|
1513
|
+
typeof outcome.data === "object" &&
|
|
1514
|
+
outcome.data !== null
|
|
1515
|
+
? (outcome.data as Record<string, unknown>)
|
|
1516
|
+
: {};
|
|
1517
|
+
const reading = harnessReading(outcomeData, (problem) => {
|
|
1518
|
+
// A usage the harness got wrong is the harness's bug; say which run.
|
|
1519
|
+
void ctx.logger
|
|
1520
|
+
.write(`run ${ctx.runId}: the harness reported a usage that is not standard: ${problem}`)
|
|
1521
|
+
.catch(() => undefined);
|
|
1522
|
+
});
|
|
1523
|
+
|
|
1524
|
+
let nextAttempt: TaskAttempt = {
|
|
1525
|
+
...attempt,
|
|
1526
|
+
run: ctx.runId,
|
|
1527
|
+
worktree: path,
|
|
1528
|
+
branch,
|
|
1529
|
+
base,
|
|
1530
|
+
sessionId: reading.sessionId,
|
|
1531
|
+
cost: reading.cost,
|
|
1532
|
+
costMicros: reading.costMicros,
|
|
1533
|
+
costQuality: reading.costQuality,
|
|
1534
|
+
workLog: reading.log,
|
|
1535
|
+
tokens: reading.tokens,
|
|
1536
|
+
workMs: reading.durationMs,
|
|
1537
|
+
finalMessage: reading.finalMessage,
|
|
1538
|
+
worked: true,
|
|
1539
|
+
// The worker the pool ran, so the next attempt can ask for it again.
|
|
1540
|
+
worker: typeof outcomeData.worker === "string" ? outcomeData.worker : null,
|
|
1541
|
+
fallbackFrom:
|
|
1542
|
+
typeof outcomeData.fallbackFrom === "string" ? outcomeData.fallbackFrom : null,
|
|
1543
|
+
workerChanged: workerChangedFrom ?? null,
|
|
1544
|
+
};
|
|
1545
|
+
|
|
1546
|
+
// The worker ran past its limit: the step stopped it, or the harness's own
|
|
1547
|
+
// wall time did.
|
|
1548
|
+
const timedOutRun =
|
|
1549
|
+
outcome?.result !== "done" &&
|
|
1550
|
+
(timedOut ||
|
|
1551
|
+
(outcomeData.reason === "wall" && hostError === undefined));
|
|
1552
|
+
|
|
1553
|
+
const finish = async (
|
|
1554
|
+
result: string,
|
|
1555
|
+
extra: Readonly<Record<string, unknown>>,
|
|
1556
|
+
waitsForModel = false,
|
|
1557
|
+
): Promise<PluginStepResult> => {
|
|
1558
|
+
const note = readNote(path);
|
|
1559
|
+
const progress: Progress | undefined =
|
|
1560
|
+
note === null && !timedOutRun
|
|
1561
|
+
? undefined
|
|
1562
|
+
: { note, commits: commitsSince(path, base), timedOut: timedOutRun };
|
|
1563
|
+
nextAttempt = {
|
|
1564
|
+
...nextAttempt,
|
|
1565
|
+
result,
|
|
1566
|
+
workNote:
|
|
1567
|
+
result !== "done" && typeof extra.message === "string" ? extra.message : null,
|
|
1568
|
+
...(waitsForModel ? {} : { workRetryAt: null }),
|
|
1569
|
+
// An attempt that left no note keeps the one before it for later attempts.
|
|
1570
|
+
progress: progress ?? progressOf(attempt.previousProgress) ?? null,
|
|
1571
|
+
workTimedOut: timedOutRun,
|
|
1572
|
+
// A commit the worker made after the last verify has no result yet; the
|
|
1573
|
+
// verify before it must not stand for it, not even in the same run.
|
|
1574
|
+
...(typeof extra.head === "string" && attempt.verified !== extra.head
|
|
1575
|
+
? { verified: null, verify: null, review: null }
|
|
1576
|
+
: {}),
|
|
1577
|
+
};
|
|
1578
|
+
const reason = typeof extra.reason === "string" ? extra.reason : "";
|
|
1579
|
+
const stop: StopRecord | null =
|
|
1580
|
+
result === "failed"
|
|
1581
|
+
? {
|
|
1582
|
+
step: "work",
|
|
1583
|
+
result,
|
|
1584
|
+
reason,
|
|
1585
|
+
...(typeof extra.use === "string" ? { use: extra.use } : {}),
|
|
1586
|
+
}
|
|
1587
|
+
: null;
|
|
1588
|
+
// A failure outside the task's work is retried by the flow, not by a person.
|
|
1589
|
+
const retried =
|
|
1590
|
+
stop !== null &&
|
|
1591
|
+
classifyStop({ step: "work", result, reason, use: stop.use }).kind ===
|
|
1592
|
+
"environment";
|
|
1593
|
+
const written = await saveTaskGuarded(
|
|
1594
|
+
ctx,
|
|
1595
|
+
context.taskKey,
|
|
1596
|
+
{
|
|
1597
|
+
...task,
|
|
1598
|
+
stop,
|
|
1599
|
+
// Only `done` continues to the gate; every other result goes to the
|
|
1600
|
+
// person wait, and the task says so while it waits. A model that is
|
|
1601
|
+
// unavailable is not a person's business: the work step runs again.
|
|
1602
|
+
phase:
|
|
1603
|
+
result === "done" || waitsForModel || retried ? "running" : "waiting",
|
|
1604
|
+
run: ctx.runId,
|
|
1605
|
+
attempts,
|
|
1606
|
+
attempt: nextAttempt,
|
|
1607
|
+
...(reading.cost === null
|
|
1608
|
+
? {}
|
|
1609
|
+
: { cost: reading.cost, costQuality: reading.costQuality }),
|
|
1610
|
+
},
|
|
1611
|
+
"dev:work",
|
|
1612
|
+
);
|
|
1613
|
+
if (!written) return cancelledStep();
|
|
1614
|
+
return {
|
|
1615
|
+
result,
|
|
1616
|
+
data: resultData(nextAttempt, reading, {
|
|
1617
|
+
worktree: path,
|
|
1618
|
+
path,
|
|
1619
|
+
branch,
|
|
1620
|
+
base,
|
|
1621
|
+
prompt,
|
|
1622
|
+
...(progress === undefined
|
|
1623
|
+
? {}
|
|
1624
|
+
: { progress: progress.note, commits: progress.commits }),
|
|
1625
|
+
...(nextAttempt.worker === null || nextAttempt.worker === undefined
|
|
1626
|
+
? {}
|
|
1627
|
+
: {
|
|
1628
|
+
work: workLine(nextAttempt),
|
|
1629
|
+
worker: nextAttempt.worker,
|
|
1630
|
+
...(typeof nextAttempt.fallbackFrom === "string"
|
|
1631
|
+
? { fallbackFrom: nextAttempt.fallbackFrom }
|
|
1632
|
+
: {}),
|
|
1633
|
+
}),
|
|
1634
|
+
...extra,
|
|
1635
|
+
}),
|
|
1636
|
+
};
|
|
1637
|
+
};
|
|
1638
|
+
|
|
1639
|
+
untrackNote(path);
|
|
1640
|
+
if (timedOutRun) {
|
|
1641
|
+
const committed = commitWip(path);
|
|
1642
|
+
const left = changedFiles(path);
|
|
1643
|
+
const seconds = Math.round(limitMs / 1000);
|
|
1644
|
+
return finish("failed", {
|
|
1645
|
+
reason: "timeout",
|
|
1646
|
+
message: `the work ran out of time (${seconds}s); ${
|
|
1647
|
+
committed
|
|
1648
|
+
? "what it left was committed as work in progress"
|
|
1649
|
+
: left.length === 0
|
|
1650
|
+
? "nothing was left uncommitted"
|
|
1651
|
+
: `uncommitted changes: ${left.join(", ")}`
|
|
1652
|
+
}`,
|
|
1653
|
+
...(left.length === 0 ? {} : { files: left }),
|
|
1654
|
+
});
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
// Inspect the tree before deciding: a harness failure must still name what
|
|
1658
|
+
// it left uncommitted, and a success must still fail on a dirty tree.
|
|
1659
|
+
let dirty = changedFiles(path);
|
|
1660
|
+
|
|
1661
|
+
// A worker whose sandbox cannot write .git leaves its work uncommitted; the
|
|
1662
|
+
// stage asks dev to commit it, before verify so the check sees the commit.
|
|
1663
|
+
if (
|
|
1664
|
+
stageParams.flowCommit === true &&
|
|
1665
|
+
hostError === undefined &&
|
|
1666
|
+
outcome?.result === "done" &&
|
|
1667
|
+
dirty.length > 0
|
|
1668
|
+
) {
|
|
1669
|
+
commitLeft(path, `${context.taskId}: ${task.title}`);
|
|
1670
|
+
dirty = changedFiles(path);
|
|
1671
|
+
}
|
|
1672
|
+
|
|
1673
|
+
if (hostError !== undefined) {
|
|
1674
|
+
return finish("failed", {
|
|
1675
|
+
reason:
|
|
1676
|
+
notLoaded !== undefined
|
|
1677
|
+
? STOP_REASONS.stepNotLoaded
|
|
1678
|
+
: isConnectionError(hostError)
|
|
1679
|
+
? STOP_REASONS.connection
|
|
1680
|
+
: "harness",
|
|
1681
|
+
...(notLoaded === undefined ? {} : { use: notLoaded }),
|
|
1682
|
+
message: hostError,
|
|
1683
|
+
...(dirty.length === 0 ? {} : { files: dirty }),
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
if (outcome !== undefined && outcome.result !== "done") {
|
|
1688
|
+
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;
|
|
1691
|
+
nextAttempt = { ...nextAttempt, workWaits: waits + 1, workRetryAt: retryAt };
|
|
1692
|
+
return finish(
|
|
1693
|
+
"unavailable",
|
|
1694
|
+
{
|
|
1695
|
+
reason: "model_unavailable",
|
|
1696
|
+
message: `the worker's model was unavailable; the work runs again at ${new Date(retryAt).toISOString()}`,
|
|
1697
|
+
retryAt,
|
|
1698
|
+
...(dirty.length === 0 ? {} : { files: dirty }),
|
|
1699
|
+
},
|
|
1700
|
+
true,
|
|
1701
|
+
);
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
if (outcome === undefined || outcome.result !== "done") {
|
|
1706
|
+
const message =
|
|
1707
|
+
typeof outcomeData.message === "string"
|
|
1708
|
+
? outcomeData.message
|
|
1709
|
+
: `the harness step ended "${outcome?.result ?? "unknown"}"`;
|
|
1710
|
+
// A harness that was stopped, or killed by a signal no cancel sent, says
|
|
1711
|
+
// nothing about the work.
|
|
1712
|
+
const stopped =
|
|
1713
|
+
outcome?.result === "interrupted" &&
|
|
1714
|
+
(outcomeData.reason === "signal" || outcomeData.reason === "cancelled");
|
|
1715
|
+
return finish("failed", {
|
|
1716
|
+
reason: stopped
|
|
1717
|
+
? STOP_REASONS.stopped
|
|
1718
|
+
: isConnectionError(message, ...stderrLines(outcomeData.stderr))
|
|
1719
|
+
? STOP_REASONS.connection
|
|
1720
|
+
: "harness",
|
|
1721
|
+
harnessResult: outcome?.result ?? "unknown",
|
|
1722
|
+
// A failed attempt still reports the files it left behind.
|
|
1723
|
+
message:
|
|
1724
|
+
dirty.length === 0
|
|
1725
|
+
? message
|
|
1726
|
+
: `${message}; uncommitted changes: ${dirty.join(", ")}`,
|
|
1727
|
+
...(dirty.length === 0 ? {} : { files: dirty }),
|
|
1728
|
+
stderr: outcomeData.stderr ?? [],
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
if (dirty.length > 0) {
|
|
1733
|
+
return finish("failed", {
|
|
1734
|
+
reason: "changes",
|
|
1735
|
+
files: dirty,
|
|
1736
|
+
message: `uncommitted changes: ${dirty.join(", ")}`,
|
|
1737
|
+
});
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
const head = headOf(path);
|
|
1741
|
+
let note: string | undefined;
|
|
1742
|
+
if (
|
|
1743
|
+
head === undefined ||
|
|
1744
|
+
base === null ||
|
|
1745
|
+
head === base ||
|
|
1746
|
+
// A reset below the base, or to unrelated history, is not new work: the
|
|
1747
|
+
// branch must still descend from the base before anything is pushed.
|
|
1748
|
+
!isAncestor(path, base, head)
|
|
1749
|
+
) {
|
|
1750
|
+
if (head !== undefined && head === base && hasUncheckedWork(path, head, attempt, context)) {
|
|
1751
|
+
// An earlier run committed this work and stopped before verify ended.
|
|
1752
|
+
note = UNCHECKED_WORK_NOTE;
|
|
1753
|
+
} else {
|
|
1754
|
+
return finish("nothing", { head: head ?? base });
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
const push = git(path, [
|
|
1759
|
+
"push",
|
|
1760
|
+
context.settings.remote,
|
|
1761
|
+
`HEAD:refs/heads/${branch}`,
|
|
1762
|
+
]);
|
|
1763
|
+
if (!push.ok) {
|
|
1764
|
+
return finish("failed", {
|
|
1765
|
+
reason: "push",
|
|
1766
|
+
head,
|
|
1767
|
+
message: `cannot push "${branch}" to "${context.settings.remote}": ${push.err || push.out}`,
|
|
1768
|
+
});
|
|
1769
|
+
}
|
|
1770
|
+
return finish("done", {
|
|
1771
|
+
head,
|
|
1772
|
+
pushed: true,
|
|
1773
|
+
...(note === undefined ? {} : { message: note }),
|
|
1774
|
+
});
|
|
1775
|
+
}
|