@operad-io/dev 0.1.0 → 0.2.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.
package/src/throughput.ts CHANGED
@@ -8,11 +8,12 @@
8
8
 
9
9
  import {
10
10
  foldObjectFacts,
11
- type PluginFact,
11
+ formatElapsed,
12
12
  type StoredObject,
13
13
  type ViewContext,
14
14
  } from "@operad-io/engine";
15
15
  import {
16
+ allFactsOf,
16
17
  listAll,
17
18
  repositoryData,
18
19
  taskData,
@@ -60,14 +61,6 @@ export function percentile(values: readonly number[], p: number): number {
60
61
  return sorted[Math.min(sorted.length, rank) - 1] ?? 0;
61
62
  }
62
63
 
63
- function duration(ms: number): string {
64
- const total = Math.max(0, Math.round(ms / 1000));
65
- if (total < 60) return `${total}s`;
66
- const minutes = Math.round(total / 60);
67
- if (minutes < 60) return `${minutes}m`;
68
- return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
69
- }
70
-
71
64
  function pad(value: number): string {
72
65
  return String(value).padStart(2, "0");
73
66
  }
@@ -156,17 +149,7 @@ async function readTask(
156
149
  // Each attempt's cost, the latest recorded for it: a rework is paid for too.
157
150
  const attemptCosts = new Map<number, number>();
158
151
  const reasons = new Set<string>();
159
- const facts: PluginFact[] = [];
160
- let cursor: string | undefined;
161
- for (;;) {
162
- const page = await ctx.store.facts(
163
- { type: object.type, id: object.id },
164
- cursor === undefined ? {} : { cursor },
165
- );
166
- facts.push(...page.facts);
167
- if (page.next === undefined) break;
168
- cursor = page.next;
169
- }
152
+ const facts = await allFactsOf(ctx.store, object);
170
153
  for (const version of foldObjectFacts(facts)) {
171
154
  const data = taskData(version.data);
172
155
  const attempt = data.attempt;
@@ -309,7 +292,7 @@ export async function repositoryMetrics(
309
292
  }
310
293
  const stepRows = STEP_ROWS.map((step) => {
311
294
  const values = timed.map((times) => times[step]);
312
- return [step, duration(percentile(values, 50)), duration(percentile(values, 90))];
295
+ return [step, formatElapsed(percentile(values, 50)), formatElapsed(percentile(values, 90))];
313
296
  });
314
297
  const reworks = merged.map((task) => task.reworks);
315
298
  const rounds = (value: number): string => String(value);
package/src/timeouts.ts CHANGED
@@ -30,6 +30,14 @@ export function reviewWaitMs(retrySecs: number, n: number): number {
30
30
  return Math.min(retrySecs * 2 ** doublings, cap) * 1000;
31
31
  }
32
32
 
33
+ /**
34
+ * The longest a model's `retry_after_secs` is waited out by dev. Past it, or
35
+ * on a usage limit, the task waits for a person: half an hour is as long as a
36
+ * review wait is allowed to last, and a longer wait is usually a quota period
37
+ * the owner must decide about (switch the worker or wait for the reset).
38
+ */
39
+ export const MAX_MODEL_RETRY_SECS = 30 * 60;
40
+
33
41
  /**
34
42
  * How many times one review round may wait for an unavailable model before it
35
43
  * waits for a person instead. It was 36 waits of a flat `retrySecs` (about 72
@@ -42,8 +50,8 @@ export const MAX_REVIEW_WAITS = 6;
42
50
 
43
51
  /**
44
52
  * How many times one attempt's work step may wait for an unavailable model
45
- * before the failure goes to a person. The work wait stays flat at
46
- * `reviewer.retrySecs`.
53
+ * before the failure goes to a person. The work wait is the model's
54
+ * `retry_after_secs` when it gives one, else flat at `reviewer.retrySecs`.
47
55
  */
48
56
  export const MAX_WORK_WAITS = 36;
49
57
 
package/src/views.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  /** How a plan and a task appear in a list and a detail page. */
2
2
 
3
+ import { isRecord, messageOf } from "@operad-io/engine";
3
4
  import {
4
5
  foldObjectFacts,
5
6
  type ObjectRow,
6
7
  type ObjectViews,
7
- type PluginFact,
8
8
  type StoredObject,
9
9
  type ViewContext,
10
10
  type ViewSection,
@@ -18,9 +18,9 @@ import {
18
18
  } from "node:fs";
19
19
  import { join } from "node:path";
20
20
  import {
21
- bareId,
21
+ allFactsOf,
22
+ idOfKey,
22
23
  hasRework,
23
- listAll,
24
24
  PLAN_FINAL_STATES,
25
25
  TASK_FINAL_STATES,
26
26
  dependencyKey,
@@ -39,12 +39,14 @@ import {
39
39
  type TaskData,
40
40
  } from "./model.ts";
41
41
  import { placeWaitNote } from "./place-wait.ts";
42
+ import { checkHostWarning } from "./check-host.ts";
42
43
  import { planMark, repositoryMark, taskBadge, taskMark } from "./marks.ts";
43
- import { git, workBranch } from "./steps.ts";
44
+ import { branchExists, commitOf, git } from "./git.ts";
45
+ import { workBranch } from "./steps.ts";
44
46
  import { repositoryMetrics } from "./throughput.ts";
45
47
  import { findRepository, listRepositories } from "./service.ts";
46
48
  import { DEV_SETTINGS_FILE, readDevSettings, settingsProblem } from "./settings.ts";
47
- import { oneLine } from "@operad-io/engine";
49
+ import { formatElapsed, oneLine } from "@operad-io/engine";
48
50
 
49
51
  function costNote(cost: unknown, quality?: unknown): string | undefined {
50
52
  if (typeof cost === "number" && Number.isFinite(cost)) {
@@ -154,6 +156,10 @@ export const repoViews: ObjectViews = {
154
156
  try {
155
157
  const settings = await readDevSettings(repository.path);
156
158
  const problem = settingsProblem(repository.path);
159
+ const hostWarning =
160
+ problem === undefined
161
+ ? checkHostWarning(repository.name, settings, ctx.settings)
162
+ : undefined;
157
163
  const file = join(repository.path, DEV_SETTINGS_FILE);
158
164
  lines.push(
159
165
  `- Default branch: \`${settings.mainBranch}\` on \`${settings.remote}\``,
@@ -167,9 +173,10 @@ export const repoViews: ObjectViews = {
167
173
  `- Worker: \`${settings.worker.use}\``,
168
174
  `- Reviewer: \`${settings.reviewer.use}\``,
169
175
  );
176
+ if (hostWarning !== undefined) lines.push(`- Test host: not set; ${hostWarning}`);
170
177
  } catch (error) {
171
178
  lines.push(
172
- `- ${DEV_SETTINGS_FILE}: ${error instanceof Error ? error.message : String(error)}`,
179
+ `- ${DEV_SETTINGS_FILE}: ${messageOf(error)}`,
173
180
  );
174
181
  }
175
182
  if (repository.removed) lines.push("- Removed from the registered repositories.");
@@ -181,7 +188,7 @@ export const planViews: ObjectViews = {
181
188
  row(object: StoredObject): ObjectRow {
182
189
  const plan = planData(object.data);
183
190
  return {
184
- id: bareId(object.id),
191
+ id: idOfKey(object.id),
185
192
  title: plan.title,
186
193
  state: planState(plan),
187
194
  note: planNote(plan),
@@ -236,7 +243,7 @@ export const taskViews: ObjectViews = {
236
243
  .filter((part): part is string => part !== undefined)
237
244
  .join(" · ");
238
245
  return {
239
- id: bareId(object.id),
246
+ id: idOfKey(object.id),
240
247
  title: task.title,
241
248
  state: taskRowState(task),
242
249
  note,
@@ -338,20 +345,18 @@ function clockTime(at: number): string {
338
345
  }
339
346
 
340
347
  function tokenText(usage: unknown): string | undefined {
341
- if (typeof usage !== "object" || usage === null) return undefined;
342
- const record = usage as Record<string, unknown>;
343
- const input = numberField(record, "input");
344
- const output = numberField(record, "output");
348
+ if (!isRecord(usage)) return undefined;
349
+ const input = numberField(usage, "input");
350
+ const output = numberField(usage, "output");
345
351
  if (input === undefined && output === undefined) return undefined;
346
352
  return `${input ?? 0} in / ${output ?? 0} out tokens`;
347
353
  }
348
354
 
349
355
  /** The cost a log line carries, as dollars: pi's `total`, or `micros`. */
350
356
  function costText(cost: unknown): string | undefined {
351
- if (typeof cost !== "object" || cost === null) return undefined;
352
- const record = cost as Record<string, unknown>;
353
- const micros = numberField(record, "micros");
354
- const dollars = micros !== undefined ? micros / 1e6 : numberField(record, "total");
357
+ if (!isRecord(cost)) return undefined;
358
+ const micros = numberField(cost, "micros");
359
+ const dollars = micros !== undefined ? micros / 1e6 : numberField(cost, "total");
355
360
  return dollars === undefined ? undefined : `$${dollars.toFixed(4)}`;
356
361
  }
357
362
 
@@ -393,9 +398,7 @@ function inlineCode(text: string): string {
393
398
  function parseObject(text: string): Record<string, unknown> | undefined {
394
399
  try {
395
400
  const value: unknown = JSON.parse(text);
396
- return typeof value === "object" && value !== null && !Array.isArray(value)
397
- ? (value as Record<string, unknown>)
398
- : undefined;
401
+ return isRecord(value) ? value : undefined;
399
402
  } catch {
400
403
  return undefined;
401
404
  }
@@ -442,7 +445,7 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
442
445
  end !== undefined
443
446
  ? end.durationMs === undefined
444
447
  ? ""
445
- : ` ${seconds(end.durationMs)}`
448
+ : ` ${formatElapsed(end.durationMs)}`
446
449
  : finished
447
450
  ? ` no end logged${at === undefined ? "" : ` (started ${clockTime(at)})`}`
448
451
  : ` running${at === undefined ? "" : ` since ${clockTime(at)}`}`;
@@ -496,13 +499,13 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
496
499
  continue;
497
500
  }
498
501
  if (record !== undefined && (kind === "journal" || kind === undefined) && typeof record.event === "string") {
499
- const data = isObject(record.data) ? record.data : {};
502
+ const data = isRecord(record.data) ? record.data : {};
500
503
  if (record.event === "MessageAppended") {
501
- const message = isObject(data.message) ? data.message : {};
502
- const assistant = isObject(message.assistant) ? message.assistant : undefined;
504
+ const message = isRecord(data.message) ? data.message : {};
505
+ const assistant = isRecord(message.assistant) ? message.assistant : undefined;
503
506
  const blocks: unknown[] = Array.isArray(assistant?.content) ? assistant.content : [];
504
507
  const text = blocks
505
- .map((block) => (isObject(block) && isObject(block.text) ? stringField(block.text, ["text"]) : undefined))
508
+ .map((block) => (isRecord(block) && isRecord(block.text) ? stringField(block.text, ["text"]) : undefined))
506
509
  .filter((part): part is string => part !== undefined)
507
510
  .join(" ");
508
511
  if (text.trim().length > 0) {
@@ -556,10 +559,10 @@ export function readableLogLine(line: string): string | undefined {
556
559
  } catch {
557
560
  return oneLine(text, LOG_LINE_CHARS);
558
561
  }
559
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
562
+ if (!isRecord(value)) {
560
563
  return oneLine(text, LOG_LINE_CHARS);
561
564
  }
562
- const record = value as Record<string, unknown>;
565
+ const record = value;
563
566
  const kind = stringField(record, ["type"]) ?? "";
564
567
  const tool = stringField(record, ["tool", "tool_name", "toolName", "name"]);
565
568
  const event = stringField(record, ["event"]) ?? "";
@@ -712,17 +715,7 @@ async function answerSection(
712
715
  readonly pages?: readonly { readonly label: string; readonly cursor?: string }[];
713
716
  }> {
714
717
  const byAttempt = new Map<number, string>();
715
- const facts: PluginFact[] = [];
716
- let page: string | undefined;
717
- for (;;) {
718
- const read = await ctx.store.facts(
719
- { type: object.type, id: object.id },
720
- page === undefined ? {} : { cursor: page },
721
- );
722
- facts.push(...read.facts);
723
- if (read.next === undefined) break;
724
- page = read.next;
725
- }
718
+ const facts = await allFactsOf(ctx.store, object);
726
719
  for (const version of foldObjectFacts(facts)) {
727
720
  const attempt = taskData(version.data).attempt;
728
721
  if (attempt === undefined) continue;
@@ -755,7 +748,8 @@ async function answerSection(
755
748
  }
756
749
 
757
750
  /* ---------------------------------------------------------------------------
758
- * Diff: the task branch against main, one page per file when it is long.
751
+ * Diff: the task branch against main, one page per file when it is long. A
752
+ * merged task shows what its merge commit brought; its branch is gone by then.
759
753
  * ------------------------------------------------------------------------- */
760
754
 
761
755
  /** A diff longer than this many characters is paged by file. */
@@ -765,6 +759,84 @@ function fence(diff: string): string {
765
759
  return `\`\`\`\`diff\n${diff.trimEnd()}\n\`\`\`\``;
766
760
  }
767
761
 
762
+ /** The commit whose change a merged task brought, when dev recorded one. */
763
+ function mergedCommitOf(task: TaskData): string | undefined {
764
+ const integration = task.attempt?.integration;
765
+ if (
766
+ integration === undefined ||
767
+ integration === null ||
768
+ (integration.result !== undefined && integration.result !== "merged")
769
+ ) {
770
+ return undefined;
771
+ }
772
+ const candidate = integration.candidate;
773
+ if (typeof candidate !== "string" || !/^[0-9a-f]{7,64}$/i.test(candidate)) return undefined;
774
+ // `already on main` records main itself when no commit carries the change.
775
+ if (integration.base === candidate) return undefined;
776
+ return candidate;
777
+ }
778
+
779
+ /** A GitHub-style remote's web page for a commit, when the remote names one. */
780
+ function commitWebUrl(repositoryPath: string, remote: string, sha: string): string | undefined {
781
+ const configured = git(repositoryPath, ["remote", "get-url", remote]);
782
+ if (!configured.ok || configured.out.length === 0) return undefined;
783
+ const text = configured.out.trim();
784
+ let host: string;
785
+ let path: string;
786
+ if (text.includes("://")) {
787
+ let url: URL;
788
+ try {
789
+ url = new URL(text);
790
+ } catch {
791
+ return undefined;
792
+ }
793
+ if (
794
+ url.protocol !== "https:" &&
795
+ url.protocol !== "http:" &&
796
+ url.protocol !== "ssh:" &&
797
+ url.protocol !== "git:"
798
+ ) {
799
+ return undefined;
800
+ }
801
+ host = url.hostname;
802
+ path = url.pathname;
803
+ } else {
804
+ const match = /^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(text);
805
+ if (match === null) return undefined;
806
+ host = match[1] ?? "";
807
+ path = match[2] ?? "";
808
+ }
809
+ if (host !== "github.com" && !host.startsWith("github.") && !host.endsWith(".github.com")) {
810
+ return undefined;
811
+ }
812
+ const parts = path
813
+ .replace(/^\/+/, "")
814
+ .replace(/\/+$/, "")
815
+ .replace(/\.git$/, "")
816
+ .split("/")
817
+ .filter((part) => part.length > 0);
818
+ const owner = parts[0];
819
+ const name = parts[1];
820
+ if (owner === undefined || name === undefined) return undefined;
821
+ return `https://${host}/${owner}/${name}/commit/${sha}`;
822
+ }
823
+
824
+ /** What a merged task says when its own change cannot be shown. */
825
+ function mergedMarkdown(repositoryPath: string, remote: string, sha: string | undefined): string {
826
+ if (sha === undefined) return "_Merged._";
827
+ const short = sha.slice(0, 7);
828
+ const url = commitWebUrl(repositoryPath, remote, sha);
829
+ return url === undefined ? `_Merged as ${short}._` : `_Merged as [${short}](${url})._`;
830
+ }
831
+
832
+ /** True when the task's branch is still in the repository, here or on its remote. */
833
+ function branchIsThere(repositoryPath: string, remote: string, branch: string): boolean {
834
+ return (
835
+ branchExists(repositoryPath, branch) ||
836
+ branchExists(repositoryPath, branch, remote)
837
+ );
838
+ }
839
+
768
840
  async function diffSection(
769
841
  ctx: ViewContext,
770
842
  object: StoredObject,
@@ -779,15 +851,39 @@ async function diffSection(
779
851
  if (found === undefined) return { markdown: "_The repository is not registered._" };
780
852
  const repository = repositoryData(found.data);
781
853
  const settings = await readDevSettings(repository.path);
782
- const branch = task.attempt?.branch ?? workBranch(task.worktree ?? bareId(object.id));
854
+ const branch = task.attempt?.branch ?? workBranch(task.worktree ?? idOfKey(object.id));
783
855
  const main = `${settings.remote}/${settings.mainBranch}`;
784
- const range = `${main}...${branch}`;
785
- const stat = git(repository.path, ["diff", "--stat", range], true);
786
- if (!stat.ok) {
787
- return { markdown: `_No diff: ${stat.err || `cannot compare ${branch} with ${main}`}._` };
856
+ const merged = task.phase === "merged";
857
+ const recorded = merged ? mergedCommitOf(task) : undefined;
858
+ let range: string;
859
+ let fallback: string;
860
+ if (merged) {
861
+ if (recorded === undefined) return { markdown: "_Merged._" };
862
+ const found = commitOf(repository.path, recorded);
863
+ const sha = found ?? recorded;
864
+ const parent =
865
+ found === undefined ? undefined : commitOf(repository.path, `${sha}^1`);
866
+ if (parent === undefined) {
867
+ return { markdown: mergedMarkdown(repository.path, settings.remote, sha) };
868
+ }
869
+ range = `${sha}^1..${sha}`;
870
+ fallback = mergedMarkdown(repository.path, settings.remote, sha);
871
+ } else {
872
+ if (!branchIsThere(repository.path, settings.remote, branch)) {
873
+ return {
874
+ markdown:
875
+ task.phase === "cancelled"
876
+ ? "_The branch of this task is gone, so there is no diff to show._"
877
+ : "_The branch of this task is not here, so there is no diff to show._",
878
+ };
879
+ }
880
+ range = `${main}...${branch}`;
881
+ fallback = `_No diff: cannot compare ${branch} with ${main}._`;
788
882
  }
883
+ const stat = git(repository.path, ["diff", "--stat", range], true);
884
+ if (!stat.ok) return { markdown: fallback };
789
885
  if (stat.out.length === 0) {
790
- return { markdown: `_${branch} has no changes against ${main}._` };
886
+ return { markdown: merged ? fallback : `_${branch} has no changes against ${main}._` };
791
887
  }
792
888
  const whole = git(repository.path, ["diff", range]);
793
889
  if (whole.out.length <= DIFF_PAGE_CHARS && cursor === undefined) {
@@ -829,13 +925,6 @@ async function diffSection(
829
925
 
830
926
  const METRIC_STEPS = ["worktree", "work", "reverify", "verify", "review", "integrate"] as const;
831
927
 
832
- function seconds(ms: number): string {
833
- if (ms < 1000) return "<1s";
834
- const total = Math.round(ms / 1000);
835
- const minutes = Math.floor(total / 60);
836
- return minutes === 0 ? `${total}s` : `${minutes}m${String(total % 60).padStart(2, "0")}s`;
837
- }
838
-
839
928
  interface AttemptMetrics {
840
929
  readonly number: number;
841
930
  /** The runs that ran it, in the order the task first named them. */
@@ -879,15 +968,6 @@ export function tokenCount(count: number): string {
879
968
  return count < 10_000 ? String(count) : `${(count / 1000).toFixed(1)}k`;
880
969
  }
881
970
 
882
- /** A wall time for the narrow table: seconds, minutes, or hours and minutes. */
883
- function wallTime(ms: number): string {
884
- const total = Math.max(0, Math.round(ms / 1000));
885
- if (total < 60) return `${total}s`;
886
- const minutes = Math.round(total / 60);
887
- if (minutes < 60) return `${minutes}m`;
888
- return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
889
- }
890
-
891
971
  function findingsText(review: ReviewRecord): string {
892
972
  const count = review.findings?.length;
893
973
  if (count === undefined) return "review: findings";
@@ -958,17 +1038,7 @@ export async function metrics(
958
1038
  now: number = Date.now(),
959
1039
  ): Promise<string> {
960
1040
  const byAttempt = new Map<number, AttemptMetrics>();
961
- const facts: PluginFact[] = [];
962
- let cursor: string | undefined;
963
- for (;;) {
964
- const page = await ctx.store.facts(
965
- { type: object.type, id: object.id },
966
- cursor === undefined ? {} : { cursor },
967
- );
968
- facts.push(...page.facts);
969
- if (page.next === undefined) break;
970
- cursor = page.next;
971
- }
1041
+ const facts = await allFactsOf(ctx.store, object);
972
1042
  for (const version of foldObjectFacts(facts)) {
973
1043
  const attempt = taskData(version.data).attempt;
974
1044
  if (attempt === undefined) continue;
@@ -1080,13 +1150,13 @@ export async function metrics(
1080
1150
  if (last.costQuality === "incomplete") quality = "incomplete";
1081
1151
  else if (last.costQuality === "estimated" && quality === "") quality = "estimated";
1082
1152
  }
1083
- const time = entry.timed ? `${wallTime(entry.ms)}${entry.running === undefined ? "" : " …"}` : "–";
1153
+ const time = entry.timed ? `${formatElapsed(entry.ms)}${entry.running === undefined ? "" : " …"}` : "–";
1084
1154
  lines.push(
1085
1155
  `| ${entry.number} | ${time} | ${costNote(last?.cost, last?.costQuality) ?? "–"} | ${attemptResult(entry, entry.number === newest, phase, entry.running)} |`,
1086
1156
  );
1087
1157
  }
1088
1158
  lines.push(
1089
- `| total | ${anyTimed ? wallTime(totalMs) : "–"} | ${costed ? costNote(totalCost, quality) : "–"} | |`,
1159
+ `| total | ${anyTimed ? formatElapsed(totalMs) : "–"} | ${costed ? costNote(totalCost, quality) : "–"} | |`,
1090
1160
  );
1091
1161
  const perAttempt = [...entries].reverse().map((entry) => {
1092
1162
  const mark = " (running)";
@@ -1095,12 +1165,12 @@ export async function metrics(
1095
1165
  // time (a retry wait, a rework) follows, and the one running always shows.
1096
1166
  for (const name of METRIC_STEPS) {
1097
1167
  const spent = entry.steps.get(name);
1098
- if (spent !== undefined) parts.push(`${name} ${seconds(spent)}${entry.running === name ? mark : ""}`);
1168
+ if (spent !== undefined) parts.push(`${name} ${formatElapsed(spent)}${entry.running === name ? mark : ""}`);
1099
1169
  }
1100
1170
  for (const [name, spent] of entry.steps) {
1101
1171
  if ((METRIC_STEPS as readonly string[]).includes(name)) continue;
1102
1172
  if (spent < 1000 && entry.running !== name) continue;
1103
- parts.push(`${name.replaceAll("_", " ")} ${seconds(spent)}${entry.running === name ? mark : ""}`);
1173
+ parts.push(`${name.replaceAll("_", " ")} ${formatElapsed(spent)}${entry.running === name ? mark : ""}`);
1104
1174
  }
1105
1175
  const tokens = entry.last?.tokens;
1106
1176
  if (tokens !== undefined && tokens !== null) {
@@ -1110,7 +1180,7 @@ export async function metrics(
1110
1180
  });
1111
1181
  const waitLine =
1112
1182
  waitedMs > 0 || waiting
1113
- ? [`**Waiting for a person** ${seconds(waitedMs)}${waiting ? " (waiting)" : ""}`]
1183
+ ? [`**Waiting for a person** ${formatElapsed(waitedMs)}${waiting ? " (waiting)" : ""}`]
1114
1184
  : [];
1115
1185
  const summary = [lines.join("\n"), perAttempt.join("\n\n"), ...waitLine].join("\n\n");
1116
1186
  const perWorker = workerTable(entries);
@@ -1156,12 +1226,8 @@ function workerTable(entries: readonly AttemptMetrics[]): string | undefined {
1156
1226
  const cost = row.costed ? `$${row.cost.toFixed(2)}` : "-";
1157
1227
  const first = row.reviewed === 0 ? "-" : `${row.first}/${row.reviewed}`;
1158
1228
  lines.push(
1159
- `| ${cell(worker)} | ${row.attempts} | ${cost} | ${seconds(row.ms)} | ${first} |`,
1229
+ `| ${cell(worker)} | ${row.attempts} | ${cost} | ${formatElapsed(row.ms)} | ${first} |`,
1160
1230
  );
1161
1231
  }
1162
1232
  return lines.join("\n");
1163
1233
  }
1164
-
1165
- function isObject(value: unknown): value is Record<string, unknown> {
1166
- return typeof value === "object" && value !== null && !Array.isArray(value);
1167
- }
package/src/waits.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * drift apart.
7
7
  */
8
8
 
9
+ import type { ChoiceInfo } from "@operad-io/engine";
9
10
  import { isIntegrating, type ReviewRecord, type TaskData } from "./model.ts";
10
11
 
11
12
  /** The actions a person wait answers. */
@@ -18,9 +19,21 @@ export const WAIT_STEPS = {
18
19
  "review-timeout": "wait_review_timeout",
19
20
  "review-unavailable": "wait_review_unavailable",
20
21
  "review-out-of-time": "wait_review_out_of_time",
22
+ // A worker's own question, such as a permission ask from its harness.
23
+ "work-question": "wait_work_question",
21
24
  } as const;
22
25
  export type WaitKind = keyof typeof WAIT_STEPS;
23
26
 
27
+ /** The answers a worker's harness may ask for when its question outlives its grace. */
28
+ export const WORK_QUESTION_CHOICES = ["allow_once", "reject_once"] as const;
29
+ export const WORK_QUESTION_LATE_CHOICES = ["allow_always"] as const;
30
+
31
+ /** True for the wait a worker's own question goes to (one per code stage). */
32
+ export function isWorkQuestionWait(id: string): boolean {
33
+ const base = WAIT_STEPS["work-question"];
34
+ return id === base || id.startsWith(`${base}_`);
35
+ }
36
+
24
37
  const WAIT_ACCEPTS: Readonly<Record<WaitKind, readonly WaitAction[]>> = {
25
38
  person: WAIT_ACTIONS,
26
39
  // A timed-out or out-of-time review is the reviewer's business: a person can
@@ -29,6 +42,8 @@ const WAIT_ACCEPTS: Readonly<Record<WaitKind, readonly WaitAction[]>> = {
29
42
  "review-out-of-time": ["merge", "reject", "rework"],
30
43
  // The reviewer may be back: the same commit can be checked again.
31
44
  "review-unavailable": ["merge", "reject", "rework", "reverify"],
45
+ // The worker's own question is not one of dev's task actions.
46
+ "work-question": [],
32
47
  };
33
48
 
34
49
  /** The choices of a wait; a flow with no check or review has nothing to reverify. */
@@ -40,6 +55,50 @@ export function waitChoices(
40
55
  return hasReverify ? accepts : accepts.filter((action) => action !== "reverify");
41
56
  }
42
57
 
58
+ /** What each task wait choice is, apart from whether merge is the recommended one. */
59
+ const WAIT_CHOICE_INFO: Readonly<Record<WaitAction, ChoiceInfo>> = {
60
+ merge: {
61
+ label: "Merge",
62
+ hint: "Merge the task's changes into main.",
63
+ },
64
+ rework: {
65
+ label: "Rework",
66
+ hint: "Send the task back to the agent with your note.",
67
+ // dev:rework refuses an empty note, so a client must ask for one.
68
+ note: "required",
69
+ },
70
+ reverify: {
71
+ label: "Check again",
72
+ hint: "Run the checks and the review again.",
73
+ },
74
+ reject: {
75
+ label: "Reject",
76
+ hint: "Discard the task's changes.",
77
+ role: "destructive",
78
+ },
79
+ };
80
+
81
+ /**
82
+ * What the offered choices say. `primary` marks merge as the recommended answer;
83
+ * a wait after a failed check, failed work or no change leaves it out.
84
+ */
85
+ export function waitChoiceInfo(
86
+ choices: readonly string[],
87
+ primary: boolean,
88
+ ): Readonly<Record<string, ChoiceInfo>> {
89
+ const info: Record<string, ChoiceInfo> = {};
90
+ for (const choice of choices) {
91
+ if (!(WAIT_ACTIONS as readonly string[]).includes(choice)) continue;
92
+ const action = choice as WaitAction;
93
+ const copy = WAIT_CHOICE_INFO[action];
94
+ info[choice] =
95
+ action === "merge" && primary
96
+ ? { ...copy, role: "primary" }
97
+ : copy;
98
+ }
99
+ return info;
100
+ }
101
+
43
102
  /**
44
103
  * True while a review waits for its model to come back. The flow is not asking
45
104
  * a person anything then, so no wait action is offered.