@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/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 { baseName, 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,9 +156,13 @@ 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
- `- Default branch: \`${settings.mainBranch}\` on \`${settings.remote}\``,
165
+ `- Default branch: \`${settings.mainBranch}\`${settings.remote === undefined ? " (no remote)" : ` on \`${settings.remote}\``}`,
160
166
  `- ${DEV_SETTINGS_FILE}: ${
161
167
  problem !== undefined
162
168
  ? `invalid, the last valid settings stay in force (${problem})`
@@ -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,
@@ -269,6 +276,7 @@ export const taskViews: ObjectViews = {
269
276
  sections.push({ id: "answer", title: "Answer" });
270
277
  }
271
278
  sections.push({ id: "log", title: "Log", live: true });
279
+ if (hasReview(task)) sections.push({ id: "review", title: "Review" });
272
280
  sections.push({ id: "diff", title: "Diff" });
273
281
  sections.push({ id: "metrics", title: "Metrics" });
274
282
  return sections;
@@ -290,6 +298,7 @@ export const taskViews: ObjectViews = {
290
298
  if (sectionId === "changes") return { markdown: renderChanges(parts.changes) };
291
299
  if (sectionId === "answer") return answerSection(ctx, object, options.cursor);
292
300
  if (sectionId === "log") return { markdown: await workerLog(ctx, task) };
301
+ if (sectionId === "review") return reviewSection(ctx, object, options.cursor);
293
302
  if (sectionId === "diff") return diffSection(ctx, object, options.cursor);
294
303
  if (sectionId === "metrics") return { markdown: await metrics(ctx, object) };
295
304
  return { markdown: "" };
@@ -338,20 +347,18 @@ function clockTime(at: number): string {
338
347
  }
339
348
 
340
349
  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");
350
+ if (!isRecord(usage)) return undefined;
351
+ const input = numberField(usage, "input");
352
+ const output = numberField(usage, "output");
345
353
  if (input === undefined && output === undefined) return undefined;
346
354
  return `${input ?? 0} in / ${output ?? 0} out tokens`;
347
355
  }
348
356
 
349
357
  /** The cost a log line carries, as dollars: pi's `total`, or `micros`. */
350
358
  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");
359
+ if (!isRecord(cost)) return undefined;
360
+ const micros = numberField(cost, "micros");
361
+ const dollars = micros !== undefined ? micros / 1e6 : numberField(cost, "total");
355
362
  return dollars === undefined ? undefined : `$${dollars.toFixed(4)}`;
356
363
  }
357
364
 
@@ -393,9 +400,7 @@ function inlineCode(text: string): string {
393
400
  function parseObject(text: string): Record<string, unknown> | undefined {
394
401
  try {
395
402
  const value: unknown = JSON.parse(text);
396
- return typeof value === "object" && value !== null && !Array.isArray(value)
397
- ? (value as Record<string, unknown>)
398
- : undefined;
403
+ return isRecord(value) ? value : undefined;
399
404
  } catch {
400
405
  return undefined;
401
406
  }
@@ -429,9 +434,37 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
429
434
  const out: string[] = [];
430
435
  // Whether the agent has said something since the last turn ended.
431
436
  let said = false;
437
+ // Text deltas not yet shown. A harness that logs the whole text after them
438
+ // (`text_end`, or a `message_end` with its text) shows it there; one that
439
+ // logs only deltas (codex) has them joined into text where the agent turns
440
+ // to a tool, a result or the end of the log.
441
+ let deltas = "";
442
+ const flushDeltas = (): void => {
443
+ if (deltas.trim().length > 0) {
444
+ out.push(`**agent:** ${agentText(deltas)}`);
445
+ said = true;
446
+ }
447
+ deltas = "";
448
+ };
432
449
  for (const line of lines) {
433
450
  const record = parseObject(line.trim());
434
451
  const kind = record === undefined ? undefined : stringField(record, ["type"]);
452
+ if (record !== undefined && kind === "text_delta") {
453
+ deltas += stringField(record, ["text"]) ?? "";
454
+ continue;
455
+ }
456
+ if (kind === "text_end" || (kind === "message_end" && record !== undefined && stringField(record, ["text"]) !== undefined)) {
457
+ deltas = "";
458
+ } else if (
459
+ kind === "tool_execution_start" ||
460
+ kind === "tool_execution_end" ||
461
+ kind === "message_end" ||
462
+ kind === "blocked" ||
463
+ kind === "result" ||
464
+ kind === "Result"
465
+ ) {
466
+ flushDeltas();
467
+ }
435
468
  if (record !== undefined && kind === "tool_execution_start") {
436
469
  const id = stringField(record, ["toolCallId"]);
437
470
  const name = stringField(record, ["toolName"]) ?? "tool";
@@ -442,13 +475,19 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
442
475
  end !== undefined
443
476
  ? end.durationMs === undefined
444
477
  ? ""
445
- : ` ${seconds(end.durationMs)}`
478
+ : ` ${formatElapsed(end.durationMs)}`
446
479
  : finished
447
480
  ? ` no end logged${at === undefined ? "" : ` (started ${clockTime(at)})`}`
448
481
  : ` running${at === undefined ? "" : ` since ${clockTime(at)}`}`;
482
+ const guard = input === undefined ? undefined : guardedCall(input);
483
+ if (guard !== undefined) {
484
+ // A call the access profile stopped is a normal guard, not a failure.
485
+ out.push(`tool ${guard.tool}${when} blocked by the access profile${guard.rule === undefined ? "" : `: ${inlineCode(guard.rule)}`}`);
486
+ continue;
487
+ }
449
488
  const command = input === undefined ? "" : shownCommand(input, options.worktree);
450
489
  out.push(`tool ${name}${when}${command.length === 0 ? "" : ` ${inlineCode(command)}`}`);
451
- if (end?.error !== undefined) out.push(`tool ${name} failed: ${end.error.replace(/\s+/g, " ")}`);
490
+ if (end?.error !== undefined && end.error !== PROFILE_REFUSAL) out.push(`tool ${name} failed: ${end.error.replace(/\s+/g, " ")}`);
452
491
  continue;
453
492
  }
454
493
  if (record !== undefined && kind === "tool_execution_end") {
@@ -456,7 +495,7 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
456
495
  const error = stringField(record, ["error"]);
457
496
  const id = stringField(record, ["toolCallId"]);
458
497
  const hasStart = id !== undefined && starts.has(id);
459
- if (error !== undefined && !hasStart) {
498
+ if (error !== undefined && !hasStart && error !== PROFILE_REFUSAL) {
460
499
  out.push(oneLine(`tool ${stringField(record, ["toolName"]) ?? "tool"} failed: ${error}`, LOG_LINE_CHARS));
461
500
  }
462
501
  continue;
@@ -477,6 +516,8 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
477
516
  }
478
517
  if (record !== undefined && kind === "blocked") {
479
518
  const reason = stringField(record, ["reason"]);
519
+ // The start line already says the profile blocked the call.
520
+ if (reason === PROFILE_REFUSAL) continue;
480
521
  out.push(
481
522
  oneLine(`blocked ${stringField(record, ["toolName"]) ?? "tool"}${reason === undefined ? "" : `: ${reason}`}`, LOG_LINE_CHARS),
482
523
  );
@@ -496,13 +537,13 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
496
537
  continue;
497
538
  }
498
539
  if (record !== undefined && (kind === "journal" || kind === undefined) && typeof record.event === "string") {
499
- const data = isObject(record.data) ? record.data : {};
540
+ const data = isRecord(record.data) ? record.data : {};
500
541
  if (record.event === "MessageAppended") {
501
- const message = isObject(data.message) ? data.message : {};
502
- const assistant = isObject(message.assistant) ? message.assistant : undefined;
542
+ const message = isRecord(data.message) ? data.message : {};
543
+ const assistant = isRecord(message.assistant) ? message.assistant : undefined;
503
544
  const blocks: unknown[] = Array.isArray(assistant?.content) ? assistant.content : [];
504
545
  const text = blocks
505
- .map((block) => (isObject(block) && isObject(block.text) ? stringField(block.text, ["text"]) : undefined))
546
+ .map((block) => (isRecord(block) && isRecord(block.text) ? stringField(block.text, ["text"]) : undefined))
506
547
  .filter((part): part is string => part !== undefined)
507
548
  .join(" ");
508
549
  if (text.trim().length > 0) {
@@ -543,9 +584,21 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
543
584
  const readable = readableLogLine(line);
544
585
  if (readable !== undefined) out.push(readable);
545
586
  }
587
+ flushDeltas();
546
588
  return out;
547
589
  }
548
590
 
591
+ /** What a harness logs for a call the access profile refused. */
592
+ const PROFILE_REFUSAL = "refused by the access profile";
593
+ const PROFILE_DENIED = /^(.*?) denied by the access profile(?: \(rule: (.*)\))?$/s;
594
+
595
+ /** The tool and rule of a call the access profile denied, from its logged input. */
596
+ function guardedCall(input: string): { readonly tool: string; readonly rule: string | undefined } | undefined {
597
+ const found = PROFILE_DENIED.exec(input.trim());
598
+ if (found === null) return undefined;
599
+ return { tool: found[1] ?? "tool", rule: found[2] === undefined ? undefined : oneLine(found[2], LOG_LINE_CHARS) };
600
+ }
601
+
549
602
  /** One worker log line as a sentence, or undefined for bookkeeping. */
550
603
  export function readableLogLine(line: string): string | undefined {
551
604
  const text = line.trim();
@@ -556,10 +609,10 @@ export function readableLogLine(line: string): string | undefined {
556
609
  } catch {
557
610
  return oneLine(text, LOG_LINE_CHARS);
558
611
  }
559
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
612
+ if (!isRecord(value)) {
560
613
  return oneLine(text, LOG_LINE_CHARS);
561
614
  }
562
- const record = value as Record<string, unknown>;
615
+ const record = value;
563
616
  const kind = stringField(record, ["type"]) ?? "";
564
617
  const tool = stringField(record, ["tool", "tool_name", "toolName", "name"]);
565
618
  const event = stringField(record, ["event"]) ?? "";
@@ -606,7 +659,13 @@ async function workerLogPath(
606
659
  if (found === undefined) return undefined;
607
660
  const settings = await readDevSettings(repositoryData(found.data).path);
608
661
  const ran = settings.workers.workers.find((worker) => worker.name === attempt.worker);
609
- const [plugin, step] = (ran?.use ?? settings.worker.use).split("/");
662
+ // While the work runs the attempt has no worker yet; the step recorded the
663
+ // one the pool placed, which may be in a pool other than the default.
664
+ const use =
665
+ typeof attempt.workerUse === "string" && attempt.workerUse.length > 0 && attempt.worker == null
666
+ ? attempt.workerUse
667
+ : (ran?.use ?? settings.worker.use);
668
+ const [plugin, step] = use.split("/");
610
669
  if (plugin === undefined || step === undefined) return undefined;
611
670
  return join(
612
671
  ctx.store.root,
@@ -712,17 +771,7 @@ async function answerSection(
712
771
  readonly pages?: readonly { readonly label: string; readonly cursor?: string }[];
713
772
  }> {
714
773
  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
- }
774
+ const facts = await allFactsOf(ctx.store, object);
726
775
  for (const version of foldObjectFacts(facts)) {
727
776
  const attempt = taskData(version.data).attempt;
728
777
  if (attempt === undefined) continue;
@@ -755,7 +804,124 @@ async function answerSection(
755
804
  }
756
805
 
757
806
  /* ---------------------------------------------------------------------------
758
- * Diff: the task branch against main, one page per file when it is long.
807
+ * Review: the reviewer's report of each round, newest first.
808
+ * ------------------------------------------------------------------------- */
809
+
810
+ /** Text from a reviewer or a model, safe inside Markdown: no markup, no raw HTML. */
811
+ export function markdownSafe(text: string): string {
812
+ return text
813
+ .replace(/\r/g, "")
814
+ .replace(/[\\`*_{}[\]<>#|~!]/g, (char) => `\\${char}`)
815
+ .replace(/^(\s*)([-+]|\d+[.)])(\s)/gm, "$1\\$2$3");
816
+ }
817
+
818
+ function hasReview(task: TaskData): boolean {
819
+ const attempt = task.attempt;
820
+ return (
821
+ (attempt?.review !== undefined && attempt.review !== null) ||
822
+ (attempt?.reviewRuns ?? []).length > 0 ||
823
+ (attempt?.reviewPending !== undefined && attempt.reviewPending !== null) ||
824
+ (Array.isArray(task.reviewHistory) && task.reviewHistory.length > 0)
825
+ );
826
+ }
827
+
828
+ const SEVERITY_ORDER = ["critical", "major", "minor"];
829
+
830
+ function severityCounts(findings: readonly { readonly severity: string }[]): string {
831
+ if (findings.length === 0) return "none";
832
+ const known = SEVERITY_ORDER.flatMap((severity) => {
833
+ const count = findings.filter((finding) => finding.severity === severity).length;
834
+ return count === 0 ? [] : [`${count} ${severity}`];
835
+ });
836
+ return known.length === 0 ? String(findings.length) : known.join(", ");
837
+ }
838
+
839
+ /** One recorded review round as Markdown. */
840
+ export function reviewRound(record: ReviewRecord, attempt: number, fixLevel: string | undefined): string {
841
+ const runs = record.runs ?? [];
842
+ const last = runs[runs.length - 1];
843
+ const findings = record.findings ?? [];
844
+ const decision = record.decision ?? record.result;
845
+ const lines: string[] = [];
846
+ const round = typeof record.round === "number" ? record.round : 1;
847
+ lines.push(`### Attempt ${attempt}, round ${round}`);
848
+ const outcome =
849
+ decision === "passed" || decision === "pass"
850
+ ? "pass"
851
+ : decision === "findings" || decision === "fail"
852
+ ? `findings (${severityCounts(findings)})`
853
+ : markdownSafe(String(decision).replace(/_/g, " "));
854
+ lines.push("", `- Result: ${outcome}`);
855
+ if (fixLevel !== undefined) lines.push(`- Fix level: ${markdownSafe(fixLevel)} (findings at or above it need a fix)`);
856
+ const agent = last?.use ?? record.reviewSettings?.use;
857
+ if (agent !== undefined) lines.push(`- Reviewer agent: ${inlineCode(agent)}`);
858
+ const model = record.model ?? last?.model;
859
+ if (typeof model === "string" && model.length > 0) lines.push(`- Model: ${inlineCode(model)}`);
860
+ if (typeof record.sha === "string" && record.sha.length > 0) lines.push(`- Commit reviewed: ${inlineCode(record.sha.slice(0, 12))}`);
861
+ if (typeof record.message === "string" && record.message.length > 0) {
862
+ lines.push("", markdownSafe(record.message.trim()));
863
+ }
864
+ if (findings.length > 0) {
865
+ lines.push("", "**Findings**", "");
866
+ for (const finding of findings) {
867
+ const place = inlineCode(`${finding.file}:${finding.line}`);
868
+ const note = finding.preExisting === true || finding.pre_existing === true ? " (already there before this change)" : "";
869
+ const trigger = typeof finding.trigger === "string" && finding.trigger.length > 0 ? ` — ${markdownSafe(finding.trigger.trim())}` : "";
870
+ lines.push(`- ${place} ${markdownSafe(finding.severity)}: ${markdownSafe(finding.summary.trim())}${trigger}${note}`);
871
+ }
872
+ }
873
+ const verified = record.verified ?? [];
874
+ if (verified.length > 0) {
875
+ lines.push("", "**Checked**", "", ...verified.map((item) => `- ${markdownSafe(item.trim())}`));
876
+ }
877
+ return lines.join("\n");
878
+ }
879
+
880
+ async function reviewSection(
881
+ ctx: ViewContext,
882
+ object: StoredObject,
883
+ cursor: string | undefined,
884
+ ): Promise<{
885
+ readonly markdown: string;
886
+ readonly next?: string;
887
+ readonly pages?: readonly { readonly label: string; readonly cursor?: string }[];
888
+ }> {
889
+ // The latest record of each round, found in the object's history: the task
890
+ // keeps only the newest round in its own data.
891
+ const rounds = new Map<string, { readonly attempt: number; readonly round: number; readonly record: ReviewRecord }>();
892
+ const keep = (data: TaskData): void => {
893
+ const attempt = data.attempt;
894
+ const record = attempt?.review;
895
+ if (attempt === undefined || record === undefined || record === null) return;
896
+ const round = typeof record.round === "number" ? record.round : 1;
897
+ rounds.set(`${attempt.number}.${round}`, { attempt: attempt.number, round, record });
898
+ };
899
+ for (const version of foldObjectFacts(await allFactsOf(ctx.store, object))) keep(taskData(version.data));
900
+ keep(taskData(object.data));
901
+ const ordered = [...rounds.values()].sort((a, b) => b.attempt - a.attempt || b.round - a.round);
902
+ if (ordered.length === 0) return { markdown: "_No review yet._" };
903
+ const index = cursor === undefined ? 0 : Number(cursor);
904
+ const shown = Number.isInteger(index) ? ordered[index] : undefined;
905
+ if (shown === undefined) return { markdown: "_That page of the reviews does not exist._" };
906
+ // The level recorded with the round; an older round has none, so the line is left out.
907
+ const fixLevel = typeof shown.record.fixLevel === "string" ? shown.record.fixLevel : undefined;
908
+ return {
909
+ markdown: reviewRound(shown.record, shown.attempt, fixLevel),
910
+ ...(ordered.length > 1
911
+ ? {
912
+ pages: ordered.map((entry, at) => ({
913
+ label: `attempt ${entry.attempt}, round ${entry.round}`,
914
+ ...(at === 0 ? {} : { cursor: String(at) }),
915
+ })),
916
+ }
917
+ : {}),
918
+ ...(index + 1 < ordered.length ? { next: String(index + 1) } : {}),
919
+ };
920
+ }
921
+
922
+ /* ---------------------------------------------------------------------------
923
+ * Diff: the task branch against main, one page per file when it is long. A
924
+ * merged task shows what its merge commit brought; its branch is gone by then.
759
925
  * ------------------------------------------------------------------------- */
760
926
 
761
927
  /** A diff longer than this many characters is paged by file. */
@@ -765,6 +931,85 @@ function fence(diff: string): string {
765
931
  return `\`\`\`\`diff\n${diff.trimEnd()}\n\`\`\`\``;
766
932
  }
767
933
 
934
+ /** The commit whose change a merged task brought, when dev recorded one. */
935
+ function mergedCommitOf(task: TaskData): string | undefined {
936
+ const integration = task.attempt?.integration;
937
+ if (
938
+ integration === undefined ||
939
+ integration === null ||
940
+ (integration.result !== undefined && integration.result !== "merged")
941
+ ) {
942
+ return undefined;
943
+ }
944
+ const candidate = integration.candidate;
945
+ if (typeof candidate !== "string" || !/^[0-9a-f]{7,64}$/i.test(candidate)) return undefined;
946
+ // `already on main` records main itself when no commit carries the change.
947
+ if (integration.base === candidate) return undefined;
948
+ return candidate;
949
+ }
950
+
951
+ /** A GitHub-style remote's web page for a commit, when the remote names one. */
952
+ function commitWebUrl(repositoryPath: string, remote: string | undefined, sha: string): string | undefined {
953
+ if (remote === undefined) return undefined;
954
+ const configured = git(repositoryPath, ["remote", "get-url", remote]);
955
+ if (!configured.ok || configured.out.length === 0) return undefined;
956
+ const text = configured.out.trim();
957
+ let host: string;
958
+ let path: string;
959
+ if (text.includes("://")) {
960
+ let url: URL;
961
+ try {
962
+ url = new URL(text);
963
+ } catch {
964
+ return undefined;
965
+ }
966
+ if (
967
+ url.protocol !== "https:" &&
968
+ url.protocol !== "http:" &&
969
+ url.protocol !== "ssh:" &&
970
+ url.protocol !== "git:"
971
+ ) {
972
+ return undefined;
973
+ }
974
+ host = url.hostname;
975
+ path = url.pathname;
976
+ } else {
977
+ const match = /^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(text);
978
+ if (match === null) return undefined;
979
+ host = match[1] ?? "";
980
+ path = match[2] ?? "";
981
+ }
982
+ if (host !== "github.com" && !host.startsWith("github.") && !host.endsWith(".github.com")) {
983
+ return undefined;
984
+ }
985
+ const parts = path
986
+ .replace(/^\/+/, "")
987
+ .replace(/\/+$/, "")
988
+ .replace(/\.git$/, "")
989
+ .split("/")
990
+ .filter((part) => part.length > 0);
991
+ const owner = parts[0];
992
+ const name = parts[1];
993
+ if (owner === undefined || name === undefined) return undefined;
994
+ return `https://${host}/${owner}/${name}/commit/${sha}`;
995
+ }
996
+
997
+ /** What a merged task says when its own change cannot be shown. */
998
+ function mergedMarkdown(repositoryPath: string, remote: string | undefined, sha: string | undefined): string {
999
+ if (sha === undefined) return "_Merged._";
1000
+ const short = sha.slice(0, 7);
1001
+ const url = commitWebUrl(repositoryPath, remote, sha);
1002
+ return url === undefined ? `_Merged as ${short}._` : `_Merged as [${short}](${url})._`;
1003
+ }
1004
+
1005
+ /** True when the task's branch is still in the repository, here or on its remote. */
1006
+ function branchIsThere(repositoryPath: string, remote: string | undefined, branch: string): boolean {
1007
+ return (
1008
+ branchExists(repositoryPath, branch) ||
1009
+ (remote !== undefined && branchExists(repositoryPath, branch, remote))
1010
+ );
1011
+ }
1012
+
768
1013
  async function diffSection(
769
1014
  ctx: ViewContext,
770
1015
  object: StoredObject,
@@ -779,15 +1024,39 @@ async function diffSection(
779
1024
  if (found === undefined) return { markdown: "_The repository is not registered._" };
780
1025
  const repository = repositoryData(found.data);
781
1026
  const settings = await readDevSettings(repository.path);
782
- const branch = task.attempt?.branch ?? workBranch(task.worktree ?? bareId(object.id));
783
- 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}`}._` };
1027
+ const branch = task.attempt?.branch ?? workBranch(task.worktree ?? idOfKey(object.id));
1028
+ const main = baseName(settings);
1029
+ const merged = task.phase === "merged";
1030
+ const recorded = merged ? mergedCommitOf(task) : undefined;
1031
+ let range: string;
1032
+ let fallback: string;
1033
+ if (merged) {
1034
+ if (recorded === undefined) return { markdown: "_Merged._" };
1035
+ const found = commitOf(repository.path, recorded);
1036
+ const sha = found ?? recorded;
1037
+ const parent =
1038
+ found === undefined ? undefined : commitOf(repository.path, `${sha}^1`);
1039
+ if (parent === undefined) {
1040
+ return { markdown: mergedMarkdown(repository.path, settings.remote, sha) };
1041
+ }
1042
+ range = `${sha}^1..${sha}`;
1043
+ fallback = mergedMarkdown(repository.path, settings.remote, sha);
1044
+ } else {
1045
+ if (!branchIsThere(repository.path, settings.remote, branch)) {
1046
+ return {
1047
+ markdown:
1048
+ task.phase === "cancelled"
1049
+ ? "_The branch of this task is gone, so there is no diff to show._"
1050
+ : "_The branch of this task is not here, so there is no diff to show._",
1051
+ };
1052
+ }
1053
+ range = `${main}...${branch}`;
1054
+ fallback = `_No diff: cannot compare ${branch} with ${main}._`;
788
1055
  }
1056
+ const stat = git(repository.path, ["diff", "--stat", range], true);
1057
+ if (!stat.ok) return { markdown: fallback };
789
1058
  if (stat.out.length === 0) {
790
- return { markdown: `_${branch} has no changes against ${main}._` };
1059
+ return { markdown: merged ? fallback : `_${branch} has no changes against ${main}._` };
791
1060
  }
792
1061
  const whole = git(repository.path, ["diff", range]);
793
1062
  if (whole.out.length <= DIFF_PAGE_CHARS && cursor === undefined) {
@@ -829,13 +1098,6 @@ async function diffSection(
829
1098
 
830
1099
  const METRIC_STEPS = ["worktree", "work", "reverify", "verify", "review", "integrate"] as const;
831
1100
 
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
1101
  interface AttemptMetrics {
840
1102
  readonly number: number;
841
1103
  /** The runs that ran it, in the order the task first named them. */
@@ -879,15 +1141,6 @@ export function tokenCount(count: number): string {
879
1141
  return count < 10_000 ? String(count) : `${(count / 1000).toFixed(1)}k`;
880
1142
  }
881
1143
 
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
1144
  function findingsText(review: ReviewRecord): string {
892
1145
  const count = review.findings?.length;
893
1146
  if (count === undefined) return "review: findings";
@@ -958,17 +1211,7 @@ export async function metrics(
958
1211
  now: number = Date.now(),
959
1212
  ): Promise<string> {
960
1213
  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
- }
1214
+ const facts = await allFactsOf(ctx.store, object);
972
1215
  for (const version of foldObjectFacts(facts)) {
973
1216
  const attempt = taskData(version.data).attempt;
974
1217
  if (attempt === undefined) continue;
@@ -1080,13 +1323,13 @@ export async function metrics(
1080
1323
  if (last.costQuality === "incomplete") quality = "incomplete";
1081
1324
  else if (last.costQuality === "estimated" && quality === "") quality = "estimated";
1082
1325
  }
1083
- const time = entry.timed ? `${wallTime(entry.ms)}${entry.running === undefined ? "" : " …"}` : "–";
1326
+ const time = entry.timed ? `${formatElapsed(entry.ms)}${entry.running === undefined ? "" : " …"}` : "–";
1084
1327
  lines.push(
1085
1328
  `| ${entry.number} | ${time} | ${costNote(last?.cost, last?.costQuality) ?? "–"} | ${attemptResult(entry, entry.number === newest, phase, entry.running)} |`,
1086
1329
  );
1087
1330
  }
1088
1331
  lines.push(
1089
- `| total | ${anyTimed ? wallTime(totalMs) : "–"} | ${costed ? costNote(totalCost, quality) : "–"} | |`,
1332
+ `| total | ${anyTimed ? formatElapsed(totalMs) : "–"} | ${costed ? costNote(totalCost, quality) : "–"} | |`,
1090
1333
  );
1091
1334
  const perAttempt = [...entries].reverse().map((entry) => {
1092
1335
  const mark = " (running)";
@@ -1095,12 +1338,12 @@ export async function metrics(
1095
1338
  // time (a retry wait, a rework) follows, and the one running always shows.
1096
1339
  for (const name of METRIC_STEPS) {
1097
1340
  const spent = entry.steps.get(name);
1098
- if (spent !== undefined) parts.push(`${name} ${seconds(spent)}${entry.running === name ? mark : ""}`);
1341
+ if (spent !== undefined) parts.push(`${name} ${formatElapsed(spent)}${entry.running === name ? mark : ""}`);
1099
1342
  }
1100
1343
  for (const [name, spent] of entry.steps) {
1101
1344
  if ((METRIC_STEPS as readonly string[]).includes(name)) continue;
1102
1345
  if (spent < 1000 && entry.running !== name) continue;
1103
- parts.push(`${name.replaceAll("_", " ")} ${seconds(spent)}${entry.running === name ? mark : ""}`);
1346
+ parts.push(`${name.replaceAll("_", " ")} ${formatElapsed(spent)}${entry.running === name ? mark : ""}`);
1104
1347
  }
1105
1348
  const tokens = entry.last?.tokens;
1106
1349
  if (tokens !== undefined && tokens !== null) {
@@ -1110,7 +1353,7 @@ export async function metrics(
1110
1353
  });
1111
1354
  const waitLine =
1112
1355
  waitedMs > 0 || waiting
1113
- ? [`**Waiting for a person** ${seconds(waitedMs)}${waiting ? " (waiting)" : ""}`]
1356
+ ? [`**Waiting for a person** ${formatElapsed(waitedMs)}${waiting ? " (waiting)" : ""}`]
1114
1357
  : [];
1115
1358
  const summary = [lines.join("\n"), perAttempt.join("\n\n"), ...waitLine].join("\n\n");
1116
1359
  const perWorker = workerTable(entries);
@@ -1156,12 +1399,8 @@ function workerTable(entries: readonly AttemptMetrics[]): string | undefined {
1156
1399
  const cost = row.costed ? `$${row.cost.toFixed(2)}` : "-";
1157
1400
  const first = row.reviewed === 0 ? "-" : `${row.first}/${row.reviewed}`;
1158
1401
  lines.push(
1159
- `| ${cell(worker)} | ${row.attempts} | ${cost} | ${seconds(row.ms)} | ${first} |`,
1402
+ `| ${cell(worker)} | ${row.attempts} | ${cost} | ${formatElapsed(row.ms)} | ${first} |`,
1160
1403
  );
1161
1404
  }
1162
1405
  return lines.join("\n");
1163
1406
  }
1164
-
1165
- function isObject(value: unknown): value is Record<string, unknown> {
1166
- return typeof value === "object" && value !== null && !Array.isArray(value);
1167
- }