Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | 32x 32x 12x 12x 12x 25x 25x 12x 2x 2x 2x 11x 11x 30x 59x 9x 331x 300x 296x 29x 29x 4x 9x 7x 9x 18x 18x 18x 130x 130x 130x 98x 32x 10x 5x 5x 5x 4x 9x 218x 218x 255x 255x 215x 255x 178x 125x 125x 107x 23x 102x 718x 59x 102x 125x 98x 125x 90x 6x 8x 92x 116x 85x 31x 232x 31x 116x 107x 107x 31x 9x 40x 40x 31x 31x 31x 92x 92x 92x 92x 92x 92x 92x 21x 21x 103x 103x 103x 103x 103x 103x 103x 112x 112x 112x 105x 103x 103x 103x 26x 26x 26x 215x 215x 104x 103x 103x 215x 215x 215x 215x 26x 26x 103x 112x 26x 77x 103x | import type {
SwarmMember,
SwarmRun,
SwarmRunSummary,
SwarmTask,
SwarmTaskKind,
SwarmThreadStep,
SwarmWrapUpReason,
Topology,
TopologyParam,
} from "@/objects/Swarm";
import { parseServerDate } from "@/util/time";
/**
* How a swarm and its runs read on a page: durations, figures, the words for
* each kind of task and each early stop, and the team's work as a tree.
*/
/** "45 min", "2 h", "1 h 30 min". */
export function formatDuration(seconds: number): string {
const minutes = Math.max(0, Math.round(seconds / 60));
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
return rest ? `${hours} h ${rest} min` : `${hours} h`;
}
/** Seconds until the run's deadline, never below zero. A run waiting on a
* person has its clock stopped: what it had left when the wait began. */
export function secondsLeft(
run: Pick<SwarmRunSummary, "deadline_at" | "paused_at">,
now: number,
): number {
const at = run.paused_at ? parseServerDate(run.paused_at).getTime() : now;
return Math.max(0, (parseServerDate(run.deadline_at).getTime() - at) / 1000);
}
/** How long a task's last start took — "45 s", "12 min" — or null when it
* has not finished one. */
export function taskTook(task: Pick<SwarmTask, "started_at" | "finished_at">): string | null {
if (!task.started_at || !task.finished_at) return null;
const seconds =
(parseServerDate(task.finished_at).getTime() - parseServerDate(task.started_at).getTime()) /
1000;
Iif (seconds < 0) return null;
return seconds < 60 ? `${Math.round(seconds)} s` : formatDuration(seconds);
}
/** How much of its time a run has used, 0–1. */
export function timeShare(
run: Pick<SwarmRunSummary, "deadline_at" | "paused_at" | "time_cap_s">,
now: number,
): number {
Iif (!run.time_cap_s) return 0;
return Math.min(1, 1 - secondsLeft(run, now) / run.time_cap_s);
}
/** How much of its budget a run has spent (as a budget counts it), 0–1. */
export function spendShare(run: Pick<SwarmRunSummary, "spent_usd" | "budget_usd">): number {
return run.budget_usd > 0 ? run.spent_usd / run.budget_usd : 0;
}
/** Where the answer's reserve begins on the budget bar, 0–1. */
export function reserveMark(run: Pick<SwarmRunSummary, "reserve_usd" | "budget_usd">): number | null {
return run.budget_usd > 0 ? 1 - run.reserve_usd / run.budget_usd : null;
}
/** What each kind of task is, as a person reads it. */
export const TASK_KIND_LABEL: Record<SwarmTaskKind, string> = {
plan: "Plan",
work: "Work",
review: "Review",
synthesise: "Answer",
route: "Routing",
vote: "Vote",
};
/** What a task is, as a person reads it: below the lead, a plan is a
* team's plan for its part and an answer is its report up. */
export function taskKindLabel(task: Pick<SwarmTask, "kind" | "depth">): string {
if ((task.depth ?? 0) > 0 && task.kind === "plan") return "Team plan";
if ((task.depth ?? 0) > 0 && task.kind === "synthesise") return "Report";
return TASK_KIND_LABEL[task.kind];
}
/** Whether a setting applies, given the others (`shown_when`). */
export function paramShown(param: TopologyParam, params: Record<string, unknown>): boolean {
const when = param.shown_when;
if (!when) return true;
return when.values.some((value) => value === params[when.param]);
}
/** Why a run wrapped up early. */
export const WRAP_UP_LABEL: Record<SwarmWrapUpReason, string> = {
budget: "its budget ran low",
time: "its time ran low",
stopped: "it was stopped",
unanswered: "nobody answered its question within a day",
};
/** The shape a swarm takes, by its catalogue label — or its key while the
* catalogue is loading or no longer offers it. */
export function shapeLabel(topologies: Topology[], key: string): string {
return topologies.find((t) => t.key === key)?.label ?? key;
}
/** The member who plays a task's part, from the run's roster. */
export function memberOf(run: SwarmRun, task: SwarmTask): SwarmMember | undefined {
return (run.config.roster ?? []).find(
(m) => m.agent_id === task.agent_id && m.role === task.role,
);
}
/** A run's first line of task, for lists. */
export function taskExcerpt(text: string, max = 120): string {
const line = text.trim().split("\n")[0] ?? "";
return line.length > max ? `${line.slice(0, max - 1)}…` : line;
}
// ─── A thread of requests ────────────────────────────────────────────────────
/** Where a run stands in its thread: its place, how many there are, and the
* requests either side of it. A run of no thread is request 1 of 1. */
export interface ThreadPlace {
seq: number;
count: number;
previous: SwarmThreadStep | null;
next: SwarmThreadStep | null;
/** The thread's latest request — the one a follow-up goes to. */
latest: SwarmThreadStep | null;
steps: SwarmThreadStep[];
}
export function threadPlace(run: Pick<SwarmRun, "id" | "thread" | "thread_seq">): ThreadPlace {
const steps = [...(run.thread ?? [])].sort((a, b) => a.seq - b.seq);
const index = steps.findIndex((s) => s.id === run.id);
if (index < 0) {
return { seq: run.thread_seq ?? 1, count: 1, previous: null, next: null, latest: null, steps };
}
return {
seq: steps[index].seq,
count: steps.length,
previous: index > 0 ? steps[index - 1] : null,
next: index < steps.length - 1 ? steps[index + 1] : null,
latest: steps[steps.length - 1],
steps,
};
}
/** The earlier pieces a piece builds on, each with the request it is of —
* `2.T1` is request 2's piece T1 — and that request's run, when the thread
* holds it. */
export function buildsOn(
task: Pick<SwarmTask, "brief">,
steps: SwarmThreadStep[],
): { ref: string; seq: number; handle: string; runId: string | null }[] {
return (task.brief?.builds_on ?? []).flatMap((ref) => {
const at = ref.indexOf(".");
const seq = Number(ref.slice(0, at));
if (at < 1 || !Number.isInteger(seq)) return [];
const handle = ref.slice(at + 1);
return [{ ref, seq, handle, runId: steps.find((s) => s.seq === seq)?.id ?? null }];
});
}
// ─── Rounds, redos and who asked for them ────────────────────────────────────
/** Which round of work a task is of: its own, else its team's (a team's
* pieces, review and report are of the round its plan was asked in), else
* the first. A piece done again stays in its original's round. */
export function roundOf(task: SwarmTask, byId: Map<string, SwarmTask>): number {
let at: SwarmTask | undefined = task;
for (let hops = 0; at && hops < 8; hops += 1) {
const round = Number(at.brief?.round);
if (Number.isInteger(round) && round > 0) return round;
const parent: SwarmTask | undefined = at.parent_id ? byId.get(at.parent_id) : undefined;
// Only a team's plan passes its round down; the lead's plan has none.
at = parent && (parent.depth ?? 0) > 0 ? parent : undefined;
}
return 1;
}
/** The review that asked for a task: a piece of a further round, or one done
* again. svc-core names it (`brief.asked_by`); for a run from before it did,
* it is found — a redo's is the first review that read the piece it redoes,
* a further round's piece's the review of the round before under the same
* plan. A council's rounds have no review, so none. */
export function askedBy(task: SwarmTask, tasks: SwarmTask[]): SwarmTask | null {
const named = task.brief?.asked_by;
if (named) {
const found = tasks.find((t) => t.id === named);
Eif (found) return found;
}
const reviews = tasks
.filter((t) => t.kind === "review" && t.id !== task.id)
.sort((a, b) => a.seq - b.seq);
const redoes = task.brief?.redoes;
if (redoes) return reviews.find((r) => (r.depends_on ?? []).includes(redoes)) ?? null;
const round = Number(task.brief?.round);
if (Number.isInteger(round) && round > 1 && task.parent_id && task.kind !== "review") {
const byId = new Map(tasks.map((t) => [t.id, t]));
return (
reviews.find((r) => r.parent_id === task.parent_id && roundOf(r, byId) === round - 1) ??
null
);
}
return null;
}
/** A group of the task list: a round of work, or the answer. */
export interface RoundGroup {
key: string;
label: string;
tasks: SwarmTask[];
}
/** The run's tasks by round of work, each in the order it was made, with
* the answer (and a council's votes) last — so work a review asked for
* reads after the review, not beside the first round. */
export function roundGroups(tasks: SwarmTask[]): RoundGroup[] {
const byId = new Map(tasks.map((t) => [t.id, t]));
const ordered = [...tasks].sort((a, b) => a.seq - b.seq);
const isAnswer = (t: SwarmTask) =>
(t.kind === "synthesise" && (t.depth ?? 0) === 0) || t.kind === "vote";
const rounds = new Map<number, SwarmTask[]>();
for (const task of ordered.filter((t) => !isAnswer(t))) {
const round = roundOf(task, byId);
rounds.set(round, [...(rounds.get(round) ?? []), task]);
}
const groups: RoundGroup[] = [...rounds.entries()]
.sort(([a], [b]) => a - b)
.map(([round, members]) => {
// The review that asked for the round's first piece.
const asker = round > 1 ? askedBy(members[0], tasks) : null;
return {
key: `round-${round}`,
label: asker ? `Round ${round} · asked for by ${asker.handle}` : `Round ${round}`,
tasks: members,
};
});
const answer = ordered.filter(isAnswer);
if (answer.length) groups.push({ key: "answer", label: "The answer", tasks: answer });
return groups;
}
/** What marks a task out, in a word or two each: its round past the first,
* the piece it redoes, and how many tries it took. */
export function taskChips(task: SwarmTask, byId: Map<string, SwarmTask>): string[] {
const chips: string[] = [];
const round = roundOf(task, byId);
if (round > 1) chips.push(`Round ${round}`);
const original = task.brief?.redoes ? byId.get(task.brief.redoes) : undefined;
if (original) chips.push(`Redo of ${original.handle}`);
if ((task.attempts ?? 0) > 1) chips.push(`${task.attempts} tries`);
return chips;
}
/** A sum a task's brief keeps as a decimal string, or null. */
export function briefUsd(
task: Pick<SwarmTask, "brief">,
key: "topped_up_usd" | "passed_on_usd" | "team_budget",
): number | null {
const value = Number(task.brief?.[key]);
return task.brief?.[key] != null && Number.isFinite(value) ? value : null;
}
// ─── The team's work as a tree ───────────────────────────────────────────────
/** Why a task follows another: it needs its result, it does it again, or a
* review asked for it. */
export type TreeEdgeKind = "needs" | "redo" | "asked";
export interface TreeEdge {
source: string;
target: string;
kind: TreeEdgeKind;
}
export interface TreeModel {
/** Each task with its column: how many steps of work stand before it. */
nodes: { id: string; column: number; task: SwarmTask }[];
edges: TreeEdge[];
}
/**
* The tasks a task follows, and why: what it waits for, the piece it redoes,
* the review that asked for it — and, for a task that follows none of those,
* the task its work belongs under. A task named twice keeps the first why.
*/
export function predecessors(
task: SwarmTask,
ids: Set<string>,
tasks: SwarmTask[] = [],
): { id: string; kind: TreeEdgeKind }[] {
const before: { id: string; kind: TreeEdgeKind }[] = (task.depends_on ?? []).map((id) => ({
id,
kind: "needs",
}));
if (task.brief?.redoes) before.push({ id: task.brief.redoes, kind: "redo" });
const asker = askedBy(task, tasks);
if (asker) before.push({ id: asker.id, kind: "asked" });
if (before.length === 0 && task.parent_id) before.push({ id: task.parent_id, kind: "needs" });
const seen = new Set<string>();
return before.filter(({ id }) => {
Iif (seen.has(id) || !ids.has(id) || id === task.id) return false;
seen.add(id);
return true;
});
}
/**
* The run's tasks laid out left to right in the order the work flowed: a
* task's column is one past the latest task it follows — the plan first, the
* pieces after it (later, for a piece that needs another's result), the
* review, then what the review asked for (a piece done again, a further
* round) after it, and the answer last. Dropped pieces are left out.
*/
export function treeOf(run: Pick<SwarmRun, "tasks">): TreeModel {
const tasks = (run.tasks ?? []).filter((t) => t.status !== "cancelled");
const ids = new Set(tasks.map((t) => t.id));
const byId = new Map(tasks.map((t) => [t.id, t]));
const before = new Map(tasks.map((t) => [t.id, predecessors(t, ids, tasks)]));
const column = new Map<string, number>();
const visiting = new Set<string>();
const columnOf = (id: string): number => {
const known = column.get(id);
if (known !== undefined) return known;
if (visiting.has(id)) return 0; // a cycle: never from svc-core, never fatal
visiting.add(id);
const preds = byId.has(id) ? (before.get(id) ?? []) : [];
const at = preds.length ? Math.max(...preds.map((p) => columnOf(p.id))) + 1 : 0;
visiting.delete(id);
column.set(id, at);
return at;
};
const edges: TreeEdge[] = [];
for (const task of tasks) {
for (const { id, kind } of before.get(task.id) ?? []) {
edges.push({ source: id, target: task.id, kind });
}
}
return {
nodes: [...tasks]
.sort((a, b) => a.seq - b.seq)
.map((task) => ({ id: task.id, column: columnOf(task.id), task })),
edges,
};
}
|