@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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dev.schema.json +631 -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 +2950 -0
  17. package/src/git.ts +138 -0
  18. package/src/index.ts +227 -0
  19. package/src/integrate.ts +1213 -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 +1171 -0
  25. package/src/notcode.ts +305 -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 +192 -0
  33. package/src/refusals.ts +336 -0
  34. package/src/rerun.ts +390 -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 +1495 -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
@@ -0,0 +1,1495 @@
1
+ /**
2
+ * A repository's dev settings: `<repository>/.operad/dev.json`, checked against
3
+ * the shipped `dev.schema.json`. The file is JSON; the schema is what editors
4
+ * read, and this module applies the same rules when a step loads the file.
5
+ */
6
+
7
+ import { createHash } from "node:crypto";
8
+ import {
9
+ existsSync,
10
+ mkdirSync,
11
+ readFileSync,
12
+ realpathSync,
13
+ renameSync,
14
+ writeFileSync,
15
+ } from "node:fs";
16
+ import {
17
+ basename,
18
+ dirname,
19
+ isAbsolute,
20
+ join,
21
+ normalize,
22
+ resolve,
23
+ sep,
24
+ } from "node:path";
25
+ import {
26
+ DEFAULT_POOL,
27
+ harnessOf,
28
+ parseWorkers,
29
+ WorkerDefinitionError,
30
+ type ParsedWorkers,
31
+ type WorkerDefinition,
32
+ } from "@operad-io/pool";
33
+ import { defaultOperadHome, isRecord } from "@operad-io/engine";
34
+ import { DevError, type AutoMode } from "./model.ts";
35
+ import {
36
+ type DevFlowSpec,
37
+ type DevFlows,
38
+ type DevStage,
39
+ } from "./flow-compiler.ts";
40
+
41
+ /** Where a repository keeps its dev settings. */
42
+ export const DEV_SETTINGS_FILE = ".operad/dev.json";
43
+
44
+ /** The `$id` of the shipped schema, written as a generated file's `$schema`. */
45
+ export const DEV_SETTINGS_SCHEMA = "https://operad.io/schemas/dev.schema.json";
46
+
47
+ /** The default location of a repository's worker brief. */
48
+ export const WORKER_BRIEF_FILE = ".operad/worker-brief.md";
49
+
50
+ /** The harness step a repository uses when it names none. */
51
+ export const DEFAULT_WORKER_USE = "radian/agent";
52
+
53
+ /** How long a review waits before it runs again after a model was unavailable. */
54
+ export const DEFAULT_REVIEWER_RETRY_SECS = 120;
55
+
56
+ /** What a repository may configure for the worker harness step. */
57
+ export interface WorkerSettings {
58
+ readonly use: string;
59
+ readonly args: readonly string[];
60
+ readonly wallTimeSecs?: number | undefined;
61
+ readonly stallSecs?: number | undefined;
62
+ }
63
+
64
+ /** The name of a harness step's plugin, or the whole text when it has no `/`. */
65
+ function workerNameOf(use: string): string {
66
+ return use.includes("/") ? harnessOf(use) : use;
67
+ }
68
+
69
+ /**
70
+ * The old single `worker` as a pool: one worker named after its harness,
71
+ * `count` = `concurrency`, in a pool named `default`.
72
+ */
73
+ function legacyWorkers(worker: WorkerSettings, concurrency: number): ParsedWorkers {
74
+ const name = workerNameOf(worker.use);
75
+ return {
76
+ workers: [
77
+ {
78
+ name,
79
+ use: worker.use,
80
+ args: worker.args,
81
+ count: concurrency,
82
+ ...(worker.wallTimeSecs === undefined ? {} : { wallTimeSecs: worker.wallTimeSecs }),
83
+ ...(worker.stallSecs === undefined ? {} : { stallSecs: worker.stallSecs }),
84
+ },
85
+ ],
86
+ pools: { [DEFAULT_POOL]: [name] },
87
+ };
88
+ }
89
+
90
+ /** How serious a review finding must be before it fails the gate. */
91
+ export type FixLevel = "critical" | "major" | "minor";
92
+
93
+ /** How a failed check command runs only the tests that failed. */
94
+ export interface FailedRerun {
95
+ /** A regex with one capture group: the failed test's name. */
96
+ readonly match: string;
97
+ /** The command that runs one test again; `{name}` and `{pattern}` are replaced. */
98
+ readonly rerun: string;
99
+ /** The most failed tests that are run again; more fails the check. */
100
+ readonly max: number;
101
+ /** The command that reproduces a flaky test; `{name}`, `{pattern}` and `{file}` are replaced. */
102
+ readonly stress?: string;
103
+ /** A path inside the repository to the text of its rule for flaky tests. */
104
+ readonly rule?: string;
105
+ }
106
+
107
+ /** A check command: a shell line, or a line with a rerun of its failed tests. */
108
+ export type CheckCommand =
109
+ | string
110
+ | { readonly run: string; readonly failed?: FailedRerun };
111
+
112
+ /** How a work step that is running out of time is told to stop. */
113
+ export interface WorkSettings {
114
+ /**
115
+ * The share of the work step's time limit, above 0 and below 1, at which the
116
+ * worker is asked to stop starting new things, commit and write a progress
117
+ * note.
118
+ */
119
+ readonly wrapUpAt: number;
120
+ }
121
+
122
+ /** The commands a task's gate runs and how long each may take. */
123
+ export interface GateSettings {
124
+ readonly commands: readonly CheckCommand[];
125
+ readonly commandTimeoutSecs: number;
126
+ /** How long a gate command may write nothing; unset turns the limit off. */
127
+ readonly stallSecs?: number;
128
+ /** The most checks of this repository that run at once; unset means no limit of its own. */
129
+ readonly places?: number;
130
+ }
131
+
132
+ /** What a failed check does before it counts as a failure. */
133
+ export interface CheckSettings {
134
+ /** How many times a failed check line list runs again; 0 turns it off. */
135
+ readonly rerun: number;
136
+ /**
137
+ * How many passes on rerun of one test in a repository propose a task to fix
138
+ * it; 0 turns the proposal off.
139
+ */
140
+ readonly flakyTask: number;
141
+ /**
142
+ * The plan the proposed flaky-test tasks go into, by id. Unset, or when that
143
+ * plan is finished or cancelled, dev uses its own plan `flaky-tests`.
144
+ */
145
+ readonly flakyPlan?: string | undefined;
146
+ /**
147
+ * The 1-minute load average below which a machine counts as idle enough to
148
+ * trust a check. Unset: the number of cores.
149
+ */
150
+ readonly loadLimit?: number | undefined;
151
+ /**
152
+ * The 1-minute load above which a failed test was seen under load and never
153
+ * counts toward a flaky-test task. Unset: twice the number of cores.
154
+ */
155
+ readonly flakyLoadLimit?: number | undefined;
156
+ }
157
+
158
+ /** What a task does when its step failed for a reason outside its own work. */
159
+ export interface RetrySettings {
160
+ /**
161
+ * How long a retry waits for what was missing (a step that is not loaded,
162
+ * settings that cannot be read) before the task waits for a person.
163
+ */
164
+ readonly environmentWaitMinutes: number;
165
+ }
166
+
167
+ /** How the integrate step lands a verified commit on main. */
168
+ export type IntegrationStyle = "merge" | "squash";
169
+
170
+ /** How the integrate step builds and lands a candidate on main. */
171
+ export interface IntegrationSettings {
172
+ readonly style: IntegrationStyle;
173
+ /** Commands that must pass on the candidate before it is pushed. */
174
+ readonly keyCommands: readonly CheckCommand[];
175
+ /** The most tasks one integration may merge together; 1 means one at a time. */
176
+ readonly batch: number;
177
+ }
178
+
179
+ /** Commands the cleanup step runs after a merge. */
180
+ export interface HookSettings {
181
+ readonly afterMerge: readonly string[];
182
+ }
183
+
184
+ /** A second harness step the reviewer may fall back to. */
185
+ export interface ReviewerFallback {
186
+ readonly use: string;
187
+ readonly args: readonly string[];
188
+ }
189
+
190
+ /** What a first review may set differently from the default block. */
191
+ export interface ReviewerFirst {
192
+ readonly use?: string | undefined;
193
+ readonly args?: readonly string[] | undefined;
194
+ readonly timeoutSecs?: number | undefined;
195
+ readonly stallSecs?: number | undefined;
196
+ }
197
+
198
+ /** What a repository may configure for the review harness step. */
199
+ export interface ReviewerSettings {
200
+ readonly use: string;
201
+ readonly args: readonly string[];
202
+ /** The arguments of the first review of an attempt, when they differ. */
203
+ readonly firstArgs?: readonly string[] | undefined;
204
+ /**
205
+ * The first review of a task: a block whose set values replace the
206
+ * reviewer's own for that review. Every later review uses the reviewer's.
207
+ */
208
+ readonly first?: ReviewerFirst | undefined;
209
+ /**
210
+ * The step, or the steps in order, used when the primary reviewer is
211
+ * unavailable or does not write the report.
212
+ */
213
+ readonly fallback?: ReviewerFallback | readonly ReviewerFallback[] | undefined;
214
+ readonly timeoutSecs: number;
215
+ /** How long a review may print nothing; unset uses the harness default. */
216
+ readonly stallSecs?: number | undefined;
217
+ readonly fixLevel: FixLevel;
218
+ /** Whether findings that did not fail a review become a follow-up task. */
219
+ readonly followups: boolean;
220
+ /** How long an unavailable review waits before it runs again. */
221
+ readonly retrySecs: number;
222
+ /** The largest diff one file may put in the review prompt. */
223
+ readonly maxFileDiffBytes: number;
224
+ /** The largest diff the whole review prompt may carry. */
225
+ readonly maxDiffBytes: number;
226
+ }
227
+
228
+ /** The whole `.operad/dev.json` document, with every default filled. */
229
+ export interface DevSettings {
230
+ readonly name?: string | undefined;
231
+ readonly remote: string;
232
+ readonly mainBranch: string;
233
+ readonly worktreeRoot: string;
234
+ /**
235
+ * The cap `concurrency` sets on running tasks. When the file does not set
236
+ * it, the default pool's counts alone decide (see `runningTaskCap`).
237
+ */
238
+ readonly concurrency: number;
239
+ /** Whether the file wrote `concurrency` itself. */
240
+ readonly concurrencySet: boolean;
241
+ /**
242
+ * The worker the repository's work step runs first: the old `worker`
243
+ * setting, or the first worker of the `default` pool.
244
+ */
245
+ readonly worker: WorkerSettings;
246
+ /**
247
+ * Every worker and pool of the repository. The old `worker` setting is one
248
+ * worker named after its harness, with `count` = `concurrency`, in `default`.
249
+ */
250
+ readonly workers: ParsedWorkers;
251
+ readonly workerBrief: string;
252
+ /**
253
+ * Commands run in every checkout dev makes (the worker's worktree, the gate
254
+ * checkout, the integration checkout) after it is created or moved to a new
255
+ * commit and before a step uses it.
256
+ */
257
+ readonly prepare: readonly string[];
258
+ readonly gate: GateSettings;
259
+ readonly check: CheckSettings;
260
+ readonly work: WorkSettings;
261
+ readonly reviewer: ReviewerSettings;
262
+ readonly integration: IntegrationSettings;
263
+ readonly hooks: HookSettings;
264
+ readonly maxAutoRework: number;
265
+ /** The auto level a new plan starts at. */
266
+ readonly autoDefault: AutoMode;
267
+ readonly retry: RetrySettings;
268
+ /** The repository's own flows; an absent map runs the built-in default. */
269
+ readonly flows: DevFlows;
270
+ }
271
+
272
+ /**
273
+ * The commands cleanup runs when a repository sets none. They remove the task
274
+ * and gate worktrees, prune a worktree that was removed by hand, and delete the
275
+ * task's local and remote branch. The step records a failure and keeps going.
276
+ * Each default hook does nothing when its work is already done, so cleanup run
277
+ * again after a kill ends as clean as the first run.
278
+ */
279
+ export const DEFAULT_AFTER_MERGE: readonly string[] = [
280
+ "if [ -e \"$OPERAD_WORKTREE\" ]; then git worktree remove --force \"$OPERAD_WORKTREE\"; fi",
281
+ "if [ -e \"$OPERAD_WORKTREE-gate\" ]; then git worktree remove --force \"$OPERAD_WORKTREE-gate\"; fi",
282
+ "git worktree prune",
283
+ "if git show-ref --verify --quiet \"refs/heads/work/$OPERAD_TASK\"; then git branch -D \"work/$OPERAD_TASK\"; fi",
284
+ "if git ls-remote --exit-code --heads \"$OPERAD_REMOTE\" \"work/$OPERAD_TASK\" >/dev/null; then git push \"$OPERAD_REMOTE\" --delete \"work/$OPERAD_TASK\"; else [ $? -eq 2 ]; fi",
285
+ ];
286
+
287
+ /**
288
+ * The text a task's worker gets when the repository ships no brief of its own.
289
+ * It says the four things every worker must know and nothing project-specific.
290
+ */
291
+ export const DEFAULT_WORKER_BRIEF = [
292
+ "Work only in this worktree. Do not change files outside it.",
293
+ "Commit each whole piece of work as you finish it; leave the worktree clean.",
294
+ "Before you finish, run the repository's verify command and make it pass.",
295
+ "End with a summary of what you changed and what is left.",
296
+ ].join("\n");
297
+
298
+ export const DEFAULT_DEV_SETTINGS: DevSettings = {
299
+ remote: "origin",
300
+ mainBranch: "main",
301
+ worktreeRoot: ".operad-worktrees",
302
+ concurrency: 1,
303
+ concurrencySet: false,
304
+ worker: {
305
+ use: DEFAULT_WORKER_USE,
306
+ args: [],
307
+ },
308
+ workers: legacyWorkers({ use: DEFAULT_WORKER_USE, args: [] }, 1),
309
+ workerBrief: WORKER_BRIEF_FILE,
310
+ prepare: [],
311
+ gate: {
312
+ commands: [],
313
+ commandTimeoutSecs: 1800,
314
+ },
315
+ check: { rerun: 1, flakyTask: 2 },
316
+ work: { wrapUpAt: 0.85 },
317
+ reviewer: {
318
+ use: DEFAULT_WORKER_USE,
319
+ args: [],
320
+ timeoutSecs: 600,
321
+ fixLevel: "major",
322
+ followups: true,
323
+ retrySecs: DEFAULT_REVIEWER_RETRY_SECS,
324
+ maxFileDiffBytes: 200_000,
325
+ maxDiffBytes: 1_000_000,
326
+ },
327
+ integration: {
328
+ style: "merge",
329
+ keyCommands: [],
330
+ batch: 1,
331
+ },
332
+ hooks: {
333
+ afterMerge: DEFAULT_AFTER_MERGE,
334
+ },
335
+ maxAutoRework: 2,
336
+ autoDefault: "off",
337
+ retry: { environmentWaitMinutes: 60 },
338
+ flows: {},
339
+ };
340
+
341
+ const KNOWN_FIELDS = new Set([
342
+ "$schema",
343
+ "name",
344
+ "remote",
345
+ "mainBranch",
346
+ "worktreeRoot",
347
+ // Written by versions before the step work; `worktrees` is the old name of
348
+ // `worktreeRoot`, `sandbox` is no longer used at all.
349
+ "worktrees",
350
+ "sandbox",
351
+ "concurrency",
352
+ "worker",
353
+ "workers",
354
+ "pools",
355
+ "workerBrief",
356
+ "prepare",
357
+ "gate",
358
+ "check",
359
+ "work",
360
+ "reviewer",
361
+ "integration",
362
+ "hooks",
363
+ "maxAutoRework",
364
+ "autoDefault",
365
+ "retry",
366
+ "flows",
367
+ ]);
368
+
369
+ function nonEmptyString(value: unknown, field: string): string {
370
+ if (typeof value !== "string" || value.trim().length === 0) {
371
+ throw new DevError(field, "must be a non-empty string");
372
+ }
373
+ return value;
374
+ }
375
+
376
+ /**
377
+ * A directory setting must stay inside the repository: an absolute path or one
378
+ * that climbs out would put worktrees where `dev` does not own them.
379
+ */
380
+ function repositoryRelativePath(value: unknown, field: string): string {
381
+ const path = nonEmptyString(value, field);
382
+ if (isAbsolute(path)) {
383
+ throw new DevError(field, "must be relative to the repository");
384
+ }
385
+ const normalized = normalize(path);
386
+ if (normalized === ".." || normalized.startsWith(`..${sep}`)) {
387
+ throw new DevError(field, "must stay inside the repository");
388
+ }
389
+ return path;
390
+ }
391
+
392
+ /**
393
+ * The real path of `path`, resolving the symlinks of every part that exists.
394
+ * A tail that does not exist yet is appended unchanged, so the answer is where
395
+ * creating it now would land.
396
+ */
397
+ function realPathOf(path: string): string {
398
+ const target = resolve(path);
399
+ let current = target;
400
+ const missing: string[] = [];
401
+ for (;;) {
402
+ try {
403
+ return join(realpathSync(current), ...missing.reverse());
404
+ } catch {
405
+ const parent = dirname(current);
406
+ if (parent === current) return target;
407
+ missing.push(basename(current));
408
+ current = parent;
409
+ }
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Refuses a path that resolves outside the repository. The lexical check in
415
+ * `repositoryRelativePath` cannot see a symlink; this one follows every part
416
+ * that exists, including a `worktreeRoot` that is a link to somewhere else.
417
+ */
418
+ export function assertInsideRepository(
419
+ repositoryPath: string,
420
+ path: string,
421
+ field: string,
422
+ ): void {
423
+ const repository = realPathOf(repositoryPath);
424
+ const target = realPathOf(path);
425
+ if (target !== repository && !target.startsWith(`${repository}${sep}`)) {
426
+ throw new DevError(field, "must stay inside the repository");
427
+ }
428
+ }
429
+
430
+ function autoMode(value: unknown, field: string): AutoMode {
431
+ if (value !== "off" && value !== "run" && value !== "merge") {
432
+ throw new DevError(field, 'must be "off", "run" or "merge"');
433
+ }
434
+ return value;
435
+ }
436
+
437
+ function positiveNumber(value: unknown, field: string): number {
438
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
439
+ throw new DevError(field, "must be a positive number");
440
+ }
441
+ return value;
442
+ }
443
+
444
+ function positiveSeconds(value: unknown, field: string): number {
445
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
446
+ throw new DevError(field, "must be a positive number of seconds");
447
+ }
448
+ return value;
449
+ }
450
+
451
+ function settingsStringList(value: unknown, field: string): readonly string[] {
452
+ if (!Array.isArray(value)) {
453
+ throw new DevError(field, "must be an array of strings");
454
+ }
455
+ return value.map((item, index) => {
456
+ if (typeof item !== "string") {
457
+ throw new DevError(`${field}[${index}]`, "must be a string");
458
+ }
459
+ return item;
460
+ });
461
+ }
462
+
463
+ function workerSettings(value: unknown, field: string): WorkerSettings {
464
+ if (!isRecord(value)) {
465
+ throw new DevError(field, "must be an object");
466
+ }
467
+ for (const key of Object.keys(value)) {
468
+ if (key !== "use" && key !== "args" && key !== "wallTimeSecs" && key !== "stallSecs") {
469
+ throw new DevError(`${field}.${key}`, "is not a worker setting");
470
+ }
471
+ }
472
+ const use =
473
+ value.use === undefined
474
+ ? DEFAULT_DEV_SETTINGS.worker.use
475
+ : nonEmptyString(value.use, `${field}.use`);
476
+ const args =
477
+ value.args === undefined
478
+ ? []
479
+ : settingsStringList(value.args, `${field}.args`);
480
+ const wallTimeSecs =
481
+ value.wallTimeSecs === undefined
482
+ ? undefined
483
+ : positiveSeconds(value.wallTimeSecs, `${field}.wallTimeSecs`);
484
+ const stallSecs =
485
+ value.stallSecs === undefined
486
+ ? undefined
487
+ : positiveSeconds(value.stallSecs, `${field}.stallSecs`);
488
+ return {
489
+ use,
490
+ args,
491
+ ...(wallTimeSecs === undefined ? {} : { wallTimeSecs }),
492
+ ...(stallSecs === undefined ? {} : { stallSecs }),
493
+ };
494
+ }
495
+
496
+ function positiveInteger(value: unknown, field: string): number {
497
+ if (
498
+ typeof value !== "number" ||
499
+ !Number.isFinite(value) ||
500
+ !Number.isInteger(value) ||
501
+ value <= 0
502
+ ) {
503
+ throw new DevError(field, "must be a positive integer");
504
+ }
505
+ return value;
506
+ }
507
+
508
+ function nonNegativeInteger(value: unknown, field: string): number {
509
+ if (
510
+ typeof value !== "number" ||
511
+ !Number.isFinite(value) ||
512
+ !Number.isInteger(value) ||
513
+ value < 0
514
+ ) {
515
+ throw new DevError(field, "must be zero or a positive integer");
516
+ }
517
+ return value;
518
+ }
519
+
520
+ function lineList(value: unknown, field: string): readonly string[] {
521
+ const lines = settingsStringList(value, field);
522
+ lines.forEach((line, index) => {
523
+ if (line.trim().length === 0) {
524
+ throw new DevError(`${field}[${index}]`, "must be a non-empty string");
525
+ }
526
+ });
527
+ return lines;
528
+ }
529
+
530
+ /** A path relative to the repository that stays inside it. */
531
+ function rulePath(value: unknown, field: string): string {
532
+ const path = nonEmptyString(value, field);
533
+ const parts = path.split(/[\\/]/);
534
+ if (isAbsolute(path) || parts.includes("..")) {
535
+ throw new DevError(field, "must be a path inside the repository");
536
+ }
537
+ return path;
538
+ }
539
+
540
+ function failedRerun(value: unknown, field: string): FailedRerun {
541
+ if (!isRecord(value)) throw new DevError(field, "must be an object");
542
+ for (const key of Object.keys(value)) {
543
+ if (key !== "match" && key !== "rerun" && key !== "max" && key !== "stress" && key !== "rule") {
544
+ throw new DevError(`${field}.${key}`, "is not a failed setting");
545
+ }
546
+ }
547
+ const match = nonEmptyString(value.match, `${field}.match`);
548
+ let groups: number;
549
+ try {
550
+ groups = (new RegExp(`${match}|`).exec("")?.length ?? 1) - 1;
551
+ } catch {
552
+ throw new DevError(`${field}.match`, "must be a valid regular expression");
553
+ }
554
+ if (groups !== 1) {
555
+ throw new DevError(`${field}.match`, "must have exactly one capture group");
556
+ }
557
+ const rerun = nonEmptyString(value.rerun, `${field}.rerun`);
558
+ if (!rerun.includes("{name}") && !rerun.includes("{pattern}")) {
559
+ throw new DevError(`${field}.rerun`, "must contain {name} or {pattern}");
560
+ }
561
+ return {
562
+ match,
563
+ rerun,
564
+ max:
565
+ value.max === undefined
566
+ ? 10
567
+ : positiveInteger(value.max, `${field}.max`),
568
+ ...(value.stress === undefined
569
+ ? {}
570
+ : { stress: nonEmptyString(value.stress, `${field}.stress`) }),
571
+ ...(value.rule === undefined ? {} : { rule: rulePath(value.rule, `${field}.rule`) }),
572
+ };
573
+ }
574
+
575
+ function commandList(value: unknown, field: string): readonly CheckCommand[] {
576
+ if (!Array.isArray(value)) {
577
+ throw new DevError(field, "must be an array of commands");
578
+ }
579
+ return value.map((command: unknown, index): CheckCommand => {
580
+ const at = `${field}[${index}]`;
581
+ if (typeof command === "string") return nonEmptyString(command, at);
582
+ if (!isRecord(command)) {
583
+ throw new DevError(at, "must be a string or an object");
584
+ }
585
+ for (const key of Object.keys(command)) {
586
+ if (key !== "run" && key !== "failed") {
587
+ throw new DevError(`${at}.${key}`, "is not a command setting");
588
+ }
589
+ }
590
+ const run = nonEmptyString(command.run, `${at}.run`);
591
+ return command.failed === undefined
592
+ ? { run }
593
+ : { run, failed: failedRerun(command.failed, `${at}.failed`) };
594
+ });
595
+ }
596
+
597
+ function prepareList(value: unknown, field: string): readonly string[] {
598
+ if (!Array.isArray(value)) {
599
+ throw new DevError(field, "must be an array of command lines");
600
+ }
601
+ return value.map((line: unknown, index) =>
602
+ nonEmptyString(line, `${field}[${index}]`),
603
+ );
604
+ }
605
+
606
+ function positiveCount(value: unknown, field: string): number {
607
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
608
+ throw new DevError(field, "must be an integer of 1 or more");
609
+ }
610
+ return value;
611
+ }
612
+
613
+ function gateSettings(value: unknown, field: string): GateSettings {
614
+ if (!isRecord(value)) {
615
+ throw new DevError(field, "must be an object");
616
+ }
617
+ for (const key of Object.keys(value)) {
618
+ if (
619
+ key !== "commands" &&
620
+ key !== "commandTimeoutSecs" &&
621
+ key !== "stallSecs" &&
622
+ key !== "places"
623
+ ) {
624
+ throw new DevError(`${field}.${key}`, "is not a gate setting");
625
+ }
626
+ }
627
+ return {
628
+ commands:
629
+ value.commands === undefined
630
+ ? DEFAULT_DEV_SETTINGS.gate.commands
631
+ : commandList(value.commands, `${field}.commands`),
632
+ commandTimeoutSecs:
633
+ value.commandTimeoutSecs === undefined
634
+ ? DEFAULT_DEV_SETTINGS.gate.commandTimeoutSecs
635
+ : positiveSeconds(value.commandTimeoutSecs, `${field}.commandTimeoutSecs`),
636
+ ...(value.stallSecs === undefined
637
+ ? {}
638
+ : { stallSecs: positiveSeconds(value.stallSecs, `${field}.stallSecs`) }),
639
+ ...(value.places === undefined
640
+ ? {}
641
+ : { places: positiveCount(value.places, `${field}.places`) }),
642
+ };
643
+ }
644
+
645
+ function flakyPlanId(value: unknown, field: string): string {
646
+ if (typeof value !== "string" || value.trim() === "") {
647
+ throw new DevError(field, "must be a plan id");
648
+ }
649
+ return value.trim();
650
+ }
651
+
652
+ function checkSettings(value: unknown, field: string): CheckSettings {
653
+ if (!isRecord(value)) {
654
+ throw new DevError(field, "must be an object");
655
+ }
656
+ for (const key of Object.keys(value)) {
657
+ if (key !== "rerun" &&
658
+ key !== "flakyTask" &&
659
+ key !== "flakyPlan" &&
660
+ key !== "loadLimit" &&
661
+ key !== "flakyLoadLimit") {
662
+ throw new DevError(`${field}.${key}`, "is not a check setting");
663
+ }
664
+ }
665
+ return {
666
+ rerun:
667
+ value.rerun === undefined
668
+ ? DEFAULT_DEV_SETTINGS.check.rerun
669
+ : nonNegativeInteger(value.rerun, `${field}.rerun`),
670
+ flakyTask:
671
+ value.flakyTask === undefined
672
+ ? DEFAULT_DEV_SETTINGS.check.flakyTask
673
+ : nonNegativeInteger(value.flakyTask, `${field}.flakyTask`),
674
+ ...(value.flakyPlan === undefined
675
+ ? {}
676
+ : { flakyPlan: flakyPlanId(value.flakyPlan, `${field}.flakyPlan`) }),
677
+ ...(value.loadLimit === undefined
678
+ ? {}
679
+ : { loadLimit: positiveNumber(value.loadLimit, `${field}.loadLimit`) }),
680
+ ...(value.flakyLoadLimit === undefined
681
+ ? {}
682
+ : { flakyLoadLimit: positiveNumber(value.flakyLoadLimit, `${field}.flakyLoadLimit`) }),
683
+ };
684
+ }
685
+
686
+ function workSettings(value: unknown, field: string): WorkSettings {
687
+ if (!isRecord(value)) {
688
+ throw new DevError(field, "must be an object");
689
+ }
690
+ for (const key of Object.keys(value)) {
691
+ if (key !== "wrapUpAt") {
692
+ throw new DevError(`${field}.${key}`, "is not a work setting");
693
+ }
694
+ }
695
+ const at = value.wrapUpAt;
696
+ if (at === undefined) return DEFAULT_DEV_SETTINGS.work;
697
+ if (typeof at !== "number" || !Number.isFinite(at) || at <= 0 || at >= 1) {
698
+ throw new DevError(
699
+ `${field}.wrapUpAt`,
700
+ "must be a number above 0 and below 1",
701
+ );
702
+ }
703
+ return { wrapUpAt: at };
704
+ }
705
+
706
+ function retrySettings(value: unknown, field: string): RetrySettings {
707
+ if (!isRecord(value)) {
708
+ throw new DevError(field, "must be an object");
709
+ }
710
+ for (const key of Object.keys(value)) {
711
+ if (key !== "environmentWaitMinutes") {
712
+ throw new DevError(`${field}.${key}`, "is not a retry setting");
713
+ }
714
+ }
715
+ return {
716
+ environmentWaitMinutes:
717
+ value.environmentWaitMinutes === undefined
718
+ ? DEFAULT_DEV_SETTINGS.retry.environmentWaitMinutes
719
+ : positiveInteger(
720
+ value.environmentWaitMinutes,
721
+ `${field}.environmentWaitMinutes`,
722
+ ),
723
+ };
724
+ }
725
+
726
+ function fixLevelOf(value: unknown, field: string): FixLevel {
727
+ if (value === undefined) return DEFAULT_DEV_SETTINGS.reviewer.fixLevel;
728
+ if (value !== "critical" && value !== "major" && value !== "minor") {
729
+ throw new DevError(field, 'must be "critical", "major" or "minor"');
730
+ }
731
+ return value;
732
+ }
733
+
734
+ /** The fallbacks of a reviewer in the order they are tried. */
735
+ export function reviewerFallbacks(
736
+ fallback: ReviewerFallback | readonly ReviewerFallback[] | undefined,
737
+ ): readonly ReviewerFallback[] {
738
+ if (fallback === undefined) return [];
739
+ return Array.isArray(fallback) ? fallback : [fallback as ReviewerFallback];
740
+ }
741
+
742
+ function reviewerFallbackSetting(
743
+ value: unknown,
744
+ field: string,
745
+ ): ReviewerFallback | readonly ReviewerFallback[] {
746
+ if (!Array.isArray(value)) return reviewerFallback(value, field);
747
+ if (value.length === 0) throw new DevError(field, "must not be an empty list");
748
+ return value.map((entry, index) =>
749
+ reviewerFallback(entry, `${field}[${index}]`),
750
+ );
751
+ }
752
+
753
+ function reviewerFallback(value: unknown, field: string): ReviewerFallback {
754
+ if (!isRecord(value)) {
755
+ throw new DevError(field, "must be an object");
756
+ }
757
+ for (const key of Object.keys(value)) {
758
+ if (key !== "use" && key !== "args") {
759
+ throw new DevError(`${field}.${key}`, "is not a fallback setting");
760
+ }
761
+ }
762
+ return {
763
+ use: nonEmptyString(value.use, `${field}.use`),
764
+ args:
765
+ value.args === undefined ? [] : settingsStringList(value.args, `${field}.args`),
766
+ };
767
+ }
768
+
769
+ function booleanOf(value: unknown, field: string): boolean {
770
+ if (typeof value !== "boolean") throw new DevError(field, "must be true or false");
771
+ return value;
772
+ }
773
+
774
+ function reviewerFirst(value: unknown, field: string): ReviewerFirst {
775
+ if (!isRecord(value)) throw new DevError(field, "must be an object");
776
+ for (const key of Object.keys(value)) {
777
+ if (
778
+ key !== "use" &&
779
+ key !== "args" &&
780
+ key !== "timeoutSecs" &&
781
+ key !== "stallSecs"
782
+ ) {
783
+ throw new DevError(`${field}.${key}`, "is not a first review setting");
784
+ }
785
+ }
786
+ return {
787
+ ...(value.use === undefined
788
+ ? {}
789
+ : { use: nonEmptyString(value.use, `${field}.use`) }),
790
+ ...(value.args === undefined
791
+ ? {}
792
+ : { args: settingsStringList(value.args, `${field}.args`) }),
793
+ ...(value.timeoutSecs === undefined
794
+ ? {}
795
+ : { timeoutSecs: positiveSeconds(value.timeoutSecs, `${field}.timeoutSecs`) }),
796
+ ...(value.stallSecs === undefined
797
+ ? {}
798
+ : { stallSecs: positiveSeconds(value.stallSecs, `${field}.stallSecs`) }),
799
+ };
800
+ }
801
+
802
+ function reviewerSettings(value: unknown, field: string): ReviewerSettings {
803
+ if (!isRecord(value)) {
804
+ throw new DevError(field, "must be an object");
805
+ }
806
+ for (const key of Object.keys(value)) {
807
+ if (
808
+ key !== "use" &&
809
+ key !== "args" &&
810
+ key !== "firstArgs" &&
811
+ key !== "first" &&
812
+ key !== "fallback" &&
813
+ key !== "timeoutSecs" &&
814
+ key !== "stallSecs" &&
815
+ key !== "fixLevel" &&
816
+ key !== "followups" &&
817
+ key !== "retrySecs" &&
818
+ key !== "maxFileDiffBytes" &&
819
+ key !== "maxDiffBytes"
820
+ ) {
821
+ throw new DevError(`${field}.${key}`, "is not a reviewer setting");
822
+ }
823
+ }
824
+ const firstArgs =
825
+ value.firstArgs === undefined
826
+ ? undefined
827
+ : settingsStringList(value.firstArgs, `${field}.firstArgs`);
828
+ const first =
829
+ value.first === undefined
830
+ ? undefined
831
+ : reviewerFirst(value.first, `${field}.first`);
832
+ const fallback =
833
+ value.fallback === undefined
834
+ ? undefined
835
+ : reviewerFallbackSetting(value.fallback, `${field}.fallback`);
836
+ return {
837
+ use:
838
+ value.use === undefined
839
+ ? DEFAULT_DEV_SETTINGS.reviewer.use
840
+ : nonEmptyString(value.use, `${field}.use`),
841
+ args:
842
+ value.args === undefined
843
+ ? []
844
+ : settingsStringList(value.args, `${field}.args`),
845
+ ...(firstArgs === undefined ? {} : { firstArgs }),
846
+ ...(first === undefined ? {} : { first }),
847
+ ...(fallback === undefined ? {} : { fallback }),
848
+ timeoutSecs:
849
+ value.timeoutSecs === undefined
850
+ ? DEFAULT_DEV_SETTINGS.reviewer.timeoutSecs
851
+ : positiveSeconds(value.timeoutSecs, `${field}.timeoutSecs`),
852
+ ...(value.stallSecs === undefined
853
+ ? {}
854
+ : { stallSecs: positiveSeconds(value.stallSecs, `${field}.stallSecs`) }),
855
+ fixLevel: fixLevelOf(value.fixLevel, `${field}.fixLevel`),
856
+ followups:
857
+ value.followups === undefined
858
+ ? DEFAULT_DEV_SETTINGS.reviewer.followups
859
+ : booleanOf(value.followups, `${field}.followups`),
860
+ retrySecs:
861
+ value.retrySecs === undefined
862
+ ? DEFAULT_DEV_SETTINGS.reviewer.retrySecs
863
+ : positiveSeconds(value.retrySecs, `${field}.retrySecs`),
864
+ maxFileDiffBytes:
865
+ value.maxFileDiffBytes === undefined
866
+ ? DEFAULT_DEV_SETTINGS.reviewer.maxFileDiffBytes
867
+ : positiveInteger(value.maxFileDiffBytes, `${field}.maxFileDiffBytes`),
868
+ maxDiffBytes:
869
+ value.maxDiffBytes === undefined
870
+ ? DEFAULT_DEV_SETTINGS.reviewer.maxDiffBytes
871
+ : positiveInteger(value.maxDiffBytes, `${field}.maxDiffBytes`),
872
+ };
873
+ }
874
+
875
+ function integrationStyle(value: unknown, field: string): IntegrationStyle {
876
+ if (value === undefined) return DEFAULT_DEV_SETTINGS.integration.style;
877
+ if (value !== "merge" && value !== "squash") {
878
+ throw new DevError(field, 'must be "merge" or "squash"');
879
+ }
880
+ return value;
881
+ }
882
+
883
+ function integrationSettings(value: unknown, field: string): IntegrationSettings {
884
+ if (!isRecord(value)) {
885
+ throw new DevError(field, "must be an object");
886
+ }
887
+ for (const key of Object.keys(value)) {
888
+ if (key !== "style" && key !== "keyCommands" && key !== "batch") {
889
+ throw new DevError(`${field}.${key}`, "is not an integration setting");
890
+ }
891
+ }
892
+ return {
893
+ style: integrationStyle(value.style, `${field}.style`),
894
+ keyCommands:
895
+ value.keyCommands === undefined
896
+ ? DEFAULT_DEV_SETTINGS.integration.keyCommands
897
+ : commandList(value.keyCommands, `${field}.keyCommands`),
898
+ batch:
899
+ value.batch === undefined
900
+ ? DEFAULT_DEV_SETTINGS.integration.batch
901
+ : positiveInteger(value.batch, `${field}.batch`),
902
+ };
903
+ }
904
+
905
+ function hookSettings(value: unknown, field: string): HookSettings {
906
+ if (!isRecord(value)) {
907
+ throw new DevError(field, "must be an object");
908
+ }
909
+ for (const key of Object.keys(value)) {
910
+ if (key !== "afterMerge") {
911
+ throw new DevError(`${field}.${key}`, "is not a hook setting");
912
+ }
913
+ }
914
+ return {
915
+ afterMerge:
916
+ value.afterMerge === undefined
917
+ ? DEFAULT_DEV_SETTINGS.hooks.afterMerge
918
+ : lineList(value.afterMerge, `${field}.afterMerge`),
919
+ };
920
+ }
921
+
922
+ /**
923
+ * The root task worktrees live in. Settings written before the step work used
924
+ * `worktrees`; it is read as the same setting so an upgrade needs no edit.
925
+ */
926
+ function worktreeRootOf(value: Record<string, unknown>): {
927
+ readonly root: string;
928
+ readonly field: string;
929
+ } {
930
+ if (value.worktreeRoot !== undefined) {
931
+ return {
932
+ root: repositoryRelativePath(value.worktreeRoot, "worktreeRoot"),
933
+ field: "worktreeRoot",
934
+ };
935
+ }
936
+ if (value.worktrees !== undefined) {
937
+ return {
938
+ root: repositoryRelativePath(value.worktrees, "worktrees"),
939
+ field: "worktrees",
940
+ };
941
+ }
942
+ return { root: DEFAULT_DEV_SETTINGS.worktreeRoot, field: "worktreeRoot" };
943
+ }
944
+
945
+ /** The first worker of the `default` pool, as the single-worker settings. */
946
+ function firstWorker(workers: ParsedWorkers): WorkerSettings {
947
+ const name = workers.pools[DEFAULT_POOL]?.[0];
948
+ const found = workers.workers.find((worker) => worker.name === name);
949
+ if (found === undefined) {
950
+ throw new DevError("pools", `needs a pool named "${DEFAULT_POOL}"`);
951
+ }
952
+ return {
953
+ use: found.use,
954
+ args: found.args,
955
+ ...(found.wallTimeSecs === undefined ? {} : { wallTimeSecs: found.wallTimeSecs }),
956
+ ...(found.stallSecs === undefined ? {} : { stallSecs: found.stallSecs }),
957
+ };
958
+ }
959
+
960
+ /** Reads `worker` or `workers` and `pools`; both forms together are refused. */
961
+ function workerSettingsOf(
962
+ value: Readonly<Record<string, unknown>>,
963
+ concurrency: number,
964
+ ): { readonly worker: WorkerSettings; readonly workers: ParsedWorkers } {
965
+ if (value.workers === undefined) {
966
+ if (value.pools !== undefined) {
967
+ throw new DevError("pools", "needs workers; the single worker setting has no pools");
968
+ }
969
+ const worker =
970
+ value.worker === undefined
971
+ ? DEFAULT_DEV_SETTINGS.worker
972
+ : workerSettings(value.worker, "worker");
973
+ return { worker, workers: legacyWorkers(worker, concurrency) };
974
+ }
975
+ if (value.worker !== undefined) {
976
+ throw new DevError(
977
+ "worker",
978
+ "cannot be set together with workers; use one or the other",
979
+ );
980
+ }
981
+ let workers: ParsedWorkers;
982
+ try {
983
+ workers = parseWorkers(value.workers, value.pools);
984
+ } catch (error) {
985
+ if (error instanceof WorkerDefinitionError) {
986
+ throw new DevError(error.field, error.message.slice(error.field.length + 2));
987
+ }
988
+ throw error;
989
+ }
990
+ if (workers.pools[DEFAULT_POOL] === undefined) {
991
+ throw new DevError("pools", `needs a pool named "${DEFAULT_POOL}", the one the dev flow uses`);
992
+ }
993
+ return { worker: firstWorker(workers), workers };
994
+ }
995
+
996
+ /** The workers of one pool, in the order the pool lists them. */
997
+ export function poolWorkers(
998
+ settings: DevSettings,
999
+ pool: string,
1000
+ ): readonly WorkerDefinition[] {
1001
+ const names = settings.workers.pools[pool] ?? [];
1002
+ const found: WorkerDefinition[] = [];
1003
+ for (const name of names) {
1004
+ const worker = settings.workers.workers.find((item) => item.name === name);
1005
+ if (worker !== undefined) found.push(worker);
1006
+ }
1007
+ return found;
1008
+ }
1009
+
1010
+ /** The pool's own cap: its workers' counts, or its `concurrency` when smaller. */
1011
+ export function poolCap(settings: DevSettings, pool: string): number {
1012
+ const total = poolWorkers(settings, pool).reduce((sum, worker) => sum + worker.count, 0);
1013
+ const limit = settings.workers.poolConcurrency?.[pool];
1014
+ return limit === undefined ? total : Math.min(total, limit);
1015
+ }
1016
+
1017
+ /**
1018
+ * How many tasks one pool runs at once (the `default` pool unless one is
1019
+ * named): its cap, further limited by the file's `concurrency` when written.
1020
+ */
1021
+ export function runningTaskCap(settings: DevSettings, pool: string = DEFAULT_POOL): number {
1022
+ const total = poolCap(settings, pool);
1023
+ return settings.concurrencySet ? Math.min(total, settings.concurrency) : total;
1024
+ }
1025
+
1026
+ /**
1027
+ * How many tasks the repository runs at once across all pools: every pool's
1028
+ * cap added up, and the file's `concurrency` when written caps them together.
1029
+ */
1030
+ export function repositoryTaskCap(settings: DevSettings): number {
1031
+ const total = Object.keys(settings.workers.pools).reduce(
1032
+ (sum, name) => sum + poolCap(settings, name),
1033
+ 0,
1034
+ );
1035
+ return settings.concurrencySet ? Math.min(total, settings.concurrency) : total;
1036
+ }
1037
+
1038
+ /** The pool a flow's tasks count against: its first work stage's pool, or `default`. */
1039
+ export function flowPool(settings: DevSettings, flowName: string | undefined): string {
1040
+ const spec = settings.flows[flowName ?? "default"];
1041
+ for (const stage of spec?.stages ?? []) {
1042
+ if (stage.stage === "work") return stage.pool ?? DEFAULT_POOL;
1043
+ }
1044
+ return DEFAULT_POOL;
1045
+ }
1046
+
1047
+ /** The fields a stage of each kind may name. */
1048
+ const STAGE_FIELDS: Readonly<Record<DevStage["stage"], readonly string[]>> = {
1049
+ work: ["stage", "use", "args", "pool", "workerBrief", "commit", "brief", "beforeAttempt"],
1050
+ check: ["stage", "commands", "rerun"],
1051
+ review: ["stage", "use", "args", "later", "grading"],
1052
+ human: ["stage"],
1053
+ };
1054
+
1055
+ function stageOf(value: unknown, field: string): DevStage {
1056
+ if (!isRecord(value)) {
1057
+ throw new DevError(field, "must be a JSON object");
1058
+ }
1059
+ const kind = value.stage;
1060
+ if (
1061
+ kind !== "work" &&
1062
+ kind !== "check" &&
1063
+ kind !== "review" &&
1064
+ kind !== "human"
1065
+ ) {
1066
+ throw new DevError(
1067
+ `${field}.stage`,
1068
+ 'must be "work", "check", "review" or "human"',
1069
+ );
1070
+ }
1071
+ for (const key of Object.keys(value)) {
1072
+ if (!STAGE_FIELDS[kind].includes(key)) {
1073
+ throw new DevError(`${field}.${key}`, "is not a stage setting");
1074
+ }
1075
+ }
1076
+ const optionalString = (key: string): string | undefined =>
1077
+ value[key] === undefined ? undefined : nonEmptyString(value[key], `${field}.${key}`);
1078
+ const optionalList = (key: string): readonly string[] | undefined =>
1079
+ value[key] === undefined ? undefined : settingsStringList(value[key], `${field}.${key}`);
1080
+ switch (kind) {
1081
+ case "work": {
1082
+ const use = optionalString("use");
1083
+ const args = optionalList("args");
1084
+ const pool = optionalString("pool");
1085
+ const brief = optionalString("brief");
1086
+ const workerBrief = optionalString("workerBrief");
1087
+ if (value.commit !== undefined && typeof value.commit !== "boolean") {
1088
+ throw new DevError(`${field}.commit`, "must be true or false");
1089
+ }
1090
+ const commit = value.commit;
1091
+ const beforeAttempt = optionalString("beforeAttempt");
1092
+ if (
1093
+ beforeAttempt !== undefined &&
1094
+ beforeAttempt !== "merge-main" &&
1095
+ beforeAttempt !== "none"
1096
+ ) {
1097
+ throw new DevError(
1098
+ `${field}.beforeAttempt`,
1099
+ 'must be "merge-main" or "none"',
1100
+ );
1101
+ }
1102
+ return {
1103
+ stage: "work",
1104
+ ...(use === undefined ? {} : { use }),
1105
+ ...(args === undefined ? {} : { args }),
1106
+ ...(pool === undefined ? {} : { pool }),
1107
+ ...(workerBrief === undefined ? {} : { workerBrief }),
1108
+ ...(commit === undefined ? {} : { commit }),
1109
+ ...(brief === undefined ? {} : { brief }),
1110
+ ...(beforeAttempt === undefined ? {} : { beforeAttempt }),
1111
+ };
1112
+ }
1113
+ case "check": {
1114
+ const commands =
1115
+ value.commands === undefined
1116
+ ? undefined
1117
+ : commandList(value.commands, `${field}.commands`);
1118
+ const rerun =
1119
+ value.rerun === undefined
1120
+ ? undefined
1121
+ : nonNegativeInteger(value.rerun, `${field}.rerun`);
1122
+ return {
1123
+ stage: "check",
1124
+ ...(commands === undefined ? {} : { commands }),
1125
+ ...(rerun === undefined ? {} : { rerun }),
1126
+ };
1127
+ }
1128
+ case "review": {
1129
+ const use = optionalString("use");
1130
+ const args = optionalList("args");
1131
+ const later = optionalList("later");
1132
+ const grading = optionalString("grading");
1133
+ return {
1134
+ stage: "review",
1135
+ ...(use === undefined ? {} : { use }),
1136
+ ...(args === undefined ? {} : { args }),
1137
+ ...(later === undefined ? {} : { later }),
1138
+ ...(grading === undefined ? {} : { grading }),
1139
+ };
1140
+ }
1141
+ case "human":
1142
+ return { stage: "human" };
1143
+ }
1144
+ }
1145
+
1146
+ function flowSpecOf(value: unknown, field: string): DevFlowSpec {
1147
+ if (!isRecord(value)) {
1148
+ throw new DevError(field, "must be a JSON object");
1149
+ }
1150
+ for (const key of Object.keys(value)) {
1151
+ if (key !== "stages") {
1152
+ throw new DevError(`${field}.${key}`, "is not a flow setting");
1153
+ }
1154
+ }
1155
+ if (!Array.isArray(value.stages)) {
1156
+ throw new DevError(`${field}.stages`, "must be an array of stages");
1157
+ }
1158
+ const stages = value.stages.map((stage: unknown, index) =>
1159
+ stageOf(stage, `${field}.stages[${index}]`),
1160
+ );
1161
+ return { stages };
1162
+ }
1163
+
1164
+ /**
1165
+ * The repository's flows, and the two hard rules: a flow needs a check, review
1166
+ * or human stage, and its last stage is human because integrate is the step
1167
+ * that puts a change on main.
1168
+ */
1169
+ function flowsOf(
1170
+ value: unknown,
1171
+ pools: Readonly<Record<string, readonly string[]>>,
1172
+ ): DevFlows {
1173
+ if (value === undefined) return DEFAULT_DEV_SETTINGS.flows;
1174
+ if (!isRecord(value)) {
1175
+ throw new DevError("flows", "must be a JSON object");
1176
+ }
1177
+ const flows: Record<string, DevFlowSpec> = {};
1178
+ for (const [name, raw] of Object.entries(value)) {
1179
+ if (name.trim().length === 0) {
1180
+ throw new DevError("flows", "a flow needs a non-empty name");
1181
+ }
1182
+ const field = `flows.${name}`;
1183
+ const flow = flowSpecOf(raw, field);
1184
+ if (!flow.stages.some((stage) => stage.stage !== "work")) {
1185
+ throw new DevError(
1186
+ `${field}.stages`,
1187
+ "needs at least one check, review or human stage",
1188
+ );
1189
+ }
1190
+ flow.stages.forEach((stage, index) => {
1191
+ if (stage.stage === "work" && stage.pool !== undefined && pools[stage.pool] === undefined) {
1192
+ throw new DevError(
1193
+ `${field}.stages[${index}].pool`,
1194
+ `no pool named "${stage.pool}" in pools`,
1195
+ );
1196
+ }
1197
+ });
1198
+ flows[name] = flow;
1199
+ }
1200
+ return flows;
1201
+ }
1202
+
1203
+ /**
1204
+ * Validates one parsed dev.json value and fills the defaults.
1205
+ */
1206
+ export function validateDevSettings(value: unknown): DevSettings {
1207
+ if (!isRecord(value)) {
1208
+ throw new DevError("dev.json", "must be a JSON object");
1209
+ }
1210
+ for (const key of Object.keys(value)) {
1211
+ if (!KNOWN_FIELDS.has(key)) {
1212
+ throw new DevError(key, "is not a dev setting");
1213
+ }
1214
+ }
1215
+ const worktreeRoot = worktreeRootOf(value);
1216
+ const concurrency =
1217
+ value.concurrency === undefined
1218
+ ? DEFAULT_DEV_SETTINGS.concurrency
1219
+ : positiveInteger(value.concurrency, "concurrency");
1220
+ const { worker, workers } = workerSettingsOf(value, concurrency);
1221
+ return {
1222
+ ...(value.name === undefined
1223
+ ? {}
1224
+ : { name: nonEmptyString(value.name, "name") }),
1225
+ remote:
1226
+ value.remote === undefined
1227
+ ? DEFAULT_DEV_SETTINGS.remote
1228
+ : nonEmptyString(value.remote, "remote"),
1229
+ mainBranch:
1230
+ value.mainBranch === undefined
1231
+ ? DEFAULT_DEV_SETTINGS.mainBranch
1232
+ : nonEmptyString(value.mainBranch, "mainBranch"),
1233
+ worktreeRoot: worktreeRoot.root,
1234
+ concurrency,
1235
+ concurrencySet: value.concurrency !== undefined,
1236
+ worker,
1237
+ workers,
1238
+ workerBrief:
1239
+ value.workerBrief === undefined
1240
+ ? DEFAULT_DEV_SETTINGS.workerBrief
1241
+ : nonEmptyString(value.workerBrief, "workerBrief"),
1242
+ prepare:
1243
+ value.prepare === undefined
1244
+ ? DEFAULT_DEV_SETTINGS.prepare
1245
+ : prepareList(value.prepare, "prepare"),
1246
+ gate:
1247
+ value.gate === undefined
1248
+ ? DEFAULT_DEV_SETTINGS.gate
1249
+ : gateSettings(value.gate, "gate"),
1250
+ check:
1251
+ value.check === undefined
1252
+ ? DEFAULT_DEV_SETTINGS.check
1253
+ : checkSettings(value.check, "check"),
1254
+ work:
1255
+ value.work === undefined
1256
+ ? DEFAULT_DEV_SETTINGS.work
1257
+ : workSettings(value.work, "work"),
1258
+ reviewer:
1259
+ value.reviewer === undefined
1260
+ ? DEFAULT_DEV_SETTINGS.reviewer
1261
+ : reviewerSettings(value.reviewer, "reviewer"),
1262
+ integration:
1263
+ value.integration === undefined
1264
+ ? DEFAULT_DEV_SETTINGS.integration
1265
+ : integrationSettings(value.integration, "integration"),
1266
+ hooks:
1267
+ value.hooks === undefined
1268
+ ? DEFAULT_DEV_SETTINGS.hooks
1269
+ : hookSettings(value.hooks, "hooks"),
1270
+ maxAutoRework:
1271
+ value.maxAutoRework === undefined
1272
+ ? DEFAULT_DEV_SETTINGS.maxAutoRework
1273
+ : nonNegativeInteger(value.maxAutoRework, "maxAutoRework"),
1274
+ autoDefault:
1275
+ value.autoDefault === undefined
1276
+ ? DEFAULT_DEV_SETTINGS.autoDefault
1277
+ : autoMode(value.autoDefault, "autoDefault"),
1278
+ retry:
1279
+ value.retry === undefined
1280
+ ? DEFAULT_DEV_SETTINGS.retry
1281
+ : retrySettings(value.retry, "retry"),
1282
+ flows: flowsOf(value.flows, workers.pools),
1283
+ };
1284
+ }
1285
+
1286
+ interface ReadSettings {
1287
+ readonly settings: DevSettings;
1288
+ /** The file's text; empty when the file does not exist. */
1289
+ readonly text: string;
1290
+ }
1291
+
1292
+ /** Parses and checks the text of a settings file for the repository at `repositoryPath`. */
1293
+ function settingsFromText(
1294
+ repositoryPath: string,
1295
+ path: string,
1296
+ text: string,
1297
+ ): ReadSettings {
1298
+ let parsed: unknown;
1299
+ try {
1300
+ parsed = JSON.parse(text);
1301
+ } catch (error) {
1302
+ throw new DevError("dev.json", `invalid JSON in ${path}: ${String(error)}`);
1303
+ }
1304
+ const settings = validateDevSettings(parsed);
1305
+ const field =
1306
+ isRecord(parsed) &&
1307
+ parsed.worktreeRoot === undefined &&
1308
+ parsed.worktrees !== undefined
1309
+ ? "worktrees"
1310
+ : "worktreeRoot";
1311
+ assertInsideRepository(
1312
+ repositoryPath,
1313
+ resolve(repositoryPath, settings.worktreeRoot),
1314
+ field,
1315
+ );
1316
+ for (const [name, flow] of Object.entries(settings.flows ?? {})) {
1317
+ flow.stages.forEach((stage, index) => {
1318
+ if (stage.stage !== "work" || stage.workerBrief === undefined) return;
1319
+ const field = `flows.${name}.stages[${index}].workerBrief`;
1320
+ if (isAbsolute(stage.workerBrief)) {
1321
+ throw new DevError(field, "must be a path relative to the repository");
1322
+ }
1323
+ const file = resolve(repositoryPath, stage.workerBrief);
1324
+ if (!existsSync(file)) {
1325
+ throw new DevError(field, `${file} does not exist`);
1326
+ }
1327
+ assertInsideRepository(repositoryPath, file, field);
1328
+ });
1329
+ }
1330
+ return { settings, text };
1331
+ }
1332
+
1333
+ /** Reads the file as it is now; any problem with it is thrown. */
1334
+ function readSettingsNow(repositoryPath: string): ReadSettings {
1335
+ const path = join(repositoryPath, DEV_SETTINGS_FILE);
1336
+ if (!existsSync(path)) {
1337
+ assertInsideRepository(
1338
+ repositoryPath,
1339
+ resolve(repositoryPath, DEFAULT_DEV_SETTINGS.worktreeRoot),
1340
+ "worktreeRoot",
1341
+ );
1342
+ return { settings: DEFAULT_DEV_SETTINGS, text: "" };
1343
+ }
1344
+ let text: string;
1345
+ try {
1346
+ text = readFileSync(path, "utf8");
1347
+ } catch (error) {
1348
+ throw new DevError("dev.json", `cannot read ${path}: ${String(error)}`);
1349
+ }
1350
+ return settingsFromText(repositoryPath, path, text);
1351
+ }
1352
+
1353
+ /**
1354
+ * The last settings of each repository that were valid, by repository path.
1355
+ * A process keeps them in memory; the text is also kept in the home, so a
1356
+ * process that starts while the file is invalid finds the same settings.
1357
+ */
1358
+ const lastValid = new Map<string, ReadSettings>();
1359
+
1360
+ function keptFile(home: string, repositoryPath: string): string {
1361
+ const key = createHash("sha1").update(repositoryPath).digest("hex");
1362
+ return join(home, "dev", "settings", `${key}.json`);
1363
+ }
1364
+
1365
+ function keptHome(): string | undefined {
1366
+ const home = defaultOperadHome();
1367
+ return existsSync(join(home, "config.json")) ? home : undefined;
1368
+ }
1369
+
1370
+ function keep(repositoryPath: string, read: ReadSettings): void {
1371
+ const before = lastValid.get(repositoryPath);
1372
+ if (before !== undefined && before.text === read.text) return;
1373
+ lastValid.set(repositoryPath, read);
1374
+ const home = keptHome();
1375
+ if (home === undefined) return;
1376
+ try {
1377
+ const file = keptFile(home, repositoryPath);
1378
+ mkdirSync(dirname(file), { recursive: true });
1379
+ const temporary = `${file}.${process.pid}.tmp`;
1380
+ writeFileSync(temporary, JSON.stringify({ path: repositoryPath, text: read.text }));
1381
+ renameSync(temporary, file);
1382
+ } catch {
1383
+ // The copy is a convenience for the next process; the memory copy stays.
1384
+ }
1385
+ }
1386
+
1387
+ function recall(repositoryPath: string): ReadSettings | undefined {
1388
+ const remembered = lastValid.get(repositoryPath);
1389
+ if (remembered !== undefined) return remembered;
1390
+ const home = keptHome();
1391
+ if (home === undefined) return undefined;
1392
+ try {
1393
+ const raw: unknown = JSON.parse(readFileSync(keptFile(home, repositoryPath), "utf8"));
1394
+ if (isRecord(raw) && typeof raw.text === "string") {
1395
+ const read =
1396
+ raw.text === ""
1397
+ ? readDefaults(repositoryPath)
1398
+ : settingsFromText(
1399
+ repositoryPath,
1400
+ join(repositoryPath, DEV_SETTINGS_FILE),
1401
+ raw.text,
1402
+ );
1403
+ lastValid.set(repositoryPath, read);
1404
+ return read;
1405
+ }
1406
+ } catch {
1407
+ // No usable copy.
1408
+ }
1409
+ return undefined;
1410
+ }
1411
+
1412
+ function readDefaults(repositoryPath: string): ReadSettings {
1413
+ assertInsideRepository(
1414
+ repositoryPath,
1415
+ resolve(repositoryPath, DEFAULT_DEV_SETTINGS.worktreeRoot),
1416
+ "worktreeRoot",
1417
+ );
1418
+ return { settings: DEFAULT_DEV_SETTINGS, text: "" };
1419
+ }
1420
+
1421
+ /**
1422
+ * Reads a repository's settings. A missing file means the defaults, so a work
1423
+ * tree that `operad repo add` has not written yet still runs. A file that is
1424
+ * not valid never stops work: the last valid settings stay in force. Only a
1425
+ * repository that never had valid settings gets the error.
1426
+ */
1427
+ export async function readDevSettings(
1428
+ repositoryPath: string,
1429
+ ): Promise<DevSettings> {
1430
+ try {
1431
+ const read = readSettingsNow(repositoryPath);
1432
+ keep(repositoryPath, read);
1433
+ return read.settings;
1434
+ } catch (error) {
1435
+ const kept = recall(repositoryPath);
1436
+ if (kept !== undefined) return kept.settings;
1437
+ throw error;
1438
+ }
1439
+ }
1440
+
1441
+ /** What is wrong with the repository's settings file now, or undefined when it is valid. */
1442
+ export function settingsProblem(repositoryPath: string): string | undefined {
1443
+ try {
1444
+ keep(repositoryPath, readSettingsNow(repositoryPath));
1445
+ return undefined;
1446
+ } catch (error) {
1447
+ return error instanceof Error ? error.message : String(error);
1448
+ }
1449
+ }
1450
+
1451
+ /** True when the repository has valid settings to fall back on. */
1452
+ export function hasValidSettings(repositoryPath: string): boolean {
1453
+ return recall(repositoryPath) !== undefined;
1454
+ }
1455
+
1456
+ /** An alias for callers that name the file rather than the plugin. */
1457
+ export const readRepositorySettings = readDevSettings;
1458
+
1459
+ /** The absolute path of the brief a worker reads, whether it exists or not. */
1460
+ export function workerBriefPath(
1461
+ repositoryPath: string,
1462
+ settings: DevSettings,
1463
+ ): string {
1464
+ return isAbsolute(settings.workerBrief)
1465
+ ? settings.workerBrief
1466
+ : resolve(repositoryPath, settings.workerBrief);
1467
+ }
1468
+
1469
+ /**
1470
+ * The worker brief: the repository's own file when it has one, otherwise the
1471
+ * built-in text. A path that points at nothing is not an error; the repository
1472
+ * simply wanted the default.
1473
+ */
1474
+ export async function readWorkerBrief(
1475
+ repositoryPath: string,
1476
+ settings: DevSettings,
1477
+ stageFile?: string,
1478
+ ): Promise<string> {
1479
+ if (stageFile !== undefined) {
1480
+ // A stage's own file replaces the repository's; it must exist.
1481
+ const file = resolve(repositoryPath, stageFile);
1482
+ try {
1483
+ return readFileSync(file, "utf8");
1484
+ } catch (error) {
1485
+ throw new DevError("workerBrief", `cannot read ${file}: ${String(error)}`);
1486
+ }
1487
+ }
1488
+ const path = workerBriefPath(repositoryPath, settings);
1489
+ if (!existsSync(path)) return DEFAULT_WORKER_BRIEF;
1490
+ try {
1491
+ return readFileSync(path, "utf8");
1492
+ } catch (error) {
1493
+ throw new DevError("workerBrief", `cannot read ${path}: ${String(error)}`);
1494
+ }
1495
+ }