@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/actions.ts CHANGED
@@ -6,10 +6,11 @@ import type {
6
6
  ObjectStore,
7
7
  StoredObject,
8
8
  } from "@operad-io/engine";
9
+ import { isRecord } from "@operad-io/engine";
9
10
  import {
10
11
  appendChange,
11
12
  appendRework,
12
- bareId,
13
+ idOfKey,
13
14
  DevError,
14
15
  DevRefusal,
15
16
  isIntegrating,
@@ -40,6 +41,7 @@ import {
40
41
  getPlan,
41
42
  getTask,
42
43
  releaseWaitingClaim,
44
+ addRepository,
43
45
  setAuto,
44
46
  setConcurrency,
45
47
  validatePlanConcurrency,
@@ -63,7 +65,7 @@ async function planOfTask(
63
65
  /** What a task action's line needs to know about the task. */
64
66
  async function taskFacts(store: ObjectStore, object: StoredObject): Promise<Facts> {
65
67
  const task = taskData(object.data);
66
- const id = bareId(object.id);
68
+ const id = idOfKey(object.id);
67
69
  return task.phase === "proposed"
68
70
  ? { id, plan: await planOfTask(store, task) }
69
71
  : { id };
@@ -92,14 +94,14 @@ export function planRefusal(
92
94
  action: PlanActionName,
93
95
  object: StoredObject,
94
96
  ): string | undefined {
95
- const said = planLine(action, planData(object.data), { id: bareId(object.id) });
97
+ const said = planLine(action, planData(object.data), { id: idOfKey(object.id) });
96
98
  return said?.kind === "refuse" ? said.text : undefined;
97
99
  }
98
100
 
99
101
  /** Whether a set-a-value action gets the value the plan already has. */
100
102
  function sameValue(action: PlanActionName, plan: PlanData, args: unknown): string | number | undefined {
101
103
  const given =
102
- typeof args === "object" && args !== null ? (args as Record<string, unknown>) : {};
104
+ isRecord(args) ? args : {};
103
105
  if (action === "auto" && given.level === plan.auto) return plan.auto;
104
106
  if (action === "priority" && given.level === plan.priority) return plan.priority;
105
107
  if (action === "concurrency" && given.count === plan.concurrency) return plan.concurrency;
@@ -115,7 +117,7 @@ const planWhy = (action: PlanActionName) =>
115
117
  /** The line for a task action whose result is already true. */
116
118
  const taskSettled = (action: TaskActionName) =>
117
119
  (object: StoredObject): string | undefined => {
118
- const said = taskLine(action, taskData(object.data), { id: bareId(object.id) });
120
+ const said = taskLine(action, taskData(object.data), { id: idOfKey(object.id) });
119
121
  return said?.kind === "done" ? said.text : undefined;
120
122
  };
121
123
 
@@ -124,7 +126,7 @@ const planSettled = (action: PlanActionName) =>
124
126
  (object: StoredObject, args: unknown): string | undefined => {
125
127
  const plan = planData(object.data);
126
128
  const value = sameValue(action, plan, args);
127
- const said = planLine(action, plan, { id: bareId(object.id), value }, value !== undefined);
129
+ const said = planLine(action, plan, { id: idOfKey(object.id), value }, value !== undefined);
128
130
  return said?.kind === "done" ? said.text : undefined;
129
131
  };
130
132
 
@@ -176,16 +178,19 @@ export const PLAN_RANKS: Record<PlanActionName, (state: Parameters<typeof planDa
176
178
  cancel: () => 9,
177
179
  };
178
180
 
181
+ /** The rank of the action that adds a task: after the plan's own actions, before cancel. */
182
+ export const PLAN_CREATE_TASK_RANK = 4;
183
+
179
184
  /** Reads a required enum argument; the kernel checks it first, this is for types. */
180
185
  function enumArgument<T extends string>(
181
186
  args: unknown,
182
187
  field: string,
183
188
  allowed: readonly T[],
184
189
  ): T {
185
- if (typeof args !== "object" || args === null) {
190
+ if (!isRecord(args)) {
186
191
  throw new DevError(field, `must be one of ${allowed.join(", ")}`);
187
192
  }
188
- const raw = (args as Record<string, unknown>)[field];
193
+ const raw = args[field];
189
194
  if (typeof raw !== "string" || !(allowed as readonly string[]).includes(raw)) {
190
195
  throw new DevError(field, `must be one of ${allowed.join(", ")}`);
191
196
  }
@@ -246,7 +251,7 @@ async function claimAndAnswer(
246
251
  // action that starts after a competing one wrote must still lose.
247
252
  const seen = ctx.object.version ?? object.version;
248
253
  if (ctx.answer === undefined) {
249
- throw new DevRefusal(`${bareId(ctx.object.id)} is not waiting for an answer now`);
254
+ throw new DevRefusal(`${idOfKey(ctx.object.id)} is not waiting for an answer now`);
250
255
  }
251
256
  const claim = await claimWaitingTask(
252
257
  ctx.store,
@@ -284,7 +289,7 @@ const mergeTask: ActionTypeDefinition = {
284
289
  // The merge step would refuse later, in the background; say so now.
285
290
  throw new DevError(
286
291
  "merge",
287
- `${bareId(ctx.object.id)} has no verified commit; run operad dev:reverify ${bareId(ctx.object.id)} first`,
292
+ `${idOfKey(ctx.object.id)} has no verified commit; run operad dev:reverify ${idOfKey(ctx.object.id)} first`,
288
293
  );
289
294
  }
290
295
  return { ...latest, brief: appendChange(latest.brief, "merge requested") };
@@ -375,6 +380,12 @@ const reverifyTaskAction: ActionTypeDefinition = {
375
380
  "the task has no work to verify yet; rework it instead",
376
381
  );
377
382
  }
383
+ if (latest.attempt.workDone === false) {
384
+ throw new DevError(
385
+ "reverify",
386
+ "the work did not finish, so there is nothing to verify again; rework it instead",
387
+ );
388
+ }
378
389
  return {
379
390
  ...latest,
380
391
  phase: "running",
@@ -399,7 +410,56 @@ const reverifyTaskAction: ActionTypeDefinition = {
399
410
  },
400
411
  };
401
412
 
413
+ /**
414
+ * Registers a repository from a client that talks to a serve on another
415
+ * machine. The path is on the serve's machine; the refusal is `addRepository`'s,
416
+ * the same line the command prints.
417
+ */
418
+ const repoAddAction: ActionTypeDefinition = {
419
+ name: "repo-add",
420
+ args: {
421
+ type: "object",
422
+ properties: {
423
+ path: {
424
+ type: "string",
425
+ minLength: 1,
426
+ description: "The repository's path on the machine that runs serve.",
427
+ },
428
+ name: {
429
+ type: "string",
430
+ minLength: 1,
431
+ description: "The name to register it under; the folder name when left out.",
432
+ },
433
+ },
434
+ required: ["path"],
435
+ additionalProperties: false,
436
+ },
437
+ confirm: true,
438
+ when() {
439
+ return true;
440
+ },
441
+ async run(ctx, args) {
442
+ const given =
443
+ isRecord(args) ? args : {};
444
+ const path = given.path;
445
+ const name = given.name;
446
+ if (typeof path !== "string") {
447
+ throw new DevError("path", "repo add needs a path");
448
+ }
449
+ if (name !== undefined && typeof name !== "string") {
450
+ throw new DevError("name", "must be a string");
451
+ }
452
+ const repository = await addRepository(ctx.store, {
453
+ path,
454
+ ...(name === undefined ? {} : { name }),
455
+ cwd: ctx.cwd,
456
+ });
457
+ return `added ${repository.name} (${repository.path})`;
458
+ },
459
+ };
460
+
402
461
  export const actions: readonly ActionTypeDefinition[] = [
462
+ repoAddAction,
403
463
  {
404
464
  name: "confirm",
405
465
  on: "plan",
@@ -443,10 +503,17 @@ export const actions: readonly ActionTypeDefinition[] = [
443
503
  why: planWhy("cancel"),
444
504
  settled: planSettled("cancel"),
445
505
  async run(ctx) {
446
- await cancelPlan(ctx.store, ctx.object.id, {
506
+ const cancelled = await cancelPlan(ctx.store, ctx.object.id, {
447
507
  runs: ctx.runs,
448
508
  home: ctx.home,
449
509
  });
510
+ const lines = [
511
+ ...(cancelled.merged.length === 0
512
+ ? []
513
+ : [`${cancelled.merged.map(idOfKey).join(", ")} merged before the cancel and stays merged`]),
514
+ ...cancelled.notes,
515
+ ];
516
+ return lines.length === 0 ? undefined : lines.join("; ");
450
517
  },
451
518
  },
452
519
  {
@@ -466,7 +533,7 @@ export const actions: readonly ActionTypeDefinition[] = [
466
533
  runs: ctx.runs,
467
534
  home: ctx.home,
468
535
  });
469
- return cancelled.alreadyMerged;
536
+ return cancelled.alreadyMerged ?? cancelled.note;
470
537
  },
471
538
  },
472
539
  {
@@ -556,7 +623,7 @@ export const actions: readonly ActionTypeDefinition[] = [
556
623
  async run(ctx, args) {
557
624
  const level = enumArgument(args, "level", PRIORITIES);
558
625
  await setPriority(ctx.store, ctx.object.id, level);
559
- const id = bareId(ctx.object.id);
626
+ const id = idOfKey(ctx.object.id);
560
627
  if (planData((await getPlan(ctx.store, ctx.object.id)).data).auto === "off") {
561
628
  return `${id} has auto off: the scheduler does not start its tasks; run operad dev:auto ${id} --level merge`;
562
629
  }
@@ -587,10 +654,7 @@ export const actions: readonly ActionTypeDefinition[] = [
587
654
  why: planWhy("concurrency"),
588
655
  settled: planSettled("concurrency"),
589
656
  async run(ctx, args) {
590
- const count =
591
- typeof args === "object" && args !== null
592
- ? (args as Record<string, unknown>).count
593
- : undefined;
657
+ const count = isRecord(args) ? args.count : undefined;
594
658
  await setConcurrency(ctx.store, ctx.object.id, validatePlanConcurrency(count));
595
659
  },
596
660
  },
package/src/announce.ts CHANGED
@@ -8,7 +8,10 @@
8
8
 
9
9
  import type { PluginStepResult, StepContext } from "@operad-io/engine";
10
10
  import { messageOf } from "@operad-io/engine";
11
- import type { TaskData } from "./model.ts";
11
+ import type { ReviewFinding, TaskData } from "./model.ts";
12
+ import { severityRank } from "./rework.ts";
13
+ import { edgeParamsOf, type EdgeParams } from "./step-edge.ts";
14
+ import { WAIT_ACTIONS, waitChoiceInfo, type WaitAction } from "./waits.ts";
12
15
  import {
13
16
  cancelledStep,
14
17
  claimAllows,
@@ -21,10 +24,7 @@ import {
21
24
  export const WAITING_EVENT = "dev.waiting";
22
25
 
23
26
  /** The edge a task took into the wait, as the flow names it in its params. */
24
- export interface AnnounceParams {
25
- readonly from: string;
26
- readonly result: string;
27
- }
27
+ export type AnnounceParams = EdgeParams;
28
28
 
29
29
  /** Why a task waits: the short reason for the key, and what to add to the line. */
30
30
  export interface WaitingReason {
@@ -34,16 +34,6 @@ export interface WaitingReason {
34
34
  readonly step?: string | undefined;
35
35
  }
36
36
 
37
- function paramsOf(params: unknown): AnnounceParams {
38
- const record =
39
- typeof params === "object" && params !== null && !Array.isArray(params)
40
- ? (params as Record<string, unknown>)
41
- : {};
42
- const from = typeof record.from === "string" ? record.from : "";
43
- const result = typeof record.result === "string" ? record.result : "";
44
- return { from, result };
45
- }
46
-
47
37
  /** The step a repair run says stopped, from the line the worktree step wrote. */
48
38
  function stoppedStep(task: TaskData, fallback: string): string {
49
39
  const lines = task.brief.replace(/\r\n/g, "\n").split("\n");
@@ -96,7 +86,10 @@ export function waitingReason(
96
86
  return { reason: "run stopped during work", step: "work" };
97
87
  }
98
88
  if (conflicted) return { reason: "conflict" };
99
- if (edge.result === "nothing") return { reason: "work did nothing" };
89
+ if (edge.result === "nothing") {
90
+ // The only note a "nothing" visit carries is the main-checkout line.
91
+ return { reason: "work did nothing", detail: nonEmpty(attempt?.workNote) };
92
+ }
100
93
  if (attempt?.workTimedOut === true) {
101
94
  return { reason: "work timed out", detail: nonEmpty(attempt.workNote) };
102
95
  }
@@ -145,6 +138,106 @@ export function waitingReason(
145
138
  }
146
139
  }
147
140
 
141
+ /** The most serious finding of the review that is at or above the fix level. */
142
+ function highestFinding(
143
+ task: TaskData,
144
+ fixLevel: string | undefined,
145
+ ): ReviewFinding | undefined {
146
+ const findings = (task.attempt?.review?.findings ?? []).filter(
147
+ (finding) =>
148
+ finding.preExisting !== true &&
149
+ finding.pre_existing !== true &&
150
+ (fixLevel === undefined ||
151
+ severityRank(finding.severity) >= severityRank(fixLevel)),
152
+ );
153
+ return [...findings].sort(
154
+ (left, right) =>
155
+ severityRank(right.severity) - severityRank(left.severity) ||
156
+ left.file.localeCompare(right.file) ||
157
+ left.line - right.line,
158
+ )[0];
159
+ }
160
+
161
+ function findingSentence(finding: ReviewFinding): string {
162
+ const trigger = finding.trigger.trim();
163
+ return `${finding.severity} finding at ${finding.file}:${finding.line}: ${finding.summary}${
164
+ trigger.length === 0 ? "" : ` (${trigger})`
165
+ }`;
166
+ }
167
+
168
+ /**
169
+ * Why the task waits, in one or two plain sentences. It reads the task's own
170
+ * record for the review's highest finding, the failed check's command and the
171
+ * integration's reason; the choice list is never part of a prompt.
172
+ */
173
+ export function waitingPrompt(
174
+ found: WaitingReason,
175
+ task: TaskData,
176
+ fixLevel: string | undefined,
177
+ ): string {
178
+ const attempt = task.attempt;
179
+ const finding = highestFinding(task, fixLevel);
180
+ if (found.reason === "ready to merge") {
181
+ return "The checks and the review passed; the task is ready to merge.";
182
+ }
183
+ if (found.reason === "work did nothing") {
184
+ return found.detail === undefined
185
+ ? "The worker changed nothing."
186
+ : `The worker changed nothing in its worktree, but it ${found.detail}.`;
187
+ }
188
+ if (found.reason === "work timed out") {
189
+ return `The worker timed out.${found.detail === undefined ? "" : ` ${found.detail}.`}`;
190
+ }
191
+ if (found.reason === "work failed") {
192
+ return `The worker failed${found.detail === undefined ? "" : `: ${found.detail}`}.`;
193
+ }
194
+ if (found.reason === "conflict") {
195
+ return "The worker's changes conflict with main.";
196
+ }
197
+ if (found.reason === "review timed out twice") {
198
+ return "review timed out twice";
199
+ }
200
+ if (found.reason === "review did not finish") {
201
+ return `review did not finish${found.detail === undefined ? "" : ` (${found.detail})`}`;
202
+ }
203
+ if (found.reason === "review failed twice in a row") {
204
+ return `The review failed twice in a row.${
205
+ finding === undefined ? "" : ` Highest finding: ${findingSentence(finding)}.`
206
+ }`;
207
+ }
208
+ if (found.reason === "review findings" || found.reason === "rework limit") {
209
+ const source = attempt?.rework?.source;
210
+ if (source === "review" || (source === undefined && attempt?.review !== undefined)) {
211
+ return finding === undefined
212
+ ? "The review failed."
213
+ : `The review failed: ${findingSentence(finding)}.`;
214
+ }
215
+ const command = attempt?.verify?.command;
216
+ return typeof command !== "string" || command.length === 0
217
+ ? `The check failed${attempt?.verify?.message === undefined ? "." : `: ${attempt.verify.message}.`}`
218
+ : `The check failed: \`${command}\`.`;
219
+ }
220
+ if (found.reason === "gate failed") {
221
+ const command = attempt?.verify?.command;
222
+ return typeof command !== "string" || command.length === 0
223
+ ? `The check failed${attempt?.verify?.message === undefined ? "." : `: ${attempt.verify.message}.`}`
224
+ : `The check failed: \`${command}\`.`;
225
+ }
226
+ if (found.reason === "merge refused") {
227
+ return `The merge failed${found.detail === undefined ? "" : `: ${found.detail}`}.`;
228
+ }
229
+ if (found.reason === "no verified commit") {
230
+ return "The task has no verified commit to merge.";
231
+ }
232
+ if (found.reason === "dependency cancelled") {
233
+ return "A task this one waits for was cancelled.";
234
+ }
235
+ if (found.reason.startsWith("run stopped during ")) {
236
+ return `The run stopped during ${found.reason.slice("run stopped during ".length)}.`;
237
+ }
238
+ return `${found.reason.charAt(0).toUpperCase()}${found.reason.slice(1)}.`;
239
+ }
240
+
148
241
  /** One line a person reads: the task, why it waits, and the detail if any. */
149
242
  export function waitingSummary(taskId: string, found: WaitingReason): string {
150
243
  const detail = found.detail === undefined ? "" : ` (${found.detail})`;
@@ -158,7 +251,7 @@ export async function runAnnounce(
158
251
  ): Promise<PluginStepResult> {
159
252
  const context = await taskContext(ctx);
160
253
  if (!claimAllows(ctx, context.task)) return cancelledStep();
161
- const edge = paramsOf(stepParams);
254
+ const edge = edgeParamsOf(stepParams);
162
255
  const path = context.task.attempt?.worktree;
163
256
  const conflicted =
164
257
  edge.from === "work" &&
@@ -213,6 +306,30 @@ export async function runAnnounce(
213
306
  await ctx.logger.write(`could not mark the task waiting: ${messageOf(error)}`);
214
307
  }
215
308
  }
309
+ // The wait that follows asks the person. It carries this task's own reason
310
+ // and choice information; asking with no grace hands the question over to
311
+ // the wait step at once, keeping one item and one wait id.
312
+ const choices = edge.choices;
313
+ if (choices !== undefined && choices.length > 0) {
314
+ const actions = choices.filter((choice): choice is WaitAction =>
315
+ (WAIT_ACTIONS as readonly string[]).includes(choice),
316
+ );
317
+ await ctx.ask({
318
+ prompt: waitingPrompt(
319
+ found,
320
+ context.task,
321
+ context.settings.reviewer.fixLevel,
322
+ ),
323
+ choices,
324
+ choiceInfo: waitChoiceInfo(
325
+ actions,
326
+ found.reason === "ready to merge",
327
+ ),
328
+ graceSecs: 0,
329
+ onTimeout: "waiting",
330
+ resume: null,
331
+ });
332
+ }
216
333
  // A stopped run keeps its result, so the wait can say which step stopped.
217
334
  return {
218
335
  result: found.step === undefined ? "done" : "interrupted",