@operad-io/dev 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +795 -2
  3. package/dev.schema.json +602 -0
  4. package/flows/chat-worktree.flow.ts +18 -0
  5. package/flows/dev.flow.ts +7 -0
  6. package/package.json +29 -4
  7. package/src/actions.ts +591 -0
  8. package/src/announce.ts +225 -0
  9. package/src/chat.ts +234 -0
  10. package/src/check.ts +80 -0
  11. package/src/commands.ts +417 -0
  12. package/src/editor.ts +55 -0
  13. package/src/flaky.ts +716 -0
  14. package/src/flow-compiler.ts +858 -0
  15. package/src/followups.ts +223 -0
  16. package/src/gate.ts +2897 -0
  17. package/src/git.ts +138 -0
  18. package/src/index.ts +226 -0
  19. package/src/integrate.ts +1201 -0
  20. package/src/integration-queue.ts +393 -0
  21. package/src/lock.ts +36 -0
  22. package/src/mainclone.ts +102 -0
  23. package/src/marks.ts +126 -0
  24. package/src/model.ts +1165 -0
  25. package/src/notcode.ts +266 -0
  26. package/src/place-order.ts +161 -0
  27. package/src/place-wait.ts +64 -0
  28. package/src/places.ts +368 -0
  29. package/src/prepare.ts +106 -0
  30. package/src/progress.ts +115 -0
  31. package/src/project-flows.ts +160 -0
  32. package/src/project-settings.ts +185 -0
  33. package/src/refusals.ts +336 -0
  34. package/src/rerun.ts +378 -0
  35. package/src/reruns.ts +62 -0
  36. package/src/retry.ts +212 -0
  37. package/src/rework.ts +366 -0
  38. package/src/schedule.ts +1052 -0
  39. package/src/service.ts +2160 -0
  40. package/src/settings.ts +1463 -0
  41. package/src/standing.ts +87 -0
  42. package/src/stdin.ts +105 -0
  43. package/src/steps.ts +1775 -0
  44. package/src/stops.ts +103 -0
  45. package/src/throughput.ts +347 -0
  46. package/src/timeouts.ts +60 -0
  47. package/src/views.ts +1167 -0
  48. package/src/waits.ts +105 -0
package/src/rerun.ts ADDED
@@ -0,0 +1,378 @@
1
+ /**
2
+ * Runs a check line list through `shell/check` and, when it fails, once more.
3
+ * A test that crossed its timeout while several checks ran at once is not the
4
+ * task's fault; a second run tells the two apart without parsing any output.
5
+ * A timeout is not rerun: a hang stays a hang.
6
+ */
7
+
8
+ import {
9
+ closeSync,
10
+ fstatSync,
11
+ openSync,
12
+ readFileSync,
13
+ readSync,
14
+ statSync,
15
+ writeFileSync,
16
+ } from "node:fs";
17
+ import { isRecord, messageOf, type PluginStepResult, type StepContext, type StepRunOptions } from "@operad-io/engine";
18
+
19
+ import type { CheckCommand, FailedRerun } from "./settings.ts";
20
+ import {
21
+ CheckPlaceCancelled,
22
+ withCheckPlace,
23
+ type CheckPlaces,
24
+ } from "./places.ts";
25
+
26
+ export interface CheckRun {
27
+ readonly outcome: PluginStepResult | undefined;
28
+ readonly hostError: string | undefined;
29
+ /** Set when the first run failed and the check ran again. */
30
+ readonly rerun: boolean;
31
+ /** A short note for a pass that needed the rerun, otherwise undefined. */
32
+ readonly note: string | undefined;
33
+ /** The tests that failed in a first run and passed when run alone. */
34
+ readonly passedOnRerun: readonly string[];
35
+ /** The `failed` settings of the command whose match found each of those tests. */
36
+ readonly failedBy?: ReadonlyMap<string, FailedRerun> | undefined;
37
+ }
38
+
39
+ /** The line drawn between the two runs in the check log. */
40
+ export const RERUN_SEPARATOR = "===== check failed; running it once more =====";
41
+
42
+ async function once(
43
+ runStep: NonNullable<StepContext["runStep"]>,
44
+ params: Readonly<Record<string, unknown>>,
45
+ options: StepRunOptions,
46
+ places: CheckPlaces | undefined,
47
+ ): Promise<Pick<CheckRun, "outcome" | "hostError">> {
48
+ try {
49
+ const run = (): Promise<PluginStepResult> =>
50
+ Promise.resolve(runStep("shell/check", params, options));
51
+ return {
52
+ outcome: await (places === undefined ? run() : withCheckPlace(places, run)),
53
+ hostError: undefined,
54
+ };
55
+ } catch (error) {
56
+ if (error instanceof CheckPlaceCancelled) {
57
+ return {
58
+ outcome: { result: "interrupted", data: { reason: "cancelled" } },
59
+ hostError: undefined,
60
+ };
61
+ }
62
+ return { outcome: undefined, hostError: messageOf(error) };
63
+ }
64
+ }
65
+
66
+ function dataOf(outcome: PluginStepResult | undefined): Record<string, unknown> {
67
+ return outcome !== undefined && isRecord(outcome.data) ? outcome.data : {};
68
+ }
69
+
70
+ /** The step's log path, when the outcome names one. */
71
+ function logOf(outcome: PluginStepResult | undefined): string | undefined {
72
+ const log = dataOf(outcome).log;
73
+ return typeof log === "string" ? log : undefined;
74
+ }
75
+
76
+ /** Where the step's own output began in the shared log; 0 when it does not say. */
77
+ function logStartOf(outcome: PluginStepResult | undefined): number {
78
+ const start = dataOf(outcome).logStart;
79
+ return typeof start === "number" ? start : 0;
80
+ }
81
+
82
+ /** How many bytes the log holds now; a log that cannot be read holds none. */
83
+ function sizeOf(path: string | undefined): number {
84
+ if (path === undefined) return 0;
85
+ try {
86
+ return statSync(path).size;
87
+ } catch {
88
+ return 0;
89
+ }
90
+ }
91
+
92
+ /** Draws the separator at `offset`, where the first run's output ended. */
93
+ function markRerun(
94
+ path: string | undefined,
95
+ offset: number,
96
+ heading: string = RERUN_SEPARATOR,
97
+ ): void {
98
+ if (path === undefined) return;
99
+ try {
100
+ const bytes = readFileSync(path);
101
+ const before = bytes.subarray(0, offset).toString("utf8");
102
+ const after = bytes.subarray(offset).toString("utf8");
103
+ const gap = before.endsWith("\n") || before.length === 0 ? "" : "\n";
104
+ writeFileSync(path, `${before}${gap}${heading}\n${after}`);
105
+ } catch {
106
+ // A log that cannot be read stays as it is; the result does not depend on it.
107
+ }
108
+ }
109
+
110
+ export async function runCheckWithRerun(
111
+ runStep: NonNullable<StepContext["runStep"]>,
112
+ params: Readonly<Record<string, unknown>>,
113
+ options: StepRunOptions,
114
+ rerun: number,
115
+ places?: CheckPlaces,
116
+ lineOffset = 0,
117
+ ): Promise<CheckRun> {
118
+ const first = await once(runStep, params, options, places);
119
+ const firstData = dataOf(first.outcome);
120
+ const failed = first.hostError !== undefined || first.outcome?.result === "fail";
121
+ // Only a plain failure is rerun: not a cancel, not a hang.
122
+ if (!failed || rerun <= 0 || firstData.reason === "timeout" || first.hostError !== undefined) {
123
+ return { ...first, rerun: false, note: undefined, passedOnRerun: [] };
124
+ }
125
+ const label =
126
+ typeof firstData.lineNumber === "number"
127
+ ? `check line ${firstData.lineNumber + lineOffset}`
128
+ : "the check";
129
+ let last = first;
130
+ let attempts = 0;
131
+ for (let round = 0; round < rerun; round += 1) {
132
+ const offset = sizeOf(logOf(last.outcome));
133
+ last = await once(runStep, params, options, places);
134
+ attempts += 1;
135
+ markRerun(logOf(last.outcome), offset);
136
+ if (
137
+ last.hostError === undefined &&
138
+ last.outcome?.result === "pass"
139
+ ) {
140
+ return {
141
+ ...last,
142
+ rerun: true,
143
+ passedOnRerun: [],
144
+ note: `${label} failed, passed on rerun${attempts > 1 ? ` ${attempts}` : ""}`,
145
+ };
146
+ }
147
+ if (
148
+ last.hostError !== undefined ||
149
+ last.outcome?.result !== "fail" ||
150
+ dataOf(last.outcome).reason === "timeout"
151
+ ) {
152
+ break;
153
+ }
154
+ }
155
+ return { ...last, rerun: true, note: undefined, passedOnRerun: [] };
156
+ }
157
+
158
+ /* ---------------------------------------------------------------------------
159
+ * Commands that rerun only their failed tests
160
+ * ------------------------------------------------------------------------- */
161
+
162
+ /** `text` inside single quotes, safe for `sh -c`. */
163
+ export function shellQuote(text: string): string {
164
+ return `'${text.replace(/'/g, `'\\''`)}'`;
165
+ }
166
+
167
+ /**
168
+ * A regex that matches exactly one test. A failure line joins describe blocks
169
+ * with " > ", while bun's `-t` matches the names joined with a space, so the
170
+ * separator is turned into a space.
171
+ */
172
+ export function anchoredPattern(name: string): string {
173
+ const joined = name.replace(/ > /g, " ");
174
+ return `^${joined.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}$`;
175
+ }
176
+
177
+ /** The rerun command for one failed test. */
178
+ export function rerunCommand(template: string, name: string): string {
179
+ return template
180
+ .replace(/\{(name|pattern)\}/g, (_, kind: string) =>
181
+ shellQuote(kind === "name" ? name : anchoredPattern(name)),
182
+ );
183
+ }
184
+
185
+ /** The failed test names `failed.match` finds in `text`, each once, in order. */
186
+ export function failedNames(failed: FailedRerun, text: string): string[] {
187
+ const names = new Set<string>();
188
+ for (const found of text.matchAll(new RegExp(failed.match, "gm"))) {
189
+ const name = found[1];
190
+ if (name !== undefined && name.length > 0) names.add(name);
191
+ }
192
+ return [...names];
193
+ }
194
+
195
+ function withLineNumber(
196
+ outcome: PluginStepResult | undefined,
197
+ lineNumber: number,
198
+ message?: string,
199
+ ): PluginStepResult | undefined {
200
+ if (outcome === undefined) return undefined;
201
+ return {
202
+ ...outcome,
203
+ data: {
204
+ ...dataOf(outcome),
205
+ lineNumber,
206
+ ...(message === undefined ? {} : { message }),
207
+ },
208
+ };
209
+ }
210
+
211
+ /** Reads the log from `offset` on; a log that cannot be read holds no names. */
212
+ export function readSince(path: string | undefined, offset: number): string {
213
+ if (path === undefined) return "";
214
+ try {
215
+ const fd = openSync(path, "r");
216
+ try {
217
+ const size = fstatSync(fd).size;
218
+ if (size <= offset) return "";
219
+ const buffer = Buffer.allocUnsafe(size - offset);
220
+ let read = 0;
221
+ while (read < buffer.length) {
222
+ const count = readSync(fd, buffer, read, buffer.length - read, offset + read);
223
+ if (count === 0) break;
224
+ read += count;
225
+ }
226
+ return buffer.subarray(0, read).toString("utf8");
227
+ } finally {
228
+ closeSync(fd);
229
+ }
230
+ } catch {
231
+ return "";
232
+ }
233
+ }
234
+
235
+ function describePass(names: readonly string[]): string | undefined {
236
+ return names.length === 0
237
+ ? undefined
238
+ : `passed on rerun: ${names.join("; ")}`;
239
+ }
240
+
241
+ /**
242
+ * Runs a list of check commands. A list of plain strings is one `shell/check`
243
+ * with the whole-list rerun. A command with `failed` runs alone; when it exits
244
+ * non-zero and its log names a few failed tests, only those run again.
245
+ */
246
+ export async function runCheckCommands(
247
+ runStep: NonNullable<StepContext["runStep"]>,
248
+ base: { readonly cwd: string; readonly timeoutSecs?: number },
249
+ commands: readonly CheckCommand[],
250
+ options: StepRunOptions,
251
+ rerun: number,
252
+ places?: CheckPlaces,
253
+ ): Promise<CheckRun> {
254
+ const runOf = (command: CheckCommand): string =>
255
+ typeof command === "string" ? command : command.run;
256
+ const failedOf = (command: CheckCommand): FailedRerun | undefined =>
257
+ typeof command === "string" ? undefined : command.failed;
258
+ const paramsFor = (lines: readonly string[]) => ({ ...base, lines });
259
+
260
+ if (!commands.some((command) => failedOf(command) !== undefined)) {
261
+ return runCheckWithRerun(
262
+ runStep,
263
+ paramsFor(commands.map(runOf)),
264
+ options,
265
+ rerun,
266
+ places,
267
+ );
268
+ }
269
+
270
+ const notes: string[] = [];
271
+ const passed: string[] = [];
272
+ const failedBy = new Map<string, FailedRerun>();
273
+ let reran = false;
274
+ let last: Pick<CheckRun, "outcome" | "hostError"> = {
275
+ outcome: { result: "pass", data: { lines: 0, tail: [] } },
276
+ hostError: undefined,
277
+ };
278
+ const finish = (
279
+ result: Pick<CheckRun, "outcome" | "hostError">,
280
+ ): CheckRun => ({
281
+ ...result,
282
+ rerun: reran,
283
+ passedOnRerun: passed,
284
+ failedBy,
285
+ note: notes.length === 0 ? undefined : notes.join("; "),
286
+ });
287
+
288
+ let index = 0;
289
+ while (index < commands.length) {
290
+ const command = commands[index];
291
+ if (command === undefined) break;
292
+ const failed = failedOf(command);
293
+ if (failed === undefined) {
294
+ // A run of commands without `failed` keeps the whole-list rerun.
295
+ let end = index;
296
+ while (end < commands.length) {
297
+ const next = commands[end];
298
+ if (next === undefined || failedOf(next) !== undefined) break;
299
+ end += 1;
300
+ }
301
+ const group = await runCheckWithRerun(
302
+ runStep,
303
+ paramsFor(commands.slice(index, end).map(runOf)),
304
+ options,
305
+ rerun,
306
+ places,
307
+ index,
308
+ );
309
+ reran = reran || group.rerun;
310
+ if (group.note !== undefined) notes.push(group.note);
311
+ const lineNumber = dataOf(group.outcome).lineNumber;
312
+ const outcome =
313
+ typeof lineNumber === "number"
314
+ ? withLineNumber(group.outcome, lineNumber + index)
315
+ : group.outcome;
316
+ last = { outcome, hostError: group.hostError };
317
+ if (group.hostError !== undefined || outcome?.result !== "pass") {
318
+ return finish(last);
319
+ }
320
+ index = end;
321
+ continue;
322
+ }
323
+
324
+ const lineNumber = index + 1;
325
+ const first = await once(runStep, paramsFor([runOf(command)]), options, places);
326
+ const firstData = dataOf(first.outcome);
327
+ const numbered = {
328
+ outcome: withLineNumber(first.outcome, lineNumber),
329
+ hostError: first.hostError,
330
+ };
331
+ if (first.hostError === undefined && first.outcome?.result === "pass") {
332
+ last = numbered;
333
+ index += 1;
334
+ continue;
335
+ }
336
+ if (
337
+ first.hostError !== undefined ||
338
+ first.outcome?.result !== "fail" ||
339
+ firstData.reason !== "exit"
340
+ ) {
341
+ return finish(numbered);
342
+ }
343
+ const log = logOf(first.outcome);
344
+ const names = failedNames(failed, readSince(log, logStartOf(first.outcome)));
345
+ if (names.length === 0 || names.length > failed.max) return finish(numbered);
346
+
347
+ reran = true;
348
+ for (const name of names) {
349
+ const rerunLine = rerunCommand(failed.rerun, name);
350
+ const heading = `===== rerun of failed test: ${name} =====`;
351
+ const before = sizeOf(log);
352
+ const again = await once(runStep, paramsFor([rerunLine]), options, places);
353
+ markRerun(logOf(again.outcome) ?? log, before, heading);
354
+ const result = {
355
+ outcome: withLineNumber(again.outcome, lineNumber),
356
+ hostError: again.hostError,
357
+ };
358
+ if (again.hostError === undefined && again.outcome?.result === "pass") {
359
+ passed.push(name);
360
+ failedBy.set(name, failed);
361
+ last = result;
362
+ continue;
363
+ }
364
+ return finish({
365
+ outcome: withLineNumber(
366
+ again.outcome,
367
+ lineNumber,
368
+ `the failed test "${name}" failed again when run alone`,
369
+ ),
370
+ hostError: again.hostError,
371
+ });
372
+ }
373
+ const note = describePass(passed);
374
+ if (note !== undefined) notes.push(note);
375
+ index += 1;
376
+ }
377
+ return finish(last);
378
+ }
package/src/reruns.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * How often each test passed only on its own rerun, counted per test name over
3
+ * the whole home. The counts show which flaky tests are worth fixing.
4
+ */
5
+
6
+ import { join } from "node:path";
7
+ import type { ObjectStore } from "@operad-io/engine";
8
+ import { withLockFile } from "@operad-io/engine/platform";
9
+ import { listAll } from "./model.ts";
10
+
11
+ const RERUN_TYPE = "rerun-count";
12
+
13
+ export interface RerunCount {
14
+ readonly name: string;
15
+ readonly count: number;
16
+ }
17
+
18
+ function countOf(data: unknown): RerunCount | undefined {
19
+ if (typeof data !== "object" || data === null) return undefined;
20
+ const { name, count } = data as { name?: unknown; count?: unknown };
21
+ return typeof name === "string" && typeof count === "number"
22
+ ? { name, count }
23
+ : undefined;
24
+ }
25
+
26
+ /** Adds one pass on rerun for each name. Two processes take turns on a lock file. */
27
+ export async function recordRerunPasses(
28
+ store: ObjectStore,
29
+ names: readonly string[],
30
+ ): Promise<void> {
31
+ if (names.length === 0) return;
32
+ await withLockFile(
33
+ join(store.root, "dev", "reruns.lock"),
34
+ async () => {
35
+ for (const name of names) {
36
+ const key = Buffer.from(name).toString("hex");
37
+ const current = countOf((await store.get(RERUN_TYPE, key))?.data);
38
+ await store.put(
39
+ RERUN_TYPE,
40
+ key,
41
+ { name, count: (current?.count ?? 0) + 1 },
42
+ "dev:rerun-count",
43
+ );
44
+ }
45
+ },
46
+ { label: "dev reruns", onLog: () => {} },
47
+ );
48
+ }
49
+
50
+ /** Every counted test, the most frequent first, then by name. */
51
+ export async function listRerunCounts(
52
+ store: ObjectStore,
53
+ ): Promise<readonly RerunCount[]> {
54
+ const counts: RerunCount[] = [];
55
+ for (const object of await listAll(store, RERUN_TYPE)) {
56
+ const count = countOf(object.data);
57
+ if (count !== undefined) counts.push(count);
58
+ }
59
+ return counts.sort(
60
+ (a, b) => b.count - a.count || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0),
61
+ );
62
+ }
package/src/retry.ts ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Steps `dev/retry` and `dev/retry_due`: a step that stopped because of operad
3
+ * or the machine, not because of the task's own work, runs once more without a
4
+ * person. The flow runs `retry` in front of every announcement of such a stop.
5
+ * A second stop of that kind in the same attempt, or a wait that ran out, goes
6
+ * to a person with the cause in the waiting line.
7
+ */
8
+
9
+ import type { PluginStepResult, StepContext } from "@operad-io/engine";
10
+ import { reviewTestHooks, waitFor } from "./gate.ts";
11
+ import type { RetryRecord, TaskData } from "./model.ts";
12
+ import { DEFAULT_DEV_SETTINGS, readDevSettings } from "./settings.ts";
13
+ import { classifyStop } from "./stops.ts";
14
+ import {
15
+ cancelledStep,
16
+ claimAllows,
17
+ looseTaskContext,
18
+ saveTaskGuarded,
19
+ } from "./steps.ts";
20
+
21
+ /** How often a retry looks again at what it waits for. */
22
+ export const RETRY_POLL_MS = 5_000;
23
+
24
+ /** The edge a task took into the retry step, as the flow names it in its params. */
25
+ export interface RetryParams {
26
+ readonly from: string;
27
+ /** `failed`, `interrupted`, or `waited` after the wait for what was missing. */
28
+ readonly result: string;
29
+ }
30
+
31
+ function paramsOf(params: unknown): RetryParams {
32
+ const record =
33
+ typeof params === "object" && params !== null && !Array.isArray(params)
34
+ ? (params as Record<string, unknown>)
35
+ : {};
36
+ return {
37
+ from: typeof record.from === "string" ? record.from : "",
38
+ result: typeof record.result === "string" ? record.result : "",
39
+ };
40
+ }
41
+
42
+ function attemptNumber(task: TaskData): number {
43
+ return task.attempt?.number ?? task.attempts;
44
+ }
45
+
46
+ /** The retry this attempt already used, if any. */
47
+ function usedRetry(task: TaskData): RetryRecord | undefined {
48
+ const retry = task.retry;
49
+ return retry !== undefined && retry !== null && retry.attempt === attemptNumber(task)
50
+ ? retry
51
+ : undefined;
52
+ }
53
+
54
+ function now(): number {
55
+ return reviewTestHooks.now?.() ?? Date.now();
56
+ }
57
+
58
+ /** Step `dev/retry`. */
59
+ export async function runRetry(
60
+ ctx: StepContext,
61
+ stepParams: unknown,
62
+ ): Promise<PluginStepResult> {
63
+ const context = await looseTaskContext(ctx);
64
+ const task = context.task;
65
+ if (!claimAllows(ctx, task)) return cancelledStep();
66
+ const edge = paramsOf(stepParams);
67
+ const used = usedRetry(task);
68
+
69
+ const write = async (
70
+ patch: Partial<Pick<TaskData, "stop" | "retry" | "phase">>,
71
+ ): Promise<boolean> =>
72
+ saveTaskGuarded(
73
+ ctx,
74
+ context.taskKey,
75
+ { ...task, ...patch },
76
+ "dev:retry",
77
+ );
78
+
79
+ if (edge.result === "waited") {
80
+ // The wait for what was missing is over: it ended well, or it ran out.
81
+ if (used?.state === "ready") {
82
+ return (await write({ stop: null }))
83
+ ? { result: "again", data: { reason: "retry", cause: used.cause } }
84
+ : cancelledStep();
85
+ }
86
+ const cause = used?.cause ?? `run stopped during ${edge.from}`;
87
+ const asked: RetryRecord | undefined =
88
+ used === undefined ? undefined : { ...used, state: "asked" };
89
+ const written = await write({
90
+ stop: null,
91
+ phase: "waiting",
92
+ ...(asked === undefined ? {} : { retry: asked }),
93
+ });
94
+ return written
95
+ ? { result: "give_up", data: { reason: "wait_expired", cause } }
96
+ : cancelledStep();
97
+ }
98
+
99
+ const stop = task.stop;
100
+ const classified = classifyStop({
101
+ step: edge.from,
102
+ result: edge.result,
103
+ reason: stop?.step === edge.from ? stop.reason : undefined,
104
+ use: stop?.use,
105
+ });
106
+ // A stopped run whose settings still cannot be read would only fail again:
107
+ // wait for the settings first, within the same bound.
108
+ const verdict =
109
+ classified.kind === "environment" &&
110
+ classified.waitFor === undefined &&
111
+ context.settingsError !== undefined
112
+ ? classifyStop({ step: edge.from, result: "failed", reason: "settings_unreadable" })
113
+ : classified;
114
+ if (verdict.kind === "task") {
115
+ if (stop !== undefined && stop !== null && !(await write({ stop: null }))) {
116
+ return cancelledStep();
117
+ }
118
+ return { result: "ask", data: { reason: "task" } };
119
+ }
120
+ const cause = verdict.cause ?? `run stopped during ${edge.from}`;
121
+
122
+ if (used !== undefined) {
123
+ // The one retry of this attempt is spent: a person decides now.
124
+ const written = await write({
125
+ stop: null,
126
+ retry: { ...used, cause, state: "asked" },
127
+ // A person decides now: the task says it waits, however the step ended.
128
+ phase: "waiting" as const,
129
+ });
130
+ return written
131
+ ? { result: "give_up", data: { reason: "retry_failed", cause } }
132
+ : cancelledStep();
133
+ }
134
+
135
+ const waits = verdict.waitFor !== undefined;
136
+ const retry: RetryRecord = {
137
+ attempt: attemptNumber(task),
138
+ step: edge.from,
139
+ cause,
140
+ at: now(),
141
+ ...(verdict.waitFor === undefined ? {} : { waitFor: verdict.waitFor }),
142
+ ...(verdict.use === undefined ? {} : { use: verdict.use }),
143
+ state: waits ? "waiting" : "retrying",
144
+ };
145
+ const written = await write({ stop: null, retry, phase: "running" });
146
+ if (!written) return cancelledStep();
147
+ return {
148
+ result: waits ? "hold" : "again",
149
+ data: { reason: "retry", cause },
150
+ };
151
+ }
152
+
153
+ /** True when what the retry waited for is there now. */
154
+ async function causeGone(
155
+ ctx: StepContext,
156
+ retry: RetryRecord,
157
+ repositoryPath: string,
158
+ ): Promise<boolean> {
159
+ if (retry.waitFor === "step") {
160
+ return retry.use === undefined || ctx.stepLoaded?.(retry.use) !== false;
161
+ }
162
+ try {
163
+ await readDevSettings(repositoryPath);
164
+ return true;
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Step `dev/retry_due`: the wait in front of a retry whose cause must go first.
172
+ * It lets the flow carry on when the step is loaded or the settings can be
173
+ * read, or when the bound from `retry.environmentWaitMinutes` has passed; the
174
+ * retry step after it tells the two apart.
175
+ */
176
+ export async function runRetryDue(ctx: StepContext): Promise<PluginStepResult> {
177
+ const context = await looseTaskContext(ctx);
178
+ if (!claimAllows(ctx, context.task)) {
179
+ return { result: "interrupted", data: { reason: "cancelled" } };
180
+ }
181
+ const retry = usedRetry(context.task);
182
+ if (retry === undefined || retry.state !== "waiting") {
183
+ return { result: "ready", data: { at: now() } };
184
+ }
185
+ const minutes =
186
+ context.settings?.retry.environmentWaitMinutes ??
187
+ DEFAULT_DEV_SETTINGS.retry.environmentWaitMinutes;
188
+ const deadline = retry.at + minutes * 60_000;
189
+ const finish = async (state: "ready" | "expired"): Promise<PluginStepResult> => {
190
+ const written = await saveTaskGuarded(
191
+ ctx,
192
+ context.taskKey,
193
+ { ...context.task, retry: { ...retry, state } },
194
+ "dev:retry",
195
+ );
196
+ return written
197
+ ? { result: "ready", data: { state } }
198
+ : { result: "interrupted", data: { reason: "cancelled" } };
199
+ };
200
+ if (await causeGone(ctx, retry, context.repository.path)) {
201
+ return finish("ready");
202
+ }
203
+ if (now() >= deadline) return finish("expired");
204
+ const wait = reviewTestHooks.wait ?? waitFor;
205
+ const waited = await wait(
206
+ Math.max(0, Math.min(RETRY_POLL_MS, deadline - now())),
207
+ ctx.signal,
208
+ );
209
+ if (!waited) return { result: "interrupted", data: { reason: "cancelled" } };
210
+ // Not over: the flow's wait asks again.
211
+ return { result: "waiting", data: { cause: retry.cause } };
212
+ }