@operad-io/dev 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +795 -2
- package/dev.schema.json +602 -0
- package/flows/chat-worktree.flow.ts +18 -0
- package/flows/dev.flow.ts +7 -0
- package/package.json +29 -4
- package/src/actions.ts +591 -0
- package/src/announce.ts +225 -0
- package/src/chat.ts +234 -0
- package/src/check.ts +80 -0
- package/src/commands.ts +417 -0
- package/src/editor.ts +55 -0
- package/src/flaky.ts +716 -0
- package/src/flow-compiler.ts +858 -0
- package/src/followups.ts +223 -0
- package/src/gate.ts +2897 -0
- package/src/git.ts +138 -0
- package/src/index.ts +226 -0
- package/src/integrate.ts +1201 -0
- package/src/integration-queue.ts +393 -0
- package/src/lock.ts +36 -0
- package/src/mainclone.ts +102 -0
- package/src/marks.ts +126 -0
- package/src/model.ts +1165 -0
- package/src/notcode.ts +266 -0
- package/src/place-order.ts +161 -0
- package/src/place-wait.ts +64 -0
- package/src/places.ts +368 -0
- package/src/prepare.ts +106 -0
- package/src/progress.ts +115 -0
- package/src/project-flows.ts +160 -0
- package/src/project-settings.ts +185 -0
- package/src/refusals.ts +336 -0
- package/src/rerun.ts +378 -0
- package/src/reruns.ts +62 -0
- package/src/retry.ts +212 -0
- package/src/rework.ts +366 -0
- package/src/schedule.ts +1052 -0
- package/src/service.ts +2160 -0
- package/src/settings.ts +1463 -0
- package/src/standing.ts +87 -0
- package/src/stdin.ts +105 -0
- package/src/steps.ts +1775 -0
- package/src/stops.ts +103 -0
- package/src/throughput.ts +347 -0
- package/src/timeouts.ts +60 -0
- package/src/views.ts +1167 -0
- package/src/waits.ts +105 -0
package/src/views.ts
ADDED
|
@@ -0,0 +1,1167 @@
|
|
|
1
|
+
/** How a plan and a task appear in a list and a detail page. */
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
foldObjectFacts,
|
|
5
|
+
type ObjectRow,
|
|
6
|
+
type ObjectViews,
|
|
7
|
+
type PluginFact,
|
|
8
|
+
type StoredObject,
|
|
9
|
+
type ViewContext,
|
|
10
|
+
type ViewSection,
|
|
11
|
+
} from "@operad-io/engine";
|
|
12
|
+
import {
|
|
13
|
+
closeSync,
|
|
14
|
+
existsSync,
|
|
15
|
+
fstatSync,
|
|
16
|
+
openSync,
|
|
17
|
+
readSync,
|
|
18
|
+
} from "node:fs";
|
|
19
|
+
import { join } from "node:path";
|
|
20
|
+
import {
|
|
21
|
+
bareId,
|
|
22
|
+
hasRework,
|
|
23
|
+
listAll,
|
|
24
|
+
PLAN_FINAL_STATES,
|
|
25
|
+
TASK_FINAL_STATES,
|
|
26
|
+
dependencyKey,
|
|
27
|
+
dependencyLabel,
|
|
28
|
+
planData,
|
|
29
|
+
planNote,
|
|
30
|
+
planState,
|
|
31
|
+
renderChanges,
|
|
32
|
+
repositoryData,
|
|
33
|
+
splitBrief,
|
|
34
|
+
storeKey,
|
|
35
|
+
taskData,
|
|
36
|
+
taskRowState,
|
|
37
|
+
type ReviewRecord,
|
|
38
|
+
type TaskAttempt,
|
|
39
|
+
type TaskData,
|
|
40
|
+
} from "./model.ts";
|
|
41
|
+
import { placeWaitNote } from "./place-wait.ts";
|
|
42
|
+
import { planMark, repositoryMark, taskBadge, taskMark } from "./marks.ts";
|
|
43
|
+
import { git, workBranch } from "./steps.ts";
|
|
44
|
+
import { repositoryMetrics } from "./throughput.ts";
|
|
45
|
+
import { findRepository, listRepositories } from "./service.ts";
|
|
46
|
+
import { DEV_SETTINGS_FILE, readDevSettings, settingsProblem } from "./settings.ts";
|
|
47
|
+
import { oneLine } from "@operad-io/engine";
|
|
48
|
+
|
|
49
|
+
function costNote(cost: unknown, quality?: unknown): string | undefined {
|
|
50
|
+
if (typeof cost === "number" && Number.isFinite(cost)) {
|
|
51
|
+
// `~` marks an estimated cost, `≥` an incomplete one; an exact one is bare.
|
|
52
|
+
const symbol = quality === "estimated" ? "~" : quality === "incomplete" ? "≥" : "";
|
|
53
|
+
return `${symbol}$${cost.toFixed(2)}`;
|
|
54
|
+
}
|
|
55
|
+
if (typeof cost === "string" && cost.trim().length > 0) return cost.trim();
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The short note a waiting task shows. A refused push leaves the integration
|
|
61
|
+
* message that names the remote, the branch and git's own words; the person
|
|
62
|
+
* sees it next to the task before deciding what to do.
|
|
63
|
+
*/
|
|
64
|
+
function waitNote(task: TaskData): string | undefined {
|
|
65
|
+
const place = TASK_FINAL_STATES.includes(task.phase) ? undefined : placeWaitNote(task);
|
|
66
|
+
if (place !== undefined) return place;
|
|
67
|
+
const turn = task.attempt?.integrationWait;
|
|
68
|
+
// A task that ended (cancelled while it waited) is not waiting any more.
|
|
69
|
+
if (
|
|
70
|
+
typeof turn === "string" &&
|
|
71
|
+
turn.length > 0 &&
|
|
72
|
+
!TASK_FINAL_STATES.includes(task.phase)
|
|
73
|
+
) {
|
|
74
|
+
return `waiting to integrate: ${turn}`;
|
|
75
|
+
}
|
|
76
|
+
const workerWait = task.attempt?.workerWait;
|
|
77
|
+
if (task.phase === "running" && typeof workerWait === "string" && workerWait.length > 0) {
|
|
78
|
+
return workerWait;
|
|
79
|
+
}
|
|
80
|
+
if (
|
|
81
|
+
task.phase === "ready" &&
|
|
82
|
+
task.dependencyHeld === true &&
|
|
83
|
+
(task.dependencyHeldFor ?? []).length > 0
|
|
84
|
+
) {
|
|
85
|
+
return `waiting for ${(task.dependencyHeldFor ?? []).join(", ")}`;
|
|
86
|
+
}
|
|
87
|
+
if (task.phase === "ready" && task.slotHeld !== undefined) return task.slotHeld;
|
|
88
|
+
if (
|
|
89
|
+
(task.phase === "ready" || (task.phase === "waiting" && task.run === null)) &&
|
|
90
|
+
task.flowHeld !== undefined
|
|
91
|
+
) {
|
|
92
|
+
return task.flowHeld;
|
|
93
|
+
}
|
|
94
|
+
if (task.phase !== "waiting") return undefined;
|
|
95
|
+
const integration = task.attempt?.integration;
|
|
96
|
+
if (integration === undefined || integration === null) return undefined;
|
|
97
|
+
if (integration.result !== "failed") return undefined;
|
|
98
|
+
const message = integration.message;
|
|
99
|
+
return typeof message === "string" && message.trim().length > 0
|
|
100
|
+
? message.trim()
|
|
101
|
+
: undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The longest worker name a list row shows; the full name is in Metrics. */
|
|
105
|
+
export const ROW_WORKER_CHARS = 16;
|
|
106
|
+
|
|
107
|
+
/** The last attempt's worker for a row: the name only, cut when it is long. */
|
|
108
|
+
function workerNote(task: TaskData): string | undefined {
|
|
109
|
+
const worker = task.attempt?.worker;
|
|
110
|
+
if (typeof worker !== "string") return undefined;
|
|
111
|
+
const flat = worker.replace(/\s+/g, " ").trim();
|
|
112
|
+
if (flat.length === 0) return undefined;
|
|
113
|
+
return flat.length <= ROW_WORKER_CHARS
|
|
114
|
+
? flat
|
|
115
|
+
: `${flat.slice(0, ROW_WORKER_CHARS - 1)}…`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function cell(text: string): string {
|
|
119
|
+
return text.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A list names each row's repository once more than one is registered. */
|
|
123
|
+
async function showRepository(ctx: ViewContext): Promise<boolean> {
|
|
124
|
+
return (await listRepositories(ctx.store)).length > 1;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** A repository: its row reads the stored counts; Overview reads dev.json. */
|
|
128
|
+
export const repoViews: ObjectViews = {
|
|
129
|
+
row(object: StoredObject): ObjectRow {
|
|
130
|
+
const repository = repositoryData(object.data);
|
|
131
|
+
const state = repository.removed ? "removed" : "active";
|
|
132
|
+
return {
|
|
133
|
+
id: repository.name,
|
|
134
|
+
title: repository.name,
|
|
135
|
+
state,
|
|
136
|
+
note: `plans: ${repository.openPlans ?? 0} · tasks: ${repository.openTasks ?? 0}`,
|
|
137
|
+
final: repository.removed,
|
|
138
|
+
mark: repositoryMark(repository),
|
|
139
|
+
};
|
|
140
|
+
},
|
|
141
|
+
|
|
142
|
+
sections(): readonly ViewSection[] {
|
|
143
|
+
return [
|
|
144
|
+
{ id: "overview", title: "Overview" },
|
|
145
|
+
{ id: "metrics", title: "Metrics" },
|
|
146
|
+
];
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
async load(ctx, object, sectionId) {
|
|
150
|
+
if (sectionId === "metrics") return { markdown: await repositoryMetrics(ctx, object) };
|
|
151
|
+
if (sectionId !== "overview") return { markdown: "" };
|
|
152
|
+
const repository = repositoryData(object.data);
|
|
153
|
+
const lines = [`- Path: \`${repository.path}\``];
|
|
154
|
+
try {
|
|
155
|
+
const settings = await readDevSettings(repository.path);
|
|
156
|
+
const problem = settingsProblem(repository.path);
|
|
157
|
+
const file = join(repository.path, DEV_SETTINGS_FILE);
|
|
158
|
+
lines.push(
|
|
159
|
+
`- Default branch: \`${settings.mainBranch}\` on \`${settings.remote}\``,
|
|
160
|
+
`- ${DEV_SETTINGS_FILE}: ${
|
|
161
|
+
problem !== undefined
|
|
162
|
+
? `invalid, the last valid settings stay in force (${problem})`
|
|
163
|
+
: existsSync(file)
|
|
164
|
+
? "in force"
|
|
165
|
+
: "not written, the defaults are in force"
|
|
166
|
+
}`,
|
|
167
|
+
`- Worker: \`${settings.worker.use}\``,
|
|
168
|
+
`- Reviewer: \`${settings.reviewer.use}\``,
|
|
169
|
+
);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
lines.push(
|
|
172
|
+
`- ${DEV_SETTINGS_FILE}: ${error instanceof Error ? error.message : String(error)}`,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
if (repository.removed) lines.push("- Removed from the registered repositories.");
|
|
176
|
+
return { markdown: lines.join("\n") };
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
export const planViews: ObjectViews = {
|
|
181
|
+
row(object: StoredObject): ObjectRow {
|
|
182
|
+
const plan = planData(object.data);
|
|
183
|
+
return {
|
|
184
|
+
id: bareId(object.id),
|
|
185
|
+
title: plan.title,
|
|
186
|
+
state: planState(plan),
|
|
187
|
+
note: planNote(plan),
|
|
188
|
+
scope: plan.repository,
|
|
189
|
+
final: PLAN_FINAL_STATES.includes(planState(plan)),
|
|
190
|
+
mark: planMark(plan),
|
|
191
|
+
// The level dev:auto is asked for: a client marks the current one from it.
|
|
192
|
+
badge: plan.auto,
|
|
193
|
+
parent: `repo:${plan.repository}`,
|
|
194
|
+
};
|
|
195
|
+
},
|
|
196
|
+
|
|
197
|
+
showScope: showRepository,
|
|
198
|
+
|
|
199
|
+
sections(): readonly ViewSection[] {
|
|
200
|
+
return [
|
|
201
|
+
{ id: "request", title: "Request" },
|
|
202
|
+
];
|
|
203
|
+
},
|
|
204
|
+
|
|
205
|
+
async load(ctx, object, sectionId) {
|
|
206
|
+
const plan = planData(object.data);
|
|
207
|
+
if (sectionId === "request") {
|
|
208
|
+
return { markdown: plan.request };
|
|
209
|
+
}
|
|
210
|
+
return { markdown: "" };
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
export const taskViews: ObjectViews = {
|
|
215
|
+
row(object: StoredObject): ObjectRow {
|
|
216
|
+
const task = taskData(object.data);
|
|
217
|
+
const areaWait =
|
|
218
|
+
task.phase === "ready" && task.areaHeldBy !== undefined
|
|
219
|
+
? `waiting for area ${task.area ?? ""} (${task.areaHeldBy})${
|
|
220
|
+
(task.areaAhead ?? 0) > 0 ? `, ${task.areaAhead} ahead` : ""
|
|
221
|
+
}`
|
|
222
|
+
: undefined;
|
|
223
|
+
const areaNote =
|
|
224
|
+
areaWait ?? (task.area === undefined ? undefined : `area: ${task.area}`);
|
|
225
|
+
// The wait reason, whole, also goes in its own field for clients.
|
|
226
|
+
const heldWait = waitNote(task);
|
|
227
|
+
const wait = areaWait ?? heldWait;
|
|
228
|
+
// The cost is always first, so the app's split at the first ` · ` keeps it.
|
|
229
|
+
const note = [
|
|
230
|
+
costNote(task.cost, task.costQuality) ?? "$0.00",
|
|
231
|
+
workerNote(task),
|
|
232
|
+
areaNote,
|
|
233
|
+
task.flowShown === undefined ? undefined : `flow: ${task.flowShown}`,
|
|
234
|
+
heldWait,
|
|
235
|
+
]
|
|
236
|
+
.filter((part): part is string => part !== undefined)
|
|
237
|
+
.join(" · ");
|
|
238
|
+
return {
|
|
239
|
+
id: bareId(object.id),
|
|
240
|
+
title: task.title,
|
|
241
|
+
state: taskRowState(task),
|
|
242
|
+
note,
|
|
243
|
+
...(wait === undefined ? {} : { wait }),
|
|
244
|
+
scope: task.repository,
|
|
245
|
+
final: TASK_FINAL_STATES.includes(task.phase),
|
|
246
|
+
mark: taskMark(task),
|
|
247
|
+
// A proposed task has no run but waits for the owner, as pending says.
|
|
248
|
+
...(task.phase === "proposed" ? { waiting: true } : {}),
|
|
249
|
+
badge: taskBadge(task),
|
|
250
|
+
parent: `plan:${storeKey(task.repository, task.plan)}`,
|
|
251
|
+
...(task.after.length === 0 ? {} : {
|
|
252
|
+
after: task.after.map((entry) =>
|
|
253
|
+
dependencyLabel(task.repository, dependencyKey(task.repository, entry)),
|
|
254
|
+
),
|
|
255
|
+
}),
|
|
256
|
+
};
|
|
257
|
+
},
|
|
258
|
+
|
|
259
|
+
showScope: showRepository,
|
|
260
|
+
|
|
261
|
+
sections(object: StoredObject): readonly ViewSection[] {
|
|
262
|
+
const task = taskData(object.data);
|
|
263
|
+
const sections: ViewSection[] = [{ id: "brief", title: "Brief" }];
|
|
264
|
+
if (hasRework(task.brief)) {
|
|
265
|
+
sections.push({ id: "rework", title: "Rework" });
|
|
266
|
+
}
|
|
267
|
+
sections.push({ id: "changes", title: "Changes" });
|
|
268
|
+
if (typeof task.attempt?.finalMessage === "string" || (task.attempt?.number ?? 1) > 1) {
|
|
269
|
+
sections.push({ id: "answer", title: "Answer" });
|
|
270
|
+
}
|
|
271
|
+
sections.push({ id: "log", title: "Log", live: true });
|
|
272
|
+
sections.push({ id: "diff", title: "Diff" });
|
|
273
|
+
sections.push({ id: "metrics", title: "Metrics" });
|
|
274
|
+
return sections;
|
|
275
|
+
},
|
|
276
|
+
|
|
277
|
+
async load(ctx, object, sectionId, options) {
|
|
278
|
+
const task = taskData(object.data);
|
|
279
|
+
const parts = splitBrief(task.brief);
|
|
280
|
+
if (sectionId === "brief") {
|
|
281
|
+
const header = [
|
|
282
|
+
...(task.area === undefined ? [] : [`Area: ${task.area}`]),
|
|
283
|
+
...(task.flowShown === undefined ? [] : [`Flow: ${task.flowShown}`]),
|
|
284
|
+
];
|
|
285
|
+
return {
|
|
286
|
+
markdown: header.length === 0 ? parts.body : `${header.join("\n\n")}\n\n${parts.body}`,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
if (sectionId === "rework") return { markdown: parts.reworks };
|
|
290
|
+
if (sectionId === "changes") return { markdown: renderChanges(parts.changes) };
|
|
291
|
+
if (sectionId === "answer") return answerSection(ctx, object, options.cursor);
|
|
292
|
+
if (sectionId === "log") return { markdown: await workerLog(ctx, task) };
|
|
293
|
+
if (sectionId === "diff") return diffSection(ctx, object, options.cursor);
|
|
294
|
+
if (sectionId === "metrics") return { markdown: await metrics(ctx, object) };
|
|
295
|
+
return { markdown: "" };
|
|
296
|
+
},
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
/* ---------------------------------------------------------------------------
|
|
300
|
+
* Log: the tail of the current attempt's worker log, as readable lines.
|
|
301
|
+
* ------------------------------------------------------------------------- */
|
|
302
|
+
|
|
303
|
+
const LOG_TAIL_BYTES = 256 * 1024;
|
|
304
|
+
const LOG_TAIL_LINES = 80;
|
|
305
|
+
const LOG_EARLIER_LINES = 20;
|
|
306
|
+
const LOG_LINE_CHARS = 240;
|
|
307
|
+
|
|
308
|
+
/** An agent message as one paragraph of at most 300 characters. */
|
|
309
|
+
function agentText(text: string): string {
|
|
310
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
311
|
+
return flat.length <= 300 ? flat : `${flat.slice(0, 299)}…`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function stringField(
|
|
315
|
+
record: Record<string, unknown>,
|
|
316
|
+
names: readonly string[],
|
|
317
|
+
): string | undefined {
|
|
318
|
+
for (const name of names) {
|
|
319
|
+
const value = record[name];
|
|
320
|
+
if (typeof value === "string" && value.trim().length > 0) return value;
|
|
321
|
+
}
|
|
322
|
+
return undefined;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** How a tool call that has an end line finished. */
|
|
326
|
+
interface ToolEnd {
|
|
327
|
+
readonly durationMs: number | undefined;
|
|
328
|
+
readonly error: string | undefined;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function numberField(record: Record<string, unknown>, name: string): number | undefined {
|
|
332
|
+
const value = record[name];
|
|
333
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function clockTime(at: number): string {
|
|
337
|
+
return `${new Date(at).toISOString().slice(11, 19)}Z`;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
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");
|
|
345
|
+
if (input === undefined && output === undefined) return undefined;
|
|
346
|
+
return `${input ?? 0} in / ${output ?? 0} out tokens`;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** The cost a log line carries, as dollars: pi's `total`, or `micros`. */
|
|
350
|
+
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");
|
|
355
|
+
return dollars === undefined ? undefined : `$${dollars.toFixed(4)}`;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** A command's characters shown in a log line before it is cut. */
|
|
359
|
+
const COMMAND_SHOWN_CHARS = 160;
|
|
360
|
+
|
|
361
|
+
function escapeRegExp(text: string): string {
|
|
362
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* A command as the log shows it: the `cd` into the task's worktree dropped,
|
|
367
|
+
* the worktree path relative, then the first line only (with the count of the
|
|
368
|
+
* lines left) and at most 160 characters.
|
|
369
|
+
*/
|
|
370
|
+
function shownCommand(command: string, worktree: string | undefined): string {
|
|
371
|
+
let text = command;
|
|
372
|
+
if (worktree !== undefined && worktree.length > 0) {
|
|
373
|
+
const root = worktree.replace(/\/+$/, "");
|
|
374
|
+
const path = escapeRegExp(root);
|
|
375
|
+
text = text.replace(new RegExp(`^[ \\t]*cd[ \\t]+(?:"${path}"|'${path}'|${path})/?[ \\t]*(?:;|&&)[ \\t]*`), "");
|
|
376
|
+
text = text.replace(new RegExp(`${path}/`, "g"), "");
|
|
377
|
+
text = text.replace(new RegExp(`${path}(?![\\w./-])`, "g"), ".");
|
|
378
|
+
}
|
|
379
|
+
// Every line counts, blank ones too, and the first line is the command's first.
|
|
380
|
+
const lines = text.split("\n");
|
|
381
|
+
const first = (lines[0] ?? "").trim();
|
|
382
|
+
const head = first.length <= COMMAND_SHOWN_CHARS ? first : `${first.slice(0, COMMAND_SHOWN_CHARS - 1)}…`;
|
|
383
|
+
return lines.length > 1 ? `${head} … (+${lines.length - 1} lines)` : head;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Text as Markdown inline code; the fence is longer than any backtick run inside. */
|
|
387
|
+
function inlineCode(text: string): string {
|
|
388
|
+
const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
|
|
389
|
+
const fence = "`".repeat(longest + 1);
|
|
390
|
+
return longest > 0 ? `${fence} ${text} ${fence}` : `${fence}${text}${fence}`;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function parseObject(text: string): Record<string, unknown> | undefined {
|
|
394
|
+
try {
|
|
395
|
+
const value: unknown = JSON.parse(text);
|
|
396
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
397
|
+
? (value as Record<string, unknown>)
|
|
398
|
+
: undefined;
|
|
399
|
+
} catch {
|
|
400
|
+
return undefined;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Worker log lines as readable lines, in order. A tool call is one line: what
|
|
406
|
+
* ran and how long it took, or since when it has been running when no end line
|
|
407
|
+
* follows. The agent's own text is marked as the agent's; a turn's end gives
|
|
408
|
+
* its stop reason, tokens and cost; a tool's output is never shown, only the
|
|
409
|
+
* first line of an error. A command is shown as inline code after its label.
|
|
410
|
+
* A turn's end is shown only after the agent's own text in that turn.
|
|
411
|
+
*/
|
|
412
|
+
export function readableLog(lines: readonly string[], options: { readonly worktree?: string | undefined } = {}): string[] {
|
|
413
|
+
const ends = new Map<string, ToolEnd>();
|
|
414
|
+
const starts = new Set<string>();
|
|
415
|
+
let finished = false;
|
|
416
|
+
for (const line of lines) {
|
|
417
|
+
const record = parseObject(line.trim());
|
|
418
|
+
if (record === undefined) continue;
|
|
419
|
+
if (record.type === "result" || record.type === "Result") finished = true;
|
|
420
|
+
const id = stringField(record, ["toolCallId"]);
|
|
421
|
+
if (id === undefined) continue;
|
|
422
|
+
if (record.type === "tool_execution_start") starts.add(id);
|
|
423
|
+
if (record.type !== "tool_execution_end") continue;
|
|
424
|
+
ends.set(id, {
|
|
425
|
+
durationMs: numberField(record, "durationMs"),
|
|
426
|
+
error: record.isError === true ? stringField(record, ["error"]) : undefined,
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
const out: string[] = [];
|
|
430
|
+
// Whether the agent has said something since the last turn ended.
|
|
431
|
+
let said = false;
|
|
432
|
+
for (const line of lines) {
|
|
433
|
+
const record = parseObject(line.trim());
|
|
434
|
+
const kind = record === undefined ? undefined : stringField(record, ["type"]);
|
|
435
|
+
if (record !== undefined && kind === "tool_execution_start") {
|
|
436
|
+
const id = stringField(record, ["toolCallId"]);
|
|
437
|
+
const name = stringField(record, ["toolName"]) ?? "tool";
|
|
438
|
+
const end = id === undefined ? undefined : ends.get(id);
|
|
439
|
+
const at = numberField(record, "at");
|
|
440
|
+
const input = stringField(record, ["input"]);
|
|
441
|
+
const when =
|
|
442
|
+
end !== undefined
|
|
443
|
+
? end.durationMs === undefined
|
|
444
|
+
? ""
|
|
445
|
+
: ` ${seconds(end.durationMs)}`
|
|
446
|
+
: finished
|
|
447
|
+
? ` no end logged${at === undefined ? "" : ` (started ${clockTime(at)})`}`
|
|
448
|
+
: ` running${at === undefined ? "" : ` since ${clockTime(at)}`}`;
|
|
449
|
+
const command = input === undefined ? "" : shownCommand(input, options.worktree);
|
|
450
|
+
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, " ")}`);
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
if (record !== undefined && kind === "tool_execution_end") {
|
|
455
|
+
// An end whose start is not in the tail still tells of its error.
|
|
456
|
+
const error = stringField(record, ["error"]);
|
|
457
|
+
const id = stringField(record, ["toolCallId"]);
|
|
458
|
+
const hasStart = id !== undefined && starts.has(id);
|
|
459
|
+
if (error !== undefined && !hasStart) {
|
|
460
|
+
out.push(oneLine(`tool ${stringField(record, ["toolName"]) ?? "tool"} failed: ${error}`, LOG_LINE_CHARS));
|
|
461
|
+
}
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
if (record !== undefined && kind === "message_end") {
|
|
465
|
+
const text = stringField(record, ["text"]);
|
|
466
|
+
if (text !== undefined) {
|
|
467
|
+
out.push(`**agent:** ${agentText(text)}`);
|
|
468
|
+
said = true;
|
|
469
|
+
}
|
|
470
|
+
const stop = stringField(record, ["stopReason"]);
|
|
471
|
+
const parts = [stop, tokenText(record.usage), costText(record.cost)].filter(
|
|
472
|
+
(part): part is string => part !== undefined,
|
|
473
|
+
);
|
|
474
|
+
if (parts.length > 0 && said && stop !== "tool_use") out.push(`turn ended: ${parts.join(" · ")}`);
|
|
475
|
+
said = false;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (record !== undefined && kind === "blocked") {
|
|
479
|
+
const reason = stringField(record, ["reason"]);
|
|
480
|
+
out.push(
|
|
481
|
+
oneLine(`blocked ${stringField(record, ["toolName"]) ?? "tool"}${reason === undefined ? "" : `: ${reason}`}`, LOG_LINE_CHARS),
|
|
482
|
+
);
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
if (record !== undefined && (kind === "result" || kind === "Result")) {
|
|
486
|
+
if (kind === "Result") {
|
|
487
|
+
const text = stringField(record, ["text"]);
|
|
488
|
+
if (text !== undefined) out.push(`**agent:** ${agentText(text)}`);
|
|
489
|
+
}
|
|
490
|
+
const parts = [
|
|
491
|
+
stringField(record, kind === "Result" ? ["stop_reason"] : ["result"]),
|
|
492
|
+
tokenText(record.usage),
|
|
493
|
+
costText(record.cost),
|
|
494
|
+
].filter((part): part is string => part !== undefined);
|
|
495
|
+
if (parts.length > 0 || kind !== "Result") out.push(`result: ${parts.join(" · ")}`);
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (record !== undefined && (kind === "journal" || kind === undefined) && typeof record.event === "string") {
|
|
499
|
+
const data = isObject(record.data) ? record.data : {};
|
|
500
|
+
if (record.event === "MessageAppended") {
|
|
501
|
+
const message = isObject(data.message) ? data.message : {};
|
|
502
|
+
const assistant = isObject(message.assistant) ? message.assistant : undefined;
|
|
503
|
+
const blocks: unknown[] = Array.isArray(assistant?.content) ? assistant.content : [];
|
|
504
|
+
const text = blocks
|
|
505
|
+
.map((block) => (isObject(block) && isObject(block.text) ? stringField(block.text, ["text"]) : undefined))
|
|
506
|
+
.filter((part): part is string => part !== undefined)
|
|
507
|
+
.join(" ");
|
|
508
|
+
if (text.trim().length > 0) {
|
|
509
|
+
out.push(`**agent:** ${agentText(text)}`);
|
|
510
|
+
said = true;
|
|
511
|
+
}
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (record.event === "ModelUsageRecorded") {
|
|
515
|
+
const parts = [stringField(data, ["stop_reason"]), tokenText(data.usage), costText(data.fee)].filter(
|
|
516
|
+
(part): part is string => part !== undefined,
|
|
517
|
+
);
|
|
518
|
+
if (parts.length > 0 && said && stringField(data, ["stop_reason"]) !== "tool_use") {
|
|
519
|
+
out.push(`turn ended: ${parts.join(" · ")}`);
|
|
520
|
+
}
|
|
521
|
+
said = false;
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
if (
|
|
526
|
+
record !== undefined &&
|
|
527
|
+
[
|
|
528
|
+
"session",
|
|
529
|
+
"rate_limit",
|
|
530
|
+
"agent_settled",
|
|
531
|
+
"grant_use",
|
|
532
|
+
// Live increments and tool output belong to a chat's live view; a
|
|
533
|
+
// task's log keeps the lines it showed before they existed.
|
|
534
|
+
"text_delta",
|
|
535
|
+
"thinking_delta",
|
|
536
|
+
"text_end",
|
|
537
|
+
"thinking_end",
|
|
538
|
+
"tool_output",
|
|
539
|
+
].includes(kind ?? "")
|
|
540
|
+
) {
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
const readable = readableLogLine(line);
|
|
544
|
+
if (readable !== undefined) out.push(readable);
|
|
545
|
+
}
|
|
546
|
+
return out;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** One worker log line as a sentence, or undefined for bookkeeping. */
|
|
550
|
+
export function readableLogLine(line: string): string | undefined {
|
|
551
|
+
const text = line.trim();
|
|
552
|
+
if (text.length === 0) return undefined;
|
|
553
|
+
let value: unknown;
|
|
554
|
+
try {
|
|
555
|
+
value = JSON.parse(text);
|
|
556
|
+
} catch {
|
|
557
|
+
return oneLine(text, LOG_LINE_CHARS);
|
|
558
|
+
}
|
|
559
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
560
|
+
return oneLine(text, LOG_LINE_CHARS);
|
|
561
|
+
}
|
|
562
|
+
const record = value as Record<string, unknown>;
|
|
563
|
+
const kind = stringField(record, ["type"]) ?? "";
|
|
564
|
+
const tool = stringField(record, ["tool", "tool_name", "toolName", "name"]);
|
|
565
|
+
const event = stringField(record, ["event"]) ?? "";
|
|
566
|
+
if (tool !== undefined) {
|
|
567
|
+
const input = record.input ?? record.args ?? record.arguments;
|
|
568
|
+
const shown =
|
|
569
|
+
input === undefined
|
|
570
|
+
? ""
|
|
571
|
+
: ` ${oneLine(typeof input === "string" ? input : JSON.stringify(input), LOG_LINE_CHARS)}`;
|
|
572
|
+
return oneLine(`tool ${tool}${shown}`, LOG_LINE_CHARS);
|
|
573
|
+
}
|
|
574
|
+
if (kind === "journal") {
|
|
575
|
+
return /tool/i.test(event) ? oneLine(`tool: ${event}`, LOG_LINE_CHARS) : undefined;
|
|
576
|
+
}
|
|
577
|
+
const said = stringField(record, ["text", "message", "content"]);
|
|
578
|
+
if (said !== undefined) {
|
|
579
|
+
return oneLine(`${kind === "Result" ? "result" : "assistant"}: ${said}`, LOG_LINE_CHARS);
|
|
580
|
+
}
|
|
581
|
+
return undefined;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function segment(value: string): string {
|
|
585
|
+
const cleaned = value.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
586
|
+
return cleaned.length === 0 || cleaned === "." || cleaned === ".."
|
|
587
|
+
? "_"
|
|
588
|
+
: cleaned;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
async function workerLogPath(
|
|
592
|
+
ctx: ViewContext,
|
|
593
|
+
task: TaskData,
|
|
594
|
+
): Promise<string | undefined> {
|
|
595
|
+
const attempt = task.attempt;
|
|
596
|
+
if (attempt === undefined) return undefined;
|
|
597
|
+
if (typeof attempt.workLog === "string" && attempt.workLog.length > 0) {
|
|
598
|
+
return attempt.workLog;
|
|
599
|
+
}
|
|
600
|
+
// While the worker runs its log is not recorded yet; it is where the
|
|
601
|
+
// harness's logger puts it for this run.
|
|
602
|
+
if (typeof attempt.run !== "string" || attempt.run.length === 0) {
|
|
603
|
+
return undefined;
|
|
604
|
+
}
|
|
605
|
+
const found = await findRepository(ctx.store, task.repository);
|
|
606
|
+
if (found === undefined) return undefined;
|
|
607
|
+
const settings = await readDevSettings(repositoryData(found.data).path);
|
|
608
|
+
const ran = settings.workers.workers.find((worker) => worker.name === attempt.worker);
|
|
609
|
+
const [plugin, step] = (ran?.use ?? settings.worker.use).split("/");
|
|
610
|
+
if (plugin === undefined || step === undefined) return undefined;
|
|
611
|
+
return join(
|
|
612
|
+
ctx.store.root,
|
|
613
|
+
"logs",
|
|
614
|
+
segment(plugin),
|
|
615
|
+
"runs",
|
|
616
|
+
segment(attempt.run),
|
|
617
|
+
`${segment(step)}.log`,
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function logPathFor(ctx: ViewContext, use: string, run: string): string | undefined {
|
|
622
|
+
const [plugin, step] = use.split("/");
|
|
623
|
+
if (plugin === undefined || step === undefined) return undefined;
|
|
624
|
+
return join(ctx.store.root, "logs", segment(plugin), "runs", segment(run), `${segment(step)}.log`);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/** The last `limit` bytes of a file, never the bytes before them. */
|
|
628
|
+
function readTail(path: string, limit: number): Buffer {
|
|
629
|
+
const fd = openSync(path, "r");
|
|
630
|
+
try {
|
|
631
|
+
const size = fstatSync(fd).size;
|
|
632
|
+
const start = Math.max(0, size - limit);
|
|
633
|
+
const buffer = Buffer.allocUnsafe(size - start);
|
|
634
|
+
let read = 0;
|
|
635
|
+
while (read < buffer.length) {
|
|
636
|
+
const count = readSync(fd, buffer, read, buffer.length - read, start + read);
|
|
637
|
+
if (count === 0) break;
|
|
638
|
+
read += count;
|
|
639
|
+
}
|
|
640
|
+
return buffer.subarray(0, read);
|
|
641
|
+
} finally {
|
|
642
|
+
closeSync(fd);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** The readable lines of one log file, or undefined when there is no file. */
|
|
647
|
+
function readLogLines(path: string | undefined, worktree: string | undefined): string[] | undefined {
|
|
648
|
+
if (path === undefined || !existsSync(path)) return undefined;
|
|
649
|
+
const tail = readTail(path, LOG_TAIL_BYTES);
|
|
650
|
+
return readableLog(tail.toString("utf8").split("\n"), { worktree });
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* The log of the current attempt. The worker's lines come first; once the
|
|
655
|
+
* attempt is under review, each reviewer round's lines follow. A section that
|
|
656
|
+
* holds more than one agent says which agent each block is from.
|
|
657
|
+
*/
|
|
658
|
+
async function workerLog(ctx: ViewContext, task: TaskData): Promise<string> {
|
|
659
|
+
const attempt = task.attempt;
|
|
660
|
+
const blocks: Array<{ readonly label: string; readonly lines: string[] }> = [];
|
|
661
|
+
const worktree = typeof attempt?.worktree === "string" ? attempt.worktree : undefined;
|
|
662
|
+
const worker = readLogLines(await workerLogPath(ctx, task), worktree);
|
|
663
|
+
if (worker !== undefined && worker.length > 0) {
|
|
664
|
+
blocks.push({ label: `Worker, attempt ${attempt?.number ?? 1}`, lines: worker });
|
|
665
|
+
}
|
|
666
|
+
const seen = new Set<string>();
|
|
667
|
+
const reviews = [
|
|
668
|
+
...(attempt?.reviewRuns ?? []),
|
|
669
|
+
...(attempt?.reviewPending === undefined || attempt.reviewPending === null
|
|
670
|
+
? []
|
|
671
|
+
: [attempt.reviewPending]),
|
|
672
|
+
];
|
|
673
|
+
let reviewing = false;
|
|
674
|
+
for (const review of reviews) {
|
|
675
|
+
if (typeof review.run !== "string" || review.run.length === 0) continue;
|
|
676
|
+
const path = logPathFor(ctx, review.use, review.run);
|
|
677
|
+
if (path === undefined || seen.has(path)) continue;
|
|
678
|
+
seen.add(path);
|
|
679
|
+
reviewing = true;
|
|
680
|
+
const lines = readLogLines(path, worktree);
|
|
681
|
+
if (lines === undefined || lines.length === 0) continue;
|
|
682
|
+
blocks.push({ label: `Reviewer, round ${review.round} (${review.model})`, lines });
|
|
683
|
+
}
|
|
684
|
+
if (blocks.length === 0) {
|
|
685
|
+
return worker === undefined && !reviewing
|
|
686
|
+
? "_No worker log yet._"
|
|
687
|
+
: "_The worker has written nothing readable yet._";
|
|
688
|
+
}
|
|
689
|
+
if (blocks.length === 1) {
|
|
690
|
+
return (blocks[0]?.lines ?? []).slice(-LOG_TAIL_LINES).join("\n\n");
|
|
691
|
+
}
|
|
692
|
+
// The newest block gets the whole tail; the earlier ones a short one.
|
|
693
|
+
return blocks
|
|
694
|
+
.map((block, index) => {
|
|
695
|
+
const keep = index === blocks.length - 1 ? LOG_TAIL_LINES : LOG_EARLIER_LINES;
|
|
696
|
+
return [`**${block.label}**`, ...block.lines.slice(-keep)].join("\n\n");
|
|
697
|
+
})
|
|
698
|
+
.join("\n\n---\n\n");
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/* ---------------------------------------------------------------------------
|
|
702
|
+
* Answer: the worker's last message of each attempt, in full, newest first.
|
|
703
|
+
* ------------------------------------------------------------------------- */
|
|
704
|
+
|
|
705
|
+
async function answerSection(
|
|
706
|
+
ctx: ViewContext,
|
|
707
|
+
object: StoredObject,
|
|
708
|
+
cursor: string | undefined,
|
|
709
|
+
): Promise<{
|
|
710
|
+
readonly markdown: string;
|
|
711
|
+
readonly next?: string;
|
|
712
|
+
readonly pages?: readonly { readonly label: string; readonly cursor?: string }[];
|
|
713
|
+
}> {
|
|
714
|
+
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
|
+
}
|
|
726
|
+
for (const version of foldObjectFacts(facts)) {
|
|
727
|
+
const attempt = taskData(version.data).attempt;
|
|
728
|
+
if (attempt === undefined) continue;
|
|
729
|
+
if (typeof attempt.finalMessage === "string" && attempt.finalMessage.length > 0) {
|
|
730
|
+
byAttempt.set(attempt.number, attempt.finalMessage);
|
|
731
|
+
} else if (attempt.finalMessage === null) {
|
|
732
|
+
byAttempt.delete(attempt.number);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
const numbers = [...byAttempt.keys()].sort((a, b) => b - a);
|
|
736
|
+
if (numbers.length === 0) return { markdown: "_No answer yet._" };
|
|
737
|
+
const index = cursor === undefined ? 0 : Number(cursor);
|
|
738
|
+
const number = Number.isInteger(index) ? numbers[index] : undefined;
|
|
739
|
+
const text = number === undefined ? undefined : byAttempt.get(number);
|
|
740
|
+
if (number === undefined || text === undefined) {
|
|
741
|
+
return { markdown: "_That page of the answers does not exist._" };
|
|
742
|
+
}
|
|
743
|
+
return {
|
|
744
|
+
markdown: text,
|
|
745
|
+
...(numbers.length > 1
|
|
746
|
+
? {
|
|
747
|
+
pages: numbers.map((n, at) => ({
|
|
748
|
+
label: `attempt ${n}`,
|
|
749
|
+
...(at === 0 ? {} : { cursor: String(at) }),
|
|
750
|
+
})),
|
|
751
|
+
}
|
|
752
|
+
: {}),
|
|
753
|
+
...(index + 1 < numbers.length ? { next: String(index + 1) } : {}),
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/* ---------------------------------------------------------------------------
|
|
758
|
+
* Diff: the task branch against main, one page per file when it is long.
|
|
759
|
+
* ------------------------------------------------------------------------- */
|
|
760
|
+
|
|
761
|
+
/** A diff longer than this many characters is paged by file. */
|
|
762
|
+
export const DIFF_PAGE_CHARS = 60_000;
|
|
763
|
+
|
|
764
|
+
function fence(diff: string): string {
|
|
765
|
+
return `\`\`\`\`diff\n${diff.trimEnd()}\n\`\`\`\``;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
async function diffSection(
|
|
769
|
+
ctx: ViewContext,
|
|
770
|
+
object: StoredObject,
|
|
771
|
+
cursor: string | undefined,
|
|
772
|
+
): Promise<{
|
|
773
|
+
readonly markdown: string;
|
|
774
|
+
readonly next?: string;
|
|
775
|
+
readonly pages?: readonly { readonly label: string; readonly cursor?: string }[];
|
|
776
|
+
}> {
|
|
777
|
+
const task = taskData(object.data);
|
|
778
|
+
const found = await findRepository(ctx.store, task.repository);
|
|
779
|
+
if (found === undefined) return { markdown: "_The repository is not registered._" };
|
|
780
|
+
const repository = repositoryData(found.data);
|
|
781
|
+
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}`}._` };
|
|
788
|
+
}
|
|
789
|
+
if (stat.out.length === 0) {
|
|
790
|
+
return { markdown: `_${branch} has no changes against ${main}._` };
|
|
791
|
+
}
|
|
792
|
+
const whole = git(repository.path, ["diff", range]);
|
|
793
|
+
if (whole.out.length <= DIFF_PAGE_CHARS && cursor === undefined) {
|
|
794
|
+
return { markdown: `${fence(stat.out)}\n\n${fence(whole.out)}` };
|
|
795
|
+
}
|
|
796
|
+
const names = git(repository.path, ["diff", "--name-only", range]).out
|
|
797
|
+
.split("\n")
|
|
798
|
+
.filter((name) => name.length > 0);
|
|
799
|
+
const pages = [
|
|
800
|
+
{ label: "overview" },
|
|
801
|
+
...names.map((name, at) => ({ label: name, cursor: String(at + 1) })),
|
|
802
|
+
];
|
|
803
|
+
const index = cursor === undefined ? 0 : Number(cursor);
|
|
804
|
+
if (!Number.isInteger(index) || index < 0 || index > names.length) {
|
|
805
|
+
return { markdown: "_That page of the diff does not exist._" };
|
|
806
|
+
}
|
|
807
|
+
if (index === 0) {
|
|
808
|
+
return {
|
|
809
|
+
markdown: `${fence(stat.out)}\n\nThe diff is long: one page per file.\n\n${names
|
|
810
|
+
.map((name, at) => `${at + 1}. \`${name}\``)
|
|
811
|
+
.join("\n")}`,
|
|
812
|
+
next: "1",
|
|
813
|
+
pages,
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
const name = names[index - 1];
|
|
817
|
+
if (name === undefined) return { markdown: "" };
|
|
818
|
+
const file = git(repository.path, ["diff", range, "--", name]);
|
|
819
|
+
return {
|
|
820
|
+
markdown: `### ${name}\n\n${fence(file.out)}`,
|
|
821
|
+
pages,
|
|
822
|
+
...(index < names.length ? { next: String(index + 1) } : {}),
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/* ---------------------------------------------------------------------------
|
|
827
|
+
* Metrics: a narrow summary table and one line per attempt.
|
|
828
|
+
* ------------------------------------------------------------------------- */
|
|
829
|
+
|
|
830
|
+
const METRIC_STEPS = ["worktree", "work", "reverify", "verify", "review", "integrate"] as const;
|
|
831
|
+
|
|
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
|
+
interface AttemptMetrics {
|
|
840
|
+
readonly number: number;
|
|
841
|
+
/** The runs that ran it, in the order the task first named them. */
|
|
842
|
+
readonly runs: string[];
|
|
843
|
+
last: TaskAttempt | undefined;
|
|
844
|
+
/** The latest step recorded for it. */
|
|
845
|
+
lastStep: string;
|
|
846
|
+
/** False when no run of it could be read, so it has no times. */
|
|
847
|
+
timed: boolean;
|
|
848
|
+
/** Its time: from its run's start to its run's end, without the waits for a person. */
|
|
849
|
+
ms: number;
|
|
850
|
+
/** Each step's time, in the order the run took them. */
|
|
851
|
+
readonly steps: Map<string, number>;
|
|
852
|
+
/** The step its run is in now, when the run is active and not waiting for a person. */
|
|
853
|
+
running: string | undefined;
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
type RunTimes = NonNullable<Awaited<ReturnType<NonNullable<ViewContext["runTimes"]>>>>;
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* A run's stretches cut into one group per attempt. A new attempt begins when
|
|
860
|
+
* the worktree step is entered again after the worker has run: a worktree
|
|
861
|
+
* retry before any work is the same attempt, a rework or reject is the next.
|
|
862
|
+
*/
|
|
863
|
+
function attemptCycles(segments: RunTimes["segments"]): RunTimes["segments"][number][][] {
|
|
864
|
+
const cycles: RunTimes["segments"][number][][] = [[]];
|
|
865
|
+
let worked = false;
|
|
866
|
+
for (const segment of segments) {
|
|
867
|
+
if (!segment.person && segment.step === "worktree" && worked) {
|
|
868
|
+
cycles.push([]);
|
|
869
|
+
worked = false;
|
|
870
|
+
}
|
|
871
|
+
if (!segment.person && segment.step === "work") worked = true;
|
|
872
|
+
cycles[cycles.length - 1]?.push(segment);
|
|
873
|
+
}
|
|
874
|
+
return cycles;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** A token count: whole below 10k, then in k with one decimal. */
|
|
878
|
+
export function tokenCount(count: number): string {
|
|
879
|
+
return count < 10_000 ? String(count) : `${(count / 1000).toFixed(1)}k`;
|
|
880
|
+
}
|
|
881
|
+
|
|
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
|
+
function findingsText(review: ReviewRecord): string {
|
|
892
|
+
const count = review.findings?.length;
|
|
893
|
+
if (count === undefined) return "review: findings";
|
|
894
|
+
return `review: ${count} ${count === 1 ? "finding" : "findings"}`;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* How the attempt's latest step ended it, when it did. Only the record that
|
|
899
|
+
* step wrote counts: an older review or verify record of the same attempt
|
|
900
|
+
* (a reverify keeps them) says nothing about it.
|
|
901
|
+
*/
|
|
902
|
+
function endedBy(entry: AttemptMetrics): string | undefined {
|
|
903
|
+
const last = entry.last;
|
|
904
|
+
if (entry.lastStep === "verify") {
|
|
905
|
+
return last?.verify?.result === "fail" ? "verify failed" : undefined;
|
|
906
|
+
}
|
|
907
|
+
if (entry.lastStep === "review") {
|
|
908
|
+
const review = last?.review;
|
|
909
|
+
if (review === undefined || review === null) return undefined;
|
|
910
|
+
if (review.result === "findings" || review.result === "fail") return findingsText(review);
|
|
911
|
+
if (review.result === "pass" || review.result === "passed") return undefined;
|
|
912
|
+
return `review ${review.result.replace("_", " ")}`;
|
|
913
|
+
}
|
|
914
|
+
if (entry.lastStep === "integrate") {
|
|
915
|
+
const integration = last?.integration?.result;
|
|
916
|
+
if (integration === "merged") return "merged";
|
|
917
|
+
if (integration === "conflict") return "conflict";
|
|
918
|
+
if (integration === "fail" || integration === "failed") return "integrate failed";
|
|
919
|
+
}
|
|
920
|
+
const result = last?.result;
|
|
921
|
+
if (
|
|
922
|
+
(entry.lastStep === "worktree" || entry.lastStep === "reverify" || entry.lastStep === "work") &&
|
|
923
|
+
(result === "failed" || result === "blocked" || result === "nothing")
|
|
924
|
+
) {
|
|
925
|
+
return `${entry.lastStep} ${result}`;
|
|
926
|
+
}
|
|
927
|
+
return undefined;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
/** How an attempt that is not running ended, from its recorded results only. */
|
|
931
|
+
function attemptResult(
|
|
932
|
+
entry: AttemptMetrics,
|
|
933
|
+
latest: boolean,
|
|
934
|
+
phase: TaskData["phase"],
|
|
935
|
+
current: string | undefined,
|
|
936
|
+
): string {
|
|
937
|
+
if (latest && phase === "cancelled") return "cancelled";
|
|
938
|
+
if (current !== undefined) return `running ${current.replaceAll("_", " ")}`;
|
|
939
|
+
const ended = endedBy(entry);
|
|
940
|
+
if (ended !== undefined) return ended;
|
|
941
|
+
if (entry.lastStep === "review") return "review passed";
|
|
942
|
+
if (latest && phase === "merged") return "merged";
|
|
943
|
+
return latest && phase === "waiting" ? "waiting" : "–";
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/**
|
|
947
|
+
* The task's attempts: a narrow summary table (number, time, cost, result;
|
|
948
|
+
* one row per attempt and a total), then one short line per attempt, newest
|
|
949
|
+
* first, with its per-step times and tokens. Every time comes from the run's
|
|
950
|
+
* own facts: an attempt runs from its run's start to its run's end, a step
|
|
951
|
+
* from its entry to its result or the run's end, and the time spent waiting
|
|
952
|
+
* for a person is a line of its own, inside neither. `now` closes what a
|
|
953
|
+
* run that is still active has open.
|
|
954
|
+
*/
|
|
955
|
+
export async function metrics(
|
|
956
|
+
ctx: ViewContext,
|
|
957
|
+
object: StoredObject,
|
|
958
|
+
now: number = Date.now(),
|
|
959
|
+
): Promise<string> {
|
|
960
|
+
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
|
+
}
|
|
972
|
+
for (const version of foldObjectFacts(facts)) {
|
|
973
|
+
const attempt = taskData(version.data).attempt;
|
|
974
|
+
if (attempt === undefined) continue;
|
|
975
|
+
let entry = byAttempt.get(attempt.number);
|
|
976
|
+
if (entry === undefined) {
|
|
977
|
+
entry = {
|
|
978
|
+
number: attempt.number,
|
|
979
|
+
runs: [],
|
|
980
|
+
last: undefined,
|
|
981
|
+
lastStep: "",
|
|
982
|
+
timed: false,
|
|
983
|
+
ms: 0,
|
|
984
|
+
steps: new Map(),
|
|
985
|
+
running: undefined,
|
|
986
|
+
};
|
|
987
|
+
byAttempt.set(attempt.number, entry);
|
|
988
|
+
}
|
|
989
|
+
const step = /^dev:(\w+)$/.exec(version.fact.cause)?.[1];
|
|
990
|
+
if (step !== undefined && (METRIC_STEPS as readonly string[]).includes(step)) {
|
|
991
|
+
entry.lastStep = step;
|
|
992
|
+
}
|
|
993
|
+
entry.last = attempt;
|
|
994
|
+
if (typeof attempt.run === "string" && !entry.runs.includes(attempt.run)) {
|
|
995
|
+
entry.runs.push(attempt.run);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
// Only an attempt that ran a step is one: the others are facts about a task.
|
|
999
|
+
for (const [number, entry] of byAttempt) if (entry.lastStep === "") byAttempt.delete(number);
|
|
1000
|
+
if (byAttempt.size === 0) return "_No attempts yet._";
|
|
1001
|
+
const entries = [...byAttempt.values()].sort(
|
|
1002
|
+
(left, right) => left.number - right.number,
|
|
1003
|
+
);
|
|
1004
|
+
const task = taskData(object.data);
|
|
1005
|
+
const phase = task.phase;
|
|
1006
|
+
|
|
1007
|
+
// The attempts of each run, in order, take that run's groups of stretches in order.
|
|
1008
|
+
const runIds = [...new Set(entries.flatMap((entry) => entry.runs))];
|
|
1009
|
+
let waitedMs = 0;
|
|
1010
|
+
let waiting = false;
|
|
1011
|
+
for (const runId of runIds) {
|
|
1012
|
+
const times = ctx.runTimes === undefined ? undefined : await ctx.runTimes(runId);
|
|
1013
|
+
if (times === undefined) continue;
|
|
1014
|
+
const cycles = attemptCycles(times.segments);
|
|
1015
|
+
const owners = entries.filter((entry) => entry.runs.includes(runId));
|
|
1016
|
+
// A group the run has begun whose attempt the task has not recorded yet
|
|
1017
|
+
// (the worktree of a rework is being prepared): the next attempt, already
|
|
1018
|
+
// running or cancelled in it.
|
|
1019
|
+
// An older run's group nobody recorded is no attempt to number: it would
|
|
1020
|
+
// pass the newer ones and take their result.
|
|
1021
|
+
while (runId === runIds[runIds.length - 1] && owners.length < cycles.length) {
|
|
1022
|
+
const pending: AttemptMetrics = {
|
|
1023
|
+
number: (entries[entries.length - 1]?.number ?? 0) + 1,
|
|
1024
|
+
runs: [runId],
|
|
1025
|
+
last: undefined,
|
|
1026
|
+
lastStep: "worktree",
|
|
1027
|
+
timed: false,
|
|
1028
|
+
ms: 0,
|
|
1029
|
+
steps: new Map(),
|
|
1030
|
+
running: undefined,
|
|
1031
|
+
};
|
|
1032
|
+
entries.push(pending);
|
|
1033
|
+
owners.push(pending);
|
|
1034
|
+
}
|
|
1035
|
+
for (const segment of times.segments) {
|
|
1036
|
+
if (segment.person) {
|
|
1037
|
+
waitedMs += Math.max(0, (segment.to ?? now) - segment.from);
|
|
1038
|
+
if (segment.to === null) waiting = true;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
owners.forEach((entry, index) => {
|
|
1042
|
+
const cycle = cycles[index];
|
|
1043
|
+
if (cycle === undefined) return;
|
|
1044
|
+
const first = cycle[0];
|
|
1045
|
+
const nextFrom = cycles[index + 1]?.[0]?.from;
|
|
1046
|
+
const from = index === 0 ? times.startedAt : (first?.from ?? times.startedAt);
|
|
1047
|
+
const to = nextFrom ?? times.endedAt ?? now;
|
|
1048
|
+
let waited = 0;
|
|
1049
|
+
for (const segment of cycle) {
|
|
1050
|
+
const spent = Math.max(0, (segment.to ?? now) - segment.from);
|
|
1051
|
+
if (segment.person) {
|
|
1052
|
+
waited += spent;
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
entry.steps.set(segment.step, (entry.steps.get(segment.step) ?? 0) + spent);
|
|
1056
|
+
}
|
|
1057
|
+
entry.timed = true;
|
|
1058
|
+
entry.ms += Math.max(0, to - from - waited);
|
|
1059
|
+
const open = cycle[cycle.length - 1];
|
|
1060
|
+
if (index === cycles.length - 1 && open !== undefined && open.to === null && !open.person) {
|
|
1061
|
+
entry.running = open.step;
|
|
1062
|
+
}
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
const newest = entries[entries.length - 1]?.number;
|
|
1067
|
+
const lines = ["| # | time | cost | result |", "| --- | --- | --- | --- |"];
|
|
1068
|
+
let totalMs = 0;
|
|
1069
|
+
let anyTimed = false;
|
|
1070
|
+
let totalCost = 0;
|
|
1071
|
+
let costed = false;
|
|
1072
|
+
let quality = "";
|
|
1073
|
+
for (const entry of entries) {
|
|
1074
|
+
const last = entry.last;
|
|
1075
|
+
totalMs += entry.ms;
|
|
1076
|
+
if (entry.timed) anyTimed = true;
|
|
1077
|
+
if (typeof last?.cost === "number" && Number.isFinite(last.cost)) {
|
|
1078
|
+
totalCost += last.cost;
|
|
1079
|
+
costed = true;
|
|
1080
|
+
if (last.costQuality === "incomplete") quality = "incomplete";
|
|
1081
|
+
else if (last.costQuality === "estimated" && quality === "") quality = "estimated";
|
|
1082
|
+
}
|
|
1083
|
+
const time = entry.timed ? `${wallTime(entry.ms)}${entry.running === undefined ? "" : " …"}` : "–";
|
|
1084
|
+
lines.push(
|
|
1085
|
+
`| ${entry.number} | ${time} | ${costNote(last?.cost, last?.costQuality) ?? "–"} | ${attemptResult(entry, entry.number === newest, phase, entry.running)} |`,
|
|
1086
|
+
);
|
|
1087
|
+
}
|
|
1088
|
+
lines.push(
|
|
1089
|
+
`| total | ${anyTimed ? wallTime(totalMs) : "–"} | ${costed ? costNote(totalCost, quality) : "–"} | |`,
|
|
1090
|
+
);
|
|
1091
|
+
const perAttempt = [...entries].reverse().map((entry) => {
|
|
1092
|
+
const mark = " (running)";
|
|
1093
|
+
const parts: string[] = [];
|
|
1094
|
+
// The steps dev names come first, in its order; any other step that took
|
|
1095
|
+
// time (a retry wait, a rework) follows, and the one running always shows.
|
|
1096
|
+
for (const name of METRIC_STEPS) {
|
|
1097
|
+
const spent = entry.steps.get(name);
|
|
1098
|
+
if (spent !== undefined) parts.push(`${name} ${seconds(spent)}${entry.running === name ? mark : ""}`);
|
|
1099
|
+
}
|
|
1100
|
+
for (const [name, spent] of entry.steps) {
|
|
1101
|
+
if ((METRIC_STEPS as readonly string[]).includes(name)) continue;
|
|
1102
|
+
if (spent < 1000 && entry.running !== name) continue;
|
|
1103
|
+
parts.push(`${name.replaceAll("_", " ")} ${seconds(spent)}${entry.running === name ? mark : ""}`);
|
|
1104
|
+
}
|
|
1105
|
+
const tokens = entry.last?.tokens;
|
|
1106
|
+
if (tokens !== undefined && tokens !== null) {
|
|
1107
|
+
parts.push(`${tokenCount(tokens.input)} in / ${tokenCount(tokens.output)} out tokens`);
|
|
1108
|
+
}
|
|
1109
|
+
return `**#${entry.number}** ${parts.join(" · ")}`;
|
|
1110
|
+
});
|
|
1111
|
+
const waitLine =
|
|
1112
|
+
waitedMs > 0 || waiting
|
|
1113
|
+
? [`**Waiting for a person** ${seconds(waitedMs)}${waiting ? " (waiting)" : ""}`]
|
|
1114
|
+
: [];
|
|
1115
|
+
const summary = [lines.join("\n"), perAttempt.join("\n\n"), ...waitLine].join("\n\n");
|
|
1116
|
+
const perWorker = workerTable(entries);
|
|
1117
|
+
return perWorker === undefined ? summary : `${summary}\n\n${perWorker}`;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
/**
|
|
1121
|
+
* Cost, time and first-pass result per worker, summed over the attempts. An
|
|
1122
|
+
* attempt from before pools has no worker and is left out; no table when none
|
|
1123
|
+
* has one. First pass: the attempt's first review round passed.
|
|
1124
|
+
*/
|
|
1125
|
+
function workerTable(entries: readonly AttemptMetrics[]): string | undefined {
|
|
1126
|
+
const rows = new Map<
|
|
1127
|
+
string,
|
|
1128
|
+
{ attempts: number; cost: number; costed: boolean; ms: number; reviewed: number; first: number }
|
|
1129
|
+
>();
|
|
1130
|
+
for (const entry of entries) {
|
|
1131
|
+
const worker = entry.last?.worker;
|
|
1132
|
+
if (typeof worker !== "string" || worker.length === 0) continue;
|
|
1133
|
+
const row = rows.get(worker) ?? {
|
|
1134
|
+
attempts: 0, cost: 0, costed: false, ms: 0, reviewed: 0, first: 0,
|
|
1135
|
+
};
|
|
1136
|
+
row.attempts += 1;
|
|
1137
|
+
const cost = entry.last?.cost;
|
|
1138
|
+
if (typeof cost === "number" && Number.isFinite(cost)) {
|
|
1139
|
+
row.cost += cost;
|
|
1140
|
+
row.costed = true;
|
|
1141
|
+
}
|
|
1142
|
+
row.ms += entry.ms;
|
|
1143
|
+
const review = entry.last?.review;
|
|
1144
|
+
if (review !== undefined && review !== null) {
|
|
1145
|
+
row.reviewed += 1;
|
|
1146
|
+
if ((review.result === "passed" || review.result === "pass") && (review.round ?? 1) <= 1) row.first += 1;
|
|
1147
|
+
}
|
|
1148
|
+
rows.set(worker, row);
|
|
1149
|
+
}
|
|
1150
|
+
if (rows.size === 0) return undefined;
|
|
1151
|
+
const lines = [
|
|
1152
|
+
"| worker | attempts | cost | time | first pass |",
|
|
1153
|
+
"| --- | --- | --- | --- | --- |",
|
|
1154
|
+
];
|
|
1155
|
+
for (const [worker, row] of [...rows].sort(([a], [b]) => a.localeCompare(b))) {
|
|
1156
|
+
const cost = row.costed ? `$${row.cost.toFixed(2)}` : "-";
|
|
1157
|
+
const first = row.reviewed === 0 ? "-" : `${row.first}/${row.reviewed}`;
|
|
1158
|
+
lines.push(
|
|
1159
|
+
`| ${cell(worker)} | ${row.attempts} | ${cost} | ${seconds(row.ms)} | ${first} |`,
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
return lines.join("\n");
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
1166
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1167
|
+
}
|