@operad-io/dev 0.2.0 → 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.
package/src/views.ts CHANGED
@@ -41,7 +41,7 @@ import {
41
41
  import { placeWaitNote } from "./place-wait.ts";
42
42
  import { checkHostWarning } from "./check-host.ts";
43
43
  import { planMark, repositoryMark, taskBadge, taskMark } from "./marks.ts";
44
- import { branchExists, commitOf, git } from "./git.ts";
44
+ import { baseName, branchExists, commitOf, git } from "./git.ts";
45
45
  import { workBranch } from "./steps.ts";
46
46
  import { repositoryMetrics } from "./throughput.ts";
47
47
  import { findRepository, listRepositories } from "./service.ts";
@@ -162,7 +162,7 @@ export const repoViews: ObjectViews = {
162
162
  : undefined;
163
163
  const file = join(repository.path, DEV_SETTINGS_FILE);
164
164
  lines.push(
165
- `- Default branch: \`${settings.mainBranch}\` on \`${settings.remote}\``,
165
+ `- Default branch: \`${settings.mainBranch}\`${settings.remote === undefined ? " (no remote)" : ` on \`${settings.remote}\``}`,
166
166
  `- ${DEV_SETTINGS_FILE}: ${
167
167
  problem !== undefined
168
168
  ? `invalid, the last valid settings stay in force (${problem})`
@@ -276,6 +276,7 @@ export const taskViews: ObjectViews = {
276
276
  sections.push({ id: "answer", title: "Answer" });
277
277
  }
278
278
  sections.push({ id: "log", title: "Log", live: true });
279
+ if (hasReview(task)) sections.push({ id: "review", title: "Review" });
279
280
  sections.push({ id: "diff", title: "Diff" });
280
281
  sections.push({ id: "metrics", title: "Metrics" });
281
282
  return sections;
@@ -297,6 +298,7 @@ export const taskViews: ObjectViews = {
297
298
  if (sectionId === "changes") return { markdown: renderChanges(parts.changes) };
298
299
  if (sectionId === "answer") return answerSection(ctx, object, options.cursor);
299
300
  if (sectionId === "log") return { markdown: await workerLog(ctx, task) };
301
+ if (sectionId === "review") return reviewSection(ctx, object, options.cursor);
300
302
  if (sectionId === "diff") return diffSection(ctx, object, options.cursor);
301
303
  if (sectionId === "metrics") return { markdown: await metrics(ctx, object) };
302
304
  return { markdown: "" };
@@ -432,9 +434,37 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
432
434
  const out: string[] = [];
433
435
  // Whether the agent has said something since the last turn ended.
434
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
+ };
435
449
  for (const line of lines) {
436
450
  const record = parseObject(line.trim());
437
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
+ }
438
468
  if (record !== undefined && kind === "tool_execution_start") {
439
469
  const id = stringField(record, ["toolCallId"]);
440
470
  const name = stringField(record, ["toolName"]) ?? "tool";
@@ -449,9 +479,15 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
449
479
  : finished
450
480
  ? ` no end logged${at === undefined ? "" : ` (started ${clockTime(at)})`}`
451
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
+ }
452
488
  const command = input === undefined ? "" : shownCommand(input, options.worktree);
453
489
  out.push(`tool ${name}${when}${command.length === 0 ? "" : ` ${inlineCode(command)}`}`);
454
- 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, " ")}`);
455
491
  continue;
456
492
  }
457
493
  if (record !== undefined && kind === "tool_execution_end") {
@@ -459,7 +495,7 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
459
495
  const error = stringField(record, ["error"]);
460
496
  const id = stringField(record, ["toolCallId"]);
461
497
  const hasStart = id !== undefined && starts.has(id);
462
- if (error !== undefined && !hasStart) {
498
+ if (error !== undefined && !hasStart && error !== PROFILE_REFUSAL) {
463
499
  out.push(oneLine(`tool ${stringField(record, ["toolName"]) ?? "tool"} failed: ${error}`, LOG_LINE_CHARS));
464
500
  }
465
501
  continue;
@@ -480,6 +516,8 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
480
516
  }
481
517
  if (record !== undefined && kind === "blocked") {
482
518
  const reason = stringField(record, ["reason"]);
519
+ // The start line already says the profile blocked the call.
520
+ if (reason === PROFILE_REFUSAL) continue;
483
521
  out.push(
484
522
  oneLine(`blocked ${stringField(record, ["toolName"]) ?? "tool"}${reason === undefined ? "" : `: ${reason}`}`, LOG_LINE_CHARS),
485
523
  );
@@ -546,9 +584,21 @@ export function readableLog(lines: readonly string[], options: { readonly worktr
546
584
  const readable = readableLogLine(line);
547
585
  if (readable !== undefined) out.push(readable);
548
586
  }
587
+ flushDeltas();
549
588
  return out;
550
589
  }
551
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
+
552
602
  /** One worker log line as a sentence, or undefined for bookkeeping. */
553
603
  export function readableLogLine(line: string): string | undefined {
554
604
  const text = line.trim();
@@ -609,7 +659,13 @@ async function workerLogPath(
609
659
  if (found === undefined) return undefined;
610
660
  const settings = await readDevSettings(repositoryData(found.data).path);
611
661
  const ran = settings.workers.workers.find((worker) => worker.name === attempt.worker);
612
- 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("/");
613
669
  if (plugin === undefined || step === undefined) return undefined;
614
670
  return join(
615
671
  ctx.store.root,
@@ -747,6 +803,122 @@ async function answerSection(
747
803
  };
748
804
  }
749
805
 
806
+ /* ---------------------------------------------------------------------------
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
+
750
922
  /* ---------------------------------------------------------------------------
751
923
  * Diff: the task branch against main, one page per file when it is long. A
752
924
  * merged task shows what its merge commit brought; its branch is gone by then.
@@ -777,7 +949,8 @@ function mergedCommitOf(task: TaskData): string | undefined {
777
949
  }
778
950
 
779
951
  /** 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 {
952
+ function commitWebUrl(repositoryPath: string, remote: string | undefined, sha: string): string | undefined {
953
+ if (remote === undefined) return undefined;
781
954
  const configured = git(repositoryPath, ["remote", "get-url", remote]);
782
955
  if (!configured.ok || configured.out.length === 0) return undefined;
783
956
  const text = configured.out.trim();
@@ -822,7 +995,7 @@ function commitWebUrl(repositoryPath: string, remote: string, sha: string): stri
822
995
  }
823
996
 
824
997
  /** What a merged task says when its own change cannot be shown. */
825
- function mergedMarkdown(repositoryPath: string, remote: string, sha: string | undefined): string {
998
+ function mergedMarkdown(repositoryPath: string, remote: string | undefined, sha: string | undefined): string {
826
999
  if (sha === undefined) return "_Merged._";
827
1000
  const short = sha.slice(0, 7);
828
1001
  const url = commitWebUrl(repositoryPath, remote, sha);
@@ -830,10 +1003,10 @@ function mergedMarkdown(repositoryPath: string, remote: string, sha: string | un
830
1003
  }
831
1004
 
832
1005
  /** 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 {
1006
+ function branchIsThere(repositoryPath: string, remote: string | undefined, branch: string): boolean {
834
1007
  return (
835
1008
  branchExists(repositoryPath, branch) ||
836
- branchExists(repositoryPath, branch, remote)
1009
+ (remote !== undefined && branchExists(repositoryPath, branch, remote))
837
1010
  );
838
1011
  }
839
1012
 
@@ -852,7 +1025,7 @@ async function diffSection(
852
1025
  const repository = repositoryData(found.data);
853
1026
  const settings = await readDevSettings(repository.path);
854
1027
  const branch = task.attempt?.branch ?? workBranch(task.worktree ?? idOfKey(object.id));
855
- const main = `${settings.remote}/${settings.mainBranch}`;
1028
+ const main = baseName(settings);
856
1029
  const merged = task.phase === "merged";
857
1030
  const recorded = merged ? mergedCommitOf(task) : undefined;
858
1031
  let range: string;