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