@operad-io/dev 0.1.1 → 0.3.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 (50) hide show
  1. package/README.md +1 -1
  2. package/dev.schema.json +53 -31
  3. package/package.json +9 -6
  4. package/skills/git/SKILL.md +70 -0
  5. package/skills/setup/SKILL.md +74 -0
  6. package/src/access-grants.ts +59 -0
  7. package/src/actions.ts +81 -17
  8. package/src/announce.ts +134 -17
  9. package/src/chat.ts +586 -36
  10. package/src/check-host.ts +111 -0
  11. package/src/check-load.ts +67 -0
  12. package/src/check.ts +45 -22
  13. package/src/clock.ts +29 -0
  14. package/src/clone-chat.ts +32 -0
  15. package/src/commands.ts +103 -34
  16. package/src/create-actions.ts +210 -0
  17. package/src/flaky.ts +45 -29
  18. package/src/flow-compiler.ts +156 -69
  19. package/src/followups.ts +20 -22
  20. package/src/gate.ts +254 -88
  21. package/src/git-state.ts +155 -0
  22. package/src/git.ts +92 -4
  23. package/src/index.ts +52 -6
  24. package/src/integrate.ts +162 -62
  25. package/src/integration-queue.ts +23 -10
  26. package/src/lock.ts +101 -5
  27. package/src/mainclone.ts +61 -5
  28. package/src/model-error.ts +70 -0
  29. package/src/model.ts +61 -35
  30. package/src/notcode.ts +51 -15
  31. package/src/places.ts +2 -2
  32. package/src/prepare.ts +7 -2
  33. package/src/project-flows.ts +135 -4
  34. package/src/project-settings.ts +110 -3
  35. package/src/register-requests.ts +121 -0
  36. package/src/repository-key.ts +4 -0
  37. package/src/rerun.ts +23 -7
  38. package/src/retry.ts +2 -12
  39. package/src/rework.ts +8 -0
  40. package/src/schedule.ts +342 -93
  41. package/src/service.ts +241 -185
  42. package/src/settings.ts +409 -65
  43. package/src/setup-git.ts +366 -0
  44. package/src/standing.ts +23 -6
  45. package/src/step-edge.ts +22 -0
  46. package/src/steps.ts +945 -179
  47. package/src/throughput.ts +4 -21
  48. package/src/timeouts.ts +10 -2
  49. package/src/views.ts +325 -86
  50. package/src/waits.ts +59 -0
package/src/settings.ts CHANGED
@@ -4,14 +4,12 @@
4
4
  * read, and this module applies the same rules when a step loads the file.
5
5
  */
6
6
 
7
- import { createHash } from "node:crypto";
7
+ import { messageOf } from "@operad-io/engine";
8
8
  import {
9
9
  existsSync,
10
- mkdirSync,
11
10
  readFileSync,
12
11
  realpathSync,
13
- renameSync,
14
- writeFileSync,
12
+ statSync,
15
13
  } from "node:fs";
16
14
  import {
17
15
  basename,
@@ -31,11 +29,15 @@ import {
31
29
  type WorkerDefinition,
32
30
  } from "@operad-io/pool";
33
31
  import { defaultOperadHome, isRecord } from "@operad-io/engine";
32
+ import { writeJsonAtomicSync } from "@operad-io/engine/platform";
34
33
  import { DevError, type AutoMode } from "./model.ts";
34
+ import { git } from "./git.ts";
35
+ import { repositoryPathKey } from "./repository-key.ts";
35
36
  import {
36
37
  type DevFlowSpec,
37
38
  type DevFlows,
38
39
  type DevStage,
40
+ type StageKind,
39
41
  } from "./flow-compiler.ts";
40
42
 
41
43
  /** Where a repository keeps its dev settings. */
@@ -47,9 +49,72 @@ export const DEV_SETTINGS_SCHEMA = "https://operad.io/schemas/dev.schema.json";
47
49
  /** The default location of a repository's worker brief. */
48
50
  export const WORKER_BRIEF_FILE = ".operad/worker-brief.md";
49
51
 
50
- /** The harness step a repository uses when it names none. */
52
+ /** The skill directories a repository gives its chats when it writes none. */
53
+ export const DEFAULT_SKILLS: readonly string[] = [".agents/skills"];
54
+
55
+ /** The harness step a repository uses when it names none and the home enables none. */
51
56
  export const DEFAULT_WORKER_USE = "radian/agent";
52
57
 
58
+ /** The harness order a repository with no worker settings chooses from. */
59
+ export const DEFAULT_HARNESS_ORDER: readonly string[] = ["radian", "claude", "pi", "codex"];
60
+
61
+ /** The harness a plugin entry names, whether by its key or by its package. */
62
+ function harnessPlugin(name: string | undefined, module: unknown): string | undefined {
63
+ for (const harness of DEFAULT_HARNESS_ORDER) {
64
+ if (name === harness) return harness;
65
+ if (typeof module !== "string") continue;
66
+ if (
67
+ module === `@operad-io/harness-${harness}` ||
68
+ module.endsWith(`/harness-${harness}`) ||
69
+ module.endsWith(`/harness/${harness}/src/index.ts`)
70
+ ) {
71
+ return harness;
72
+ }
73
+ }
74
+ return undefined;
75
+ }
76
+
77
+ /**
78
+ * The first enabled harness in the home's `config.json`, in `DEFAULT_HARNESS_ORDER`.
79
+ * A missing or unreadable file keeps the old radian default.
80
+ */
81
+ export function defaultAgentUse(home: string = defaultOperadHome()): string {
82
+ let raw: unknown;
83
+ try {
84
+ raw = JSON.parse(readFileSync(join(home, "config.json"), "utf8"));
85
+ } catch {
86
+ return DEFAULT_WORKER_USE;
87
+ }
88
+ if (!isRecord(raw)) return DEFAULT_WORKER_USE;
89
+ const plugins = raw.plugins;
90
+ const enabled = new Set<string>();
91
+ if (Array.isArray(plugins)) {
92
+ for (const entry of plugins) {
93
+ if (typeof entry === "string") {
94
+ const found = harnessPlugin(undefined, entry);
95
+ if (found !== undefined) enabled.add(found);
96
+ continue;
97
+ }
98
+ const record = isRecord(entry) ? entry : undefined;
99
+ if (record?.enabled === false) continue;
100
+ const name = typeof record?.name === "string" ? record.name : undefined;
101
+ const module = record?.module;
102
+ const found = harnessPlugin(name, module) ?? harnessPlugin(undefined, module);
103
+ if (found !== undefined) enabled.add(found);
104
+ }
105
+ } else if (isRecord(plugins)) {
106
+ for (const [name, entry] of Object.entries(plugins)) {
107
+ const record = isRecord(entry) ? entry : undefined;
108
+ if (record?.enabled === false) continue;
109
+ const module = typeof entry === "string" ? entry : record?.module;
110
+ const found = harnessPlugin(name, module) ?? harnessPlugin(undefined, module);
111
+ if (found !== undefined) enabled.add(found);
112
+ }
113
+ }
114
+ const first = DEFAULT_HARNESS_ORDER.find((name) => enabled.has(name));
115
+ return first === undefined ? DEFAULT_WORKER_USE : `${first}/agent`;
116
+ }
117
+
53
118
  /** How long a review waits before it runs again after a model was unavailable. */
54
119
  export const DEFAULT_REVIEWER_RETRY_SECS = 120;
55
120
 
@@ -225,10 +290,18 @@ export interface ReviewerSettings {
225
290
  readonly maxDiffBytes: number;
226
291
  }
227
292
 
293
+ /** Where a repository's tasks work; see ADR 0039 D1. */
294
+ export type WorkIn = "branch" | "worktree";
295
+
228
296
  /** The whole `.operad/dev.json` document, with every default filled. */
229
297
  export interface DevSettings {
230
298
  readonly name?: string | undefined;
231
- readonly remote: string;
299
+ /**
300
+ * The git remote task branches are fetched from and pushed to. Undefined
301
+ * means the repository has none: the local main branch is the base, nothing
302
+ * is fetched or pushed, and a merge only moves the local main branch.
303
+ */
304
+ readonly remote?: string | undefined;
232
305
  readonly mainBranch: string;
233
306
  readonly worktreeRoot: string;
234
307
  /**
@@ -236,6 +309,11 @@ export interface DevSettings {
236
309
  * it, the default pool's counts alone decide (see `runningTaskCap`).
237
310
  */
238
311
  readonly concurrency: number;
312
+ /**
313
+ * Where a task's changes are made: a branch in the main clone (`branch`, one
314
+ * task at a time) or the task's own worktree (`worktree`, the default).
315
+ */
316
+ readonly workIn: WorkIn;
239
317
  /** Whether the file wrote `concurrency` itself. */
240
318
  readonly concurrencySet: boolean;
241
319
  /**
@@ -249,6 +327,12 @@ export interface DevSettings {
249
327
  */
250
328
  readonly workers: ParsedWorkers;
251
329
  readonly workerBrief: string;
330
+ /**
331
+ * The skill directories this repository's chats read, relative to the
332
+ * repository. A `.agents` directory is read through its `skills` directory.
333
+ * Empty gives the chats no skills.
334
+ */
335
+ readonly skills: readonly string[];
252
336
  /**
253
337
  * Commands run in every checkout dev makes (the worker's worktree, the gate
254
338
  * checkout, the integration checkout) after it is created or moved to a new
@@ -280,8 +364,8 @@ export const DEFAULT_AFTER_MERGE: readonly string[] = [
280
364
  "if [ -e \"$OPERAD_WORKTREE\" ]; then git worktree remove --force \"$OPERAD_WORKTREE\"; fi",
281
365
  "if [ -e \"$OPERAD_WORKTREE-gate\" ]; then git worktree remove --force \"$OPERAD_WORKTREE-gate\"; fi",
282
366
  "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",
367
+ "if git show-ref --verify --quiet \"refs/heads/work/$OPERAD_TASK\" && [ \"$(git symbolic-ref --short -q HEAD)\" != \"work/$OPERAD_TASK\" ]; then git branch -D \"work/$OPERAD_TASK\"; fi",
368
+ "if [ -z \"$OPERAD_REMOTE\" ]; then :; elif 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
369
  ];
286
370
 
287
371
  /**
@@ -300,6 +384,7 @@ export const DEFAULT_DEV_SETTINGS: DevSettings = {
300
384
  mainBranch: "main",
301
385
  worktreeRoot: ".operad-worktrees",
302
386
  concurrency: 1,
387
+ workIn: "worktree",
303
388
  concurrencySet: false,
304
389
  worker: {
305
390
  use: DEFAULT_WORKER_USE,
@@ -307,6 +392,7 @@ export const DEFAULT_DEV_SETTINGS: DevSettings = {
307
392
  },
308
393
  workers: legacyWorkers({ use: DEFAULT_WORKER_USE, args: [] }, 1),
309
394
  workerBrief: WORKER_BRIEF_FILE,
395
+ skills: DEFAULT_SKILLS,
310
396
  prepare: [],
311
397
  gate: {
312
398
  commands: [],
@@ -338,6 +424,17 @@ export const DEFAULT_DEV_SETTINGS: DevSettings = {
338
424
  flows: {},
339
425
  };
340
426
 
427
+ /** The defaults when the home enables `agentUse` instead of radian. */
428
+ export function defaultDevSettings(agentUse: string = defaultAgentUse()): DevSettings {
429
+ if (agentUse === DEFAULT_WORKER_USE) return DEFAULT_DEV_SETTINGS;
430
+ return {
431
+ ...DEFAULT_DEV_SETTINGS,
432
+ worker: { use: agentUse, args: [] },
433
+ workers: legacyWorkers({ use: agentUse, args: [] }, DEFAULT_DEV_SETTINGS.concurrency),
434
+ reviewer: { ...DEFAULT_DEV_SETTINGS.reviewer, use: agentUse },
435
+ };
436
+ }
437
+
341
438
  const KNOWN_FIELDS = new Set([
342
439
  "$schema",
343
440
  "name",
@@ -349,10 +446,12 @@ const KNOWN_FIELDS = new Set([
349
446
  "worktrees",
350
447
  "sandbox",
351
448
  "concurrency",
449
+ "workIn",
352
450
  "worker",
353
451
  "workers",
354
452
  "pools",
355
453
  "workerBrief",
454
+ "skills",
356
455
  "prepare",
357
456
  "gate",
358
457
  "check",
@@ -389,6 +488,16 @@ function repositoryRelativePath(value: unknown, field: string): string {
389
488
  return path;
390
489
  }
391
490
 
491
+ /** A list of skill directories, each relative to the repository. */
492
+ function repositorySkillList(value: unknown, field: string): readonly string[] {
493
+ if (!Array.isArray(value)) {
494
+ throw new DevError(field, "must be an array of strings");
495
+ }
496
+ return value.map((item, index) =>
497
+ repositoryRelativePath(item, `${field}[${index}]`),
498
+ );
499
+ }
500
+
392
501
  /**
393
502
  * The real path of `path`, resolving the symlinks of every part that exists.
394
503
  * A tail that does not exist yet is appended unchanged, so the answer is where
@@ -427,6 +536,13 @@ export function assertInsideRepository(
427
536
  }
428
537
  }
429
538
 
539
+ function workInOf(value: unknown, field: string): WorkIn {
540
+ if (value !== "branch" && value !== "worktree") {
541
+ throw new DevError(field, 'must be "branch" or "worktree"');
542
+ }
543
+ return value;
544
+ }
545
+
430
546
  function autoMode(value: unknown, field: string): AutoMode {
431
547
  if (value !== "off" && value !== "run" && value !== "merge") {
432
548
  throw new DevError(field, 'must be "off", "run" or "merge"');
@@ -460,7 +576,7 @@ function settingsStringList(value: unknown, field: string): readonly string[] {
460
576
  });
461
577
  }
462
578
 
463
- function workerSettings(value: unknown, field: string): WorkerSettings {
579
+ function workerSettings(value: unknown, field: string, defaultUse: string): WorkerSettings {
464
580
  if (!isRecord(value)) {
465
581
  throw new DevError(field, "must be an object");
466
582
  }
@@ -471,7 +587,7 @@ function workerSettings(value: unknown, field: string): WorkerSettings {
471
587
  }
472
588
  const use =
473
589
  value.use === undefined
474
- ? DEFAULT_DEV_SETTINGS.worker.use
590
+ ? defaultUse
475
591
  : nonEmptyString(value.use, `${field}.use`);
476
592
  const args =
477
593
  value.args === undefined
@@ -799,7 +915,7 @@ function reviewerFirst(value: unknown, field: string): ReviewerFirst {
799
915
  };
800
916
  }
801
917
 
802
- function reviewerSettings(value: unknown, field: string): ReviewerSettings {
918
+ function reviewerSettings(value: unknown, field: string, defaultUse: string): ReviewerSettings {
803
919
  if (!isRecord(value)) {
804
920
  throw new DevError(field, "must be an object");
805
921
  }
@@ -836,7 +952,7 @@ function reviewerSettings(value: unknown, field: string): ReviewerSettings {
836
952
  return {
837
953
  use:
838
954
  value.use === undefined
839
- ? DEFAULT_DEV_SETTINGS.reviewer.use
955
+ ? defaultUse
840
956
  : nonEmptyString(value.use, `${field}.use`),
841
957
  args:
842
958
  value.args === undefined
@@ -961,6 +1077,7 @@ function firstWorker(workers: ParsedWorkers): WorkerSettings {
961
1077
  function workerSettingsOf(
962
1078
  value: Readonly<Record<string, unknown>>,
963
1079
  concurrency: number,
1080
+ defaults: DevSettings,
964
1081
  ): { readonly worker: WorkerSettings; readonly workers: ParsedWorkers } {
965
1082
  if (value.workers === undefined) {
966
1083
  if (value.pools !== undefined) {
@@ -968,8 +1085,8 @@ function workerSettingsOf(
968
1085
  }
969
1086
  const worker =
970
1087
  value.worker === undefined
971
- ? DEFAULT_DEV_SETTINGS.worker
972
- : workerSettings(value.worker, "worker");
1088
+ ? defaults.worker
1089
+ : workerSettings(value.worker, "worker", defaults.worker.use);
973
1090
  return { worker, workers: legacyWorkers(worker, concurrency) };
974
1091
  }
975
1092
  if (value.worker !== undefined) {
@@ -1028,6 +1145,7 @@ export function runningTaskCap(settings: DevSettings, pool: string = DEFAULT_POO
1028
1145
  * cap added up, and the file's `concurrency` when written caps them together.
1029
1146
  */
1030
1147
  export function repositoryTaskCap(settings: DevSettings): number {
1148
+ if (settings.workIn === "branch") return 1;
1031
1149
  const total = Object.keys(settings.workers.pools).reduce(
1032
1150
  (sum, name) => sum + poolCap(settings, name),
1033
1151
  0,
@@ -1035,19 +1153,19 @@ export function repositoryTaskCap(settings: DevSettings): number {
1035
1153
  return settings.concurrencySet ? Math.min(total, settings.concurrency) : total;
1036
1154
  }
1037
1155
 
1038
- /** The pool a flow's tasks count against: its first work stage's pool, or `default`. */
1156
+ /** The pool a flow's tasks count against: its first code stage's pool, or `default`. */
1039
1157
  export function flowPool(settings: DevSettings, flowName: string | undefined): string {
1040
1158
  const spec = settings.flows[flowName ?? "default"];
1041
1159
  for (const stage of spec?.stages ?? []) {
1042
- if (stage.stage === "work") return stage.pool ?? DEFAULT_POOL;
1160
+ if (stage.stage === "code" || stage.stage === "work") return stage.pool ?? DEFAULT_POOL;
1043
1161
  }
1044
1162
  return DEFAULT_POOL;
1045
1163
  }
1046
1164
 
1047
1165
  /** 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"],
1166
+ const STAGE_FIELDS: Readonly<Record<StageKind, readonly string[]>> = {
1167
+ code: ["stage", "use", "args", "pool", "workerBrief", "commit", "brief", "beforeAttempt"],
1168
+ test: ["stage", "commands", "rerun"],
1051
1169
  review: ["stage", "use", "args", "later", "grading"],
1052
1170
  human: ["stage"],
1053
1171
  };
@@ -1056,18 +1174,23 @@ function stageOf(value: unknown, field: string): DevStage {
1056
1174
  if (!isRecord(value)) {
1057
1175
  throw new DevError(field, "must be a JSON object");
1058
1176
  }
1059
- const kind = value.stage;
1177
+ const written = value.stage;
1060
1178
  if (
1061
- kind !== "work" &&
1062
- kind !== "check" &&
1063
- kind !== "review" &&
1064
- kind !== "human"
1179
+ written !== "code" &&
1180
+ written !== "test" &&
1181
+ written !== "review" &&
1182
+ written !== "human" &&
1183
+ written !== "work" &&
1184
+ written !== "check"
1065
1185
  ) {
1066
1186
  throw new DevError(
1067
1187
  `${field}.stage`,
1068
- 'must be "work", "check", "review" or "human"',
1188
+ 'must be "code", "test", "review" or "human"',
1069
1189
  );
1070
1190
  }
1191
+ // The older names load as the same stages; everything written back uses the new names.
1192
+ const kind: StageKind =
1193
+ written === "work" ? "code" : written === "check" ? "test" : written;
1071
1194
  for (const key of Object.keys(value)) {
1072
1195
  if (!STAGE_FIELDS[kind].includes(key)) {
1073
1196
  throw new DevError(`${field}.${key}`, "is not a stage setting");
@@ -1078,7 +1201,7 @@ function stageOf(value: unknown, field: string): DevStage {
1078
1201
  const optionalList = (key: string): readonly string[] | undefined =>
1079
1202
  value[key] === undefined ? undefined : settingsStringList(value[key], `${field}.${key}`);
1080
1203
  switch (kind) {
1081
- case "work": {
1204
+ case "code": {
1082
1205
  const use = optionalString("use");
1083
1206
  const args = optionalList("args");
1084
1207
  const pool = optionalString("pool");
@@ -1100,7 +1223,7 @@ function stageOf(value: unknown, field: string): DevStage {
1100
1223
  );
1101
1224
  }
1102
1225
  return {
1103
- stage: "work",
1226
+ stage: "code",
1104
1227
  ...(use === undefined ? {} : { use }),
1105
1228
  ...(args === undefined ? {} : { args }),
1106
1229
  ...(pool === undefined ? {} : { pool }),
@@ -1110,7 +1233,7 @@ function stageOf(value: unknown, field: string): DevStage {
1110
1233
  ...(beforeAttempt === undefined ? {} : { beforeAttempt }),
1111
1234
  };
1112
1235
  }
1113
- case "check": {
1236
+ case "test": {
1114
1237
  const commands =
1115
1238
  value.commands === undefined
1116
1239
  ? undefined
@@ -1120,7 +1243,7 @@ function stageOf(value: unknown, field: string): DevStage {
1120
1243
  ? undefined
1121
1244
  : nonNegativeInteger(value.rerun, `${field}.rerun`);
1122
1245
  return {
1123
- stage: "check",
1246
+ stage: "test",
1124
1247
  ...(commands === undefined ? {} : { commands }),
1125
1248
  ...(rerun === undefined ? {} : { rerun }),
1126
1249
  };
@@ -1162,7 +1285,7 @@ function flowSpecOf(value: unknown, field: string): DevFlowSpec {
1162
1285
  }
1163
1286
 
1164
1287
  /**
1165
- * The repository's flows, and the two hard rules: a flow needs a check, review
1288
+ * The repository's flows, and the two hard rules: a flow needs a test, review
1166
1289
  * or human stage, and its last stage is human because integrate is the step
1167
1290
  * that puts a change on main.
1168
1291
  */
@@ -1181,14 +1304,14 @@ function flowsOf(
1181
1304
  }
1182
1305
  const field = `flows.${name}`;
1183
1306
  const flow = flowSpecOf(raw, field);
1184
- if (!flow.stages.some((stage) => stage.stage !== "work")) {
1307
+ if (!flow.stages.some((stage) => stage.stage !== "code")) {
1185
1308
  throw new DevError(
1186
1309
  `${field}.stages`,
1187
- "needs at least one check, review or human stage",
1310
+ "needs at least one test, review or human stage",
1188
1311
  );
1189
1312
  }
1190
1313
  flow.stages.forEach((stage, index) => {
1191
- if (stage.stage === "work" && stage.pool !== undefined && pools[stage.pool] === undefined) {
1314
+ if (stage.stage === "code" && stage.pool !== undefined && pools[stage.pool] === undefined) {
1192
1315
  throw new DevError(
1193
1316
  `${field}.stages[${index}].pool`,
1194
1317
  `no pool named "${stage.pool}" in pools`,
@@ -1200,10 +1323,58 @@ function flowsOf(
1200
1323
  return flows;
1201
1324
  }
1202
1325
 
1326
+ /**
1327
+ * Rewrites the older stage names in a dev.json value that has already passed
1328
+ * validation, so a settings write stores the new names.
1329
+ */
1330
+ export function useNewStageNames(value: unknown): void {
1331
+ if (!isRecord(value) || !isRecord(value.flows)) return;
1332
+ for (const flow of Object.values(value.flows)) {
1333
+ if (!isRecord(flow) || !Array.isArray(flow.stages)) continue;
1334
+ for (const stage of flow.stages) {
1335
+ if (!isRecord(stage)) continue;
1336
+ if (stage.stage === "work") stage.stage = "code";
1337
+ else if (stage.stage === "check") stage.stage = "test";
1338
+ }
1339
+ }
1340
+ }
1341
+
1342
+ /**
1343
+ * A repository that works in a branch of the main clone runs one task at a
1344
+ * time (ADR 0039 D2): refuse more, and say which setting to change.
1345
+ */
1346
+ function refuseBranchWithMany(
1347
+ concurrency: number,
1348
+ concurrencyWritten: boolean,
1349
+ workers: ParsedWorkers,
1350
+ ): void {
1351
+ if (concurrencyWritten && concurrency > 1) {
1352
+ throw new DevError(
1353
+ "workIn",
1354
+ `"branch" runs one task at a time, but concurrency is ${String(concurrency)}: set concurrency to 1, or set workIn to "worktree"`,
1355
+ );
1356
+ }
1357
+ for (const [pool, names] of Object.entries(workers.pools)) {
1358
+ let total = 0;
1359
+ for (const name of names) {
1360
+ total += workers.workers.find((item) => item.name === name)?.count ?? 0;
1361
+ }
1362
+ if (total > 1) {
1363
+ throw new DevError(
1364
+ "workIn",
1365
+ `"branch" runs one task at a time, but the workers of pool "${pool}" add up to ${String(total)}: lower their counts to 1 in all, or set workIn to "worktree"`,
1366
+ );
1367
+ }
1368
+ }
1369
+ }
1370
+
1203
1371
  /**
1204
1372
  * Validates one parsed dev.json value and fills the defaults.
1205
1373
  */
1206
- export function validateDevSettings(value: unknown): DevSettings {
1374
+ export function validateDevSettings(
1375
+ value: unknown,
1376
+ defaults: DevSettings = defaultDevSettings(),
1377
+ ): DevSettings {
1207
1378
  if (!isRecord(value)) {
1208
1379
  throw new DevError("dev.json", "must be a JSON object");
1209
1380
  }
@@ -1215,9 +1386,16 @@ export function validateDevSettings(value: unknown): DevSettings {
1215
1386
  const worktreeRoot = worktreeRootOf(value);
1216
1387
  const concurrency =
1217
1388
  value.concurrency === undefined
1218
- ? DEFAULT_DEV_SETTINGS.concurrency
1389
+ ? defaults.concurrency
1219
1390
  : positiveInteger(value.concurrency, "concurrency");
1220
- const { worker, workers } = workerSettingsOf(value, concurrency);
1391
+ const { worker, workers } = workerSettingsOf(value, concurrency, defaults);
1392
+ const workIn =
1393
+ value.workIn === undefined
1394
+ ? DEFAULT_DEV_SETTINGS.workIn
1395
+ : workInOf(value.workIn, "workIn");
1396
+ if (workIn === "branch") {
1397
+ refuseBranchWithMany(concurrency, value.concurrency !== undefined, workers);
1398
+ }
1221
1399
  return {
1222
1400
  ...(value.name === undefined
1223
1401
  ? {}
@@ -1232,6 +1410,7 @@ export function validateDevSettings(value: unknown): DevSettings {
1232
1410
  : nonEmptyString(value.mainBranch, "mainBranch"),
1233
1411
  worktreeRoot: worktreeRoot.root,
1234
1412
  concurrency,
1413
+ workIn,
1235
1414
  concurrencySet: value.concurrency !== undefined,
1236
1415
  worker,
1237
1416
  workers,
@@ -1239,6 +1418,10 @@ export function validateDevSettings(value: unknown): DevSettings {
1239
1418
  value.workerBrief === undefined
1240
1419
  ? DEFAULT_DEV_SETTINGS.workerBrief
1241
1420
  : nonEmptyString(value.workerBrief, "workerBrief"),
1421
+ skills:
1422
+ value.skills === undefined
1423
+ ? DEFAULT_DEV_SETTINGS.skills
1424
+ : repositorySkillList(value.skills, "skills"),
1242
1425
  prepare:
1243
1426
  value.prepare === undefined
1244
1427
  ? DEFAULT_DEV_SETTINGS.prepare
@@ -1257,8 +1440,8 @@ export function validateDevSettings(value: unknown): DevSettings {
1257
1440
  : workSettings(value.work, "work"),
1258
1441
  reviewer:
1259
1442
  value.reviewer === undefined
1260
- ? DEFAULT_DEV_SETTINGS.reviewer
1261
- : reviewerSettings(value.reviewer, "reviewer"),
1443
+ ? defaults.reviewer
1444
+ : reviewerSettings(value.reviewer, "reviewer", defaults.reviewer.use),
1262
1445
  integration:
1263
1446
  value.integration === undefined
1264
1447
  ? DEFAULT_DEV_SETTINGS.integration
@@ -1289,12 +1472,34 @@ interface ReadSettings {
1289
1472
  readonly text: string;
1290
1473
  }
1291
1474
 
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 {
1475
+ interface ParsedSettings {
1476
+ readonly settings: DevSettings;
1477
+ /** The name of the worktree-root field the file wrote. */
1478
+ readonly worktreeField: string;
1479
+ }
1480
+
1481
+ /** How many parsed settings texts and last-read files are kept. */
1482
+ const SETTINGS_CACHE_MAX = 64;
1483
+
1484
+ /** The last parsed value of each settings text, bounded like the file cache. */
1485
+ const parsedSettings = new Map<string, ParsedSettings>();
1486
+
1487
+ /** A copy of a parsed value, so one caller cannot change what another reads. */
1488
+ function copyParsed(value: ParsedSettings): ParsedSettings {
1489
+ return {
1490
+ settings: structuredClone(value.settings),
1491
+ worktreeField: value.worktreeField,
1492
+ };
1493
+ }
1494
+
1495
+ /** Parses and validates a settings text, reusing the last result for that text. */
1496
+ function parseSettingsText(path: string, text: string): ParsedSettings {
1497
+ const kept = parsedSettings.get(text);
1498
+ if (kept !== undefined) {
1499
+ parsedSettings.delete(text);
1500
+ parsedSettings.set(text, kept);
1501
+ return copyParsed(kept);
1502
+ }
1298
1503
  let parsed: unknown;
1299
1504
  try {
1300
1505
  parsed = JSON.parse(text);
@@ -1302,20 +1507,87 @@ function settingsFromText(
1302
1507
  throw new DevError("dev.json", `invalid JSON in ${path}: ${String(error)}`);
1303
1508
  }
1304
1509
  const settings = validateDevSettings(parsed);
1305
- const field =
1510
+ const worktreeField =
1306
1511
  isRecord(parsed) &&
1307
1512
  parsed.worktreeRoot === undefined &&
1308
1513
  parsed.worktrees !== undefined
1309
1514
  ? "worktrees"
1310
1515
  : "worktreeRoot";
1516
+ const value = { settings, worktreeField };
1517
+ parsedSettings.set(text, value);
1518
+ if (parsedSettings.size > SETTINGS_CACHE_MAX) {
1519
+ const oldest = parsedSettings.keys().next().value;
1520
+ if (oldest !== undefined) parsedSettings.delete(oldest);
1521
+ }
1522
+ return copyParsed(value);
1523
+ }
1524
+
1525
+ interface CachedSettingsText {
1526
+ readonly mtimeNs: bigint;
1527
+ readonly ctimeNs: bigint;
1528
+ readonly size: bigint;
1529
+ readonly ino: bigint;
1530
+ readonly text: string;
1531
+ }
1532
+
1533
+ /** The last text read from each settings file, with the stat that matched it. */
1534
+ const settingsTexts = new Map<string, CachedSettingsText>();
1535
+
1536
+ /** Reads a settings file, unless its stat says it is the file already read. */
1537
+ function readSettingsText(path: string): string {
1538
+ const stat = statSync(path, { bigint: true });
1539
+ const kept = settingsTexts.get(path);
1540
+ if (
1541
+ kept !== undefined &&
1542
+ kept.mtimeNs === stat.mtimeNs &&
1543
+ kept.ctimeNs === stat.ctimeNs &&
1544
+ kept.size === stat.size &&
1545
+ kept.ino === stat.ino
1546
+ ) {
1547
+ settingsTexts.delete(path);
1548
+ settingsTexts.set(path, kept);
1549
+ return kept.text;
1550
+ }
1551
+ const text = readFileSync(path, "utf8");
1552
+ settingsTexts.set(path, {
1553
+ mtimeNs: stat.mtimeNs,
1554
+ ctimeNs: stat.ctimeNs,
1555
+ size: stat.size,
1556
+ ino: stat.ino,
1557
+ text,
1558
+ });
1559
+ if (settingsTexts.size > SETTINGS_CACHE_MAX) {
1560
+ const oldest = settingsTexts.keys().next().value;
1561
+ if (oldest !== undefined) settingsTexts.delete(oldest);
1562
+ }
1563
+ return text;
1564
+ }
1565
+
1566
+ /**
1567
+ * Checks the paths a settings value references. These run on every read, even
1568
+ * when the parsed value came from the cache: a skill or a stage's workerBrief
1569
+ * can move or disappear while dev.json stays the same.
1570
+ */
1571
+ function checkSettingsPaths(
1572
+ repositoryPath: string,
1573
+ parsed: ParsedSettings,
1574
+ ): void {
1575
+ const { settings, worktreeField } = parsed;
1311
1576
  assertInsideRepository(
1312
1577
  repositoryPath,
1313
1578
  resolve(repositoryPath, settings.worktreeRoot),
1314
- field,
1579
+ worktreeField,
1315
1580
  );
1581
+ settings.skills.forEach((skill, index) => {
1582
+ assertInsideRepository(
1583
+ repositoryPath,
1584
+ resolve(repositoryPath, skill),
1585
+ `skills[${index}]`,
1586
+ );
1587
+ });
1316
1588
  for (const [name, flow] of Object.entries(settings.flows ?? {})) {
1317
1589
  flow.stages.forEach((stage, index) => {
1318
- if (stage.stage !== "work" || stage.workerBrief === undefined) return;
1590
+ if (stage.stage !== "code" || stage.workerBrief === undefined) return;
1319
1591
  const field = `flows.${name}.stages[${index}].workerBrief`;
1320
1592
  if (isAbsolute(stage.workerBrief)) {
1321
1593
  throw new DevError(field, "must be a path relative to the repository");
@@ -1327,7 +1599,37 @@ function settingsFromText(
1327
1599
  assertInsideRepository(repositoryPath, file, field);
1328
1600
  });
1329
1601
  }
1330
- return { settings, text };
1602
+ }
1603
+
1604
+ /** Parses and checks the text of a settings file for the repository at `repositoryPath`. */
1605
+ function settingsFromText(
1606
+ repositoryPath: string,
1607
+ path: string,
1608
+ text: string,
1609
+ ): ReadSettings {
1610
+ const parsed = parseSettingsText(path, text);
1611
+ checkSettingsPaths(repositoryPath, parsed);
1612
+ const raw: unknown = JSON.parse(text);
1613
+ const named = isRecord(raw) && raw.remote !== undefined;
1614
+ return {
1615
+ settings: named ? parsed.settings : withoutAbsentRemote(repositoryPath, parsed.settings),
1616
+ text,
1617
+ };
1618
+ }
1619
+
1620
+ /**
1621
+ * The settings of a file that names no remote: the default remote when the
1622
+ * repository has it, else none. A repository with no remote is a normal one.
1623
+ * The exit status of `git config --get` is the answer; it is not read from
1624
+ * output that can be empty under load.
1625
+ */
1626
+ function withoutAbsentRemote(repositoryPath: string, settings: DevSettings): DevSettings {
1627
+ const name = settings.remote;
1628
+ if (name === undefined) return settings;
1629
+ if (git(repositoryPath, ["config", "--local", "--get", `remote.${name}.url`]).ok) {
1630
+ return settings;
1631
+ }
1632
+ return { ...settings, remote: undefined };
1331
1633
  }
1332
1634
 
1333
1635
  /** Reads the file as it is now; any problem with it is thrown. */
@@ -1339,11 +1641,11 @@ function readSettingsNow(repositoryPath: string): ReadSettings {
1339
1641
  resolve(repositoryPath, DEFAULT_DEV_SETTINGS.worktreeRoot),
1340
1642
  "worktreeRoot",
1341
1643
  );
1342
- return { settings: DEFAULT_DEV_SETTINGS, text: "" };
1644
+ return { settings: withoutAbsentRemote(repositoryPath, defaultDevSettings()), text: "" };
1343
1645
  }
1344
1646
  let text: string;
1345
1647
  try {
1346
- text = readFileSync(path, "utf8");
1648
+ text = readSettingsText(path);
1347
1649
  } catch (error) {
1348
1650
  throw new DevError("dev.json", `cannot read ${path}: ${String(error)}`);
1349
1651
  }
@@ -1358,7 +1660,7 @@ function readSettingsNow(repositoryPath: string): ReadSettings {
1358
1660
  const lastValid = new Map<string, ReadSettings>();
1359
1661
 
1360
1662
  function keptFile(home: string, repositoryPath: string): string {
1361
- const key = createHash("sha1").update(repositoryPath).digest("hex");
1663
+ const key = repositoryPathKey(repositoryPath);
1362
1664
  return join(home, "dev", "settings", `${key}.json`);
1363
1665
  }
1364
1666
 
@@ -1375,10 +1677,11 @@ function keep(repositoryPath: string, read: ReadSettings): void {
1375
1677
  if (home === undefined) return;
1376
1678
  try {
1377
1679
  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);
1680
+ writeJsonAtomicSync(
1681
+ file,
1682
+ { path: repositoryPath, text: read.text },
1683
+ { newline: false },
1684
+ );
1382
1685
  } catch {
1383
1686
  // The copy is a convenience for the next process; the memory copy stays.
1384
1687
  }
@@ -1415,7 +1718,7 @@ function readDefaults(repositoryPath: string): ReadSettings {
1415
1718
  resolve(repositoryPath, DEFAULT_DEV_SETTINGS.worktreeRoot),
1416
1719
  "worktreeRoot",
1417
1720
  );
1418
- return { settings: DEFAULT_DEV_SETTINGS, text: "" };
1721
+ return { settings: withoutAbsentRemote(repositoryPath, defaultDevSettings()), text: "" };
1419
1722
  }
1420
1723
 
1421
1724
  /**
@@ -1424,27 +1727,71 @@ function readDefaults(repositoryPath: string): ReadSettings {
1424
1727
  * not valid never stops work: the last valid settings stay in force. Only a
1425
1728
  * repository that never had valid settings gets the error.
1426
1729
  */
1427
- export async function readDevSettings(
1428
- repositoryPath: string,
1429
- ): Promise<DevSettings> {
1730
+ export function readDevSettingsNow(repositoryPath: string): DevSettings {
1731
+ return readDevSettingsText(repositoryPath).settings;
1732
+ }
1733
+
1734
+ /**
1735
+ * Like `readDevSettingsNow`, with the file's text as well (empty when the file
1736
+ * does not exist). A step records the text when an attempt starts (ADR 0039 D6).
1737
+ */
1738
+ export function readDevSettingsText(repositoryPath: string): {
1739
+ readonly settings: DevSettings;
1740
+ readonly text: string;
1741
+ } {
1430
1742
  try {
1431
1743
  const read = readSettingsNow(repositoryPath);
1432
1744
  keep(repositoryPath, read);
1433
- return read.settings;
1745
+ return read;
1434
1746
  } catch (error) {
1435
1747
  const kept = recall(repositoryPath);
1436
- if (kept !== undefined) return kept.settings;
1748
+ if (kept !== undefined) return kept;
1437
1749
  throw error;
1438
1750
  }
1439
1751
  }
1440
1752
 
1753
+ /** The settings a recorded text gives, read the way the file is read. */
1754
+ export function devSettingsFromText(repositoryPath: string, text: string): DevSettings {
1755
+ return text === ""
1756
+ ? readDefaults(repositoryPath).settings
1757
+ : settingsFromText(repositoryPath, join(repositoryPath, DEV_SETTINGS_FILE), text).settings;
1758
+ }
1759
+
1760
+ /** Reads a repository's settings; an action's schema uses the synchronous form. */
1761
+ export async function readDevSettings(
1762
+ repositoryPath: string,
1763
+ ): Promise<DevSettings> {
1764
+ return readDevSettingsNow(repositoryPath);
1765
+ }
1766
+
1767
+ /**
1768
+ * What is wrong with a dev.json value that is about to be written, or
1769
+ * undefined when dev would accept it. The reason is dev's own, as it reads it
1770
+ * when it loads the file.
1771
+ */
1772
+ export function settingsValueProblem(
1773
+ repositoryPath: string,
1774
+ value: unknown,
1775
+ ): string | undefined {
1776
+ try {
1777
+ settingsFromText(
1778
+ repositoryPath,
1779
+ join(repositoryPath, DEV_SETTINGS_FILE),
1780
+ JSON.stringify(value),
1781
+ );
1782
+ return undefined;
1783
+ } catch (error) {
1784
+ return messageOf(error);
1785
+ }
1786
+ }
1787
+
1441
1788
  /** What is wrong with the repository's settings file now, or undefined when it is valid. */
1442
1789
  export function settingsProblem(repositoryPath: string): string | undefined {
1443
1790
  try {
1444
1791
  keep(repositoryPath, readSettingsNow(repositoryPath));
1445
1792
  return undefined;
1446
1793
  } catch (error) {
1447
- return error instanceof Error ? error.message : String(error);
1794
+ return messageOf(error);
1448
1795
  }
1449
1796
  }
1450
1797
 
@@ -1453,9 +1800,6 @@ export function hasValidSettings(repositoryPath: string): boolean {
1453
1800
  return recall(repositoryPath) !== undefined;
1454
1801
  }
1455
1802
 
1456
- /** An alias for callers that name the file rather than the plugin. */
1457
- export const readRepositorySettings = readDevSettings;
1458
-
1459
1803
  /** The absolute path of the brief a worker reads, whether it exists or not. */
1460
1804
  export function workerBriefPath(
1461
1805
  repositoryPath: string,