vericify 0.1.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.
@@ -0,0 +1,224 @@
1
+ export function completeCommand(input, runIds) {
2
+ const commands = ["help", "quit", "refresh", "hub", "run", "inspect", "compare", "history", "select", "next", "prev", "focus", "post", "handoff", "todo", "ledger", "event"];
3
+ const parts = input.split(/\s+/);
4
+ const token = parts.at(-1) ?? "";
5
+ const options = parts.length > 1 ? [...runIds, ...commands] : [...commands, ...runIds];
6
+ const match = options.find((option) => option.startsWith(token));
7
+ if (!match) return input;
8
+ parts[parts.length - 1] = match;
9
+ return parts.join(" ");
10
+ }
11
+
12
+ function tokenizeCommand(command) {
13
+ const tokens = [];
14
+ let current = "";
15
+ let quote = null;
16
+ let escape = false;
17
+ for (const char of command.trim()) {
18
+ if (escape) {
19
+ current += char;
20
+ escape = false;
21
+ continue;
22
+ }
23
+ if (char === "\\") {
24
+ escape = true;
25
+ continue;
26
+ }
27
+ if (quote) {
28
+ if (char === quote) {
29
+ quote = null;
30
+ } else {
31
+ current += char;
32
+ }
33
+ continue;
34
+ }
35
+ if (char === "'" || char === "\"") {
36
+ quote = char;
37
+ continue;
38
+ }
39
+ if (/\s/.test(char)) {
40
+ if (current) {
41
+ tokens.push(current);
42
+ current = "";
43
+ }
44
+ continue;
45
+ }
46
+ current += char;
47
+ }
48
+ if (current) tokens.push(current);
49
+ return tokens;
50
+ }
51
+
52
+ function parseOptions(tokens) {
53
+ const flags = {};
54
+ const positionals = [];
55
+ for (let index = 0; index < tokens.length; index += 1) {
56
+ const token = tokens[index];
57
+ if (token.startsWith("--")) {
58
+ const key = token.slice(2);
59
+ const next = tokens[index + 1];
60
+ if (next && !next.startsWith("--")) {
61
+ if (flags[key] === undefined) {
62
+ flags[key] = next;
63
+ } else if (Array.isArray(flags[key])) {
64
+ flags[key].push(next);
65
+ } else {
66
+ flags[key] = [flags[key], next];
67
+ }
68
+ index += 1;
69
+ } else {
70
+ flags[key] = true;
71
+ }
72
+ continue;
73
+ }
74
+ positionals.push(token);
75
+ }
76
+ return { flags, positionals };
77
+ }
78
+
79
+ function asArray(value) {
80
+ if (value === undefined) return [];
81
+ return Array.isArray(value) ? value : [value];
82
+ }
83
+
84
+ export function executeCommand(command, state) {
85
+ const tokens = tokenizeCommand(command);
86
+ const [name, ...args] = tokens;
87
+ if (!name) return { message: "" };
88
+ const { flags, positionals } = parseOptions(args);
89
+ if (name === "help") {
90
+ return {
91
+ message: "Commands: help quit refresh hub run inspect compare history select <n|run_id> next prev focus <run_id> post handoff todo ledger event"
92
+ };
93
+ }
94
+ if (name === "quit" || name === "q") {
95
+ return { quit: true, message: "Quitting Vericify." };
96
+ }
97
+ if (name === "refresh") {
98
+ return { refresh: true, message: "Refreshing state." };
99
+ }
100
+ if (name === "hub") {
101
+ return { patch: { view: "hub" }, message: "Switched to hub view." };
102
+ }
103
+ if (name === "run" || name === "inspect") {
104
+ return { patch: { view: "inspect" }, message: "Switched to inspect view." };
105
+ }
106
+ if (name === "compare") {
107
+ const compareTarget = positionals[0];
108
+ return { patch: { view: "compare", compareTarget }, message: "Switched to compare view." };
109
+ }
110
+ if (name === "history") {
111
+ return { patch: { view: "history" }, message: "Switched to history view." };
112
+ }
113
+ if (name === "next") {
114
+ return { patch: { selectedIndexDelta: 1 }, message: "Selected next run." };
115
+ }
116
+ if (name === "prev") {
117
+ return { patch: { selectedIndexDelta: -1 }, message: "Selected previous run." };
118
+ }
119
+ if (name === "select" || name === "focus") {
120
+ return { patch: { selectTarget: positionals.join(" ") }, message: `Selected ${positionals.join(" ")}.` };
121
+ }
122
+ if (name === "post") {
123
+ const selectedRunId = state?.projected?.runs?.[state.selectedIndex]?.run?.run_id;
124
+ return {
125
+ action: {
126
+ type: "post",
127
+ params: {
128
+ run_id: flags["run-id"] ?? selectedRunId,
129
+ branch_id: flags["branch-id"],
130
+ lane_id: flags["lane-id"],
131
+ agent_id: flags["agent-id"],
132
+ kind: flags.kind,
133
+ summary: flags.summary ?? positionals.join(" "),
134
+ tool_refs: asArray(flags["tool-ref"]),
135
+ evidence_refs: asArray(flags["evidence-ref"]),
136
+ checkpoint_ref: flags["checkpoint-ref"],
137
+ },
138
+ },
139
+ refresh: true,
140
+ message: "Process post recorded.",
141
+ };
142
+ }
143
+ if (name === "handoff") {
144
+ return {
145
+ action: {
146
+ type: "handoff",
147
+ params: {
148
+ handoff_id: flags.id,
149
+ from: flags.from,
150
+ to: flags.to,
151
+ title: flags.title ?? positionals.join(" "),
152
+ status: flags.status,
153
+ note: flags.note,
154
+ actor: flags.actor,
155
+ task_type: flags["task-type"],
156
+ priority: flags.priority,
157
+ source_file: flags["source-file"],
158
+ agent_id: flags["agent-id"],
159
+ timestamp: flags.timestamp,
160
+ },
161
+ },
162
+ refresh: true,
163
+ message: "Handoff written.",
164
+ };
165
+ }
166
+ if (name === "todo") {
167
+ return {
168
+ action: {
169
+ type: "todo",
170
+ params: {
171
+ id: flags.id,
172
+ title: flags.title ?? positionals.join(" "),
173
+ status: flags.status,
174
+ section: flags.section,
175
+ source_line: flags["source-line"] ? Number(flags["source-line"]) : undefined,
176
+ depends_on: asArray(flags["depends-on"]),
177
+ priority: flags.priority,
178
+ source_todo_path: flags["source-todo-path"],
179
+ },
180
+ },
181
+ refresh: true,
182
+ message: "Todo node written.",
183
+ };
184
+ }
185
+ if (name === "ledger") {
186
+ return {
187
+ action: {
188
+ type: "ledger",
189
+ params: {
190
+ id: flags.id,
191
+ timestamp_utc: flags.timestamp,
192
+ tool: flags.tool,
193
+ category: flags.category,
194
+ message: flags.message ?? positionals.join(" "),
195
+ artifacts: asArray(flags.artifact),
196
+ metadata_json: flags["metadata-json"],
197
+ },
198
+ },
199
+ refresh: true,
200
+ message: "Run-ledger entry written.",
201
+ };
202
+ }
203
+ if (name === "event") {
204
+ return {
205
+ action: {
206
+ type: "event",
207
+ params: {
208
+ event_id: flags.id,
209
+ trace_id: flags["trace-id"],
210
+ timestamp: flags.timestamp,
211
+ source_module: flags["source-module"],
212
+ event_type: flags["event-type"],
213
+ status: flags.status,
214
+ objective_id: flags["objective-id"],
215
+ decision_id: flags["decision-id"],
216
+ payload_json: flags["payload-json"],
217
+ },
218
+ },
219
+ refresh: true,
220
+ message: "Status event written.",
221
+ };
222
+ }
223
+ return { message: `Unknown command: ${name}` };
224
+ }
@@ -0,0 +1,440 @@
1
+ import { formatTimestamp, relativeTimeFromNow } from "../core/util.js";
2
+ import { buildRunComparison } from "../compare/engine.js";
3
+
4
+ function compactStatus(status) {
5
+ if (status === "running") return "LIVE";
6
+ if (status === "blocked") return "BLKD";
7
+ if (status === "completed") return "DONE";
8
+ if (status === "failed") return "FAIL";
9
+ if (status === "idle") return "IDLE";
10
+ return "PLAN";
11
+ }
12
+
13
+ function urgencyBadge(status) {
14
+ if (status === "blocked" || status === "failed") return "P1";
15
+ if (status === "running" || status === "open" || status === "accepted") return "P2";
16
+ if (status === "completed") return "OK";
17
+ return "P3";
18
+ }
19
+
20
+ function humanize(value) {
21
+ return String(value ?? "")
22
+ .replace(/[-_]+/g, " ")
23
+ .trim();
24
+ }
25
+
26
+ function last(items) {
27
+ return Array.isArray(items) && items.length ? items[items.length - 1] : undefined;
28
+ }
29
+
30
+ function unique(values) {
31
+ return [...new Set(values.filter(Boolean))];
32
+ }
33
+
34
+ function top(items, limit) {
35
+ return items.slice(0, limit);
36
+ }
37
+
38
+ function activityBadge(sourceKind) {
39
+ if (sourceKind === "lane_heartbeat") return "hb";
40
+ if (sourceKind === "status_event") return "ev";
41
+ if (sourceKind === "run_ledger") return "ld";
42
+ return "pp";
43
+ }
44
+
45
+ export function layoutTierForWidth(width) {
46
+ if (width < 110) return "narrow";
47
+ if (width < 170) return "medium";
48
+ return "wide";
49
+ }
50
+
51
+ function laneHeartbeat(run, lane) {
52
+ return (run.activity_items ?? [])
53
+ .filter((item) => item.source_kind === "lane_heartbeat" && item.lane_id === lane.lane_id)
54
+ .at(-1);
55
+ }
56
+
57
+ function globalActivity(projected) {
58
+ return (projected.runs ?? [])
59
+ .flatMap((run) =>
60
+ (run.activity_items ?? []).map((item) => ({
61
+ ...item,
62
+ run_title: run.run.title,
63
+ run_status: run.run.status,
64
+ }))
65
+ )
66
+ .sort((left, right) => String(right.timestamp).localeCompare(String(left.timestamp)));
67
+ }
68
+
69
+ function latestDelta(run) {
70
+ return last(run?.deltas ?? []);
71
+ }
72
+
73
+ function latestCheckpoint(run) {
74
+ return last(run?.recent_checkpoints ?? []);
75
+ }
76
+
77
+ function activeNodeLabels(run) {
78
+ return unique((run?.nodes ?? []).filter((node) => node.status !== "done").map((node) => node.title));
79
+ }
80
+
81
+ function runActors(run) {
82
+ return unique((run?.lanes ?? []).map((lane) => lane.agent_id));
83
+ }
84
+
85
+ function summarizeNeighbor(run, neighbor) {
86
+ return `${neighbor.run_id} | ${(neighbor.score * 100).toFixed(0)}% | ${compactStatus(neighbor.outcome)} | ${runActors(run).slice(0, 2).join(", ") || "no lanes"}`;
87
+ }
88
+
89
+ function branchRows(run) {
90
+ const checkpointCounts = new Map();
91
+ for (const checkpoint of run.recent_checkpoints ?? []) {
92
+ checkpointCounts.set(checkpoint.branch_id, (checkpointCounts.get(checkpoint.branch_id) ?? 0) + 1);
93
+ }
94
+ const branchActivity = new Map();
95
+ for (const item of run.activity_items ?? []) {
96
+ if (!item.branch_id) continue;
97
+ branchActivity.set(item.branch_id, (branchActivity.get(item.branch_id) ?? 0) + 1);
98
+ }
99
+ return (run.branches ?? []).map((branch) => {
100
+ const pulse = checkpointCounts.get(branch.branch_id) ?? 0;
101
+ const traffic = branchActivity.get(branch.branch_id) ?? 0;
102
+ const hotspot = (run.recent_checkpoints ?? [])
103
+ .filter((checkpoint) => checkpoint.branch_id === branch.branch_id)
104
+ .at(-1)?.task_delta_summary ?? "quiet";
105
+ return `${urgencyBadge(branch.status)} ${branch.name} | lanes ${branch.lane_ids?.length ?? 0} | pulse ${pulse} | traffic ${traffic} | hotspot ${hotspot}`;
106
+ });
107
+ }
108
+
109
+ function buildLaneSkylineRows(run, tier) {
110
+ const lanes = top(run?.lanes ?? [], tier === "narrow" ? 4 : 6);
111
+ return lanes.map((lane) => {
112
+ const heartbeat = laneHeartbeat(run, lane);
113
+ const node = lane.current_node_id ? humanize(lane.current_node_id) : "awaiting node";
114
+ const age = relativeTimeFromNow(lane.updated_at);
115
+ return `${urgencyBadge(lane.status)} ${compactStatus(lane.status)} ${lane.agent_id} | ${node} | ${age} | ${heartbeat?.summary ?? "No heartbeat yet."}`;
116
+ });
117
+ }
118
+
119
+ function buildLaneDetailRows(run, tier) {
120
+ const lanes = top(run?.lanes ?? [], tier === "narrow" ? 5 : 8);
121
+ return lanes.map((lane) => {
122
+ const heartbeat = laneHeartbeat(run, lane);
123
+ const node = lane.current_node_id ? humanize(lane.current_node_id) : "-";
124
+ return `${compactStatus(lane.status)} ${lane.agent_id} | node ${node} | heartbeat ${heartbeat?.summary ?? "No heartbeat yet."}`;
125
+ });
126
+ }
127
+
128
+ function buildRunTriageRows(run) {
129
+ if (!run) return ["No run selected."];
130
+ const rows = [];
131
+ const blockedNodes = (run.nodes ?? []).filter((node) => node.status === "blocked");
132
+ if (blockedNodes.length) {
133
+ rows.push(`P1 blocked nodes ${blockedNodes.length}: ${top(blockedNodes.map((node) => node.title), 2).join(", ")}`);
134
+ }
135
+ const queuedHandoffs = (run.handoff_timeline?.items ?? []).filter((handoff) => handoff.status === "open" || handoff.status === "blocked");
136
+ if (queuedHandoffs.length) {
137
+ rows.push(`P1 handoff queue ${queuedHandoffs.length}: ${top(queuedHandoffs.map((handoff) => handoff.handoff_id), 2).join(", ")}`);
138
+ }
139
+ const staleLanes = (run.lanes ?? [])
140
+ .filter((lane) => lane.status !== "completed")
141
+ .sort((left, right) => String(left.updated_at).localeCompare(String(right.updated_at)));
142
+ if (staleLanes.length) {
143
+ const lane = staleLanes[0];
144
+ rows.push(`P2 stale lane: ${lane.agent_id} last signaled ${relativeTimeFromNow(lane.updated_at)}`);
145
+ }
146
+ const blockedNeighbor = (run.similarity?.neighbors ?? []).find((neighbor) => neighbor.outcome === "blocked");
147
+ if (blockedNeighbor) {
148
+ rows.push(`P2 failure echo: compare with ${blockedNeighbor.run_id} at ${(blockedNeighbor.score * 100).toFixed(0)}%`);
149
+ }
150
+ const recoveryNeighbor = (run.similarity?.neighbors ?? []).find((neighbor) => neighbor.outcome === "completed");
151
+ if (recoveryNeighbor) {
152
+ rows.push(`OK recovery path: ${recoveryNeighbor.run_id} reached done from a ${(recoveryNeighbor.score * 100).toFixed(0)}% similar path`);
153
+ }
154
+ return rows.length ? rows : ["No acute risks. Run is flowing."];
155
+ }
156
+
157
+ function buildGlobalTriageRows(projected, selectedRun) {
158
+ const rows = [];
159
+ const blockedRuns = (projected.runs ?? []).filter((run) => run.run.status === "blocked");
160
+ if (blockedRuns.length) {
161
+ rows.push(`P1 blocked runs ${blockedRuns.length}: ${top(blockedRuns.map((run) => run.run.title), 3).join(", ")}`);
162
+ }
163
+ const openHandoffs = (projected.runs ?? [])
164
+ .flatMap((run) => run.handoff_timeline?.items ?? [])
165
+ .filter((handoff) => handoff.status === "open" || handoff.status === "blocked");
166
+ if (openHandoffs.length) {
167
+ rows.push(`P1 handoffs awaiting movement ${openHandoffs.length}: ${top(openHandoffs.map((handoff) => handoff.handoff_id), 3).join(", ")}`);
168
+ }
169
+ const blockedNodes = (projected.runs ?? []).flatMap((run) => run.nodes ?? []).filter((node) => node.status === "blocked");
170
+ if (blockedNodes.length) {
171
+ rows.push(`P1 blocked nodes ${blockedNodes.length}: ${top(blockedNodes.map((node) => node.title), 3).join(", ")}`);
172
+ }
173
+ const staleLanes = (projected.runs ?? [])
174
+ .flatMap((run) => (run.lanes ?? []).map((lane) => ({ run, lane })))
175
+ .filter(({ lane }) => lane.status !== "completed")
176
+ .sort((left, right) => String(left.lane.updated_at).localeCompare(String(right.lane.updated_at)));
177
+ if (staleLanes.length) {
178
+ const { run, lane } = staleLanes[0];
179
+ rows.push(`P2 stale lane ${lane.agent_id} in ${run.run.title}: last signal ${relativeTimeFromNow(lane.updated_at)}`);
180
+ }
181
+ const blockedNeighbor = selectedRun?.similarity?.neighbors?.find((neighbor) => neighbor.outcome === "blocked");
182
+ if (blockedNeighbor) {
183
+ rows.push(`P2 compare now: selected run resembles blocked ${blockedNeighbor.run_id} at ${(blockedNeighbor.score * 100).toFixed(0)}%`);
184
+ }
185
+ return rows.length ? rows : ["No hot triage. Traffic is flowing."];
186
+ }
187
+
188
+ function buildSelectedRunRadar(selectedRun) {
189
+ if (!selectedRun) return ["No selected run."];
190
+ const checkpoint = latestCheckpoint(selectedRun);
191
+ const delta = latestDelta(selectedRun);
192
+ const nextNode = activeNodeLabels(selectedRun)[0];
193
+ const queuedHandoff = (selectedRun.handoff_timeline?.items ?? []).find((handoff) => handoff.status === "open" || handoff.status === "blocked");
194
+ const risk = buildRunTriageRows(selectedRun)[0];
195
+ return [
196
+ `${compactStatus(selectedRun.run.status)} ${selectedRun.run.title}`,
197
+ `NOW ${checkpoint ? checkpoint.process_summary.split("\n")[0] : "No checkpoint yet."}`,
198
+ `NEXT ${queuedHandoff ? `${queuedHandoff.to_agent} for ${queuedHandoff.node_ref ?? queuedHandoff.handoff_id}` : nextNode ? `advance ${nextNode}` : "await new movement"}`,
199
+ `RISK ${risk}`,
200
+ `PATH ${delta ? delta.layers.join(" / ") : "entry only"} | confidence ${((selectedRun.run_summary?.completion_confidence ?? 0) * 100).toFixed(0)}%`,
201
+ ];
202
+ }
203
+
204
+ function buildTrafficRows(projected, tier) {
205
+ const limit = tier === "narrow" ? 6 : 10;
206
+ return top(globalActivity(projected), limit).map((item) =>
207
+ `${formatTimestamp(item.timestamp)} [${activityBadge(item.source_kind)}] ${urgencyBadge(item.status)} ${item.run_title} | ${item.actor_id} | ${item.summary}`
208
+ );
209
+ }
210
+
211
+ function compareCueRows(selectedRun) {
212
+ if (!selectedRun) return ["No compare target."];
213
+ const best = selectedRun.similarity?.neighbors?.[0];
214
+ const delta = latestDelta(selectedRun);
215
+ return [
216
+ `Best compare: ${best?.run_id ?? "none"}`,
217
+ `Signal: ${best ? `${(best.score * 100).toFixed(0)}%` : "-"} | outcome ${best ? compactStatus(best.outcome) : "-"}`,
218
+ `Layers: ${delta?.layers?.join(", ") ?? "-"}`,
219
+ ];
220
+ }
221
+
222
+ function historyCueRows(projected, selectedRun) {
223
+ const completed = (projected.runs ?? []).filter((run) => run.run.status === "completed").length;
224
+ const blocked = (projected.runs ?? []).filter((run) => run.run.status === "blocked").length;
225
+ const neighbor = selectedRun?.similarity?.neighbors?.[0];
226
+ return [
227
+ `Archive: ${projected.runs?.length ?? 0} runs | ${completed} done | ${blocked} blocked`,
228
+ `Echo: ${neighbor ? `${neighbor.run_id} at ${(neighbor.score * 100).toFixed(0)}%` : "no close echo"}`,
229
+ "Open history view for motifs, recoveries, and recent timeline.",
230
+ ];
231
+ }
232
+
233
+ function buildCompareSummaryRows(report) {
234
+ if (!report) return ["No comparable run available."];
235
+ return [
236
+ `${report.left_run_id} ↔ ${report.right_run_id}`,
237
+ `A ${compactStatus(report.left.status)} ${report.left.title} | checkpoint ${report.left.latest_checkpoint_summary}`,
238
+ `B ${compactStatus(report.right.status)} ${report.right.title} | checkpoint ${report.right.latest_checkpoint_summary}`,
239
+ `Composite similarity ${(report.similarity_score * 100).toFixed(0)}% | checkpoint ${(report.checkpoint_similarity * 100).toFixed(0)}%`,
240
+ ];
241
+ }
242
+
243
+ function buildLayerRows(report) {
244
+ if (!report) return ["No layer diff available."];
245
+ const rows = report.layer_grid.map((layer) => {
246
+ const status = layer.status === "shared" ? "shared" : layer.status === "left_only" ? "left-only" : "right-only";
247
+ return `${layer.layer}: ${status}`;
248
+ });
249
+ if (!rows.length) rows.push("No explicit layer data.");
250
+ return rows;
251
+ }
252
+
253
+ function buildLaneDivergenceRows(run, compareRun, report) {
254
+ if (!run || !compareRun || !report) return ["No lane divergence available."];
255
+ const leftHot = buildLaneSkylineRows(run, "medium")[0];
256
+ const rightHot = buildLaneSkylineRows(compareRun, "medium")[0];
257
+ return [
258
+ `Lane count: A ${report.left.lane_count} | B ${report.right.lane_count}`,
259
+ `Shared actors: ${report.shared_actors.length ? report.shared_actors.join(", ") : "none"}`,
260
+ `A hot lane: ${leftHot ?? "-"}`,
261
+ `B hot lane: ${rightHot ?? "-"}`,
262
+ ];
263
+ }
264
+
265
+ function buildBranchDivergenceRows(run, compareRun, report) {
266
+ if (!run || !compareRun || !report) return branchRows(run);
267
+ const left = branchRows(run);
268
+ const right = branchRows(compareRun);
269
+ return [
270
+ `Branches: A ${report.left.branch_count} | B ${report.right.branch_count}`,
271
+ `A hotspot: ${left[0] ?? "none"}`,
272
+ `B hotspot: ${right[0] ?? "none"}`,
273
+ report.divergence_explanations.some((row) => row.includes("Branch topology")) ? "Topology diverged." : "Topology aligned.",
274
+ ];
275
+ }
276
+
277
+ function buildSimilarityRows(report) {
278
+ if (!report) return ["No similarity cues."];
279
+ return report.similarity_explanations;
280
+ }
281
+
282
+ function buildDivergenceCueRows(report) {
283
+ if (!report) return ["No divergence cues."];
284
+ return report.divergence_explanations;
285
+ }
286
+
287
+ function buildRecoveryCueRows(report) {
288
+ if (!report) return ["No recovery cue."];
289
+ return [...report.recovery_explanations, ...report.recommended_actions];
290
+ }
291
+
292
+ function buildHistoryTimelineRows(projected, selectedRun, tier) {
293
+ const activity = selectedRun
294
+ ? top([...(selectedRun.activity_items ?? [])].sort((left, right) => String(right.timestamp).localeCompare(String(left.timestamp))), tier === "narrow" ? 6 : 8)
295
+ : top(globalActivity(projected), tier === "narrow" ? 6 : 8);
296
+ return activity.map((item) =>
297
+ `${formatTimestamp(item.timestamp)} [${activityBadge(item.source_kind)}] ${item.actor_id} | ${item.summary}`
298
+ );
299
+ }
300
+
301
+ function buildRepeatedMotifRows(selectedRun) {
302
+ if (!selectedRun) return ["No run selected."];
303
+ const topNeighbor = selectedRun.similarity?.neighbors?.[0];
304
+ const delta = latestDelta(selectedRun);
305
+ return [
306
+ `Dominant layers: ${delta?.layers?.join(", ") ?? "entry only"}`,
307
+ `Current active nodes: ${activeNodeLabels(selectedRun).slice(0, 3).join(", ") || "none"}`,
308
+ `Closest echo: ${topNeighbor ? `${topNeighbor.run_id} at ${(topNeighbor.score * 100).toFixed(0)}%` : "none"}`,
309
+ ];
310
+ }
311
+
312
+ function buildRecoveryPatternRows(selectedRun, projected) {
313
+ const completedNeighbors = top((selectedRun?.similarity?.neighbors ?? []).filter((neighbor) => neighbor.outcome === "completed"), 3);
314
+ if (completedNeighbors.length) {
315
+ return completedNeighbors.map((neighbor) => `Recovery: ${neighbor.run_id} | ${(neighbor.score * 100).toFixed(0)}% | completed`);
316
+ }
317
+ const completedRuns = top((projected.runs ?? []).filter((run) => run.run.status === "completed"), 3);
318
+ return completedRuns.length
319
+ ? completedRuns.map((run) => `Recovery candidate: ${run.run.run_id} | ${run.run.title}`)
320
+ : ["No completed runs recorded yet."];
321
+ }
322
+
323
+ export function buildHubMetrics(projected, options = {}) {
324
+ const { tier = "wide" } = options;
325
+ const runs = projected.runs ?? [];
326
+ const lanes = runs.flatMap((run) => run.lanes ?? []);
327
+ const nodes = runs.flatMap((run) => run.nodes ?? []);
328
+ const handoffs = runs.flatMap((run) => run.handoff_timeline?.items ?? []);
329
+ const activityCount = runs.reduce((sum, run) => sum + (run.activity_items?.length ?? 0), 0);
330
+ const runningRuns = runs.filter((run) => run.run.status === "running").length;
331
+ const blockedRuns = runs.filter((run) => run.run.status === "blocked").length;
332
+ const liveLanes = lanes.filter((lane) => lane.status === "running").length;
333
+ const blockedNodes = nodes.filter((node) => node.status === "blocked").length;
334
+ const openHandoffs = handoffs.filter((handoff) => handoff.status === "open" || handoff.status === "blocked").length;
335
+ if (tier === "narrow") {
336
+ return `Runs ${runs.length} | Live ${runningRuns} | Blkd ${blockedRuns} | Lanes ${liveLanes}/${lanes.length} | HOs ${openHandoffs} | Nodes ${blockedNodes} | Act ${activityCount}`;
337
+ }
338
+ return `Runs ${runs.length} | Live ${runningRuns} | Blocked ${blockedRuns} | Lanes ${lanes.length}/${liveLanes} live | Handoffs ${openHandoffs} open | Nodes ${blockedNodes} blocked | Activity ${activityCount}`;
339
+ }
340
+
341
+ export function buildRunBoardSection(projected, selectedRun, options = {}) {
342
+ const { tier = "wide" } = options;
343
+ const rows = top(projected.run_summaries ?? [], tier === "narrow" ? 6 : 8).map((summary) => {
344
+ const isSelected = summary.run_id === selectedRun?.run?.run_id ? ">" : " ";
345
+ const node = summary.current_node_labels?.[0] ?? "steady";
346
+ return `${isSelected} ${urgencyBadge(summary.status)} ${compactStatus(summary.status)} ${summary.title} | br ${summary.branch_count} | ln ${summary.lane_count} | node ${node} | ${relativeTimeFromNow(summary.updated_at)}`;
347
+ });
348
+ return {
349
+ title: "Run Board",
350
+ rows: rows.length ? rows : ["No runs available."],
351
+ tone: "LIVE",
352
+ };
353
+ }
354
+
355
+ export function buildHubSections(projected, selectedRun, options = {}) {
356
+ const { tier = "wide" } = options;
357
+ return [
358
+ { title: "Triage Shelf", rows: buildGlobalTriageRows(projected, selectedRun), tone: "HOT" },
359
+ { title: "Selected Run Radar", rows: buildSelectedRunRadar(selectedRun), tone: selectedRun?.run?.status === "blocked" ? "HOT" : "LIVE" },
360
+ { title: "Network Traffic", rows: buildTrafficRows(projected, tier), tone: "FLOW", fullWidth: tier === "wide" },
361
+ { title: "Compare Cue", rows: compareCueRows(selectedRun), tone: "DIFF" },
362
+ { title: "History Cue", rows: historyCueRows(projected, selectedRun), tone: "TRACE" },
363
+ ];
364
+ }
365
+
366
+ export function buildInspectSections(run, options = {}) {
367
+ const { tier = "wide" } = options;
368
+ if (!run) {
369
+ return [{ title: "Inspect", rows: ["No run selected."], tone: "WAIT" }];
370
+ }
371
+ const handoffRows = (run.handoff_timeline?.items ?? [])
372
+ .filter((handoff) => handoff.status === "open" || handoff.status === "blocked" || handoff.status === "accepted")
373
+ .slice(-5)
374
+ .map((handoff) =>
375
+ `${urgencyBadge(handoff.status)} ${handoff.status} ${handoff.from_agent} -> ${handoff.to_agent} | ${handoff.node_ref ?? handoff.handoff_id} | ${relativeTimeFromNow(handoff.updated_at ?? handoff.created_at)}`
376
+ );
377
+ const checkpointRows = (run.recent_checkpoints ?? []).slice(-6).map((checkpoint, index) => {
378
+ const delta = index > 0 ? run.deltas?.find((candidate) => candidate.to_checkpoint_id === checkpoint.checkpoint_id) : undefined;
379
+ return `${formatTimestamp(checkpoint.timestamp)} | ${checkpoint.process_summary.split("\n")[0]} | ${delta ? delta.layers.join("/") : "entry"}`;
380
+ });
381
+ const activityRows = (run.activity_items ?? []).slice(-12).map((item) =>
382
+ `${formatTimestamp(item.timestamp)} [${activityBadge(item.source_kind)}] ${urgencyBadge(item.status)} ${item.actor_id} | ${item.summary}`
383
+ );
384
+ const similarityRows = (run.similarity?.neighbors ?? []).slice(0, 4).map((neighbor) => summarizeNeighbor(run, neighbor));
385
+
386
+ return [
387
+ {
388
+ title: "Run Header",
389
+ rows: [
390
+ `${compactStatus(run.run.status)} ${run.run.title}`,
391
+ `Objective: ${run.run.objective ?? "-"}`,
392
+ `Updated: ${formatTimestamp(run.run.updated_at)} (${relativeTimeFromNow(run.run.updated_at)})`,
393
+ ],
394
+ tone: run.run.status === "blocked" ? "HOT" : "LIVE",
395
+ },
396
+ { title: "Lane Skyline", rows: buildLaneSkylineRows(run, tier), tone: "FLOW" },
397
+ { title: "Triage Shelf", rows: buildRunTriageRows(run), tone: "HOT" },
398
+ { title: "Handoff Queue", rows: handoffRows.length ? handoffRows : ["No queued handoffs."], tone: "QUEUE" },
399
+ { title: "Branch Divergence", rows: branchRows(run), tone: "FORK" },
400
+ { title: "Lane Detail", rows: buildLaneDetailRows(run, tier), tone: "FLOW" },
401
+ { title: "Checkpoint Pulse", rows: checkpointRows.length ? checkpointRows : ["No checkpoints."], tone: "PULSE" },
402
+ { title: "Activity Feed", rows: activityRows.length ? activityRows : ["No activity."], tone: "TRACE", fullWidth: tier !== "narrow" },
403
+ { title: "Similarity and Recovery", rows: similarityRows.length ? similarityRows : ["No similar runs."], tone: "DIFF" },
404
+ ];
405
+ }
406
+
407
+ export function buildCompareSections(run, compareRun) {
408
+ if (!run || !compareRun) {
409
+ return [{ title: "Compare", rows: ["No comparable run available."], tone: "WAIT" }];
410
+ }
411
+ const report = buildRunComparison(run, compareRun);
412
+ return [
413
+ { title: "Compare Summary", rows: buildCompareSummaryRows(report), tone: "DIFF" },
414
+ { title: "Layer Grid", rows: buildLayerRows(report), tone: "PULSE" },
415
+ { title: "Lane Divergence", rows: buildLaneDivergenceRows(run, compareRun, report), tone: "FLOW" },
416
+ { title: "Branch Divergence", rows: buildBranchDivergenceRows(run, compareRun, report), tone: "FORK" },
417
+ { title: "Why Similar", rows: buildSimilarityRows(report), tone: "TRACE" },
418
+ { title: "Why Diverged", rows: buildDivergenceCueRows(report), tone: "HOT" },
419
+ { title: "Recovery Cue", rows: buildRecoveryCueRows(report), tone: "RECOVER", fullWidth: true },
420
+ ];
421
+ }
422
+
423
+ export function buildHistorySections(projected, selectedRun, options = {}) {
424
+ const { tier = "wide" } = options;
425
+ return [
426
+ {
427
+ title: "Prior Runs",
428
+ rows: (selectedRun?.similarity?.neighbors ?? []).slice(0, tier === "narrow" ? 4 : 6).map((neighbor) =>
429
+ `${neighbor.run_id} | ${(neighbor.score * 100).toFixed(0)}% | ${compactStatus(neighbor.outcome)}`
430
+ ),
431
+ tone: "TRACE",
432
+ },
433
+ { title: "Repeated Motifs", rows: buildRepeatedMotifRows(selectedRun), tone: "ECHO" },
434
+ { title: "Recovery Patterns", rows: buildRecoveryPatternRows(selectedRun, projected), tone: "RECOVER" },
435
+ { title: "Timeline", rows: buildHistoryTimelineRows(projected, selectedRun, tier), tone: "FLOW", fullWidth: tier !== "narrow" },
436
+ ].map((section) => ({
437
+ ...section,
438
+ rows: section.rows.length ? section.rows : ["No history yet."],
439
+ }));
440
+ }