@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/places.ts ADDED
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Check places: at most `checks` checks run at once in one operad home, across
3
+ * every repository, plan and process. Each place is a lock file made by the
4
+ * platform's `withLockFile`, so a holder that dies gives its place back the way
5
+ * every platform lock does: the next taker sees the dead pid and takes over.
6
+ * Integration checks go before verify checks, and the wait order lives next to
7
+ * the lock files so separate processes agree on it.
8
+ */
9
+
10
+ import { readFileSync, readdirSync, writeFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import type { StepContext } from "@operad-io/engine";
13
+ import { taskPlaceWait } from "./place-wait.ts";
14
+ import { withLockFile, waitForChange } from "@operad-io/engine/platform";
15
+ import { WaitEntry, type CheckKind } from "./place-order.ts";
16
+
17
+ export { VERIFY_STARVATION_MS, type CheckKind } from "./place-order.ts";
18
+
19
+ /** How many checks may run at once when the home's dev settings say nothing. */
20
+ export const DEFAULT_CHECK_PLACES = 2;
21
+
22
+ /** How often a waiting check looks again when no release was announced. */
23
+ const RECHECK_MS = 500;
24
+
25
+ /** Where the places of one operad home live. */
26
+ export function checkPlacesDirectory(home: string): string {
27
+ return join(home, "dev", "check-places");
28
+ }
29
+
30
+ /** Reads `checks` from the plugin's settings; unset means the default. */
31
+ export function checkPlacesOf(
32
+ settings: Readonly<Record<string, unknown>>,
33
+ ): number {
34
+ const value = settings.checks;
35
+ if (value === undefined) return DEFAULT_CHECK_PLACES;
36
+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
37
+ throw new Error("dev settings: checks must be a positive integer");
38
+ }
39
+ return value;
40
+ }
41
+
42
+ /** The repository's own limit: its name for the log, a key for the lock files. */
43
+ export interface RepositoryPlaces {
44
+ readonly name: string;
45
+ readonly path: string;
46
+ readonly places: number;
47
+ }
48
+
49
+ /** Where a check takes its place and what it says while it waits. */
50
+ export interface CheckPlaces {
51
+ readonly home: string;
52
+ /** How many checks may run at once in the home. */
53
+ readonly checks: number;
54
+ /** The repository's limit, when `gate.places` sets one. */
55
+ readonly repository?: RepositoryPlaces | undefined;
56
+ /** Writes a line to the step's log. */
57
+ readonly log: (line: string) => Promise<unknown> | unknown;
58
+ readonly signal?: AbortSignal | undefined;
59
+ /** Tells the kernel the step waits for a place, so the running view shows it queued. */
60
+ readonly queued?: StepContext["queued"];
61
+ /**
62
+ * Says what the step waits for (the place group), or null once it does not;
63
+ * called again at each look while it waits. The task's row shows it.
64
+ */
65
+ readonly waiting?:
66
+ | ((key: string | null, order?: { readonly since: number; readonly ahead: number }) => Promise<void>)
67
+ | undefined;
68
+ /** What this check is for; integration checks go first. */
69
+ readonly kind?: CheckKind | undefined;
70
+ /** The clock that stamps when a check began to wait; tests inject this. */
71
+ readonly clock?: (() => number) | undefined;
72
+ /** How a waiting check waits before it looks again; tests inject this. */
73
+ readonly wait?: ((ms: number) => Promise<void>) | undefined;
74
+ }
75
+
76
+ /** Thrown when the step is cancelled while it waits for a place. */
77
+ export class CheckPlaceCancelled extends Error {
78
+ constructor() {
79
+ super("cancelled while waiting for a check place");
80
+ this.name = "CheckPlaceCancelled";
81
+ }
82
+ }
83
+
84
+ /** A check that found an earlier one still ahead after it took a lock. */
85
+ class PlaceAhead extends Error {
86
+ constructor(
87
+ readonly pool: "home" | "repository",
88
+ readonly ahead: number,
89
+ ) {
90
+ super("ahead");
91
+ }
92
+ }
93
+
94
+ /** A pool that had no free place; `pool` says which, so the log can name it. */
95
+ class PlaceBusy extends Error {
96
+ constructor(
97
+ readonly pool: "home" | "repository",
98
+ readonly inUse: number,
99
+ /** Checks that began to wait earlier and still wait; they take places first. */
100
+ readonly ahead = 0,
101
+ ) {
102
+ super("busy");
103
+ }
104
+ }
105
+
106
+ /** The lock files of the repository's places, next to the home's. */
107
+ function repositoryKey(repository: RepositoryPlaces): string {
108
+ const hash = new Bun.CryptoHasher("sha1").update(repository.path).digest("hex");
109
+ const name = repository.name.replace(/[^A-Za-z0-9._-]/g, "_");
110
+ return `repo-${name}-${hash.slice(0, 8)}`;
111
+ }
112
+
113
+ /**
114
+ * Records who last took a place, so a verify can still say it was passed over
115
+ * after the integration has left the wait order and only its lock is left.
116
+ */
117
+ function recordGrant(
118
+ directory: string,
119
+ prefix: string,
120
+ index: number,
121
+ kind: CheckKind,
122
+ at: number,
123
+ ): void {
124
+ try {
125
+ writeFileSync(join(directory, `${prefix}-${index}.grant`), `${kind}\n${at}\n`);
126
+ } catch {
127
+ // The log line is a courtesy; a check that cannot record it still runs.
128
+ }
129
+ }
130
+
131
+ /** Whether an integration took a place of this pool since `since`. */
132
+ function integrationGrantedSince(
133
+ directory: string,
134
+ prefix: string,
135
+ since: number,
136
+ ): boolean {
137
+ let names: string[];
138
+ try {
139
+ names = readdirSync(directory);
140
+ } catch {
141
+ return false;
142
+ }
143
+ for (const name of names) {
144
+ if (!name.startsWith(`${prefix}-`) || !name.endsWith(".grant")) continue;
145
+ try {
146
+ const [kind, at] = readFileSync(join(directory, name), "utf8").split("\n");
147
+ const when = Number(at);
148
+ if (kind === "integration" && Number.isFinite(when) && when >= since) return true;
149
+ } catch {
150
+ // A marker that cannot be read says nothing.
151
+ }
152
+ }
153
+ return false;
154
+ }
155
+
156
+ /** Takes one free place of a pool and runs `work`, or throws `PlaceBusy` at once. */
157
+ async function takeOne<T>(
158
+ directory: string,
159
+ prefix: string,
160
+ count: number,
161
+ pool: "home" | "repository",
162
+ entry: WaitEntry | undefined,
163
+ now: number,
164
+ kind: CheckKind,
165
+ at: () => number,
166
+ work: () => Promise<T> | T,
167
+ ): Promise<T> {
168
+ // A place is free for this check only when no earlier check still waits.
169
+ const ahead = entry?.ahead(now) ?? 0;
170
+ if (ahead > 0) throw new PlaceBusy(pool, 0, ahead);
171
+ let busy = 0;
172
+ for (let index = 1; index <= count; index += 1) {
173
+ try {
174
+ // A live holder makes the lock wait; waiting here means "taken".
175
+ return await withLockFile(
176
+ join(directory, `${prefix}-${index}.lock`),
177
+ () => {
178
+ // An earlier check may have joined between the look above and this
179
+ // lock. Give the place back instead of passing that check over.
180
+ const late = entry?.ahead(now) ?? 0;
181
+ if (late > 0) throw new PlaceAhead(pool, late);
182
+ recordGrant(directory, prefix, index, kind, at());
183
+ return work();
184
+ },
185
+ {
186
+ label: "check place",
187
+ onLog: () => {},
188
+ wait: () => Promise.reject(new PlaceBusy(pool, 0)),
189
+ },
190
+ );
191
+ } catch (error) {
192
+ if (error instanceof PlaceAhead) {
193
+ throw new PlaceBusy(error.pool, 0, error.ahead);
194
+ }
195
+ if (!(error instanceof PlaceBusy) || error.pool !== pool) throw error;
196
+ busy += 1;
197
+ }
198
+ }
199
+ throw new PlaceBusy(pool, busy);
200
+ }
201
+
202
+ /**
203
+ * Runs `work` holding a home place and, when the repository has a limit, a
204
+ * repository place. Both are taken in one order, home first, and a check that
205
+ * finds the second busy gives the first back before it waits, so it never
206
+ * waits while it holds a place. Nothing times it out while it waits: the
207
+ * check's own timeout starts when `work` does.
208
+ */
209
+ export async function withCheckPlace<T>(
210
+ places: CheckPlaces,
211
+ work: () => Promise<T> | T,
212
+ ): Promise<T> {
213
+ const directory = checkPlacesDirectory(places.home);
214
+ const repository = places.repository;
215
+ const kind = places.kind ?? "verify";
216
+ const clock = places.clock ?? Date.now;
217
+ const since = clock();
218
+ // Where this check stands in the order of each pool it needs.
219
+ let homeEntry: WaitEntry | undefined;
220
+ const repositoryEntry =
221
+ repository === undefined
222
+ ? undefined
223
+ : WaitEntry.join(directory, repositoryKey(repository), since, kind);
224
+ const leaveAll = (): void => {
225
+ homeEntry?.leave();
226
+ repositoryEntry?.leave();
227
+ };
228
+ places.signal?.addEventListener("abort", leaveAll, { once: true });
229
+ let entry = "place-1.lock";
230
+ const wait =
231
+ places.wait ??
232
+ ((ms: number) => waitForChange(directory, entry, ms));
233
+ // What the kernel was told: the place group the step is queued under.
234
+ let reported: { key: string; ahead: number; end: () => Promise<void> } | undefined;
235
+ const stopWaiting = async (): Promise<void> => {
236
+ const open = reported;
237
+ reported = undefined;
238
+ // Neither the running view nor the row may fail the check.
239
+ await open?.end().catch(() => undefined);
240
+ await places.waiting?.(null).catch(() => undefined);
241
+ };
242
+ const started = async (): Promise<T> => {
243
+ leaveAll();
244
+ await stopWaiting();
245
+ return work();
246
+ };
247
+ const inner =
248
+ repository === undefined
249
+ ? started
250
+ : () =>
251
+ takeOne(
252
+ directory,
253
+ repositoryKey(repository),
254
+ repository.places,
255
+ "repository",
256
+ repositoryEntry,
257
+ clock(),
258
+ kind,
259
+ clock,
260
+ started,
261
+ );
262
+ let said: string | undefined;
263
+ try {
264
+ for (;;) {
265
+ if (places.signal?.aborted === true) throw new CheckPlaceCancelled();
266
+ const now = clock();
267
+ try {
268
+ // While the repository's order holds this check back, it asks for no
269
+ // home place, so it does not hold up the checks behind it there.
270
+ if (homeEntry === undefined && (repositoryEntry?.ahead(now) ?? 0) > 0) {
271
+ throw new PlaceBusy("repository", 0, repositoryEntry?.ahead(now) ?? 0);
272
+ }
273
+ homeEntry ??= WaitEntry.join(directory, "home", since, kind);
274
+ return await takeOne(
275
+ directory,
276
+ "place",
277
+ places.checks,
278
+ "home",
279
+ homeEntry,
280
+ now,
281
+ kind,
282
+ clock,
283
+ inner,
284
+ );
285
+ } catch (error) {
286
+ if (!(error instanceof PlaceBusy)) throw error;
287
+ if (error.pool === "repository") {
288
+ homeEntry?.leave();
289
+ homeEntry = undefined;
290
+ }
291
+ const waitEntry = error.pool === "repository" ? repositoryEntry : homeEntry;
292
+ const ahead = waitEntry?.ahead(now) ?? error.ahead;
293
+ const prefix =
294
+ error.pool === "repository" && repository !== undefined
295
+ ? repositoryKey(repository)
296
+ : "place";
297
+ entry =
298
+ error.pool === "repository" && repository !== undefined
299
+ ? `${prefix}-1.lock`
300
+ : "place-1.lock";
301
+ const of =
302
+ error.pool === "home" || repository === undefined ? "" : ` of ${repository.name}`;
303
+ const passedOver =
304
+ kind === "verify" &&
305
+ ((waitEntry?.integrationsAhead(now) ?? 0) > 0 ||
306
+ integrationGrantedSince(directory, prefix, since));
307
+ const line = passedOver
308
+ ? `waiting for a check place${of}: passed over for an integration check`
309
+ : error.ahead > 0
310
+ ? `waiting for a check place${of}: ${error.ahead} ahead`
311
+ : `waiting for a check place${of}: ${error.inUse} in use`;
312
+ if (said !== line) {
313
+ said = line;
314
+ await places.log(line);
315
+ }
316
+ const key =
317
+ error.pool === "repository" && repository !== undefined
318
+ ? placeGroupOf(repository.name)
319
+ : placeGroupOf(undefined);
320
+ // The running view shows the ahead count told here, so a change is told again.
321
+ if ((reported?.key !== key || reported.ahead !== ahead) && places.queued !== undefined) {
322
+ const previous = reported;
323
+ reported = undefined;
324
+ await previous?.end().catch(() => undefined);
325
+ try {
326
+ reported = { key, ahead, end: await places.queued(key, ahead) };
327
+ } catch {
328
+ reported = undefined;
329
+ }
330
+ }
331
+ await places.waiting?.(key, { since, ahead }).catch(() => undefined);
332
+ }
333
+ await wait(RECHECK_MS);
334
+ }
335
+ } finally {
336
+ places.signal?.removeEventListener("abort", leaveAll);
337
+ leaveAll();
338
+ await stopWaiting();
339
+ }
340
+ }
341
+
342
+ /** The place group a waiting check is queued under: the words its log line uses. */
343
+ export function placeGroupOf(repository: string | undefined): string {
344
+ return repository === undefined ? "check place" : `check place of ${repository}`;
345
+ }
346
+
347
+ /** The places a step's checks take: the home's limit, the repository's, the step's own log. */
348
+ export function checkPlaces(
349
+ ctx: StepContext,
350
+ repository?: { readonly name: string; readonly path: string },
351
+ repositoryLimit?: number,
352
+ taskKey?: string,
353
+ kind: CheckKind = "verify",
354
+ ): CheckPlaces {
355
+ return {
356
+ home: ctx.home,
357
+ checks: checkPlacesOf(ctx.settings),
358
+ kind,
359
+ repository:
360
+ repository === undefined || repositoryLimit === undefined
361
+ ? undefined
362
+ : { name: repository.name, path: repository.path, places: repositoryLimit },
363
+ log: (line) => ctx.logger.write(line),
364
+ signal: ctx.signal,
365
+ queued: ctx.queued,
366
+ ...(taskKey === undefined ? {} : { waiting: (key, order) => taskPlaceWait(ctx, taskKey, key, order) }),
367
+ };
368
+ }
package/src/prepare.ts ADDED
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The `prepare` commands of dev.json: run in a checkout after it is created or
3
+ * moved to a new commit, before a step uses it. A checkout without them is a
4
+ * plain checkout: dev installs and links nothing itself.
5
+ */
6
+
7
+ import { isRecord, messageOf, type StepContext, type StepRunOptions } from "@operad-io/engine";
8
+
9
+ import type { CommandRunner } from "./mainclone.ts";
10
+ import type { DevSettings } from "./settings.ts";
11
+
12
+ /** The reason a step reports when a prepare command failed. */
13
+ export const PREPARE_FAILED = "prepare failed";
14
+
15
+ export function stepOptions(ctx: StepContext, cwd: string): StepRunOptions {
16
+ return {
17
+ runId: ctx.runId,
18
+ cwd,
19
+ ...(ctx.object === undefined ? {} : { object: ctx.object }),
20
+ params: ctx.params,
21
+ access: ctx.access,
22
+ ...(ctx.trigger === undefined ? {} : { trigger: ctx.trigger }),
23
+ signal: ctx.signal,
24
+ };
25
+ }
26
+
27
+ export interface PrepareFailure {
28
+ /** Always `PREPARE_FAILED`. */
29
+ readonly reason: typeof PREPARE_FAILED;
30
+ /** `prepare failed`, then the log path or the host error. */
31
+ readonly message: string;
32
+ readonly log?: string;
33
+ }
34
+
35
+ /**
36
+ * Runs `settings.prepare` in `path`. Returns undefined when it passed or there
37
+ * is nothing to run, otherwise the failure.
38
+ */
39
+ export async function runPrepare(
40
+ ctx: StepContext,
41
+ settings: DevSettings,
42
+ path: string,
43
+ ): Promise<PrepareFailure | undefined> {
44
+ if (settings.prepare.length === 0) return undefined;
45
+ const runStep = ctx.runStep;
46
+ if (runStep === undefined) {
47
+ return {
48
+ reason: PREPARE_FAILED,
49
+ message: `${PREPARE_FAILED}: the kernel did not offer a way to run the prepare commands`,
50
+ };
51
+ }
52
+ try {
53
+ const outcome = await runStep(
54
+ "shell/check",
55
+ {
56
+ cwd: path,
57
+ timeoutSecs: settings.gate.commandTimeoutSecs,
58
+ lines: settings.prepare,
59
+ },
60
+ stepOptions(ctx, path),
61
+ );
62
+ if (outcome.result === "pass") return undefined;
63
+ const data = isRecord(outcome.data) ? outcome.data : {};
64
+ const log = typeof data.log === "string" ? data.log : undefined;
65
+ return {
66
+ reason: PREPARE_FAILED,
67
+ message: `${PREPARE_FAILED}${log === undefined ? "" : `; log: ${log}`}`,
68
+ ...(log === undefined ? {} : { log }),
69
+ };
70
+ } catch (error) {
71
+ return {
72
+ reason: PREPARE_FAILED,
73
+ message: `${PREPARE_FAILED}: ${messageOf(error)}`,
74
+ };
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Runs one prepare line in the main clone through the same step a checkout's
80
+ * prepare lines use, so the shell, the environment and the time limit are the
81
+ * same.
82
+ */
83
+ export function mainCloneRunner(ctx: StepContext, settings: DevSettings): CommandRunner {
84
+ return async (cwd, line) => {
85
+ const runStep = ctx.runStep;
86
+ if (runStep === undefined) {
87
+ return { ok: false, out: "the kernel did not offer a way to run the line" };
88
+ }
89
+ try {
90
+ const outcome = await runStep(
91
+ "shell/check",
92
+ { cwd, timeoutSecs: settings.gate.commandTimeoutSecs, lines: [line] },
93
+ stepOptions(ctx, cwd),
94
+ );
95
+ if (outcome.result === "pass") return { ok: true, out: "" };
96
+ const data = isRecord(outcome.data) ? outcome.data : {};
97
+ const tail = Array.isArray(data.tail)
98
+ ? data.tail.filter((row): row is string => typeof row === "string")
99
+ : [];
100
+ const message = typeof data.message === "string" ? data.message : outcome.result;
101
+ return { ok: false, out: tail.join("\n").trim() || message };
102
+ } catch (error) {
103
+ return { ok: false, out: messageOf(error) };
104
+ }
105
+ };
106
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * What a work step leaves behind when it runs out of time: the words it says
3
+ * to the worker, the note the worker writes, and how the next attempt reads
4
+ * them. The git side lives in `steps.ts` next to the other worktree helpers.
5
+ */
6
+
7
+ /** The file in the worktree root the worker writes its progress note to. */
8
+ export const PROGRESS_FILE = ".operad-progress.md";
9
+
10
+ /** The message of the commit dev makes of whatever a timed-out step left. */
11
+ export const WIP_MESSAGE = "work in progress: the work step ran out of time";
12
+
13
+ /** The message of the commit that takes the note out of the branch again. */
14
+ export const NOTE_REMOVED_MESSAGE = "remove the progress note from the branch";
15
+
16
+ /**
17
+ * The inbox a harness step gets in `params.inbox`: it keeps what is sent until
18
+ * a harness listens, then passes everything on in order.
19
+ */
20
+ export interface Inbox {
21
+ listen(handler: (text: string) => void): () => void;
22
+ /**
23
+ * A harness calls it when its run begins, with how long the run may last in
24
+ * milliseconds. The wrap-up is timed from then, not from the step's start.
25
+ */
26
+ begin(limitMs: number): void;
27
+ }
28
+
29
+ export interface Outbox {
30
+ readonly inbox: Inbox;
31
+ send(text: string): void;
32
+ }
33
+
34
+ export function createOutbox(onBegin: (limitMs: number) => void): Outbox {
35
+ let handler: ((text: string) => void) | undefined;
36
+ const kept: string[] = [];
37
+ return {
38
+ inbox: {
39
+ begin: onBegin,
40
+ listen(next) {
41
+ handler = next;
42
+ for (const text of kept.splice(0)) next(text);
43
+ return () => {
44
+ if (handler === next) handler = undefined;
45
+ };
46
+ },
47
+ },
48
+ send(text) {
49
+ if (handler === undefined) kept.push(text);
50
+ else handler(text);
51
+ },
52
+ };
53
+ }
54
+
55
+ /** What the worker is told when the step is close to its time limit. */
56
+ export function wrapUpMessage(): string {
57
+ return [
58
+ "This work is close to its time limit. Stop starting new things.",
59
+ "Commit what you have now, so nothing is left uncommitted, and run no more than you must.",
60
+ `Then write a progress note to ${PROGRESS_FILE} in the worktree root: what is done, what is left, and what you learned. Do not commit that file.`,
61
+ "End your turn when the note is written.",
62
+ ].join("\n");
63
+ }
64
+
65
+ /** One commit a worker made. */
66
+ export interface ProgressCommit {
67
+ readonly sha: string;
68
+ readonly subject: string;
69
+ }
70
+
71
+ /** What an attempt left for the next one. */
72
+ export interface Progress {
73
+ readonly note: string | null;
74
+ readonly commits: readonly ProgressCommit[];
75
+ readonly timedOut: boolean;
76
+ }
77
+
78
+ /** Reads a stored progress record; anything that is not one is undefined. */
79
+ export function progressOf(value: unknown): Progress | undefined {
80
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
81
+ return undefined;
82
+ }
83
+ const note: unknown = Reflect.get(value, "note");
84
+ const commits: unknown = Reflect.get(value, "commits");
85
+ const timedOut: unknown = Reflect.get(value, "timedOut");
86
+ if (note !== null && typeof note !== "string") return undefined;
87
+ if (!Array.isArray(commits)) return undefined;
88
+ const list: ProgressCommit[] = [];
89
+ for (const item of commits as unknown[]) {
90
+ if (typeof item !== "object" || item === null) return undefined;
91
+ const sha: unknown = Reflect.get(item, "sha");
92
+ const subject: unknown = Reflect.get(item, "subject");
93
+ if (typeof sha !== "string" || typeof subject !== "string") return undefined;
94
+ list.push({ sha, subject });
95
+ }
96
+ return { note, commits: list, timedOut: timedOut === true };
97
+ }
98
+
99
+ /** The text at the top of the next attempt's prompt. */
100
+ export function previousAttemptText(progress: Progress): string {
101
+ const lines = [
102
+ progress.timedOut
103
+ ? "The attempt before this one ran out of time. Continue from where it got to; do not start over."
104
+ : "The attempt before this one left a progress note. Continue from where it got to; do not start over.",
105
+ ];
106
+ lines.push(
107
+ progress.commits.length === 0
108
+ ? "It made no commits."
109
+ : ["Its commits, newest first, are already in this worktree:", ...progress.commits.map((commit) => `- ${commit.sha} ${commit.subject}`)].join("\n"),
110
+ );
111
+ if (progress.note !== null) {
112
+ lines.push(["Its progress note:", progress.note.trim()].join("\n"));
113
+ }
114
+ return lines.join("\n\n");
115
+ }