@h-rig/run-plugin 0.0.6-alpha.186
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/README.md +1 -0
- package/dist/src/plugin.d.ts +4 -0
- package/dist/src/plugin.js +4319 -0
- package/dist/src/read-model/inspect-command.d.ts +19 -0
- package/dist/src/read-model/inspect-command.js +341 -0
- package/dist/src/read-model/plugin.d.ts +4 -0
- package/dist/src/read-model/plugin.js +2550 -0
- package/dist/src/read-model/read-model-backend/diagnostics.d.ts +9 -0
- package/dist/src/read-model/read-model-backend/diagnostics.js +51 -0
- package/dist/src/read-model/read-model-backend/guard.d.ts +4 -0
- package/dist/src/read-model/read-model-backend/guard.js +25 -0
- package/dist/src/read-model/read-model-backend/inbox.d.ts +23 -0
- package/dist/src/read-model/read-model-backend/inbox.js +669 -0
- package/dist/src/read-model/read-model-backend/index.d.ts +8 -0
- package/dist/src/read-model/read-model-backend/index.js +1163 -0
- package/dist/src/read-model/read-model-backend/inspect.d.ts +26 -0
- package/dist/src/read-model/read-model-backend/inspect.js +770 -0
- package/dist/src/read-model/read-model-backend/projection.d.ts +39 -0
- package/dist/src/read-model/read-model-backend/projection.js +669 -0
- package/dist/src/read-model/read-model-backend/run-status.d.ts +27 -0
- package/dist/src/read-model/read-model-backend/run-status.js +237 -0
- package/dist/src/read-model/read-model-backend/stats.d.ts +12 -0
- package/dist/src/read-model/read-model-backend/stats.js +800 -0
- package/dist/src/read-model/read-model-service.d.ts +2 -0
- package/dist/src/read-model/read-model-service.js +1725 -0
- package/dist/src/read-model/reconcile.d.ts +23 -0
- package/dist/src/read-model/reconcile.js +306 -0
- package/dist/src/read-model/run-format.d.ts +23 -0
- package/dist/src/read-model/run-format.js +202 -0
- package/dist/src/read-model/runs-screen.d.ts +14 -0
- package/dist/src/read-model/runs-screen.js +217 -0
- package/dist/src/read-model/session-journal.d.ts +26 -0
- package/dist/src/read-model/session-journal.js +355 -0
- package/dist/src/read-model/stats-command.d.ts +16 -0
- package/dist/src/read-model/stats-command.js +88 -0
- package/dist/src/read-model/stats-format.d.ts +1 -0
- package/dist/src/read-model/stats-format.js +8 -0
- package/dist/src/worker/autohost.d.ts +11 -0
- package/dist/src/worker/autohost.js +858 -0
- package/dist/src/worker/constants.d.ts +3 -0
- package/dist/src/worker/constants.js +10 -0
- package/dist/src/worker/extension.d.ts +14 -0
- package/dist/src/worker/extension.js +881 -0
- package/dist/src/worker/host.d.ts +1 -0
- package/dist/src/worker/host.js +1 -0
- package/dist/src/worker/inbox-command.d.ts +23 -0
- package/dist/src/worker/inbox-command.js +163 -0
- package/dist/src/worker/index.d.ts +2 -0
- package/dist/src/worker/index.js +1767 -0
- package/dist/src/worker/local-run-changes.d.ts +3 -0
- package/dist/src/worker/local-run-changes.js +65 -0
- package/dist/src/worker/notifications.d.ts +1 -0
- package/dist/src/worker/notifications.js +27 -0
- package/dist/src/worker/notify-cap.d.ts +11 -0
- package/dist/src/worker/notify-cap.js +13 -0
- package/dist/src/worker/panel-plugin.d.ts +11 -0
- package/dist/src/worker/panel-plugin.js +37 -0
- package/dist/src/worker/plugin.d.ts +3 -0
- package/dist/src/worker/plugin.js +1761 -0
- package/dist/src/worker/run-control-service.d.ts +2 -0
- package/dist/src/worker/run-control-service.js +210 -0
- package/dist/src/worker/session-journal-writer.d.ts +4 -0
- package/dist/src/worker/session-journal-writer.js +184 -0
- package/dist/src/worker/stall.d.ts +21 -0
- package/dist/src/worker/stall.js +55 -0
- package/dist/src/worker/utils.d.ts +21 -0
- package/dist/src/worker/utils.js +29 -0
- package/dist/src/worker/workflow-journal-writer.d.ts +7 -0
- package/dist/src/worker/workflow-journal-writer.js +76 -0
- package/package.json +47 -0
|
@@ -0,0 +1,2550 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __returnValue = (v) => v;
|
|
4
|
+
function __exportSetter(name, newValue) {
|
|
5
|
+
this[name] = __returnValue.bind(null, newValue);
|
|
6
|
+
}
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, {
|
|
10
|
+
get: all[name],
|
|
11
|
+
enumerable: true,
|
|
12
|
+
configurable: true,
|
|
13
|
+
set: __exportSetter.bind(all, name)
|
|
14
|
+
});
|
|
15
|
+
};
|
|
16
|
+
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
17
|
+
var __require = import.meta.require;
|
|
18
|
+
|
|
19
|
+
// packages/run-plugin/src/read-model/stats-format.ts
|
|
20
|
+
function formatRatePercent(value) {
|
|
21
|
+
return value === null ? "\u2014" : `${Math.round(value * 100)}%`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// packages/run-plugin/src/read-model/session-journal.ts
|
|
25
|
+
var exports_session_journal = {};
|
|
26
|
+
__export(exports_session_journal, {
|
|
27
|
+
timelineEntriesFromCustomEntries: () => timelineEntriesFromCustomEntries,
|
|
28
|
+
sessionIdFromSessionFile: () => sessionIdFromSessionFile,
|
|
29
|
+
runSessionJournalCodec: () => runSessionJournalCodec,
|
|
30
|
+
projectRunFromSession: () => projectRunFromSession,
|
|
31
|
+
parseStopSentinel: () => parseStopSentinel,
|
|
32
|
+
parseResumeSentinel: () => parseResumeSentinel,
|
|
33
|
+
parsePauseSentinel: () => parsePauseSentinel,
|
|
34
|
+
parseInboxResolutionSentinel: () => parseInboxResolutionSentinel,
|
|
35
|
+
latestTimelineEntriesFromCustomEntries: () => latestTimelineEntriesFromCustomEntries,
|
|
36
|
+
isTerminalRunStatus: () => isTerminalRunStatus,
|
|
37
|
+
foldRunSessionEntries: () => foldRunSessionEntries
|
|
38
|
+
});
|
|
39
|
+
import { Schema } from "effect";
|
|
40
|
+
import {
|
|
41
|
+
CUSTOM_TYPE_FOR,
|
|
42
|
+
RIG_CONTROL_SENTINEL_END,
|
|
43
|
+
RIG_INBOX_RESOLUTION_SENTINEL,
|
|
44
|
+
RIG_PAUSE_SENTINEL,
|
|
45
|
+
RIG_RESUME_SENTINEL,
|
|
46
|
+
RIG_STOP_SENTINEL,
|
|
47
|
+
RIG_STOP_SENTINEL_END,
|
|
48
|
+
RunJournalEvent,
|
|
49
|
+
TYPE_FOR_CUSTOM
|
|
50
|
+
} from "@rig/contracts";
|
|
51
|
+
function isTerminalRunStatus(status) {
|
|
52
|
+
return TERMINAL_RUN_STATUSES.includes(status);
|
|
53
|
+
}
|
|
54
|
+
function canTransitionRunStatus(from, to) {
|
|
55
|
+
if (from === null)
|
|
56
|
+
return true;
|
|
57
|
+
if (from === to)
|
|
58
|
+
return true;
|
|
59
|
+
return RUN_STATUS_TRANSITIONS[from].includes(to);
|
|
60
|
+
}
|
|
61
|
+
function assertRunStatusTransition(from, to) {
|
|
62
|
+
if (!canTransitionRunStatus(from, to)) {
|
|
63
|
+
throw new Error(`Illegal run status transition: ${from ?? "(none)"} -> ${to}. ` + `Allowed from ${from ?? "(none)"}: ${from ? RUN_STATUS_TRANSITIONS[from].join(", ") : "(any)"}.`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function reduceRunJournal(events, runId = null) {
|
|
67
|
+
let record = {};
|
|
68
|
+
let status = null;
|
|
69
|
+
const statusHistory = [];
|
|
70
|
+
const pendingApprovals = new Map;
|
|
71
|
+
const resolvedApprovals = [];
|
|
72
|
+
const pendingUserInputs = new Map;
|
|
73
|
+
const resolvedUserInputs = [];
|
|
74
|
+
const closeoutPhases = [];
|
|
75
|
+
let resolvedPipeline = null;
|
|
76
|
+
const stageOutcomes = [];
|
|
77
|
+
const anomalies = [];
|
|
78
|
+
let steeringCount = 0;
|
|
79
|
+
let stallCount = 0;
|
|
80
|
+
let lastSeq = 0;
|
|
81
|
+
let lastEventAt = null;
|
|
82
|
+
const projectedRunId = runId ?? events[0]?.runId ?? null;
|
|
83
|
+
for (const event of events) {
|
|
84
|
+
lastSeq = event.seq;
|
|
85
|
+
lastEventAt = event.at;
|
|
86
|
+
switch (event.type) {
|
|
87
|
+
case "status-changed": {
|
|
88
|
+
if (!canTransitionRunStatus(status, event.to)) {
|
|
89
|
+
anomalies.push({ seq: event.seq, kind: "illegal-transition", detail: `${status ?? "(none)"} -> ${event.to}` });
|
|
90
|
+
}
|
|
91
|
+
statusHistory.push({ seq: event.seq, at: event.at, from: status, to: event.to, reason: event.reason ?? null });
|
|
92
|
+
const wasTerminal = status !== null && isTerminalRunStatus(status);
|
|
93
|
+
status = event.to;
|
|
94
|
+
record = { ...record, updatedAt: event.at };
|
|
95
|
+
if (isTerminalRunStatus(event.to) && !record.completedAt)
|
|
96
|
+
record = { ...record, completedAt: event.at };
|
|
97
|
+
if (!isTerminalRunStatus(event.to) && wasTerminal)
|
|
98
|
+
record = { ...record, completedAt: null };
|
|
99
|
+
if (event.to === "running" && !record.startedAt)
|
|
100
|
+
record = { ...record, startedAt: event.at };
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
case "record-patch": {
|
|
104
|
+
const next = { ...record };
|
|
105
|
+
for (const [key, value] of Object.entries(event.patch)) {
|
|
106
|
+
if (value !== undefined)
|
|
107
|
+
next[key] = value;
|
|
108
|
+
}
|
|
109
|
+
next.updatedAt = event.patch.updatedAt ?? event.at;
|
|
110
|
+
record = next;
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
case "approval-requested": {
|
|
114
|
+
pendingApprovals.set(event.requestId, {
|
|
115
|
+
requestId: event.requestId,
|
|
116
|
+
requestKind: event.requestKind,
|
|
117
|
+
actionId: event.actionId ?? null,
|
|
118
|
+
payload: event.payload,
|
|
119
|
+
requestedAt: event.at
|
|
120
|
+
});
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
case "approval-resolved": {
|
|
124
|
+
const pending = pendingApprovals.get(event.requestId);
|
|
125
|
+
if (!pending) {
|
|
126
|
+
const alreadyResolved = resolvedApprovals.some((entry) => entry.requestId === event.requestId);
|
|
127
|
+
anomalies.push({ seq: event.seq, kind: alreadyResolved ? "duplicate-resolution" : "unknown-request", detail: `approval ${event.requestId}` });
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
pendingApprovals.delete(event.requestId);
|
|
131
|
+
resolvedApprovals.push({ ...pending, decision: event.decision, note: event.note ?? null, actor: event.actor, resolvedAt: event.at });
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
case "input-requested": {
|
|
135
|
+
pendingUserInputs.set(event.requestId, {
|
|
136
|
+
requestId: event.requestId,
|
|
137
|
+
requestKind: "user-input",
|
|
138
|
+
actionId: null,
|
|
139
|
+
payload: event.payload,
|
|
140
|
+
requestedAt: event.at
|
|
141
|
+
});
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
case "input-resolved": {
|
|
145
|
+
const pending = pendingUserInputs.get(event.requestId);
|
|
146
|
+
if (!pending) {
|
|
147
|
+
const alreadyResolved = resolvedUserInputs.some((entry) => entry.requestId === event.requestId);
|
|
148
|
+
anomalies.push({ seq: event.seq, kind: alreadyResolved ? "duplicate-resolution" : "unknown-request", detail: `user-input ${event.requestId}` });
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
pendingUserInputs.delete(event.requestId);
|
|
152
|
+
resolvedUserInputs.push({ ...pending, answers: event.answers, actor: event.actor, resolvedAt: event.at });
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
case "steering":
|
|
156
|
+
steeringCount += 1;
|
|
157
|
+
break;
|
|
158
|
+
case "adopted":
|
|
159
|
+
record = { ...record, pid: event.pid, updatedAt: event.at };
|
|
160
|
+
break;
|
|
161
|
+
case "stall-detected":
|
|
162
|
+
stallCount += 1;
|
|
163
|
+
break;
|
|
164
|
+
case "closeout-phase":
|
|
165
|
+
closeoutPhases.push({ seq: event.seq, at: event.at, phase: event.phase, outcome: event.outcome, detail: event.detail ?? null });
|
|
166
|
+
break;
|
|
167
|
+
case "pipeline-resolved":
|
|
168
|
+
resolvedPipeline = event.pipeline;
|
|
169
|
+
break;
|
|
170
|
+
case "stage-outcome":
|
|
171
|
+
stageOutcomes.push({ seq: event.seq, at: event.at, outcome: event.outcome });
|
|
172
|
+
break;
|
|
173
|
+
case "timeline-entry":
|
|
174
|
+
case "log-entry":
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
runId: projectedRunId,
|
|
180
|
+
record,
|
|
181
|
+
status,
|
|
182
|
+
statusHistory,
|
|
183
|
+
pendingApprovals: [...pendingApprovals.values()],
|
|
184
|
+
resolvedApprovals,
|
|
185
|
+
pendingUserInputs: [...pendingUserInputs.values()],
|
|
186
|
+
resolvedUserInputs,
|
|
187
|
+
steeringCount,
|
|
188
|
+
stallCount,
|
|
189
|
+
closeoutPhases,
|
|
190
|
+
resolvedPipeline,
|
|
191
|
+
stageOutcomes,
|
|
192
|
+
lastSeq,
|
|
193
|
+
lastEventAt,
|
|
194
|
+
anomalies
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
function sessionIdFromSessionFile(sessionPath) {
|
|
198
|
+
if (!sessionPath)
|
|
199
|
+
return null;
|
|
200
|
+
const file = sessionPath.split(/[\\/]/).pop() ?? "";
|
|
201
|
+
const match = file.match(/_([0-9a-fA-F][0-9a-fA-F-]{7,})\.jsonl$/);
|
|
202
|
+
return match?.[1] ?? null;
|
|
203
|
+
}
|
|
204
|
+
function isRunSessionCustomType(customType) {
|
|
205
|
+
return customType !== undefined && Object.hasOwn(TYPE_FOR_CUSTOM, customType);
|
|
206
|
+
}
|
|
207
|
+
function foldRunSessionEntries(entries, runId) {
|
|
208
|
+
const events = [];
|
|
209
|
+
entries.forEach((entry, index) => {
|
|
210
|
+
if (entry.type !== "custom" || !isRunSessionCustomType(entry.customType))
|
|
211
|
+
return;
|
|
212
|
+
const data = entry.data !== null && typeof entry.data === "object" ? entry.data : {};
|
|
213
|
+
const stamped = {
|
|
214
|
+
v: 1,
|
|
215
|
+
seq: index + 1,
|
|
216
|
+
at: typeof data.at === "string" ? data.at : new Date(0).toISOString(),
|
|
217
|
+
runId,
|
|
218
|
+
...data,
|
|
219
|
+
type: TYPE_FOR_CUSTOM[entry.customType]
|
|
220
|
+
};
|
|
221
|
+
try {
|
|
222
|
+
events.push(decodeRunJournalEvent(stamped));
|
|
223
|
+
} catch {}
|
|
224
|
+
});
|
|
225
|
+
return reduceRunJournal(events, runId);
|
|
226
|
+
}
|
|
227
|
+
function projectRunFromSession(source, runId) {
|
|
228
|
+
const entries = "getEntries" in source ? source.getEntries() : source;
|
|
229
|
+
return foldRunSessionEntries(entries, runId);
|
|
230
|
+
}
|
|
231
|
+
function isRecord(value) {
|
|
232
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
233
|
+
}
|
|
234
|
+
function timelineEntryFromCustomEntry(entry) {
|
|
235
|
+
if (entry.customType !== CUSTOM_TYPE_FOR["timeline-entry"] || !isRecord(entry.data))
|
|
236
|
+
return null;
|
|
237
|
+
const payload = isRecord(entry.data.payload) ? entry.data.payload : entry.data;
|
|
238
|
+
const type = typeof payload.type === "string" ? payload.type : "timeline";
|
|
239
|
+
const stage = typeof payload.stage === "string" ? payload.stage : typeof payload.name === "string" ? payload.name : null;
|
|
240
|
+
const status = typeof payload.status === "string" ? payload.status : typeof payload.outcome === "string" ? payload.outcome : null;
|
|
241
|
+
const detail = typeof payload.detail === "string" ? payload.detail : typeof payload.message === "string" ? payload.message : null;
|
|
242
|
+
const at = typeof entry.data.at === "string" ? entry.data.at : typeof payload.at === "string" ? payload.at : null;
|
|
243
|
+
return { at, type, stage, status, detail };
|
|
244
|
+
}
|
|
245
|
+
function timelineEntriesFromCustomEntries(entries) {
|
|
246
|
+
return entries.flatMap((entry) => {
|
|
247
|
+
const timelineEntry = timelineEntryFromCustomEntry(entry);
|
|
248
|
+
return timelineEntry ? [timelineEntry] : [];
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
function latestTimelineEntriesFromCustomEntries(entries, limit) {
|
|
252
|
+
if (limit <= 0)
|
|
253
|
+
return [];
|
|
254
|
+
const timeline = [];
|
|
255
|
+
for (let index = entries.length - 1;index >= 0 && timeline.length < limit; index -= 1) {
|
|
256
|
+
const timelineEntry = timelineEntryFromCustomEntry(entries[index]);
|
|
257
|
+
if (timelineEntry)
|
|
258
|
+
timeline.push(timelineEntry);
|
|
259
|
+
}
|
|
260
|
+
timeline.reverse();
|
|
261
|
+
return timeline;
|
|
262
|
+
}
|
|
263
|
+
function parseStopSentinel(text, expectedRunId) {
|
|
264
|
+
const start = text.indexOf(RIG_STOP_SENTINEL);
|
|
265
|
+
if (start < 0)
|
|
266
|
+
return null;
|
|
267
|
+
const end = text.indexOf(RIG_STOP_SENTINEL_END, start);
|
|
268
|
+
const body = text.slice(start + RIG_STOP_SENTINEL.length, end >= 0 ? end : undefined).trim();
|
|
269
|
+
const runId = body.match(/(?:^|\s)runId=([^\s>]+)/)?.[1] ?? "";
|
|
270
|
+
if (runId && runId !== expectedRunId)
|
|
271
|
+
return null;
|
|
272
|
+
const reason = body.match(/(?:^|\s)reason=(.+)$/)?.[1]?.trim() ?? null;
|
|
273
|
+
return { reason };
|
|
274
|
+
}
|
|
275
|
+
function parseControlSentinel(marker, text, expectedRunId) {
|
|
276
|
+
const start = text.indexOf(marker);
|
|
277
|
+
if (start < 0)
|
|
278
|
+
return null;
|
|
279
|
+
const end = text.indexOf(RIG_CONTROL_SENTINEL_END, start);
|
|
280
|
+
const body = text.slice(start + marker.length, end >= 0 ? end : undefined).trim();
|
|
281
|
+
const runId = body.match(/(?:^|\s)runId=([^\s>]+)/)?.[1] ?? "";
|
|
282
|
+
if (runId && runId !== expectedRunId)
|
|
283
|
+
return null;
|
|
284
|
+
const requestedBy = body.match(/(?:^|\s)requestedBy=([^\s>]+)/)?.[1] ?? null;
|
|
285
|
+
return { requestedBy };
|
|
286
|
+
}
|
|
287
|
+
function parsePauseSentinel(text, expectedRunId) {
|
|
288
|
+
return parseControlSentinel(RIG_PAUSE_SENTINEL, text, expectedRunId);
|
|
289
|
+
}
|
|
290
|
+
function parseResumeSentinel(text, expectedRunId) {
|
|
291
|
+
return parseControlSentinel(RIG_RESUME_SENTINEL, text, expectedRunId);
|
|
292
|
+
}
|
|
293
|
+
function decodeInboxResolutionPayload(payload) {
|
|
294
|
+
try {
|
|
295
|
+
const parsed = JSON.parse(decodeURIComponent(payload));
|
|
296
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
297
|
+
return null;
|
|
298
|
+
const record = parsed;
|
|
299
|
+
if (record.kind === "approval") {
|
|
300
|
+
const requestId = typeof record.requestId === "string" ? record.requestId.trim() : "";
|
|
301
|
+
const decision = record.decision === "approve" || record.decision === "reject" ? record.decision : null;
|
|
302
|
+
const note = typeof record.note === "string" ? record.note : record.note === null ? null : undefined;
|
|
303
|
+
if (!requestId || !decision)
|
|
304
|
+
return null;
|
|
305
|
+
return { kind: "approval", requestId, decision, ...note !== undefined ? { note } : {} };
|
|
306
|
+
}
|
|
307
|
+
if (record.kind === "input") {
|
|
308
|
+
const requestId = typeof record.requestId === "string" ? record.requestId.trim() : "";
|
|
309
|
+
const answers = record.answers && typeof record.answers === "object" && !Array.isArray(record.answers) ? Object.fromEntries(Object.entries(record.answers).filter((entry) => typeof entry[1] === "string")) : null;
|
|
310
|
+
if (!requestId || !answers)
|
|
311
|
+
return null;
|
|
312
|
+
return { kind: "input", requestId, answers };
|
|
313
|
+
}
|
|
314
|
+
} catch {
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
function parseInboxResolutionSentinel(text, expectedRunId) {
|
|
320
|
+
const start = text.indexOf(RIG_INBOX_RESOLUTION_SENTINEL);
|
|
321
|
+
if (start < 0)
|
|
322
|
+
return null;
|
|
323
|
+
const end = text.indexOf(RIG_CONTROL_SENTINEL_END, start);
|
|
324
|
+
const body = text.slice(start + RIG_INBOX_RESOLUTION_SENTINEL.length, end >= 0 ? end : undefined).trim();
|
|
325
|
+
const runId = body.match(/(?:^|\s)runId=([^\s>]+)/)?.[1] ?? "";
|
|
326
|
+
if (runId && runId !== expectedRunId)
|
|
327
|
+
return null;
|
|
328
|
+
const requestedBy = body.match(/(?:^|\s)requestedBy=([^\s>]+)/)?.[1] ?? null;
|
|
329
|
+
const payload = body.match(/(?:^|\s)data=([^\s>]+)/)?.[1] ?? "";
|
|
330
|
+
const decoded = decodeInboxResolutionPayload(payload);
|
|
331
|
+
if (!decoded)
|
|
332
|
+
return null;
|
|
333
|
+
return { ...decoded, requestedBy };
|
|
334
|
+
}
|
|
335
|
+
var decodeRunJournalEvent = (value) => Schema.decodeUnknownSync(RunJournalEvent)(value), RUN_STATUS_TRANSITIONS, TERMINAL_RUN_STATUSES, runSessionJournalCodec;
|
|
336
|
+
var init_session_journal = __esm(() => {
|
|
337
|
+
RUN_STATUS_TRANSITIONS = {
|
|
338
|
+
created: ["queued", "preparing", "running", "failed", "stopped"],
|
|
339
|
+
queued: ["preparing", "running", "failed", "stopped"],
|
|
340
|
+
preparing: ["queued", "running", "needs-attention", "failed", "stopped"],
|
|
341
|
+
running: [
|
|
342
|
+
"queued",
|
|
343
|
+
"waiting-approval",
|
|
344
|
+
"waiting-user-input",
|
|
345
|
+
"paused",
|
|
346
|
+
"validating",
|
|
347
|
+
"reviewing",
|
|
348
|
+
"closing-out",
|
|
349
|
+
"needs-attention",
|
|
350
|
+
"completed",
|
|
351
|
+
"failed",
|
|
352
|
+
"stopped"
|
|
353
|
+
],
|
|
354
|
+
"waiting-approval": ["running", "needs-attention", "failed", "stopped"],
|
|
355
|
+
"waiting-user-input": ["running", "needs-attention", "failed", "stopped"],
|
|
356
|
+
paused: ["running", "failed", "stopped"],
|
|
357
|
+
validating: ["running", "reviewing", "closing-out", "needs-attention", "completed", "failed", "stopped"],
|
|
358
|
+
reviewing: ["running", "validating", "closing-out", "needs-attention", "completed", "failed", "stopped"],
|
|
359
|
+
"closing-out": ["running", "needs-attention", "completed", "failed", "stopped"],
|
|
360
|
+
"needs-attention": ["queued", "preparing", "running", "closing-out", "completed", "failed", "stopped"],
|
|
361
|
+
completed: [],
|
|
362
|
+
failed: ["queued", "preparing", "running", "closing-out"],
|
|
363
|
+
stopped: ["queued", "preparing", "running", "closing-out"]
|
|
364
|
+
};
|
|
365
|
+
TERMINAL_RUN_STATUSES = ["completed", "failed", "stopped"];
|
|
366
|
+
runSessionJournalCodec = {
|
|
367
|
+
foldRunSessionEntries,
|
|
368
|
+
projectRunFromSession,
|
|
369
|
+
isTerminalRunStatus,
|
|
370
|
+
canTransitionRunStatus,
|
|
371
|
+
assertRunStatusTransition,
|
|
372
|
+
sessionIdFromSessionFile,
|
|
373
|
+
timelineEntriesFromCustomEntries,
|
|
374
|
+
latestTimelineEntriesFromCustomEntries,
|
|
375
|
+
parseStopSentinel,
|
|
376
|
+
parsePauseSentinel,
|
|
377
|
+
parseResumeSentinel,
|
|
378
|
+
parseInboxResolutionSentinel
|
|
379
|
+
};
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
// packages/run-plugin/src/read-model/reconcile.ts
|
|
383
|
+
import { defineCapability } from "@rig/core/capability";
|
|
384
|
+
import { loadCapabilityForRoot } from "@rig/core/capability-loaders";
|
|
385
|
+
import {
|
|
386
|
+
RUN_SESSION_JOURNAL_WRITER
|
|
387
|
+
} from "@rig/contracts";
|
|
388
|
+
async function loadCollabApi() {
|
|
389
|
+
collabApiPromise ??= import("@oh-my-pi/pi-coding-agent/collab-api").then((api) => api).catch(() => null);
|
|
390
|
+
return collabApiPromise;
|
|
391
|
+
}
|
|
392
|
+
function pidExists(pid) {
|
|
393
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
394
|
+
return false;
|
|
395
|
+
try {
|
|
396
|
+
process.kill(pid, 0);
|
|
397
|
+
return true;
|
|
398
|
+
} catch {
|
|
399
|
+
return false;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
function projectionRunId(item) {
|
|
403
|
+
if (item.runId?.trim())
|
|
404
|
+
return item.runId.trim();
|
|
405
|
+
if (item.collab?.sessionId?.trim())
|
|
406
|
+
return item.collab.sessionId.trim();
|
|
407
|
+
if (item.session.id?.trim())
|
|
408
|
+
return item.session.id.trim();
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
function isLocallyDiscovered(item) {
|
|
412
|
+
return item.source === "session-list";
|
|
413
|
+
}
|
|
414
|
+
function isActiveStatus(status) {
|
|
415
|
+
if (status === null)
|
|
416
|
+
return false;
|
|
417
|
+
return !isTerminalRunStatus(status);
|
|
418
|
+
}
|
|
419
|
+
function shouldFlip(item, status, exists) {
|
|
420
|
+
if (!isActiveStatus(status))
|
|
421
|
+
return false;
|
|
422
|
+
if (item.collab?.stale === true)
|
|
423
|
+
return true;
|
|
424
|
+
const pid = item.collab?.pid;
|
|
425
|
+
return isLocallyDiscovered(item) && pid !== undefined && ACTIVE_LOCAL_RUN_STATUSES.has(status) && !exists(pid);
|
|
426
|
+
}
|
|
427
|
+
async function reconcileActiveRuns(input, deps = {}) {
|
|
428
|
+
const collabApi = deps.listCollabSessionProjections ? null : await loadCollabApi();
|
|
429
|
+
const listProjections = deps.listCollabSessionProjections ?? collabApi?.listCollabSessionProjections;
|
|
430
|
+
const journalWriter = deps.journalWriter ?? await loadCapabilityForRoot(input.workspaceRoot, RunSessionJournalWriterCap);
|
|
431
|
+
if (!journalWriter)
|
|
432
|
+
return { flipped: [], resumable: [] };
|
|
433
|
+
const exists = deps.processExists ?? pidExists;
|
|
434
|
+
if (!listProjections)
|
|
435
|
+
return { flipped: [], resumable: [] };
|
|
436
|
+
const projections = await listProjections(input.identityFilter);
|
|
437
|
+
const flipped = [];
|
|
438
|
+
for (const item of projections) {
|
|
439
|
+
const runId = projectionRunId(item);
|
|
440
|
+
const sessionPath = item.session.path || item.collab?.sessionPath || "";
|
|
441
|
+
if (!runId || !sessionPath)
|
|
442
|
+
continue;
|
|
443
|
+
const projection = projectRunFromSession(item.customEntries, runId);
|
|
444
|
+
const status = projection.status;
|
|
445
|
+
if (status === null || !shouldFlip(item, status, exists))
|
|
446
|
+
continue;
|
|
447
|
+
const result = await journalWriter.reconcileDeadPid({
|
|
448
|
+
projectRoot: input.workspaceRoot,
|
|
449
|
+
runId,
|
|
450
|
+
sessionPath,
|
|
451
|
+
reason: "lazy-reconcile:dead-pid"
|
|
452
|
+
});
|
|
453
|
+
if (result.updated)
|
|
454
|
+
flipped.push({ runId, sessionPath, reason: "lazy-reconcile:dead-pid" });
|
|
455
|
+
}
|
|
456
|
+
return { flipped, resumable: flipped };
|
|
457
|
+
}
|
|
458
|
+
var RunSessionJournalWriterCap, collabApiPromise = null, ACTIVE_LOCAL_RUN_STATUSES;
|
|
459
|
+
var init_reconcile = __esm(() => {
|
|
460
|
+
init_session_journal();
|
|
461
|
+
RunSessionJournalWriterCap = defineCapability(RUN_SESSION_JOURNAL_WRITER);
|
|
462
|
+
ACTIVE_LOCAL_RUN_STATUSES = new Set([
|
|
463
|
+
"created",
|
|
464
|
+
"preparing",
|
|
465
|
+
"running",
|
|
466
|
+
"validating",
|
|
467
|
+
"reviewing",
|
|
468
|
+
"closing-out"
|
|
469
|
+
]);
|
|
470
|
+
});
|
|
471
|
+
|
|
472
|
+
// packages/run-plugin/src/read-model/run-format.ts
|
|
473
|
+
import pc from "picocolors";
|
|
474
|
+
import { formatSection, formatSuccessCard, formatNextSteps } from "@rig/std-shared/cli-format";
|
|
475
|
+
function projectedStatusRole(value) {
|
|
476
|
+
return typeof value === "string" && STATUS_ROLES.has(value) ? value : null;
|
|
477
|
+
}
|
|
478
|
+
function truncate(value, width) {
|
|
479
|
+
return value.length <= width ? value : `${value.slice(0, Math.max(0, width - 1))}\u2026`;
|
|
480
|
+
}
|
|
481
|
+
function pad(value, width) {
|
|
482
|
+
return value.length >= width ? value : `${value}${" ".repeat(width - value.length)}`;
|
|
483
|
+
}
|
|
484
|
+
function colorForRole(role) {
|
|
485
|
+
switch (role) {
|
|
486
|
+
case "success":
|
|
487
|
+
return pc.green;
|
|
488
|
+
case "action-yellow":
|
|
489
|
+
return pc.yellow;
|
|
490
|
+
case "active-cyan":
|
|
491
|
+
return pc.cyan;
|
|
492
|
+
case "failure":
|
|
493
|
+
return pc.red;
|
|
494
|
+
case "muted":
|
|
495
|
+
case "neutral":
|
|
496
|
+
return pc.dim;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
function inboxStatusRole(record) {
|
|
500
|
+
const projected = projectedStatusRole(record.statusRole);
|
|
501
|
+
if (projected)
|
|
502
|
+
return projected;
|
|
503
|
+
return record.status === "pending" ? "active-cyan" : "neutral";
|
|
504
|
+
}
|
|
505
|
+
function compactDate(value) {
|
|
506
|
+
const parsed = Date.parse(value);
|
|
507
|
+
if (!Number.isFinite(parsed))
|
|
508
|
+
return value;
|
|
509
|
+
return new Date(parsed).toISOString().replace("T", " ").replace(/\.\d{3}Z$/, "Z");
|
|
510
|
+
}
|
|
511
|
+
function firstString(record, keys, fallback = "") {
|
|
512
|
+
for (const key of keys) {
|
|
513
|
+
const value = record[key];
|
|
514
|
+
if (typeof value === "string" && value.trim())
|
|
515
|
+
return value;
|
|
516
|
+
}
|
|
517
|
+
return fallback;
|
|
518
|
+
}
|
|
519
|
+
function runIdOf(run) {
|
|
520
|
+
return firstString(run, ["runId", "id"], "(unknown-run)");
|
|
521
|
+
}
|
|
522
|
+
function taskIdOf(run) {
|
|
523
|
+
return firstString(run, ["taskId", "task", "task_id"]);
|
|
524
|
+
}
|
|
525
|
+
function runTitleOf(run) {
|
|
526
|
+
return firstString(run, ["title", "summary", "name"], taskIdOf(run) || "(untitled)");
|
|
527
|
+
}
|
|
528
|
+
function requestIdOf(entry) {
|
|
529
|
+
return firstString(entry, ["requestId", "id", "approvalId", "inputId"], "(unknown-request)");
|
|
530
|
+
}
|
|
531
|
+
function runLikeStatusText(run) {
|
|
532
|
+
const record = run;
|
|
533
|
+
const status = typeof record.status === "string" ? record.status.trim() : "";
|
|
534
|
+
return status || "unclassified";
|
|
535
|
+
}
|
|
536
|
+
function runLikeStatusColor(run) {
|
|
537
|
+
const record = run;
|
|
538
|
+
return colorForRole(projectedStatusRole(record.statusRole) ?? "neutral");
|
|
539
|
+
}
|
|
540
|
+
function formatStatusPill(status, role) {
|
|
541
|
+
const label = status || "unclassified";
|
|
542
|
+
return colorForRole(role ?? "neutral")(`\u25CF ${label}`);
|
|
543
|
+
}
|
|
544
|
+
function formatLegacyAutomationSurface() {
|
|
545
|
+
return [];
|
|
546
|
+
}
|
|
547
|
+
function formatRunList(runs, options = {}) {
|
|
548
|
+
if (runs.length === 0) {
|
|
549
|
+
return [
|
|
550
|
+
formatSection("Runs", "none recorded"),
|
|
551
|
+
options.source === "server" ? dim("No runs recorded on the selected server.") : dim("No runs recorded in local state."),
|
|
552
|
+
"",
|
|
553
|
+
...formatLegacyAutomationSurface()
|
|
554
|
+
].join(`
|
|
555
|
+
`);
|
|
556
|
+
}
|
|
557
|
+
const body = runs.map((run) => {
|
|
558
|
+
const row = run;
|
|
559
|
+
const runId = runIdOf(row);
|
|
560
|
+
const status = runLikeStatusText(run);
|
|
561
|
+
const runtime = firstString(row, ["runtime", "runtimeAdapter"], "");
|
|
562
|
+
return [
|
|
563
|
+
pc.bold(runId),
|
|
564
|
+
runLikeStatusColor(run)(pad(truncate(status, 12), 12)),
|
|
565
|
+
`${runTitleOf(row)}${runtime ? dim(` ${runtime}`) : ""}`
|
|
566
|
+
].join(" ");
|
|
567
|
+
});
|
|
568
|
+
return [formatSection("Runs", options.source === "server" ? "selected server" : "local state"), ...body, "", ...formatLegacyAutomationSurface()].join(`
|
|
569
|
+
`);
|
|
570
|
+
}
|
|
571
|
+
function formatSubmittedRun(input) {
|
|
572
|
+
return formatSuccessCard("Run submitted", [
|
|
573
|
+
["run", input.runId],
|
|
574
|
+
["task", input.taskId ?? undefined],
|
|
575
|
+
["title", input.title ?? undefined],
|
|
576
|
+
["queue", input.queuePosition ?? undefined]
|
|
577
|
+
]);
|
|
578
|
+
}
|
|
579
|
+
function formatRunCard(run, options = {}) {
|
|
580
|
+
const record = run;
|
|
581
|
+
const lines = [formatSection(options.title ?? "Run")];
|
|
582
|
+
for (const [label, value] of [
|
|
583
|
+
["run", runIdOf(record)],
|
|
584
|
+
["task", taskIdOf(record)],
|
|
585
|
+
["title", runTitleOf(record)],
|
|
586
|
+
["status", runLikeStatusText(run)],
|
|
587
|
+
["runtime", firstString(record, ["runtime", "runtimeAdapter"], "")],
|
|
588
|
+
["created", firstString(record, ["createdAt"], "")],
|
|
589
|
+
["updated", firstString(record, ["updatedAt"], "")]
|
|
590
|
+
]) {
|
|
591
|
+
if (value)
|
|
592
|
+
lines.push(`${faintBar} ${dim(label.padEnd(12))} ${label === "status" ? runLikeStatusColor(run)(value) : label === "created" || label === "updated" ? compactDate(value) : value}`);
|
|
593
|
+
}
|
|
594
|
+
const errorSummary = firstString(record, ["errorSummary"]);
|
|
595
|
+
if (errorSummary)
|
|
596
|
+
lines.push(`${faintBar} Error: ${errorSummary}`);
|
|
597
|
+
return lines.join(`
|
|
598
|
+
`);
|
|
599
|
+
}
|
|
600
|
+
function formatRunStatus(summary, options = {}) {
|
|
601
|
+
const activeRuns = summary.activeRuns ?? [];
|
|
602
|
+
const recentRuns = summary.recentRuns ?? [];
|
|
603
|
+
const lines = [formatSection("Run status", options.source === "server" ? "selected server" : "local state")];
|
|
604
|
+
lines.push(`Active runs (${activeRuns.length})`);
|
|
605
|
+
if (activeRuns.length === 0)
|
|
606
|
+
lines.push(dim("No active runs."));
|
|
607
|
+
else
|
|
608
|
+
for (const run of activeRuns)
|
|
609
|
+
lines.push(formatRunSummaryLine(run));
|
|
610
|
+
lines.push("", `Recent runs (${recentRuns.length})`);
|
|
611
|
+
if (recentRuns.length === 0)
|
|
612
|
+
lines.push(dim("No recent terminal runs."));
|
|
613
|
+
else
|
|
614
|
+
for (const run of recentRuns.slice(0, 10))
|
|
615
|
+
lines.push(formatRunSummaryLine(run));
|
|
616
|
+
lines.push("", ...formatLegacyAutomationSurface());
|
|
617
|
+
return lines.join(`
|
|
618
|
+
`);
|
|
619
|
+
}
|
|
620
|
+
function formatRunSummaryLine(run) {
|
|
621
|
+
const record = run;
|
|
622
|
+
const runId = runIdOf(record);
|
|
623
|
+
const taskId = taskIdOf(record);
|
|
624
|
+
const title = runTitleOf(record);
|
|
625
|
+
const status = runLikeStatusText(run);
|
|
626
|
+
const runtime = firstString(record, ["runtime", "runtimeAdapter"], "");
|
|
627
|
+
const descriptor = [taskId, title].filter(Boolean).join(" \xB7 ");
|
|
628
|
+
return `${faintBar} ${pc.bold(runId)} ${runLikeStatusColor(run)(`\u25CF ${status}`)} ${descriptor}${runtime ? dim(` ${runtime}`) : ""}`;
|
|
629
|
+
}
|
|
630
|
+
function formatInboxList(kind, entries) {
|
|
631
|
+
const title = kind === "approvals" ? "Pending approvals" : "Pending user input";
|
|
632
|
+
if (entries.length === 0) {
|
|
633
|
+
return [
|
|
634
|
+
formatSection(title, "empty"),
|
|
635
|
+
dim(kind === "approvals" ? "No pending approvals." : "No pending user-input requests."),
|
|
636
|
+
"",
|
|
637
|
+
...formatLegacyAutomationSurface()
|
|
638
|
+
].join(`
|
|
639
|
+
`);
|
|
640
|
+
}
|
|
641
|
+
const lines = [formatSection(title, `${entries.length}`)];
|
|
642
|
+
for (const record of entries) {
|
|
643
|
+
const runId = firstString(record, ["runId"], "(unknown-run)");
|
|
644
|
+
const taskId = firstString(record, ["taskId"], "");
|
|
645
|
+
const status = firstString(record, ["status"], "pending");
|
|
646
|
+
const prompt = firstString(record, ["prompt", "message", "reason", "title", "summary"], kind === "approvals" ? "Approval requested" : "Input requested");
|
|
647
|
+
lines.push(`${faintBar} ${pc.bold(requestIdOf(record))} ${formatStatusPill(status, inboxStatusRole(record))} ${prompt}`);
|
|
648
|
+
lines.push(`${faintBar} ${dim("run".padEnd(12))} ${runId}${taskId ? dim(` task ${taskId}`) : ""}`);
|
|
649
|
+
}
|
|
650
|
+
lines.push("", ...formatLegacyAutomationSurface(), ...formatNextSteps(kind === "approvals" ? ["Resolve: `rig inbox approve --run <run-id> --request <request-id> --decision approve|reject`"] : ["Reply: `rig inbox answer --run <run-id> --request <request-id> --text ...`"]));
|
|
651
|
+
return lines.join(`
|
|
652
|
+
`);
|
|
653
|
+
}
|
|
654
|
+
var dim, faintBar, accent, STATUS_ROLES;
|
|
655
|
+
var init_run_format = __esm(() => {
|
|
656
|
+
dim = pc.dim;
|
|
657
|
+
faintBar = pc.dim("\u2502");
|
|
658
|
+
accent = pc.cyan;
|
|
659
|
+
STATUS_ROLES = new Set([
|
|
660
|
+
"success",
|
|
661
|
+
"action-yellow",
|
|
662
|
+
"active-cyan",
|
|
663
|
+
"failure",
|
|
664
|
+
"muted",
|
|
665
|
+
"neutral"
|
|
666
|
+
]);
|
|
667
|
+
});
|
|
668
|
+
|
|
669
|
+
// packages/run-plugin/src/read-model/read-model-backend/guard.ts
|
|
670
|
+
var TERMINAL;
|
|
671
|
+
var init_guard = __esm(() => {
|
|
672
|
+
TERMINAL = new Set(["completed", "failed", "stopped"]);
|
|
673
|
+
});
|
|
674
|
+
|
|
675
|
+
// packages/run-plugin/src/read-model/read-model-backend/run-status.ts
|
|
676
|
+
function isTerminalRunStatus2(status) {
|
|
677
|
+
return TERMINAL_RUN_STATUSES2.includes(status);
|
|
678
|
+
}
|
|
679
|
+
function isActiveRunStatus(status) {
|
|
680
|
+
return !isTerminalRunStatus2(status);
|
|
681
|
+
}
|
|
682
|
+
function isRuntimeActiveStatus(status) {
|
|
683
|
+
return RUNTIME_ACTIVE_STATUSES.has(normalizeRunStatusToken(status));
|
|
684
|
+
}
|
|
685
|
+
function normalizeRunStatusToken(status) {
|
|
686
|
+
return String(status ?? "").trim().toLowerCase().replace(/[\s_]+/g, "-");
|
|
687
|
+
}
|
|
688
|
+
function isOperatorActiveRunStatus(status) {
|
|
689
|
+
const normalized = normalizeRunStatusToken(status);
|
|
690
|
+
if (!normalized)
|
|
691
|
+
return false;
|
|
692
|
+
return !OPERATOR_INACTIVE_RUN_STATUSES.has(normalized);
|
|
693
|
+
}
|
|
694
|
+
function canonicalStatusToken(status) {
|
|
695
|
+
const normalized = normalizeRunStatusToken(status);
|
|
696
|
+
if (normalized === "waiting-input")
|
|
697
|
+
return "waiting-user-input";
|
|
698
|
+
return normalized;
|
|
699
|
+
}
|
|
700
|
+
function asRunStatus(status) {
|
|
701
|
+
return KNOWN_RUN_STATUS[status] ? status : null;
|
|
702
|
+
}
|
|
703
|
+
function statusColorRole(status) {
|
|
704
|
+
switch (canonicalStatusToken(status)) {
|
|
705
|
+
case "done":
|
|
706
|
+
case "completed":
|
|
707
|
+
case "ready":
|
|
708
|
+
case "healthy":
|
|
709
|
+
case "approved":
|
|
710
|
+
case "merged":
|
|
711
|
+
return "success";
|
|
712
|
+
case "needs-attention":
|
|
713
|
+
case "waiting-approval":
|
|
714
|
+
case "waiting-user-input":
|
|
715
|
+
case "blocked":
|
|
716
|
+
case "paused":
|
|
717
|
+
return "action-yellow";
|
|
718
|
+
case "running":
|
|
719
|
+
case "adopted":
|
|
720
|
+
case "preparing":
|
|
721
|
+
case "created":
|
|
722
|
+
case "queued":
|
|
723
|
+
case "starting":
|
|
724
|
+
case "pending":
|
|
725
|
+
case "in-progress":
|
|
726
|
+
case "active":
|
|
727
|
+
case "booting":
|
|
728
|
+
case "validating":
|
|
729
|
+
case "reviewing":
|
|
730
|
+
case "closing-out":
|
|
731
|
+
return "active-cyan";
|
|
732
|
+
case "failed":
|
|
733
|
+
case "error":
|
|
734
|
+
case "rejected":
|
|
735
|
+
return "failure";
|
|
736
|
+
case "stopped":
|
|
737
|
+
case "cancelled":
|
|
738
|
+
case "canceled":
|
|
739
|
+
case "stale":
|
|
740
|
+
return "muted";
|
|
741
|
+
default:
|
|
742
|
+
return "neutral";
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
function isNeedsAttention(run) {
|
|
746
|
+
return canonicalStatusToken(run.status) === "needs-attention" || run.pendingApprovals + run.pendingInputs > 0 || run.stallCount > 0;
|
|
747
|
+
}
|
|
748
|
+
function phaseForStatus(status, runStatus, needsAttention) {
|
|
749
|
+
if (runStatus && isTerminalRunStatus2(runStatus))
|
|
750
|
+
return runStatus === "completed" || runStatus === "failed" || runStatus === "stopped" ? runStatus : "stopped";
|
|
751
|
+
if (needsAttention)
|
|
752
|
+
return "needs-attention";
|
|
753
|
+
switch (status) {
|
|
754
|
+
case "created":
|
|
755
|
+
case "queued":
|
|
756
|
+
case "preparing":
|
|
757
|
+
case "starting":
|
|
758
|
+
case "booting":
|
|
759
|
+
return "starting";
|
|
760
|
+
case "waiting-approval":
|
|
761
|
+
case "waiting-user-input":
|
|
762
|
+
return "waiting";
|
|
763
|
+
case "paused":
|
|
764
|
+
return "paused";
|
|
765
|
+
case "running":
|
|
766
|
+
case "validating":
|
|
767
|
+
case "reviewing":
|
|
768
|
+
case "closing-out":
|
|
769
|
+
return "active";
|
|
770
|
+
default:
|
|
771
|
+
return runStatus && isActiveRunStatus(runStatus) ? "active" : "unknown";
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
function classifyRun(run) {
|
|
775
|
+
const status = canonicalStatusToken(run.status) || (run.live && !run.stale ? "starting" : "unknown");
|
|
776
|
+
const runStatus = asRunStatus(status);
|
|
777
|
+
const isTerminal = runStatus ? isTerminalRunStatus2(runStatus) : false;
|
|
778
|
+
const isNeedsAttentionValue = isNeedsAttention(run);
|
|
779
|
+
const phase = phaseForStatus(status, runStatus, isNeedsAttentionValue);
|
|
780
|
+
return {
|
|
781
|
+
status,
|
|
782
|
+
runStatus: runStatus ?? "needs-attention",
|
|
783
|
+
phase,
|
|
784
|
+
isActive: runStatus ? isActiveRunStatus(runStatus) : !isTerminal && status !== "unknown",
|
|
785
|
+
isTerminal,
|
|
786
|
+
isNeedsAttention: isNeedsAttentionValue,
|
|
787
|
+
offersRecovery: phase === "failed"
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
function runStatusColorRole(run) {
|
|
791
|
+
const classification = classifyRun(run);
|
|
792
|
+
return classification.isNeedsAttention && !classification.isTerminal ? "action-yellow" : statusColorRole(classification.status);
|
|
793
|
+
}
|
|
794
|
+
function statusRank(run) {
|
|
795
|
+
const classification = classifyRun(run);
|
|
796
|
+
if (classification.isNeedsAttention)
|
|
797
|
+
return 0;
|
|
798
|
+
switch (classification.phase) {
|
|
799
|
+
case "needs-attention":
|
|
800
|
+
return 0;
|
|
801
|
+
case "active":
|
|
802
|
+
case "waiting":
|
|
803
|
+
case "paused":
|
|
804
|
+
return 1;
|
|
805
|
+
case "starting":
|
|
806
|
+
return 2;
|
|
807
|
+
case "completed":
|
|
808
|
+
return 3;
|
|
809
|
+
case "failed":
|
|
810
|
+
return 4;
|
|
811
|
+
case "stopped":
|
|
812
|
+
return 5;
|
|
813
|
+
case "unknown":
|
|
814
|
+
return 6;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
var OPERATOR_INACTIVE_RUN_STATUSES, TERMINAL_RUN_STATUSES2, RUNTIME_ACTIVE_STATUSES, ACTIVE_RUN_STATUSES, KNOWN_RUN_STATUS;
|
|
818
|
+
var init_run_status = __esm(() => {
|
|
819
|
+
OPERATOR_INACTIVE_RUN_STATUSES = new Set([
|
|
820
|
+
"completed",
|
|
821
|
+
"complete",
|
|
822
|
+
"done",
|
|
823
|
+
"success",
|
|
824
|
+
"succeeded",
|
|
825
|
+
"passed",
|
|
826
|
+
"failed",
|
|
827
|
+
"failure",
|
|
828
|
+
"error",
|
|
829
|
+
"errored",
|
|
830
|
+
"stopped",
|
|
831
|
+
"cancelled",
|
|
832
|
+
"canceled",
|
|
833
|
+
"aborted",
|
|
834
|
+
"abort",
|
|
835
|
+
"merged",
|
|
836
|
+
"closed",
|
|
837
|
+
"skipped",
|
|
838
|
+
"needs-attention",
|
|
839
|
+
"needs_attention"
|
|
840
|
+
]);
|
|
841
|
+
TERMINAL_RUN_STATUSES2 = ["completed", "failed", "stopped"];
|
|
842
|
+
RUNTIME_ACTIVE_STATUSES = new Set([
|
|
843
|
+
"created",
|
|
844
|
+
"preparing",
|
|
845
|
+
"running",
|
|
846
|
+
"validating",
|
|
847
|
+
"reviewing",
|
|
848
|
+
"closing-out"
|
|
849
|
+
]);
|
|
850
|
+
ACTIVE_RUN_STATUSES = [
|
|
851
|
+
"created",
|
|
852
|
+
"queued",
|
|
853
|
+
"preparing",
|
|
854
|
+
"running",
|
|
855
|
+
"waiting-approval",
|
|
856
|
+
"waiting-user-input",
|
|
857
|
+
"paused",
|
|
858
|
+
"validating",
|
|
859
|
+
"reviewing",
|
|
860
|
+
"closing-out",
|
|
861
|
+
"needs-attention"
|
|
862
|
+
];
|
|
863
|
+
KNOWN_RUN_STATUS = Object.fromEntries([...ACTIVE_RUN_STATUSES, ...TERMINAL_RUN_STATUSES2].map((status) => [status, true]));
|
|
864
|
+
});
|
|
865
|
+
|
|
866
|
+
// packages/run-plugin/src/read-model/read-model-backend/diagnostics.ts
|
|
867
|
+
function normalizeString(value) {
|
|
868
|
+
if (typeof value !== "string")
|
|
869
|
+
return null;
|
|
870
|
+
const normalized = value.replace(/\s+/g, " ").trim();
|
|
871
|
+
return normalized.length > 0 ? normalized : null;
|
|
872
|
+
}
|
|
873
|
+
function isGenericRunFailure(value) {
|
|
874
|
+
const text = normalizeString(value);
|
|
875
|
+
return Boolean(text && /^Task run failed \([^)]*\)$/i.test(text));
|
|
876
|
+
}
|
|
877
|
+
function appendCandidate(candidates, value) {
|
|
878
|
+
const text = normalizeString(value);
|
|
879
|
+
if (text && !candidates.includes(text))
|
|
880
|
+
candidates.push(text);
|
|
881
|
+
}
|
|
882
|
+
function categorizeUsefulRunError(lines) {
|
|
883
|
+
const taskSourceFailure = lines.find((line) => /failed to update task source/i.test(line));
|
|
884
|
+
if (taskSourceFailure)
|
|
885
|
+
return `Task source update failed: ${taskSourceFailure}`;
|
|
886
|
+
const moduleFailure = lines.find((line) => /cannot find module/i.test(line));
|
|
887
|
+
if (moduleFailure)
|
|
888
|
+
return `Runtime module resolution failed: ${moduleFailure}`;
|
|
889
|
+
const providerFailure = lines.find((line) => /no api key found|unauthorized|authentication failed|invalid api key/i.test(line));
|
|
890
|
+
if (providerFailure)
|
|
891
|
+
return `Provider authentication failed: ${providerFailure}`;
|
|
892
|
+
return null;
|
|
893
|
+
}
|
|
894
|
+
function summarizeRunError(projection) {
|
|
895
|
+
if (projection.status !== "failed")
|
|
896
|
+
return null;
|
|
897
|
+
const candidates = [];
|
|
898
|
+
for (const anomaly of projection.anomalies) {
|
|
899
|
+
appendCandidate(candidates, `Journal anomaly (${anomaly.kind}): ${anomaly.detail}`);
|
|
900
|
+
}
|
|
901
|
+
for (const phase of projection.closeoutPhases) {
|
|
902
|
+
if (phase.outcome === "failed")
|
|
903
|
+
appendCandidate(candidates, phase.detail);
|
|
904
|
+
}
|
|
905
|
+
for (const entry of projection.statusHistory) {
|
|
906
|
+
appendCandidate(candidates, entry.reason);
|
|
907
|
+
}
|
|
908
|
+
appendCandidate(candidates, projection.record.statusDetail);
|
|
909
|
+
appendCandidate(candidates, projection.record.errorText);
|
|
910
|
+
const nonGeneric = candidates.filter((candidate) => !isGenericRunFailure(candidate));
|
|
911
|
+
return categorizeUsefulRunError(nonGeneric) ?? nonGeneric.at(-1) ?? normalizeString(projection.record.errorText);
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
// packages/run-plugin/src/read-model/read-model-backend/projection.ts
|
|
915
|
+
var exports_projection = {};
|
|
916
|
+
__export(exports_projection, {
|
|
917
|
+
selectRunProjection: () => selectRunProjection,
|
|
918
|
+
runRecordsFromCollab: () => runRecordsFromCollab,
|
|
919
|
+
runRecordFromRegistryEntry: () => runRecordFromRegistryEntry,
|
|
920
|
+
resolveRunJoinTarget: () => resolveRunJoinTarget,
|
|
921
|
+
resolveJoinTarget: () => resolveJoinTarget,
|
|
922
|
+
readSessionRunEntries: () => readSessionRunEntries,
|
|
923
|
+
listRuns: () => listRuns,
|
|
924
|
+
listRunProjections: () => listRunProjections,
|
|
925
|
+
getRunProjection: () => getRunProjection,
|
|
926
|
+
getRun: () => getRun,
|
|
927
|
+
discoveryDiagnosticRunRecord: () => discoveryDiagnosticRunRecord
|
|
928
|
+
});
|
|
929
|
+
import { existsSync, readFileSync } from "fs";
|
|
930
|
+
import { isAbsolute, relative, resolve } from "path";
|
|
931
|
+
import { RUN_DISCOVERY, RUN_REGISTRY_BACKBONE } from "@rig/contracts";
|
|
932
|
+
import { loadCapabilityForRoot as loadCapabilityForRoot2 } from "@rig/core/capability-loaders";
|
|
933
|
+
import { defineCapability as defineCapability2 } from "@rig/core/capability";
|
|
934
|
+
function registryEntryFromCollab(collab) {
|
|
935
|
+
const record = collab;
|
|
936
|
+
return {
|
|
937
|
+
roomId: collab.sessionId,
|
|
938
|
+
title: collab.title,
|
|
939
|
+
status: record.registryStatus ?? (collab.stale ? "stale" : "running"),
|
|
940
|
+
startedAt: collab.startedAt ?? null,
|
|
941
|
+
heartbeatAt: collab.updatedAt ?? null,
|
|
942
|
+
sessionPath: collab.sessionPath ?? null,
|
|
943
|
+
cwd: collab.cwd ?? null,
|
|
944
|
+
joinLink: collab.joinLink ?? null,
|
|
945
|
+
webLink: collab.webLink ?? null,
|
|
946
|
+
relayUrl: collab.relayUrl ?? null,
|
|
947
|
+
stale: collab.stale,
|
|
948
|
+
repo: collab.selectedRepo ?? null,
|
|
949
|
+
...collab.pid === undefined ? {} : { pid: collab.pid },
|
|
950
|
+
projection: record.registryProjection ?? null
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
function readSessionRunEntries(sessionPath) {
|
|
954
|
+
if (!sessionPath || !existsSync(sessionPath))
|
|
955
|
+
return [];
|
|
956
|
+
try {
|
|
957
|
+
return parseSessionRunEntries(readFileSync(sessionPath, "utf8"));
|
|
958
|
+
} catch {
|
|
959
|
+
return [];
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
function parseSessionRunEntries(raw) {
|
|
963
|
+
const entries = [];
|
|
964
|
+
for (const line of raw.split(`
|
|
965
|
+
`)) {
|
|
966
|
+
if (!line.trim())
|
|
967
|
+
continue;
|
|
968
|
+
try {
|
|
969
|
+
const parsed = JSON.parse(line);
|
|
970
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
971
|
+
continue;
|
|
972
|
+
entries.push({
|
|
973
|
+
type: "type" in parsed && typeof parsed.type === "string" ? parsed.type : "",
|
|
974
|
+
..."customType" in parsed && typeof parsed.customType === "string" ? { customType: parsed.customType } : {},
|
|
975
|
+
..."data" in parsed ? { data: parsed.data } : {}
|
|
976
|
+
});
|
|
977
|
+
} catch {
|
|
978
|
+
continue;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
return entries;
|
|
982
|
+
}
|
|
983
|
+
function stringOrNull(value) {
|
|
984
|
+
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
|
985
|
+
}
|
|
986
|
+
function numberOrNull(value) {
|
|
987
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
988
|
+
}
|
|
989
|
+
function objectRecord(value) {
|
|
990
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
991
|
+
}
|
|
992
|
+
function payloadString(payload, keys) {
|
|
993
|
+
if (!payload || typeof payload !== "object")
|
|
994
|
+
return null;
|
|
995
|
+
const record = payload;
|
|
996
|
+
for (const key of keys) {
|
|
997
|
+
const value = record[key];
|
|
998
|
+
if (typeof value === "string" && value.trim())
|
|
999
|
+
return value.trim();
|
|
1000
|
+
}
|
|
1001
|
+
return null;
|
|
1002
|
+
}
|
|
1003
|
+
function payloadOptions(payload) {
|
|
1004
|
+
if (!payload || typeof payload !== "object")
|
|
1005
|
+
return;
|
|
1006
|
+
const record = payload;
|
|
1007
|
+
const options = Array.isArray(record.options) ? record.options : Array.isArray(record.choices) ? record.choices : null;
|
|
1008
|
+
const values = options?.filter((value) => typeof value === "string" && value.trim().length > 0) ?? [];
|
|
1009
|
+
return values.length > 0 ? values : undefined;
|
|
1010
|
+
}
|
|
1011
|
+
function inboxRequest(request, kind) {
|
|
1012
|
+
const fallback = kind === "approval" ? "Approval requested" : "Input requested";
|
|
1013
|
+
const body = payloadString(request.payload, ["body", "description", "detail", "details"]);
|
|
1014
|
+
const options = payloadOptions(request.payload);
|
|
1015
|
+
return {
|
|
1016
|
+
requestId: request.requestId,
|
|
1017
|
+
kind,
|
|
1018
|
+
title: payloadString(request.payload, ["title", "message", "reason", "prompt", "summary"]) ?? fallback,
|
|
1019
|
+
...body !== undefined ? { body } : {},
|
|
1020
|
+
...options ? { options } : {},
|
|
1021
|
+
requestedAt: request.requestedAt ?? null,
|
|
1022
|
+
source: "run"
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
function inboxFromProjection(projection) {
|
|
1026
|
+
return [
|
|
1027
|
+
...projection.pendingApprovals.map((request) => inboxRequest(request, "approval")),
|
|
1028
|
+
...projection.pendingUserInputs.map((request) => inboxRequest(request, "input"))
|
|
1029
|
+
].sort((a, b) => (Date.parse(a.requestedAt ?? "") || 0) - (Date.parse(b.requestedAt ?? "") || 0));
|
|
1030
|
+
}
|
|
1031
|
+
function isProjectPath(projectRoot, cwd) {
|
|
1032
|
+
const root = resolve(projectRoot);
|
|
1033
|
+
const candidate = resolve(cwd);
|
|
1034
|
+
const pathFromRoot = relative(root, candidate);
|
|
1035
|
+
return pathFromRoot === "" || !pathFromRoot.startsWith("../") && pathFromRoot !== ".." && !isAbsolute(pathFromRoot);
|
|
1036
|
+
}
|
|
1037
|
+
function sourceFromEntry(projectRoot, projection, entry) {
|
|
1038
|
+
const candidates = [
|
|
1039
|
+
stringOrNull(projection.collabCwd),
|
|
1040
|
+
stringOrNull(projection.cwd),
|
|
1041
|
+
stringOrNull(entry.cwd),
|
|
1042
|
+
stringOrNull(projection.worktreePath)
|
|
1043
|
+
].filter((cwd) => cwd !== null);
|
|
1044
|
+
return candidates.some((cwd) => isProjectPath(projectRoot, cwd)) ? "local" : "remote";
|
|
1045
|
+
}
|
|
1046
|
+
function pendingRequests(value, fallbackKind) {
|
|
1047
|
+
if (!Array.isArray(value))
|
|
1048
|
+
return [];
|
|
1049
|
+
return value.flatMap((item) => {
|
|
1050
|
+
const record = objectRecord(item);
|
|
1051
|
+
const requestId = stringOrNull(record?.requestId) ?? stringOrNull(record?.id);
|
|
1052
|
+
if (!record || !requestId)
|
|
1053
|
+
return [];
|
|
1054
|
+
return [{
|
|
1055
|
+
requestId,
|
|
1056
|
+
requestKind: stringOrNull(record.requestKind) ?? stringOrNull(record.kind) ?? fallbackKind,
|
|
1057
|
+
actionId: stringOrNull(record.actionId),
|
|
1058
|
+
payload: "payload" in record ? record.payload : record,
|
|
1059
|
+
requestedAt: stringOrNull(record.requestedAt) ?? stringOrNull(record.at) ?? ""
|
|
1060
|
+
}];
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
function emptyFoldedProjection(runId, projection, toRunStatus) {
|
|
1064
|
+
const projectionRecord = projection;
|
|
1065
|
+
const nestedProjection = objectRecord(projectionRecord.projection);
|
|
1066
|
+
const pendingApprovals = pendingRequests(nestedProjection?.pendingApprovals ?? projectionRecord.pendingApprovals, "approval");
|
|
1067
|
+
const pendingUserInputs = pendingRequests(nestedProjection?.pendingUserInputs ?? nestedProjection?.pendingInputs ?? projectionRecord.pendingUserInputs ?? (Array.isArray(projectionRecord.pendingInputs) ? projectionRecord.pendingInputs : undefined), "user-input");
|
|
1068
|
+
const nestedRecord = objectRecord(nestedProjection?.record);
|
|
1069
|
+
const nestedFolded = nestedProjection;
|
|
1070
|
+
return {
|
|
1071
|
+
...EMPTY_PROJECTION,
|
|
1072
|
+
...nestedFolded ?? {},
|
|
1073
|
+
record: {
|
|
1074
|
+
...nestedRecord ?? {},
|
|
1075
|
+
runId,
|
|
1076
|
+
...projection.taskId ? { taskId: projection.taskId } : {},
|
|
1077
|
+
...projection.title ? { title: projection.title } : {},
|
|
1078
|
+
...projection.startedAt ? { startedAt: projection.startedAt } : {},
|
|
1079
|
+
...projection.updatedAt ? { updatedAt: projection.updatedAt } : {},
|
|
1080
|
+
...projection.completedAt ? { completedAt: projection.completedAt } : {},
|
|
1081
|
+
...projection.sessionPath ? { sessionPath: projection.sessionPath } : {},
|
|
1082
|
+
...projection.worktreePath ? { worktreePath: projection.worktreePath } : {},
|
|
1083
|
+
...projection.prUrl ? { prUrl: projection.prUrl } : {}
|
|
1084
|
+
},
|
|
1085
|
+
status: toRunStatus(projection.status) ?? toRunStatus(nestedProjection?.status),
|
|
1086
|
+
pendingApprovals,
|
|
1087
|
+
pendingUserInputs,
|
|
1088
|
+
steeringCount: projection.steeringCount ?? numberOrNull(nestedProjection?.steeringCount) ?? 0,
|
|
1089
|
+
stallCount: projection.stallCount ?? numberOrNull(nestedProjection?.stallCount) ?? 0,
|
|
1090
|
+
lastEventAt: projection.updatedAt ?? stringOrNull(nestedProjection?.lastEventAt)
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
function foldedProjectionForRun(runId, projection, sessionPath, toRunStatus) {
|
|
1094
|
+
const registryFolded = emptyFoldedProjection(runId, projection, toRunStatus);
|
|
1095
|
+
const sessionEntries = readSessionRunEntries(sessionPath);
|
|
1096
|
+
if (sessionEntries.length === 0)
|
|
1097
|
+
return { projection: registryFolded, hasSessionEntries: false };
|
|
1098
|
+
const sessionFolded = foldRunSessionEntries(sessionEntries, runId);
|
|
1099
|
+
if (sessionFolded.lastSeq === 0)
|
|
1100
|
+
return { projection: registryFolded, hasSessionEntries: false };
|
|
1101
|
+
return {
|
|
1102
|
+
projection: {
|
|
1103
|
+
...registryFolded,
|
|
1104
|
+
...sessionFolded,
|
|
1105
|
+
record: {
|
|
1106
|
+
...registryFolded.record,
|
|
1107
|
+
...sessionFolded.record,
|
|
1108
|
+
runId
|
|
1109
|
+
},
|
|
1110
|
+
status: sessionFolded.status ?? registryFolded.status,
|
|
1111
|
+
lastEventAt: sessionFolded.lastEventAt ?? registryFolded.lastEventAt
|
|
1112
|
+
},
|
|
1113
|
+
hasSessionEntries: true
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
function runRecordFromRegistryEntry(projectRoot, entry, toRunStatus) {
|
|
1117
|
+
const projection = entry.projection && typeof entry.projection === "object" ? entry.projection : {};
|
|
1118
|
+
const projectionRecord = projection;
|
|
1119
|
+
const runId = stringOrNull(projection.runId) ?? entry.roomId;
|
|
1120
|
+
const sessionPath = stringOrNull(projection.sessionPath) ?? stringOrNull(entry.sessionPath) ?? null;
|
|
1121
|
+
const foldedResult = foldedProjectionForRun(runId, projection, sessionPath, toRunStatus);
|
|
1122
|
+
const folded = foldedResult.projection;
|
|
1123
|
+
const pushedStatus = folded.status ?? toRunStatus(projection.status) ?? toRunStatus(entry.status);
|
|
1124
|
+
const status = entry.stale ? pushedStatus && isTerminalRunStatus(pushedStatus) ? pushedStatus : "stale" : pushedStatus ?? "running";
|
|
1125
|
+
const collabCwd = stringOrNull(projection.collabCwd) ?? stringOrNull(projection.cwd) ?? stringOrNull(entry.cwd) ?? stringOrNull(projection.worktreePath);
|
|
1126
|
+
const pendingApprovals = foldedResult.hasSessionEntries ? folded.pendingApprovals.length : numberOrNull(projectionRecord.pendingApprovals) ?? folded.pendingApprovals.length;
|
|
1127
|
+
const pendingInputs = foldedResult.hasSessionEntries ? folded.pendingUserInputs.length : numberOrNull(projectionRecord.pendingInputs) ?? folded.pendingUserInputs.length;
|
|
1128
|
+
return {
|
|
1129
|
+
runId,
|
|
1130
|
+
taskId: stringOrNull(projection.taskId),
|
|
1131
|
+
title: stringOrNull(projection.title) ?? entry.title,
|
|
1132
|
+
status,
|
|
1133
|
+
source: sourceFromEntry(projectRoot, projection, entry),
|
|
1134
|
+
live: !entry.stale,
|
|
1135
|
+
stale: entry.stale,
|
|
1136
|
+
startedAt: stringOrNull(projection.startedAt) ?? entry.startedAt ?? null,
|
|
1137
|
+
updatedAt: stringOrNull(projection.updatedAt) ?? entry.heartbeatAt ?? null,
|
|
1138
|
+
completedAt: stringOrNull(projection.completedAt),
|
|
1139
|
+
joinLink: stringOrNull(projection.joinLink) ?? entry.joinLink ?? null,
|
|
1140
|
+
webLink: stringOrNull(projection.webLink) ?? entry.webLink ?? null,
|
|
1141
|
+
relayUrl: stringOrNull(projection.relayUrl) ?? entry.relayUrl ?? null,
|
|
1142
|
+
sessionPath,
|
|
1143
|
+
prUrl: stringOrNull(projection.prUrl),
|
|
1144
|
+
worktreePath: stringOrNull(projection.worktreePath) ?? collabCwd,
|
|
1145
|
+
pendingApprovals,
|
|
1146
|
+
pendingInputs,
|
|
1147
|
+
steeringCount: projection.steeringCount ?? folded.steeringCount ?? 0,
|
|
1148
|
+
stallCount: projection.stallCount ?? folded.stallCount ?? 0,
|
|
1149
|
+
errorSummary: stringOrNull(projection.errorSummary) ?? summarizeRunError(folded),
|
|
1150
|
+
timeline: Array.isArray(projection.timeline) ? [...projection.timeline] : [...timelineEntriesFromCustomEntries([])],
|
|
1151
|
+
inbox: inboxFromProjection(folded),
|
|
1152
|
+
collabCwd: collabCwd ?? null,
|
|
1153
|
+
projection: folded
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
function runRecordsFromCollab(projectRoot, collabs, toRunStatus) {
|
|
1157
|
+
return sortByRecency(collabs.map((collab) => runRecordFromRegistryEntry(projectRoot, registryEntryFromCollab(collab), toRunStatus)).filter((record) => record !== null));
|
|
1158
|
+
}
|
|
1159
|
+
function sortByRecency(records) {
|
|
1160
|
+
return [...records].sort((a, b) => {
|
|
1161
|
+
const at = Date.parse(b.updatedAt ?? b.startedAt ?? "") || 0;
|
|
1162
|
+
const bt = Date.parse(a.updatedAt ?? a.startedAt ?? "") || 0;
|
|
1163
|
+
return at - bt;
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
function discoveryDiagnosticRunRecord(projectRoot, error) {
|
|
1167
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
1168
|
+
const runId = DISCOVERY_DIAGNOSTIC_RUN_ID;
|
|
1169
|
+
const projection = {
|
|
1170
|
+
...EMPTY_PROJECTION,
|
|
1171
|
+
record: { runId, title: "Registry discovery unavailable" },
|
|
1172
|
+
status: "needs-attention",
|
|
1173
|
+
stallCount: 1
|
|
1174
|
+
};
|
|
1175
|
+
return {
|
|
1176
|
+
runId,
|
|
1177
|
+
taskId: null,
|
|
1178
|
+
title: "Registry discovery unavailable",
|
|
1179
|
+
status: "needs-attention",
|
|
1180
|
+
source: "remote",
|
|
1181
|
+
live: false,
|
|
1182
|
+
stale: true,
|
|
1183
|
+
startedAt: null,
|
|
1184
|
+
updatedAt: null,
|
|
1185
|
+
completedAt: null,
|
|
1186
|
+
joinLink: null,
|
|
1187
|
+
webLink: null,
|
|
1188
|
+
relayUrl: null,
|
|
1189
|
+
sessionPath: null,
|
|
1190
|
+
prUrl: null,
|
|
1191
|
+
worktreePath: null,
|
|
1192
|
+
pendingApprovals: 0,
|
|
1193
|
+
pendingInputs: 0,
|
|
1194
|
+
steeringCount: 0,
|
|
1195
|
+
stallCount: 1,
|
|
1196
|
+
errorSummary: `registry discovery unavailable: ${detail}`,
|
|
1197
|
+
timeline: [],
|
|
1198
|
+
inbox: [],
|
|
1199
|
+
collabCwd: null,
|
|
1200
|
+
projection
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
async function listRunProjections(projectRoot, filter = {}) {
|
|
1204
|
+
try {
|
|
1205
|
+
const discovery = await loadCapabilityForRoot2(projectRoot, RunDiscoveryCap);
|
|
1206
|
+
if (!discovery)
|
|
1207
|
+
return [discoveryDiagnosticRunRecord(projectRoot, "run discovery capability unavailable")];
|
|
1208
|
+
const backbone = await loadCapabilityForRoot2(projectRoot, RunRegistryBackboneCap);
|
|
1209
|
+
if (!backbone)
|
|
1210
|
+
return [discoveryDiagnosticRunRecord(projectRoot, "run registry backbone capability unavailable")];
|
|
1211
|
+
const collabs = await discovery.listActiveRunCollab(projectRoot, filter, { isRuntimeActiveStatus });
|
|
1212
|
+
return runRecordsFromCollab(projectRoot, collabs, backbone.registryStatusToRunStatus);
|
|
1213
|
+
} catch (error) {
|
|
1214
|
+
return [discoveryDiagnosticRunRecord(projectRoot, error)];
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
function selectRunProjection(runs, runId) {
|
|
1218
|
+
const exactRun = runs.find((run) => run.runId === runId);
|
|
1219
|
+
if (exactRun)
|
|
1220
|
+
return exactRun;
|
|
1221
|
+
const exactTask = runs.find((run) => run.taskId === runId);
|
|
1222
|
+
if (exactTask)
|
|
1223
|
+
return exactTask;
|
|
1224
|
+
const prefixMatches = runs.filter((run) => run.runId.startsWith(runId));
|
|
1225
|
+
if (prefixMatches.length === 1)
|
|
1226
|
+
return prefixMatches[0] ?? null;
|
|
1227
|
+
if (prefixMatches.length > 1) {
|
|
1228
|
+
const matches = prefixMatches.map((run) => run.runId).join(", ");
|
|
1229
|
+
throw new Error(`Ambiguous run id prefix "${runId}" matched ${prefixMatches.length} runs: ${matches}`);
|
|
1230
|
+
}
|
|
1231
|
+
return runs.find((run) => run.runId === DISCOVERY_DIAGNOSTIC_RUN_ID) ?? null;
|
|
1232
|
+
}
|
|
1233
|
+
async function getRunProjection(projectRoot, runId, filter = {}) {
|
|
1234
|
+
const runs = await listRunProjections(projectRoot, filter);
|
|
1235
|
+
return selectRunProjection(runs, runId);
|
|
1236
|
+
}
|
|
1237
|
+
async function resolveRunJoinTarget(projectRoot, runId, filter = {}) {
|
|
1238
|
+
const run = await getRunProjection(projectRoot, runId, filter);
|
|
1239
|
+
if (!run || !run.joinLink)
|
|
1240
|
+
return null;
|
|
1241
|
+
return { runId: run.runId, taskId: run.taskId, joinLink: run.joinLink, cwd: run.collabCwd ?? run.sessionPath, stale: run.stale };
|
|
1242
|
+
}
|
|
1243
|
+
var RunDiscoveryCap, RunRegistryBackboneCap, EMPTY_PROJECTION, DISCOVERY_DIAGNOSTIC_RUN_ID = "__registry_discovery_error__", listRuns, getRun, resolveJoinTarget;
|
|
1244
|
+
var init_projection = __esm(() => {
|
|
1245
|
+
init_session_journal();
|
|
1246
|
+
init_run_status();
|
|
1247
|
+
RunDiscoveryCap = defineCapability2(RUN_DISCOVERY);
|
|
1248
|
+
RunRegistryBackboneCap = defineCapability2(RUN_REGISTRY_BACKBONE);
|
|
1249
|
+
EMPTY_PROJECTION = foldRunSessionEntries([], "");
|
|
1250
|
+
listRuns = listRunProjections;
|
|
1251
|
+
getRun = getRunProjection;
|
|
1252
|
+
resolveJoinTarget = resolveRunJoinTarget;
|
|
1253
|
+
});
|
|
1254
|
+
|
|
1255
|
+
// packages/run-plugin/src/read-model/read-model-backend/inbox.ts
|
|
1256
|
+
function promptFromPayload(payload, fallback) {
|
|
1257
|
+
if (payload && typeof payload === "object") {
|
|
1258
|
+
const record = payload;
|
|
1259
|
+
for (const key of ["title", "message", "reason", "prompt", "summary"]) {
|
|
1260
|
+
const value = record[key];
|
|
1261
|
+
if (typeof value === "string" && value.trim().length > 0)
|
|
1262
|
+
return value.trim();
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
return fallback;
|
|
1266
|
+
}
|
|
1267
|
+
function recordsFromRun(run, kind) {
|
|
1268
|
+
const pending = kind === "approvals" ? run.projection.pendingApprovals : run.projection.pendingUserInputs;
|
|
1269
|
+
return pending.map((request) => ({
|
|
1270
|
+
runId: run.runId,
|
|
1271
|
+
taskId: run.taskId,
|
|
1272
|
+
requestId: request.requestId,
|
|
1273
|
+
status: "pending",
|
|
1274
|
+
prompt: promptFromPayload(request.payload, kind === "approvals" ? "Approval requested" : "Input requested"),
|
|
1275
|
+
requestedAt: request.requestedAt,
|
|
1276
|
+
payload: request.payload,
|
|
1277
|
+
kind: kind === "approvals" ? "approval" : "input"
|
|
1278
|
+
}));
|
|
1279
|
+
}
|
|
1280
|
+
function matchesFilters(run, filters) {
|
|
1281
|
+
if (filters.run && run.runId !== filters.run)
|
|
1282
|
+
return false;
|
|
1283
|
+
if (filters.task && run.taskId !== filters.task && run.runId !== filters.task)
|
|
1284
|
+
return false;
|
|
1285
|
+
return true;
|
|
1286
|
+
}
|
|
1287
|
+
async function listInboxRecords(input, kind, filters = {}, deps = {}) {
|
|
1288
|
+
const runs = await (deps.listRuns ?? listRuns)(input.projectRoot);
|
|
1289
|
+
return runs.filter((run) => matchesFilters(run, filters)).flatMap((run) => recordsFromRun(run, kind));
|
|
1290
|
+
}
|
|
1291
|
+
var init_inbox = __esm(() => {
|
|
1292
|
+
init_projection();
|
|
1293
|
+
});
|
|
1294
|
+
|
|
1295
|
+
// packages/run-plugin/src/read-model/read-model-backend/inspect.ts
|
|
1296
|
+
import { RIG_RUN_LOG_ENTRY } from "@rig/contracts";
|
|
1297
|
+
function asRecord(value) {
|
|
1298
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
1299
|
+
}
|
|
1300
|
+
function firstString2(record, keys) {
|
|
1301
|
+
for (const key of keys) {
|
|
1302
|
+
const value = record[key];
|
|
1303
|
+
if (typeof value === "string" && value.trim().length > 0)
|
|
1304
|
+
return value;
|
|
1305
|
+
}
|
|
1306
|
+
return null;
|
|
1307
|
+
}
|
|
1308
|
+
function stringifyLogPayload(value) {
|
|
1309
|
+
if (typeof value === "string")
|
|
1310
|
+
return value;
|
|
1311
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
1312
|
+
return String(value);
|
|
1313
|
+
const record = asRecord(value);
|
|
1314
|
+
if (!record)
|
|
1315
|
+
return null;
|
|
1316
|
+
const direct = firstString2(record, ["line", "message", "text", "content", "output", "summary", "detail"]);
|
|
1317
|
+
if (direct)
|
|
1318
|
+
return direct;
|
|
1319
|
+
try {
|
|
1320
|
+
return JSON.stringify(record);
|
|
1321
|
+
} catch {
|
|
1322
|
+
return String(record);
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
function logLineFromValue(value) {
|
|
1326
|
+
const record = asRecord(value);
|
|
1327
|
+
if (!record)
|
|
1328
|
+
return stringifyLogPayload(value);
|
|
1329
|
+
const direct = firstString2(record, ["line", "message", "text", "content", "output", "summary", "detail"]);
|
|
1330
|
+
if (direct)
|
|
1331
|
+
return direct;
|
|
1332
|
+
if ("payload" in record)
|
|
1333
|
+
return stringifyLogPayload(record.payload);
|
|
1334
|
+
if ("data" in record)
|
|
1335
|
+
return stringifyLogPayload(record.data);
|
|
1336
|
+
return stringifyLogPayload(record);
|
|
1337
|
+
}
|
|
1338
|
+
function logLineFromSessionEntry(entry) {
|
|
1339
|
+
if (entry.type !== "custom" || entry.customType !== RIG_RUN_LOG_ENTRY)
|
|
1340
|
+
return null;
|
|
1341
|
+
return logLineFromValue(entry.data);
|
|
1342
|
+
}
|
|
1343
|
+
function logLinesFromProjection(projection) {
|
|
1344
|
+
const projected = projection;
|
|
1345
|
+
const lines = [];
|
|
1346
|
+
for (const key of ["logs", "logEntries", "journalLogs", "runLogs"]) {
|
|
1347
|
+
const entries = projected[key];
|
|
1348
|
+
if (!Array.isArray(entries))
|
|
1349
|
+
continue;
|
|
1350
|
+
for (const entry of entries) {
|
|
1351
|
+
const line = logLineFromValue(entry);
|
|
1352
|
+
if (line !== null)
|
|
1353
|
+
lines.push(line);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
return lines;
|
|
1357
|
+
}
|
|
1358
|
+
function extractRunLogs(run, deps = {}) {
|
|
1359
|
+
const projectedLines = logLinesFromProjection(run.projection);
|
|
1360
|
+
if (projectedLines.length > 0)
|
|
1361
|
+
return projectedLines;
|
|
1362
|
+
return (deps.readSessionRunEntries ?? readSessionRunEntries)(run.sessionPath).map(logLineFromSessionEntry).filter((line) => line !== null);
|
|
1363
|
+
}
|
|
1364
|
+
function summarizeRunFailures(run) {
|
|
1365
|
+
const failures = [];
|
|
1366
|
+
const useful = summarizeRunError(run.projection);
|
|
1367
|
+
if (useful)
|
|
1368
|
+
failures.push(`${run.runId}: ${useful}`);
|
|
1369
|
+
if (run.status === "failed" || run.projection.status === "failed")
|
|
1370
|
+
failures.push(`${run.runId}: run status failed`);
|
|
1371
|
+
for (const phase of run.projection.closeoutPhases) {
|
|
1372
|
+
if (phase.outcome === "failed")
|
|
1373
|
+
failures.push(`${run.runId}: closeout ${phase.phase} failed${phase.detail ? ` \u2014 ${phase.detail}` : ""}`);
|
|
1374
|
+
}
|
|
1375
|
+
for (const anomaly of run.projection.anomalies) {
|
|
1376
|
+
failures.push(`${run.runId}: anomaly ${anomaly.kind}${anomaly.detail ? ` \u2014 ${anomaly.detail}` : ""}`);
|
|
1377
|
+
}
|
|
1378
|
+
return failures;
|
|
1379
|
+
}
|
|
1380
|
+
function runInspectSummaryRows(runs, options = {}) {
|
|
1381
|
+
const attachable = runs.filter((run) => Boolean(run.joinLink && !run.stale)).length;
|
|
1382
|
+
const pendingInbox = options.pendingInbox ?? runs.reduce((total, run) => total + run.pendingApprovals + run.pendingInputs, 0);
|
|
1383
|
+
return [
|
|
1384
|
+
{ id: "title", label: "Inspect", currentValue: "runtime", heading: true, description: "session/runtime inspection rows from @rig/client" },
|
|
1385
|
+
{ id: "inspect:sessions", label: "RUNS", currentValue: String(runs.length), heading: true, description: `${attachable} attachable OMP collab links` },
|
|
1386
|
+
{ id: "inspect:cwd", label: "PROJECT ROOT", currentValue: options.projectRoot ?? "", heading: true, description: "selected target/project root used by Rig chrome" },
|
|
1387
|
+
{ id: "inspect:inbox", label: "INBOX", currentValue: String(pendingInbox), values: ["open"], description: "pending run gates; open Inbox to resolve" },
|
|
1388
|
+
{ id: "inspect:runs", label: "RUNS", currentValue: String(runs.length), values: ["open"], description: "open Runs to inspect individual run detail, logs, and attach controls" },
|
|
1389
|
+
{ id: "inspect:audit", label: "AUDIT", currentValue: "unavailable", heading: true, description: "CLI inspect audit has no cockpit equivalent; use rig inspect audit" }
|
|
1390
|
+
];
|
|
1391
|
+
}
|
|
1392
|
+
var init_inspect = __esm(() => {
|
|
1393
|
+
init_projection();
|
|
1394
|
+
});
|
|
1395
|
+
|
|
1396
|
+
// packages/run-plugin/src/read-model/read-model-backend/stats.ts
|
|
1397
|
+
function parseTimestamp(value) {
|
|
1398
|
+
if (!value)
|
|
1399
|
+
return null;
|
|
1400
|
+
const parsed = Date.parse(value);
|
|
1401
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
1402
|
+
}
|
|
1403
|
+
function median(values) {
|
|
1404
|
+
if (values.length === 0)
|
|
1405
|
+
return null;
|
|
1406
|
+
const sorted = [...values].sort((left, right) => left - right);
|
|
1407
|
+
const middle = Math.floor(sorted.length / 2);
|
|
1408
|
+
return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
|
|
1409
|
+
}
|
|
1410
|
+
function rate(part, total) {
|
|
1411
|
+
return total === 0 ? null : part / total;
|
|
1412
|
+
}
|
|
1413
|
+
function completedDuration(run) {
|
|
1414
|
+
if (run.status !== "completed")
|
|
1415
|
+
return null;
|
|
1416
|
+
const startedAt = parseTimestamp(run.startedAt);
|
|
1417
|
+
const completedAt = parseTimestamp(run.completedAt);
|
|
1418
|
+
if (startedAt === null || completedAt === null || completedAt < startedAt)
|
|
1419
|
+
return null;
|
|
1420
|
+
return completedAt - startedAt;
|
|
1421
|
+
}
|
|
1422
|
+
async function computeStats(projectRootOrRuns, options = {}) {
|
|
1423
|
+
const sinceMs = options.since ? options.since.getTime() : null;
|
|
1424
|
+
const allRuns = typeof projectRootOrRuns === "string" ? await (options.listRuns ?? (await Promise.resolve().then(() => (init_projection(), exports_projection))).listRuns)(projectRootOrRuns) : projectRootOrRuns;
|
|
1425
|
+
const runs = allRuns.filter((run) => {
|
|
1426
|
+
if (sinceMs === null)
|
|
1427
|
+
return true;
|
|
1428
|
+
const startedAt = parseTimestamp(run.startedAt);
|
|
1429
|
+
return startedAt !== null && startedAt >= sinceMs;
|
|
1430
|
+
});
|
|
1431
|
+
const statusCounts = {};
|
|
1432
|
+
const completionDurations = [];
|
|
1433
|
+
let completedRuns = 0;
|
|
1434
|
+
let failedRuns = 0;
|
|
1435
|
+
let needsAttentionRuns = 0;
|
|
1436
|
+
let steeringTotal = 0;
|
|
1437
|
+
let stallTotal = 0;
|
|
1438
|
+
let approvalsPending = 0;
|
|
1439
|
+
let approvalsApproved = 0;
|
|
1440
|
+
let approvalsRejected = 0;
|
|
1441
|
+
for (const run of runs) {
|
|
1442
|
+
const status = run.status || "unknown";
|
|
1443
|
+
statusCounts[status] = (statusCounts[status] ?? 0) + 1;
|
|
1444
|
+
if (status === "completed")
|
|
1445
|
+
completedRuns += 1;
|
|
1446
|
+
if (status === "failed")
|
|
1447
|
+
failedRuns += 1;
|
|
1448
|
+
if (isNeedsAttention(run))
|
|
1449
|
+
needsAttentionRuns += 1;
|
|
1450
|
+
const duration = completedDuration(run);
|
|
1451
|
+
if (duration !== null)
|
|
1452
|
+
completionDurations.push(duration);
|
|
1453
|
+
steeringTotal += run.steeringCount;
|
|
1454
|
+
stallTotal += run.stallCount;
|
|
1455
|
+
approvalsPending += run.projection.pendingApprovals.length;
|
|
1456
|
+
for (const approval of run.projection.resolvedApprovals) {
|
|
1457
|
+
if (approval.decision === "approve")
|
|
1458
|
+
approvalsApproved += 1;
|
|
1459
|
+
if (approval.decision === "reject")
|
|
1460
|
+
approvalsRejected += 1;
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
const approvalsRequested = approvalsPending + approvalsApproved + approvalsRejected;
|
|
1464
|
+
const totalRuns = runs.length;
|
|
1465
|
+
return {
|
|
1466
|
+
since: options.since ? options.since.toISOString() : null,
|
|
1467
|
+
totalRuns,
|
|
1468
|
+
statusCounts,
|
|
1469
|
+
completedRuns,
|
|
1470
|
+
failedRuns,
|
|
1471
|
+
needsAttentionRuns,
|
|
1472
|
+
completionRate: rate(completedRuns, totalRuns),
|
|
1473
|
+
failureRate: rate(failedRuns, totalRuns),
|
|
1474
|
+
needsAttentionRate: rate(needsAttentionRuns, totalRuns),
|
|
1475
|
+
medianCompletionMs: median(completionDurations),
|
|
1476
|
+
steeringTotal,
|
|
1477
|
+
steeringPerRun: totalRuns === 0 ? null : steeringTotal / totalRuns,
|
|
1478
|
+
stallTotal,
|
|
1479
|
+
approvalsRequested,
|
|
1480
|
+
approvalsApproved,
|
|
1481
|
+
approvalsRejected,
|
|
1482
|
+
approvalsPending
|
|
1483
|
+
};
|
|
1484
|
+
}
|
|
1485
|
+
var init_stats = __esm(() => {
|
|
1486
|
+
init_run_status();
|
|
1487
|
+
init_run_status();
|
|
1488
|
+
});
|
|
1489
|
+
|
|
1490
|
+
// packages/run-plugin/src/read-model/read-model-backend/index.ts
|
|
1491
|
+
var init_read_model_backend = __esm(() => {
|
|
1492
|
+
init_projection();
|
|
1493
|
+
init_guard();
|
|
1494
|
+
init_inbox();
|
|
1495
|
+
init_inspect();
|
|
1496
|
+
init_run_status();
|
|
1497
|
+
init_stats();
|
|
1498
|
+
});
|
|
1499
|
+
|
|
1500
|
+
// packages/run-plugin/src/read-model/read-model-service.ts
|
|
1501
|
+
var exports_read_model_service = {};
|
|
1502
|
+
__export(exports_read_model_service, {
|
|
1503
|
+
runReadModelService: () => runReadModelService
|
|
1504
|
+
});
|
|
1505
|
+
import {
|
|
1506
|
+
RUN_REGISTRY_BACKBONE as RUN_REGISTRY_BACKBONE2
|
|
1507
|
+
} from "@rig/contracts";
|
|
1508
|
+
import { defineCapability as defineCapability3 } from "@rig/core/capability";
|
|
1509
|
+
import { requireInstalledCapability } from "@rig/core/capability-loaders";
|
|
1510
|
+
function registryBackbone() {
|
|
1511
|
+
return requireInstalledCapability(RunRegistryBackboneCap2, "RUN_REGISTRY_BACKBONE capability unavailable: the run-worker autohost installs it before building registry projections; ensure @rig/transport-plugin is installed.");
|
|
1512
|
+
}
|
|
1513
|
+
function discoveryFilter(filter) {
|
|
1514
|
+
return filter ?? {};
|
|
1515
|
+
}
|
|
1516
|
+
function requestedKinds(kind) {
|
|
1517
|
+
if (kind === "approval")
|
|
1518
|
+
return ["approvals"];
|
|
1519
|
+
if (kind === "input")
|
|
1520
|
+
return ["inputs"];
|
|
1521
|
+
return ["approvals", "inputs"];
|
|
1522
|
+
}
|
|
1523
|
+
function sourceMatches(run, source) {
|
|
1524
|
+
return !source || source === "all" || run.source === source;
|
|
1525
|
+
}
|
|
1526
|
+
function failureSummaries(run) {
|
|
1527
|
+
return summarizeRunFailures(run).map((summary) => ({ kind: "run", summary }));
|
|
1528
|
+
}
|
|
1529
|
+
function inboxRecord(record) {
|
|
1530
|
+
return {
|
|
1531
|
+
runId: record.runId,
|
|
1532
|
+
taskId: record.taskId,
|
|
1533
|
+
requestId: record.requestId,
|
|
1534
|
+
kind: record.kind,
|
|
1535
|
+
status: record.status,
|
|
1536
|
+
title: record.prompt,
|
|
1537
|
+
prompt: record.prompt,
|
|
1538
|
+
requestedAt: record.requestedAt,
|
|
1539
|
+
payload: record.payload,
|
|
1540
|
+
source: "run"
|
|
1541
|
+
};
|
|
1542
|
+
}
|
|
1543
|
+
async function listedRuns(input) {
|
|
1544
|
+
const runs = await listRuns(input.projectRoot, discoveryFilter(input.discoveryFilter));
|
|
1545
|
+
return runs.filter((run) => {
|
|
1546
|
+
if (input.taskId && run.taskId !== input.taskId && run.runId !== input.taskId)
|
|
1547
|
+
return false;
|
|
1548
|
+
return sourceMatches(run, input.source);
|
|
1549
|
+
});
|
|
1550
|
+
}
|
|
1551
|
+
async function selectedRun(input) {
|
|
1552
|
+
return getRun(input.projectRoot, input.id, discoveryFilter(input.discoveryFilter));
|
|
1553
|
+
}
|
|
1554
|
+
async function representativeRun(input) {
|
|
1555
|
+
const runs = await listedRuns({
|
|
1556
|
+
projectRoot: input.projectRoot,
|
|
1557
|
+
taskId: input.taskId,
|
|
1558
|
+
discoveryFilter: input.discoveryFilter
|
|
1559
|
+
});
|
|
1560
|
+
for (const run of runs)
|
|
1561
|
+
return run;
|
|
1562
|
+
return selectedRun({ projectRoot: input.projectRoot, id: input.taskId, discoveryFilter: input.discoveryFilter });
|
|
1563
|
+
}
|
|
1564
|
+
async function readDetails(input) {
|
|
1565
|
+
const run = await selectedRun(input);
|
|
1566
|
+
if (!run)
|
|
1567
|
+
return null;
|
|
1568
|
+
const pendingInbox = run.inbox;
|
|
1569
|
+
const inboxCounts = {
|
|
1570
|
+
approvals: run.pendingApprovals,
|
|
1571
|
+
inputs: run.pendingInputs,
|
|
1572
|
+
total: run.pendingApprovals + run.pendingInputs
|
|
1573
|
+
};
|
|
1574
|
+
const sessionEntries = run.sessionPath ? readSessionRunEntries(run.sessionPath) : undefined;
|
|
1575
|
+
return {
|
|
1576
|
+
run,
|
|
1577
|
+
projection: run.projection,
|
|
1578
|
+
pendingInbox,
|
|
1579
|
+
inboxCounts,
|
|
1580
|
+
sourceTask: null,
|
|
1581
|
+
...sessionEntries ? { sessionEntries } : {},
|
|
1582
|
+
failures: failureSummaries(run),
|
|
1583
|
+
logs: input.includeLogs ? extractRunLogs(run) : []
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
async function inboxRecords(input) {
|
|
1587
|
+
const out = [];
|
|
1588
|
+
for (const kind of requestedKinds(input.kind)) {
|
|
1589
|
+
const records = await listInboxRecords({ projectRoot: input.projectRoot }, kind, { ...input.runId ? { run: input.runId } : {}, ...input.taskId ? { task: input.taskId } : {} }, { listRuns: (projectRoot) => listedRuns({ projectRoot, discoveryFilter: input.discoveryFilter }) });
|
|
1590
|
+
out.push(...records.map(inboxRecord));
|
|
1591
|
+
}
|
|
1592
|
+
return out;
|
|
1593
|
+
}
|
|
1594
|
+
function classify(run) {
|
|
1595
|
+
const classification = classifyRun(run);
|
|
1596
|
+
return {
|
|
1597
|
+
...classification,
|
|
1598
|
+
role: runStatusColorRole(run),
|
|
1599
|
+
rank: statusRank(run)
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
function normalizeStageName(value) {
|
|
1603
|
+
const key = value?.toLowerCase().replace(/[_\s]+/g, "-");
|
|
1604
|
+
switch (key) {
|
|
1605
|
+
case "connect":
|
|
1606
|
+
case "collab-host-started":
|
|
1607
|
+
return "Connect";
|
|
1608
|
+
case "github-sync":
|
|
1609
|
+
case "github":
|
|
1610
|
+
case "running-reflection":
|
|
1611
|
+
return "GitHub-sync";
|
|
1612
|
+
case "created":
|
|
1613
|
+
case "queued":
|
|
1614
|
+
case "prepare":
|
|
1615
|
+
case "preparing":
|
|
1616
|
+
return "Prepare";
|
|
1617
|
+
case "launch":
|
|
1618
|
+
case "starting":
|
|
1619
|
+
case "booting":
|
|
1620
|
+
case "running":
|
|
1621
|
+
case "paused":
|
|
1622
|
+
return "Launch";
|
|
1623
|
+
case "plan":
|
|
1624
|
+
case "planning":
|
|
1625
|
+
return "Plan";
|
|
1626
|
+
case "implement":
|
|
1627
|
+
case "implementation":
|
|
1628
|
+
return "Implement";
|
|
1629
|
+
case "validate":
|
|
1630
|
+
case "validating":
|
|
1631
|
+
return "Validate";
|
|
1632
|
+
case "commit":
|
|
1633
|
+
return "Commit";
|
|
1634
|
+
case "push":
|
|
1635
|
+
case "pr-opened":
|
|
1636
|
+
case "open-pr":
|
|
1637
|
+
return "Open-PR";
|
|
1638
|
+
case "pr-review-merge":
|
|
1639
|
+
case "review":
|
|
1640
|
+
case "reviewing":
|
|
1641
|
+
case "review-ci":
|
|
1642
|
+
return "Review/CI";
|
|
1643
|
+
case "merge":
|
|
1644
|
+
return "Merge";
|
|
1645
|
+
case "closing-out":
|
|
1646
|
+
case "completed":
|
|
1647
|
+
case "complete":
|
|
1648
|
+
case "waiting-approval":
|
|
1649
|
+
case "waiting-input":
|
|
1650
|
+
case "waiting-user-input":
|
|
1651
|
+
case "needs-attention":
|
|
1652
|
+
case "failed":
|
|
1653
|
+
case "stopped":
|
|
1654
|
+
return "Complete/Needs-attention/Failed";
|
|
1655
|
+
default:
|
|
1656
|
+
return null;
|
|
1657
|
+
}
|
|
1658
|
+
}
|
|
1659
|
+
function stageStatusFromRunStatus(value) {
|
|
1660
|
+
const key = value?.toLowerCase().replace(/[_\s]+/g, "-");
|
|
1661
|
+
switch (key) {
|
|
1662
|
+
case "failed":
|
|
1663
|
+
return "failed";
|
|
1664
|
+
case "needs-attention":
|
|
1665
|
+
return "needs-attention";
|
|
1666
|
+
case "stopped":
|
|
1667
|
+
return "stopped";
|
|
1668
|
+
case "paused":
|
|
1669
|
+
return "paused";
|
|
1670
|
+
case "waiting-approval":
|
|
1671
|
+
return "waiting-approval";
|
|
1672
|
+
case "waiting-input":
|
|
1673
|
+
return "waiting-input";
|
|
1674
|
+
case "waiting-user-input":
|
|
1675
|
+
return "waiting-user-input";
|
|
1676
|
+
case "running":
|
|
1677
|
+
case "starting":
|
|
1678
|
+
case "booting":
|
|
1679
|
+
case "started":
|
|
1680
|
+
case "validating":
|
|
1681
|
+
case "reviewing":
|
|
1682
|
+
case "closing-out":
|
|
1683
|
+
return "running";
|
|
1684
|
+
default:
|
|
1685
|
+
return "completed";
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
function terminalStageStatus(classification) {
|
|
1689
|
+
if (classification.isNeedsAttention)
|
|
1690
|
+
return "needs-attention";
|
|
1691
|
+
switch (classification.phase) {
|
|
1692
|
+
case "completed":
|
|
1693
|
+
return "completed";
|
|
1694
|
+
case "failed":
|
|
1695
|
+
return "failed";
|
|
1696
|
+
case "stopped":
|
|
1697
|
+
return "stopped";
|
|
1698
|
+
case "paused":
|
|
1699
|
+
return "paused";
|
|
1700
|
+
default:
|
|
1701
|
+
return classification.isTerminal ? "completed" : null;
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
function projectRunStages(run) {
|
|
1705
|
+
const classification = classify(run);
|
|
1706
|
+
const statuses = new Map;
|
|
1707
|
+
const details = new Map;
|
|
1708
|
+
for (const stage of RUN_DETAIL_STAGES)
|
|
1709
|
+
statuses.set(stage, "pending");
|
|
1710
|
+
for (const history of run.projection.statusHistory ?? []) {
|
|
1711
|
+
const stage = normalizeStageName(history.to);
|
|
1712
|
+
if (stage) {
|
|
1713
|
+
statuses.set(stage, stageStatusFromRunStatus(history.to));
|
|
1714
|
+
if (history.reason)
|
|
1715
|
+
details.set(stage, history.reason);
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
for (const entry of run.timeline ?? []) {
|
|
1719
|
+
const stage = normalizeStageName(entry.stage ?? entry.type);
|
|
1720
|
+
if (!stage)
|
|
1721
|
+
continue;
|
|
1722
|
+
statuses.set(stage, stageStatusFromRunStatus(entry.status ?? entry.type));
|
|
1723
|
+
if (entry.detail)
|
|
1724
|
+
details.set(stage, entry.detail);
|
|
1725
|
+
}
|
|
1726
|
+
for (const phase of run.projection.closeoutPhases ?? []) {
|
|
1727
|
+
const stage = normalizeStageName(phase.phase);
|
|
1728
|
+
if (!stage)
|
|
1729
|
+
continue;
|
|
1730
|
+
statuses.set(stage, phase.outcome === "failed" ? "failed" : phase.outcome === "completed" ? "completed" : "running");
|
|
1731
|
+
if (phase.detail)
|
|
1732
|
+
details.set(stage, phase.detail);
|
|
1733
|
+
}
|
|
1734
|
+
const terminalStatus = terminalStageStatus(classification);
|
|
1735
|
+
if (terminalStatus) {
|
|
1736
|
+
statuses.set("Complete/Needs-attention/Failed", terminalStatus);
|
|
1737
|
+
}
|
|
1738
|
+
return RUN_DETAIL_STAGES.map((stage) => ({
|
|
1739
|
+
id: `stage:${stage}`,
|
|
1740
|
+
label: stage,
|
|
1741
|
+
currentValue: statuses.get(stage) ?? "pending",
|
|
1742
|
+
description: details.get(stage) ?? "rig.run timeline / closeout projection"
|
|
1743
|
+
}));
|
|
1744
|
+
}
|
|
1745
|
+
function buildRegistryProjection(input) {
|
|
1746
|
+
const folded = projectRunFromSession(input.entries, input.runId);
|
|
1747
|
+
const timeline = latestTimelineEntriesFromCustomEntries(input.entries, input.timelineLimit ?? REGISTRY_PROJECTION_TIMELINE_LIMIT);
|
|
1748
|
+
const cwd = input.cwd ?? process.cwd();
|
|
1749
|
+
const collabCwd = input.collabCwd ?? cwd;
|
|
1750
|
+
const dispatchHandle = input.dispatchHandle?.trim() || null;
|
|
1751
|
+
return {
|
|
1752
|
+
runId: input.runId,
|
|
1753
|
+
taskId: typeof folded.record.taskId === "string" ? folded.record.taskId : input.taskId ?? null,
|
|
1754
|
+
title: typeof folded.record.title === "string" ? folded.record.title : input.title,
|
|
1755
|
+
status: registryBackbone().coerceRegistryStatus(folded.status, "running"),
|
|
1756
|
+
source: "local",
|
|
1757
|
+
startedAt: typeof folded.record.startedAt === "string" ? folded.record.startedAt : null,
|
|
1758
|
+
updatedAt: folded.lastEventAt ?? (typeof folded.record.updatedAt === "string" ? folded.record.updatedAt : new Date().toISOString()),
|
|
1759
|
+
completedAt: typeof folded.record.completedAt === "string" ? folded.record.completedAt : null,
|
|
1760
|
+
joinLink: input.joinLink ?? null,
|
|
1761
|
+
webLink: input.webLink ?? null,
|
|
1762
|
+
relayUrl: input.relayUrl ?? null,
|
|
1763
|
+
sessionPath: typeof folded.record.sessionPath === "string" ? folded.record.sessionPath : input.sessionPath ?? null,
|
|
1764
|
+
prUrl: typeof folded.record.prUrl === "string" ? folded.record.prUrl : null,
|
|
1765
|
+
worktreePath: typeof folded.record.worktreePath === "string" ? folded.record.worktreePath : cwd,
|
|
1766
|
+
collabCwd,
|
|
1767
|
+
cwd,
|
|
1768
|
+
dispatchHandle,
|
|
1769
|
+
pendingApprovals: folded.pendingApprovals.length,
|
|
1770
|
+
pendingInputs: folded.pendingUserInputs.length,
|
|
1771
|
+
steeringCount: folded.steeringCount,
|
|
1772
|
+
stallCount: folded.stallCount,
|
|
1773
|
+
...typeof folded.record.errorText === "string" ? { errorSummary: folded.record.errorText } : { errorSummary: null },
|
|
1774
|
+
timeline: [...timeline]
|
|
1775
|
+
};
|
|
1776
|
+
}
|
|
1777
|
+
var REGISTRY_PROJECTION_TIMELINE_LIMIT = 100, RunRegistryBackboneCap2, RUN_DETAIL_STAGES, runReadModelService;
|
|
1778
|
+
var init_read_model_service = __esm(() => {
|
|
1779
|
+
init_session_journal();
|
|
1780
|
+
init_reconcile();
|
|
1781
|
+
init_run_format();
|
|
1782
|
+
init_read_model_backend();
|
|
1783
|
+
RunRegistryBackboneCap2 = defineCapability3(RUN_REGISTRY_BACKBONE2);
|
|
1784
|
+
RUN_DETAIL_STAGES = [
|
|
1785
|
+
"Connect",
|
|
1786
|
+
"GitHub-sync",
|
|
1787
|
+
"Prepare",
|
|
1788
|
+
"Launch",
|
|
1789
|
+
"Plan",
|
|
1790
|
+
"Implement",
|
|
1791
|
+
"Validate",
|
|
1792
|
+
"Commit",
|
|
1793
|
+
"Open-PR",
|
|
1794
|
+
"Review/CI",
|
|
1795
|
+
"Merge",
|
|
1796
|
+
"Complete/Needs-attention/Failed"
|
|
1797
|
+
];
|
|
1798
|
+
runReadModelService = {
|
|
1799
|
+
async listRuns(input) {
|
|
1800
|
+
return listedRuns(input);
|
|
1801
|
+
},
|
|
1802
|
+
async getRepresentativeRun(input) {
|
|
1803
|
+
return representativeRun(input);
|
|
1804
|
+
},
|
|
1805
|
+
async getRun(input) {
|
|
1806
|
+
return selectedRun({ projectRoot: input.projectRoot, id: input.selector.id, discoveryFilter: input.discoveryFilter });
|
|
1807
|
+
},
|
|
1808
|
+
async getRunProjection(input) {
|
|
1809
|
+
const run = await selectedRun({ projectRoot: input.projectRoot, id: input.runId, discoveryFilter: input.discoveryFilter });
|
|
1810
|
+
return run?.projection ?? null;
|
|
1811
|
+
},
|
|
1812
|
+
buildSessionProjection(input) {
|
|
1813
|
+
return projectRunFromSession(input.entries, input.runId);
|
|
1814
|
+
},
|
|
1815
|
+
buildRegistryProjection,
|
|
1816
|
+
async getRunDetails(input) {
|
|
1817
|
+
return readDetails({
|
|
1818
|
+
projectRoot: input.projectRoot,
|
|
1819
|
+
id: input.selector.id,
|
|
1820
|
+
includeLogs: input.includeLogs,
|
|
1821
|
+
discoveryFilter: input.discoveryFilter
|
|
1822
|
+
});
|
|
1823
|
+
},
|
|
1824
|
+
async inspectRun(input) {
|
|
1825
|
+
const details = await readDetails({
|
|
1826
|
+
projectRoot: input.projectRoot,
|
|
1827
|
+
id: input.selector.id,
|
|
1828
|
+
includeLogs: input.includeLogs,
|
|
1829
|
+
discoveryFilter: input.discoveryFilter
|
|
1830
|
+
});
|
|
1831
|
+
if (!details)
|
|
1832
|
+
return null;
|
|
1833
|
+
return {
|
|
1834
|
+
details,
|
|
1835
|
+
classification: classify(details.run),
|
|
1836
|
+
rows: runInspectSummaryRows([details.run], { projectRoot: input.projectRoot, pendingInbox: details.inboxCounts.total })
|
|
1837
|
+
};
|
|
1838
|
+
},
|
|
1839
|
+
listInboxRecords: inboxRecords,
|
|
1840
|
+
async getInboxCounts(input) {
|
|
1841
|
+
const records = await inboxRecords(input);
|
|
1842
|
+
const approvals = records.filter((record) => record.kind === "approval").length;
|
|
1843
|
+
const inputs = records.filter((record) => record.kind === "input").length;
|
|
1844
|
+
return { approvals, inputs, total: approvals + inputs };
|
|
1845
|
+
},
|
|
1846
|
+
async getStats(input) {
|
|
1847
|
+
const since = input.since ? new Date(input.since) : null;
|
|
1848
|
+
const runs = input.runs ?? await listedRuns({ projectRoot: input.projectRoot, discoveryFilter: input.discoveryFilter });
|
|
1849
|
+
return computeStats(runs, { since });
|
|
1850
|
+
},
|
|
1851
|
+
async getInspectRows(input) {
|
|
1852
|
+
const runs = input.runs ?? await listedRuns({ projectRoot: input.projectRoot, discoveryFilter: input.discoveryFilter });
|
|
1853
|
+
return runInspectSummaryRows(runs, { projectRoot: input.projectRoot, pendingInbox: input.pendingInbox ?? null });
|
|
1854
|
+
},
|
|
1855
|
+
isRuntimeActiveStatus,
|
|
1856
|
+
isOperatorActiveRunStatus,
|
|
1857
|
+
classifyRun: classify,
|
|
1858
|
+
projectRunStages,
|
|
1859
|
+
formatRunList,
|
|
1860
|
+
formatRunCard,
|
|
1861
|
+
formatRunStatus,
|
|
1862
|
+
formatSubmittedRun,
|
|
1863
|
+
formatInboxList,
|
|
1864
|
+
reconcileActiveRuns: (input) => reconcileActiveRuns(input)
|
|
1865
|
+
};
|
|
1866
|
+
});
|
|
1867
|
+
|
|
1868
|
+
// packages/run-plugin/src/read-model/stats-command.ts
|
|
1869
|
+
var exports_stats_command = {};
|
|
1870
|
+
__export(exports_stats_command, {
|
|
1871
|
+
parseSinceOption: () => parseSinceOption,
|
|
1872
|
+
formatStatsRows: () => formatStatsRows,
|
|
1873
|
+
executeStats: () => executeStats
|
|
1874
|
+
});
|
|
1875
|
+
import { RUN_READ_MODEL } from "@rig/contracts";
|
|
1876
|
+
import { defineCapability as defineCapability4 } from "@rig/core/capability";
|
|
1877
|
+
import { requireCapabilityForRoot } from "@rig/core/capability-loaders";
|
|
1878
|
+
import { CliError, requireNoExtraArgs, takeOption } from "@rig/std-shared/cli-args";
|
|
1879
|
+
import { formatStatsTable, printFormattedOutput } from "@rig/std-shared/cli-format";
|
|
1880
|
+
function parseSinceOption(value, now = new Date) {
|
|
1881
|
+
if (!value?.trim())
|
|
1882
|
+
return null;
|
|
1883
|
+
const trimmed = value.trim();
|
|
1884
|
+
const relative2 = trimmed.match(/^(\d+)d$/i);
|
|
1885
|
+
if (relative2?.[1]) {
|
|
1886
|
+
const days = Number.parseInt(relative2[1], 10);
|
|
1887
|
+
if (!Number.isFinite(days) || days <= 0)
|
|
1888
|
+
throw new CliError(`Invalid --since value: ${value}`, 2, { hint: "Use an ISO date or a relative window like `7d`." });
|
|
1889
|
+
return new Date(now.getTime() - days * DAY_MS);
|
|
1890
|
+
}
|
|
1891
|
+
const parsed = Date.parse(trimmed);
|
|
1892
|
+
if (!Number.isFinite(parsed))
|
|
1893
|
+
throw new CliError(`Invalid --since value: ${value}`, 2, { hint: "Use an ISO date or a relative window like `7d`." });
|
|
1894
|
+
return new Date(parsed);
|
|
1895
|
+
}
|
|
1896
|
+
function formatDuration(ms) {
|
|
1897
|
+
if (ms === null)
|
|
1898
|
+
return "\u2014";
|
|
1899
|
+
const seconds = Math.round(ms / 1000);
|
|
1900
|
+
if (seconds < 60)
|
|
1901
|
+
return `${seconds}s`;
|
|
1902
|
+
const minutes = Math.round(ms / 60000);
|
|
1903
|
+
if (minutes < 60)
|
|
1904
|
+
return `${minutes}m`;
|
|
1905
|
+
const hours = Math.floor(minutes / 60);
|
|
1906
|
+
const remainder = minutes % 60;
|
|
1907
|
+
return remainder === 0 ? `${hours}h` : `${hours}h ${remainder}m`;
|
|
1908
|
+
}
|
|
1909
|
+
function formatStatsRows(stats2) {
|
|
1910
|
+
return [
|
|
1911
|
+
["window", stats2.since ? `since ${stats2.since}` : "all runs"],
|
|
1912
|
+
["total runs", stats2.totalRuns],
|
|
1913
|
+
["completed", `${stats2.completedRuns} (${formatRatePercent(stats2.completionRate)})`],
|
|
1914
|
+
["failed", `${stats2.failedRuns} (${formatRatePercent(stats2.failureRate)})`],
|
|
1915
|
+
["needs attention", `${stats2.needsAttentionRuns} (${formatRatePercent(stats2.needsAttentionRate)})`],
|
|
1916
|
+
["median run time", formatDuration(stats2.medianCompletionMs)],
|
|
1917
|
+
["steering", stats2.steeringTotal],
|
|
1918
|
+
["stalls", stats2.stallTotal],
|
|
1919
|
+
["pending approvals", stats2.approvalsPending]
|
|
1920
|
+
];
|
|
1921
|
+
}
|
|
1922
|
+
async function executeStats(context, args, deps = {}) {
|
|
1923
|
+
const list = [...args];
|
|
1924
|
+
const [first = "show", ...rest] = list;
|
|
1925
|
+
const command = first.startsWith("-") ? "show" : first;
|
|
1926
|
+
const commandArgs = first.startsWith("-") ? list : rest;
|
|
1927
|
+
if (command === "help") {
|
|
1928
|
+
printFormattedOutput(`Usage: ${STATS_USAGE}`);
|
|
1929
|
+
return { ok: true, group: "stats", command };
|
|
1930
|
+
}
|
|
1931
|
+
if (command !== "show")
|
|
1932
|
+
throw new CliError(`Unknown stats command: ${command}`, 1, { hint: "Run `rig stats --help` \u2014 the default command is `show`." });
|
|
1933
|
+
const sinceResult = takeOption(commandArgs, "--since");
|
|
1934
|
+
requireNoExtraArgs(sinceResult.rest, STATS_USAGE);
|
|
1935
|
+
const since = parseSinceOption(sinceResult.value);
|
|
1936
|
+
const readModel = await requireCapabilityForRoot(context.projectRoot, RunReadModelCap, "RUN_READ_MODEL capability unavailable for this project root: load @rig/run-plugin (standard bundle).");
|
|
1937
|
+
const details = await readModel.getStats({
|
|
1938
|
+
projectRoot: context.projectRoot,
|
|
1939
|
+
since: since ? since.toISOString() : null,
|
|
1940
|
+
...deps.listRuns ? { runs: await deps.listRuns(context.projectRoot) } : {}
|
|
1941
|
+
});
|
|
1942
|
+
if ((context.outputMode ?? "text") === "text")
|
|
1943
|
+
printFormattedOutput(formatStatsTable(formatStatsRows(details)));
|
|
1944
|
+
return { ok: true, group: "stats", command, details };
|
|
1945
|
+
}
|
|
1946
|
+
var DAY_MS, STATS_USAGE = "rig stats [show] [--since <7d|30d|ISO date>]", RunReadModelCap;
|
|
1947
|
+
var init_stats_command = __esm(() => {
|
|
1948
|
+
DAY_MS = 24 * 60 * 60 * 1000;
|
|
1949
|
+
RunReadModelCap = defineCapability4(RUN_READ_MODEL);
|
|
1950
|
+
});
|
|
1951
|
+
|
|
1952
|
+
// packages/run-plugin/src/read-model/inspect-command.ts
|
|
1953
|
+
var exports_inspect_command = {};
|
|
1954
|
+
__export(exports_inspect_command, {
|
|
1955
|
+
executeInspect: () => executeInspect
|
|
1956
|
+
});
|
|
1957
|
+
import { RUN_READ_MODEL as RUN_READ_MODEL2, TASK_CLI_DATA_CAPABILITY } from "@rig/contracts";
|
|
1958
|
+
import { defineCapability as defineCapability5 } from "@rig/core/capability";
|
|
1959
|
+
import { requireCapabilityForRoot as requireCapabilityForRoot2 } from "@rig/core/capability-loaders";
|
|
1960
|
+
import { CliError as CliError2, requireNoExtraArgs as requireNoExtraArgs2, requireOption, takeOption as takeOption2 } from "@rig/std-shared/cli-args";
|
|
1961
|
+
import { printFormattedOutput as printFormattedOutput2 } from "@rig/std-shared/cli-format";
|
|
1962
|
+
function inspectHelpText() {
|
|
1963
|
+
return [
|
|
1964
|
+
`Usage: ${INSPECT_USAGE}`,
|
|
1965
|
+
"",
|
|
1966
|
+
"Commands:",
|
|
1967
|
+
" logs --task <id> Print log lines from a projected run for a task.",
|
|
1968
|
+
" artifact --task <id> --file <name>",
|
|
1969
|
+
" Preview a single task artifact.",
|
|
1970
|
+
" artifacts --task <id> List task artifacts.",
|
|
1971
|
+
" run-logs --run <id> Print log lines from a run journal.",
|
|
1972
|
+
" runs List projected runs.",
|
|
1973
|
+
" diff --task <id> List files changed by a task.",
|
|
1974
|
+
" graph [--task <id>] Print the task dependency graph.",
|
|
1975
|
+
" failures --task <id> Print run read-model failure summaries for a task."
|
|
1976
|
+
].join(`
|
|
1977
|
+
`);
|
|
1978
|
+
}
|
|
1979
|
+
function printInspectHelp() {
|
|
1980
|
+
printFormattedOutput2(inspectHelpText());
|
|
1981
|
+
}
|
|
1982
|
+
function toRunLike(run, classification) {
|
|
1983
|
+
return {
|
|
1984
|
+
runId: run.runId,
|
|
1985
|
+
taskId: run.taskId,
|
|
1986
|
+
title: run.title,
|
|
1987
|
+
status: classification?.status ?? run.status,
|
|
1988
|
+
runStatus: classification?.runStatus,
|
|
1989
|
+
statusPhase: classification?.phase,
|
|
1990
|
+
statusRole: classification?.role,
|
|
1991
|
+
statusRank: classification?.rank,
|
|
1992
|
+
isActive: classification?.isActive,
|
|
1993
|
+
isTerminal: classification?.isTerminal,
|
|
1994
|
+
isNeedsAttention: classification?.isNeedsAttention,
|
|
1995
|
+
source: run.source,
|
|
1996
|
+
live: run.live,
|
|
1997
|
+
stale: run.stale,
|
|
1998
|
+
startedAt: run.startedAt,
|
|
1999
|
+
updatedAt: run.updatedAt,
|
|
2000
|
+
completedAt: run.completedAt,
|
|
2001
|
+
joinLink: run.joinLink,
|
|
2002
|
+
prUrl: run.prUrl,
|
|
2003
|
+
pendingApprovals: run.pendingApprovals,
|
|
2004
|
+
pendingInputs: run.pendingInputs,
|
|
2005
|
+
steeringCount: run.steeringCount,
|
|
2006
|
+
stallCount: run.stallCount
|
|
2007
|
+
};
|
|
2008
|
+
}
|
|
2009
|
+
function requireRunId(value, usage) {
|
|
2010
|
+
if (!value || !value.trim())
|
|
2011
|
+
throw new CliError2(`${usage} requires a run id.`, 2, { hint: "Run `rig inspect runs` to find run ids." });
|
|
2012
|
+
return value.trim();
|
|
2013
|
+
}
|
|
2014
|
+
async function loadRunReadModel(projectRoot) {
|
|
2015
|
+
return requireCapabilityForRoot2(projectRoot, RunReadModelCap2, "RUN_READ_MODEL capability unavailable for this project root: load @rig/run-plugin (standard bundle).");
|
|
2016
|
+
}
|
|
2017
|
+
async function listRunRecords(projectRoot, deps) {
|
|
2018
|
+
return deps.listRunProjections ? deps.listRunProjections(projectRoot) : (await loadRunReadModel(projectRoot)).listRuns({ projectRoot });
|
|
2019
|
+
}
|
|
2020
|
+
async function getRunRecord(projectRoot, runId, deps) {
|
|
2021
|
+
return deps.getRunProjection ? deps.getRunProjection(projectRoot, runId) : (await loadRunReadModel(projectRoot)).getRun({ projectRoot, selector: { id: runId, kind: "any" } });
|
|
2022
|
+
}
|
|
2023
|
+
async function getRunDetails(projectRoot, runId, deps, options = {}) {
|
|
2024
|
+
return deps.getRunDetails ? deps.getRunDetails(projectRoot, runId, options) : (await loadRunReadModel(projectRoot)).getRunDetails({ projectRoot, selector: { id: runId, kind: "any" }, ...options.includeLogs === undefined ? {} : { includeLogs: options.includeLogs } });
|
|
2025
|
+
}
|
|
2026
|
+
async function runsForTaskId(projectRoot, taskId, deps) {
|
|
2027
|
+
try {
|
|
2028
|
+
if (!deps.listRunProjections) {
|
|
2029
|
+
const runs = await (await loadRunReadModel(projectRoot)).listRuns({ projectRoot, taskId });
|
|
2030
|
+
if (runs.length > 0)
|
|
2031
|
+
return runs;
|
|
2032
|
+
} else {
|
|
2033
|
+
const runs = await listRunRecords(projectRoot, deps);
|
|
2034
|
+
const filtered = runs.filter((run2) => run2.taskId === taskId || run2.runId === taskId);
|
|
2035
|
+
if (filtered.length > 0)
|
|
2036
|
+
return filtered;
|
|
2037
|
+
}
|
|
2038
|
+
} catch {}
|
|
2039
|
+
const run = await getRunRecord(projectRoot, taskId, deps);
|
|
2040
|
+
return run ? [run] : [];
|
|
2041
|
+
}
|
|
2042
|
+
async function representativeRunForTaskId(projectRoot, taskId, deps) {
|
|
2043
|
+
if (deps.listRunProjections) {
|
|
2044
|
+
const runs = await runsForTaskId(projectRoot, taskId, deps);
|
|
2045
|
+
for (const run of runs)
|
|
2046
|
+
return run;
|
|
2047
|
+
return null;
|
|
2048
|
+
}
|
|
2049
|
+
return (await loadRunReadModel(projectRoot)).getRepresentativeRun({ projectRoot, taskId, purpose: "inspect" });
|
|
2050
|
+
}
|
|
2051
|
+
function failureLine(failure) {
|
|
2052
|
+
return failure.detail ? `${failure.summary} \u2014 ${failure.detail}` : failure.summary;
|
|
2053
|
+
}
|
|
2054
|
+
async function executeLogs(context, args, deps) {
|
|
2055
|
+
const taskResult = takeOption2(args, "--task");
|
|
2056
|
+
requireNoExtraArgs2(taskResult.rest, "rig inspect logs --task <id>");
|
|
2057
|
+
const taskId = requireOption(taskResult.value, "--task", "rig inspect logs --task <id>");
|
|
2058
|
+
const projection = await representativeRunForTaskId(context.projectRoot, taskId, deps);
|
|
2059
|
+
if (!projection)
|
|
2060
|
+
throw new CliError2(`No projected runs found for task ${taskId}.`, 1, { hint: "Run `rig run list` to confirm the run journal is discoverable." });
|
|
2061
|
+
const details = await getRunDetails(context.projectRoot, projection.runId, deps, { includeLogs: true });
|
|
2062
|
+
const lines = [...details?.logs ?? []];
|
|
2063
|
+
if (context.outputMode === "text") {
|
|
2064
|
+
if (lines.length === 0)
|
|
2065
|
+
console.log(`No log entries found for task ${taskId}.`);
|
|
2066
|
+
else
|
|
2067
|
+
for (const line of lines)
|
|
2068
|
+
console.log(line);
|
|
2069
|
+
}
|
|
2070
|
+
return { ok: true, group: "inspect", command: "logs", details: { taskId, runId: projection.runId, count: lines.length, lines } };
|
|
2071
|
+
}
|
|
2072
|
+
async function executeArtifact(context, args, deps) {
|
|
2073
|
+
const taskResult = takeOption2(args, "--task");
|
|
2074
|
+
const fileResult = takeOption2(taskResult.rest, "--file");
|
|
2075
|
+
requireNoExtraArgs2(fileResult.rest, "rig inspect artifact --task <id> --file <name>");
|
|
2076
|
+
const taskId = requireOption(taskResult.value, "--task", "rig inspect artifact --task <id> --file <name>");
|
|
2077
|
+
const filename = fileResult.value?.trim();
|
|
2078
|
+
if (!filename)
|
|
2079
|
+
throw new CliError2("rig inspect artifact --task <id> --file <name> requires an artifact file name.", 2);
|
|
2080
|
+
const preview = await (deps.taskArtifactRead ?? (await taskCliData(context.projectRoot)).taskArtifactRead)(context.projectRoot, filename, { taskId, maxBytes: 64 * 1024 });
|
|
2081
|
+
if (context.outputMode === "text") {
|
|
2082
|
+
console.log(preview.contents);
|
|
2083
|
+
if (preview.truncated)
|
|
2084
|
+
console.log(`
|
|
2085
|
+
[truncated at ${preview.maxBytes} bytes; artifact is ${preview.sizeBytes} bytes]`);
|
|
2086
|
+
}
|
|
2087
|
+
return { ok: true, group: "inspect", command: "artifact", details: { taskId, file: filename, ...preview } };
|
|
2088
|
+
}
|
|
2089
|
+
async function executeRunLogs(context, args, deps) {
|
|
2090
|
+
const runResult = takeOption2(args, "--run");
|
|
2091
|
+
requireNoExtraArgs2(runResult.rest, "rig inspect run-logs --run <id>");
|
|
2092
|
+
const runId = requireRunId(runResult.value, "rig inspect run-logs --run <id>");
|
|
2093
|
+
const projection = await getRunRecord(context.projectRoot, runId, deps);
|
|
2094
|
+
if (!projection)
|
|
2095
|
+
throw new CliError2(`Run not found: ${runId}`, 2, { hint: "Run `rig inspect runs` to see runs." });
|
|
2096
|
+
const details = await getRunDetails(context.projectRoot, projection.runId, deps, { includeLogs: true });
|
|
2097
|
+
const lines = [...details?.logs ?? []];
|
|
2098
|
+
if (context.outputMode === "text") {
|
|
2099
|
+
if (lines.length === 0)
|
|
2100
|
+
console.log(`No log entries found for run ${projection.runId}.`);
|
|
2101
|
+
else
|
|
2102
|
+
for (const line of lines)
|
|
2103
|
+
console.log(line);
|
|
2104
|
+
}
|
|
2105
|
+
return { ok: true, group: "inspect", command: "run-logs", details: { runId: projection.runId, taskId: projection.taskId, count: lines.length, lines } };
|
|
2106
|
+
}
|
|
2107
|
+
async function executeRuns(context, args, deps) {
|
|
2108
|
+
requireNoExtraArgs2(args, "rig inspect runs");
|
|
2109
|
+
let formatted;
|
|
2110
|
+
if (deps.listRunProjections) {
|
|
2111
|
+
formatted = (await listRunRecords(context.projectRoot, deps)).map((run) => toRunLike(run));
|
|
2112
|
+
} else {
|
|
2113
|
+
const readModel = await loadRunReadModel(context.projectRoot);
|
|
2114
|
+
const runs = await readModel.listRuns({ projectRoot: context.projectRoot });
|
|
2115
|
+
formatted = runs.map((run) => toRunLike(run, readModel.classifyRun(run)));
|
|
2116
|
+
}
|
|
2117
|
+
if (context.outputMode === "text")
|
|
2118
|
+
printFormattedOutput2(formatRunList(formatted));
|
|
2119
|
+
return { ok: true, group: "inspect", command: "runs", details: { runs: formatted } };
|
|
2120
|
+
}
|
|
2121
|
+
async function executeArtifacts(context, args, deps) {
|
|
2122
|
+
const taskResult = takeOption2(args, "--task");
|
|
2123
|
+
requireNoExtraArgs2(taskResult.rest, "rig inspect artifacts --task <id>");
|
|
2124
|
+
const taskId = requireOption(taskResult.value, "--task", "rig inspect artifacts --task <id>");
|
|
2125
|
+
if (context.outputMode === "text")
|
|
2126
|
+
await (deps.taskArtifacts ?? (await taskCliData(context.projectRoot)).taskArtifacts)(context.projectRoot, taskId);
|
|
2127
|
+
return { ok: true, group: "inspect", command: "artifacts", details: { taskId, printed: context.outputMode === "text" } };
|
|
2128
|
+
}
|
|
2129
|
+
async function executeDiff(context, args, deps) {
|
|
2130
|
+
const taskResult = takeOption2(args, "--task");
|
|
2131
|
+
requireNoExtraArgs2(taskResult.rest, "rig inspect diff --task <id>");
|
|
2132
|
+
const taskId = requireOption(taskResult.value, "--task", "rig inspect diff --task <id>");
|
|
2133
|
+
const files = (deps.changedFilesForTask ?? (await taskCliData(context.projectRoot)).changedFilesForTask)(context.projectRoot, taskId, true);
|
|
2134
|
+
if (context.outputMode === "text")
|
|
2135
|
+
for (const file of files)
|
|
2136
|
+
console.log(file);
|
|
2137
|
+
return { ok: true, group: "inspect", command: "diff", details: { taskId, files } };
|
|
2138
|
+
}
|
|
2139
|
+
async function executeGraph(context, args, deps) {
|
|
2140
|
+
const taskResult = takeOption2(args, "--task");
|
|
2141
|
+
requireNoExtraArgs2(taskResult.rest, "rig inspect graph [--task <id>]");
|
|
2142
|
+
if (context.outputMode === "text")
|
|
2143
|
+
await (deps.taskDeps ?? (await taskCliData(context.projectRoot)).taskDeps)(context.projectRoot, taskResult.value);
|
|
2144
|
+
return { ok: true, group: "inspect", command: "graph", details: { taskId: taskResult.value ?? null, printed: context.outputMode === "text" } };
|
|
2145
|
+
}
|
|
2146
|
+
async function executeFailures(context, args, deps) {
|
|
2147
|
+
const taskResult = takeOption2(args, "--task");
|
|
2148
|
+
requireNoExtraArgs2(taskResult.rest, "rig inspect failures --task <id>");
|
|
2149
|
+
const taskId = requireOption(taskResult.value, "--task", "rig inspect failures --task <id>");
|
|
2150
|
+
const runs = await runsForTaskId(context.projectRoot, taskId, deps);
|
|
2151
|
+
const failures = (await Promise.all(runs.map(async (run) => (await getRunDetails(context.projectRoot, run.runId, deps))?.failures ?? []))).flat().map(failureLine);
|
|
2152
|
+
if (context.outputMode === "text") {
|
|
2153
|
+
if (failures.length === 0)
|
|
2154
|
+
console.log(`No failures recorded for task ${taskId}.`);
|
|
2155
|
+
else
|
|
2156
|
+
for (const failure of failures)
|
|
2157
|
+
console.log(failure);
|
|
2158
|
+
}
|
|
2159
|
+
return { ok: true, group: "inspect", command: "failures", details: { taskId, count: failures.length, failures } };
|
|
2160
|
+
}
|
|
2161
|
+
function executeAudit(args) {
|
|
2162
|
+
requireNoExtraArgs2(args, "rig inspect audit");
|
|
2163
|
+
throw new CliError2("rig inspect audit cannot read the controlled-command audit trail yet: current code only writes audit JSONL and exposes no supported reader API.", 2, { hint: "Use the OMP session history for operator audit context until a controlled-bash audit reader is added." });
|
|
2164
|
+
}
|
|
2165
|
+
async function executeInspect(context, args, deps = {}) {
|
|
2166
|
+
const [command = "failures", ...rest] = args;
|
|
2167
|
+
if (command === "--help" || command === "-h" || command === "help") {
|
|
2168
|
+
if (context.outputMode === "text")
|
|
2169
|
+
printInspectHelp();
|
|
2170
|
+
return { ok: true, group: "inspect", command: "help" };
|
|
2171
|
+
}
|
|
2172
|
+
switch (command) {
|
|
2173
|
+
case "logs":
|
|
2174
|
+
return executeLogs(context, rest, deps);
|
|
2175
|
+
case "artifact":
|
|
2176
|
+
return executeArtifact(context, rest, deps);
|
|
2177
|
+
case "artifacts":
|
|
2178
|
+
return executeArtifacts(context, rest, deps);
|
|
2179
|
+
case "run-logs":
|
|
2180
|
+
return executeRunLogs(context, rest, deps);
|
|
2181
|
+
case "runs":
|
|
2182
|
+
return executeRuns(context, rest, deps);
|
|
2183
|
+
case "diff":
|
|
2184
|
+
return executeDiff(context, rest, deps);
|
|
2185
|
+
case "graph":
|
|
2186
|
+
return executeGraph(context, rest, deps);
|
|
2187
|
+
case "failures":
|
|
2188
|
+
return executeFailures(context, rest, deps);
|
|
2189
|
+
case "audit":
|
|
2190
|
+
return executeAudit(rest);
|
|
2191
|
+
default:
|
|
2192
|
+
throw new CliError2(`Unknown inspect command: ${command}`, 1, { hint: "Run `rig inspect --help` to list inspect commands." });
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
2195
|
+
var RunReadModelCap2, TaskCliDataCap, taskCliData = (projectRoot) => requireCapabilityForRoot2(projectRoot, TaskCliDataCap, "CLI task-data capability unavailable: load @rig/tasks-plugin (default bundle)."), INSPECT_USAGE = "rig inspect <logs|artifact|artifacts|run-logs|runs|failures|graph|diff>";
|
|
2196
|
+
var init_inspect_command = __esm(() => {
|
|
2197
|
+
init_run_format();
|
|
2198
|
+
RunReadModelCap2 = defineCapability5(RUN_READ_MODEL2);
|
|
2199
|
+
TaskCliDataCap = defineCapability5(TASK_CLI_DATA_CAPABILITY);
|
|
2200
|
+
});
|
|
2201
|
+
|
|
2202
|
+
// packages/run-plugin/src/read-model/runs-screen.ts
|
|
2203
|
+
var exports_runs_screen = {};
|
|
2204
|
+
__export(exports_runs_screen, {
|
|
2205
|
+
createRunsBoardView: () => createRunsBoardView
|
|
2206
|
+
});
|
|
2207
|
+
import {
|
|
2208
|
+
DRONE_WIDTH,
|
|
2209
|
+
RIG_SPINNER_FRAMES,
|
|
2210
|
+
accent as accent2,
|
|
2211
|
+
bold,
|
|
2212
|
+
ink,
|
|
2213
|
+
ink2,
|
|
2214
|
+
ink3,
|
|
2215
|
+
ink4,
|
|
2216
|
+
phaseGlyph,
|
|
2217
|
+
red,
|
|
2218
|
+
renderDroneFrame,
|
|
2219
|
+
statusRoleColor
|
|
2220
|
+
} from "@rig/std-shared/board-theme";
|
|
2221
|
+
function createRunsBoardView(host, deps) {
|
|
2222
|
+
const { truncateToWidth, matchesKey } = deps;
|
|
2223
|
+
let runs = [];
|
|
2224
|
+
let selected = 0;
|
|
2225
|
+
let loading = true;
|
|
2226
|
+
let error = null;
|
|
2227
|
+
let tick = 0;
|
|
2228
|
+
let filter = "";
|
|
2229
|
+
let sortMode = "active";
|
|
2230
|
+
function visibleRuns() {
|
|
2231
|
+
const query = filter.trim().toLowerCase();
|
|
2232
|
+
const filtered = query ? runs.filter((run) => run.runId.toLowerCase().includes(query) || run.status.toLowerCase().includes(query) || run.title.toLowerCase().includes(query)) : [...runs];
|
|
2233
|
+
if (sortMode === "active") {
|
|
2234
|
+
return filtered.map((run, index) => ({ run, index })).sort((a, b) => a.run.rank - b.run.rank || a.index - b.index).map((entry) => entry.run);
|
|
2235
|
+
}
|
|
2236
|
+
if (sortMode === "status") {
|
|
2237
|
+
return filtered.map((run, index) => ({ run, index })).sort((a, b) => a.run.status.localeCompare(b.run.status) || a.index - b.index).map((entry) => entry.run);
|
|
2238
|
+
}
|
|
2239
|
+
return filtered;
|
|
2240
|
+
}
|
|
2241
|
+
function clampSelection() {
|
|
2242
|
+
selected = Math.max(0, Math.min(selected, Math.max(0, visibleRuns().length - 1)));
|
|
2243
|
+
}
|
|
2244
|
+
function moveSelection(delta) {
|
|
2245
|
+
const visible = visibleRuns();
|
|
2246
|
+
if (visible.length === 0)
|
|
2247
|
+
return;
|
|
2248
|
+
selected = Math.max(0, Math.min(visible.length - 1, selected + delta));
|
|
2249
|
+
}
|
|
2250
|
+
function selectedRun2() {
|
|
2251
|
+
return visibleRuns()[selected] ?? null;
|
|
2252
|
+
}
|
|
2253
|
+
function setFilter(next) {
|
|
2254
|
+
filter = next;
|
|
2255
|
+
clampSelection();
|
|
2256
|
+
}
|
|
2257
|
+
function cycleSort() {
|
|
2258
|
+
sortMode = sortMode === "active" ? "recent" : sortMode === "recent" ? "status" : "active";
|
|
2259
|
+
clampSelection();
|
|
2260
|
+
return sortMode;
|
|
2261
|
+
}
|
|
2262
|
+
function droneBoardLines(width, message, messageWidth) {
|
|
2263
|
+
const spinner = RIG_SPINNER_FRAMES[tick % RIG_SPINNER_FRAMES.length];
|
|
2264
|
+
if (width < DRONE_WIDTH + 4) {
|
|
2265
|
+
return ["", ` ${accent2(spinner)} ${ink3(message)}`, ""];
|
|
2266
|
+
}
|
|
2267
|
+
const pad2 = " ".repeat(Math.max(0, Math.floor((width - DRONE_WIDTH) / 2)));
|
|
2268
|
+
const msgPad = " ".repeat(Math.max(0, Math.floor((width - messageWidth) / 2)));
|
|
2269
|
+
return [
|
|
2270
|
+
"",
|
|
2271
|
+
...renderDroneFrame(tick).map((line) => pad2 + line),
|
|
2272
|
+
"",
|
|
2273
|
+
`${msgPad}${accent2(spinner)} ${ink3(message)}`,
|
|
2274
|
+
""
|
|
2275
|
+
];
|
|
2276
|
+
}
|
|
2277
|
+
function renderLines(width) {
|
|
2278
|
+
if (loading) {
|
|
2279
|
+
return droneBoardLines(width, "contacting the fleet\u2026", 24);
|
|
2280
|
+
}
|
|
2281
|
+
if (error) {
|
|
2282
|
+
return ["", ` ${red("runs unavailable:")} ${ink2(error)}`, ""];
|
|
2283
|
+
}
|
|
2284
|
+
const visible = visibleRuns();
|
|
2285
|
+
if (runs.length === 0) {
|
|
2286
|
+
return droneBoardLines(width, "no runs yet \u2014 n picks a task and launches one", 44);
|
|
2287
|
+
}
|
|
2288
|
+
if (visible.length === 0) {
|
|
2289
|
+
return ["", ` ${ink2("no runs match")} ${accent2(`/${filter}`)} ${ink3("\u2014 esc clears the filter")}`, ""];
|
|
2290
|
+
}
|
|
2291
|
+
const start = Math.max(0, Math.min(selected - Math.floor(MAX_VISIBLE / 2), visible.length - MAX_VISIBLE));
|
|
2292
|
+
const window = visible.slice(start, start + MAX_VISIBLE);
|
|
2293
|
+
const lines = window.map((run, index) => {
|
|
2294
|
+
const isSelected = start + index === selected;
|
|
2295
|
+
const color = statusRoleColor(run.role);
|
|
2296
|
+
const dot = color(phaseGlyph(run.phase));
|
|
2297
|
+
const id = run.runId.slice(0, 8);
|
|
2298
|
+
const status = color(run.status.padEnd(16));
|
|
2299
|
+
const title = truncateToWidth(run.title, Math.max(8, width - 36));
|
|
2300
|
+
const row = ` ${dot} ${isSelected ? bold(ink(id)) : ink3(id)} ${status} ${isSelected ? ink(title) : ink2(title)}`;
|
|
2301
|
+
return isSelected ? accent2("\u258C") + row : " " + row;
|
|
2302
|
+
});
|
|
2303
|
+
const meta = [];
|
|
2304
|
+
if (visible.length > MAX_VISIBLE)
|
|
2305
|
+
meta.push(`${selected + 1}/${visible.length}`);
|
|
2306
|
+
if (filter)
|
|
2307
|
+
meta.push(`filter: ${filter}`);
|
|
2308
|
+
meta.push(`sort: ${sortMode}`);
|
|
2309
|
+
lines.push(ink4(` ${meta.join(" \xB7 ")}`));
|
|
2310
|
+
return ["", ...lines, ""];
|
|
2311
|
+
}
|
|
2312
|
+
function handleInput(data) {
|
|
2313
|
+
const enc = (value) => encodeURIComponent(value);
|
|
2314
|
+
if (matchesKey(data, "up") || data === "k") {
|
|
2315
|
+
moveSelection(-1);
|
|
2316
|
+
host.requestRender();
|
|
2317
|
+
return true;
|
|
2318
|
+
}
|
|
2319
|
+
if (matchesKey(data, "down") || data === "j") {
|
|
2320
|
+
moveSelection(1);
|
|
2321
|
+
host.requestRender();
|
|
2322
|
+
return true;
|
|
2323
|
+
}
|
|
2324
|
+
if (matchesKey(data, "enter") || matchesKey(data, "return")) {
|
|
2325
|
+
const run = selectedRun2();
|
|
2326
|
+
if (run)
|
|
2327
|
+
host.act(`run-detail:${enc(run.runId)}`);
|
|
2328
|
+
return true;
|
|
2329
|
+
}
|
|
2330
|
+
if (data === "a") {
|
|
2331
|
+
const run = selectedRun2();
|
|
2332
|
+
if (run)
|
|
2333
|
+
host.attach(run.runId);
|
|
2334
|
+
return true;
|
|
2335
|
+
}
|
|
2336
|
+
if (data === "s") {
|
|
2337
|
+
const run = selectedRun2();
|
|
2338
|
+
if (run)
|
|
2339
|
+
host.openSteer(run.runId);
|
|
2340
|
+
return true;
|
|
2341
|
+
}
|
|
2342
|
+
if (data === "p") {
|
|
2343
|
+
const run = selectedRun2();
|
|
2344
|
+
if (run) {
|
|
2345
|
+
host.setNotice(`pause requested for ${run.runId.slice(0, 8)}\u2026`);
|
|
2346
|
+
host.act(`run-pause:${enc(run.runId)}`);
|
|
2347
|
+
}
|
|
2348
|
+
return true;
|
|
2349
|
+
}
|
|
2350
|
+
if (data === "u") {
|
|
2351
|
+
const run = selectedRun2();
|
|
2352
|
+
if (run) {
|
|
2353
|
+
host.setNotice(`resume requested for ${run.runId.slice(0, 8)}\u2026`);
|
|
2354
|
+
host.act(`run-resume:${enc(run.runId)}`);
|
|
2355
|
+
}
|
|
2356
|
+
return true;
|
|
2357
|
+
}
|
|
2358
|
+
if (data === "x") {
|
|
2359
|
+
const run = selectedRun2();
|
|
2360
|
+
if (run) {
|
|
2361
|
+
host.setNotice(`stop requested for ${run.runId.slice(0, 8)}\u2026`);
|
|
2362
|
+
host.act(`run-stop:${enc(run.runId)}`);
|
|
2363
|
+
}
|
|
2364
|
+
return true;
|
|
2365
|
+
}
|
|
2366
|
+
if (data === "n") {
|
|
2367
|
+
host.navigate("tasks");
|
|
2368
|
+
return true;
|
|
2369
|
+
}
|
|
2370
|
+
if (data === "/") {
|
|
2371
|
+
host.openSearch(filter, setFilter);
|
|
2372
|
+
return true;
|
|
2373
|
+
}
|
|
2374
|
+
if (data === "o") {
|
|
2375
|
+
const mode = cycleSort();
|
|
2376
|
+
host.setNotice(`sorted: ${mode}`);
|
|
2377
|
+
host.requestRender();
|
|
2378
|
+
return true;
|
|
2379
|
+
}
|
|
2380
|
+
if (matchesKey(data, "escape")) {
|
|
2381
|
+
if (filter) {
|
|
2382
|
+
setFilter("");
|
|
2383
|
+
host.requestRender();
|
|
2384
|
+
return true;
|
|
2385
|
+
}
|
|
2386
|
+
return false;
|
|
2387
|
+
}
|
|
2388
|
+
return false;
|
|
2389
|
+
}
|
|
2390
|
+
return {
|
|
2391
|
+
render(width) {
|
|
2392
|
+
return renderLines(width).map((line) => truncateToWidth(line, Math.max(10, width - 1)));
|
|
2393
|
+
},
|
|
2394
|
+
handleInput,
|
|
2395
|
+
setBoard(board) {
|
|
2396
|
+
if (board.kind !== "runs")
|
|
2397
|
+
return;
|
|
2398
|
+
const previous = selectedRun2()?.runId;
|
|
2399
|
+
runs = [...board.runs];
|
|
2400
|
+
if (previous) {
|
|
2401
|
+
const index = visibleRuns().findIndex((run) => run.runId === previous);
|
|
2402
|
+
if (index >= 0)
|
|
2403
|
+
selected = index;
|
|
2404
|
+
}
|
|
2405
|
+
clampSelection();
|
|
2406
|
+
loading = false;
|
|
2407
|
+
error = null;
|
|
2408
|
+
},
|
|
2409
|
+
setError(next) {
|
|
2410
|
+
error = next;
|
|
2411
|
+
},
|
|
2412
|
+
setTick(next) {
|
|
2413
|
+
tick = next;
|
|
2414
|
+
},
|
|
2415
|
+
invalidate() {}
|
|
2416
|
+
};
|
|
2417
|
+
}
|
|
2418
|
+
var MAX_VISIBLE = 16;
|
|
2419
|
+
var init_runs_screen = () => {};
|
|
2420
|
+
|
|
2421
|
+
// packages/run-plugin/src/read-model/plugin.ts
|
|
2422
|
+
import { defineCapability as defineCapability6 } from "@rig/core/capability";
|
|
2423
|
+
import { loadCapabilityForRoot as loadCapabilityForRoot3 } from "@rig/core/capability-loaders";
|
|
2424
|
+
import { definePlugin } from "@rig/core/config";
|
|
2425
|
+
import {
|
|
2426
|
+
RIG_COCKPIT_PANEL_SLOT,
|
|
2427
|
+
RUN_IDENTITY_ENV,
|
|
2428
|
+
RUN_READ_MODEL as RUN_READ_MODEL3,
|
|
2429
|
+
RUN_SESSION_JOURNAL,
|
|
2430
|
+
TASK_IO_SERVICE_CAPABILITY,
|
|
2431
|
+
TASK_PROJECTION_CAPABILITY_ID
|
|
2432
|
+
} from "@rig/contracts";
|
|
2433
|
+
var RUN_READ_MODEL_PLUGIN_NAME = "@rig/run-plugin";
|
|
2434
|
+
var RunReadModelCap3 = defineCapability6(RUN_READ_MODEL3);
|
|
2435
|
+
var RunSessionJournalCap = defineCapability6(RUN_SESSION_JOURNAL);
|
|
2436
|
+
var RunIdentityEnvCap = defineCapability6(RUN_IDENTITY_ENV);
|
|
2437
|
+
var TaskIoCap = defineCapability6(TASK_IO_SERVICE_CAPABILITY);
|
|
2438
|
+
var TaskProjectionCap = defineCapability6(TASK_PROJECTION_CAPABILITY_ID);
|
|
2439
|
+
async function resolveDiscoveryFilter(projectRoot, identityContext) {
|
|
2440
|
+
const identityEnv = await loadCapabilityForRoot3(projectRoot, RunIdentityEnvCap);
|
|
2441
|
+
return (identityContext && identityEnv ? identityEnv.resolveRigIdentityFilter(identityContext) : null) ?? {};
|
|
2442
|
+
}
|
|
2443
|
+
async function produceRunsBoard(context) {
|
|
2444
|
+
const { projectRoot, identityContext, runs: providedRuns, runClassifications } = context ?? {};
|
|
2445
|
+
if (!projectRoot)
|
|
2446
|
+
return { kind: "runs", runs: [] };
|
|
2447
|
+
const service = (await Promise.resolve().then(() => (init_read_model_service(), exports_read_model_service))).runReadModelService;
|
|
2448
|
+
const runs = providedRuns ?? await service.listRuns({ projectRoot, discoveryFilter: await resolveDiscoveryFilter(projectRoot, identityContext) });
|
|
2449
|
+
const rows = runs.map((run) => {
|
|
2450
|
+
const classification = runClassifications?.get(run.runId) ?? service.classifyRun(run);
|
|
2451
|
+
return {
|
|
2452
|
+
runId: run.runId,
|
|
2453
|
+
status: classification.status,
|
|
2454
|
+
role: classification.role,
|
|
2455
|
+
phase: classification.phase,
|
|
2456
|
+
rank: classification.rank,
|
|
2457
|
+
title: run.title
|
|
2458
|
+
};
|
|
2459
|
+
});
|
|
2460
|
+
return { kind: "runs", runs: rows };
|
|
2461
|
+
}
|
|
2462
|
+
var statsCommand = {
|
|
2463
|
+
id: `${RUN_READ_MODEL_PLUGIN_NAME}:stats`,
|
|
2464
|
+
family: "stats",
|
|
2465
|
+
description: "Inspect run statistics.",
|
|
2466
|
+
projectRequired: true,
|
|
2467
|
+
run: async (context, args) => (await Promise.resolve().then(() => (init_stats_command(), exports_stats_command))).executeStats(context, [...args]),
|
|
2468
|
+
helpDoc: {
|
|
2469
|
+
name: "stats",
|
|
2470
|
+
summary: "Legacy automation-only metrics over old run records; not the OMP live UX.",
|
|
2471
|
+
usage: ["rig stats [show] [--since <7d|30d|ISO date>]"],
|
|
2472
|
+
commands: [
|
|
2473
|
+
{ command: "show [--since <window>]", description: "Legacy automation-only: totals, completion/failure rates, run time, steering, stalls, approvals.", primary: true }
|
|
2474
|
+
],
|
|
2475
|
+
examples: [
|
|
2476
|
+
"rig stats --json # legacy automation only"
|
|
2477
|
+
],
|
|
2478
|
+
next: ["For normal UX, use the OMP Runs screen."]
|
|
2479
|
+
}
|
|
2480
|
+
};
|
|
2481
|
+
var inspectCommand = {
|
|
2482
|
+
id: `${RUN_READ_MODEL_PLUGIN_NAME}:inspect`,
|
|
2483
|
+
family: "inspect",
|
|
2484
|
+
description: "Inspect live/project Rig state.",
|
|
2485
|
+
projectRequired: false,
|
|
2486
|
+
run: async (context, args) => (await Promise.resolve().then(() => (init_inspect_command(), exports_inspect_command))).executeInspect(context, [...args]),
|
|
2487
|
+
helpDoc: {
|
|
2488
|
+
name: "inspect",
|
|
2489
|
+
summary: "Legacy automation-only artifact/log inspection; normal UX is OMP session history.",
|
|
2490
|
+
usage: ["rig inspect <logs|artifact|artifacts|run-logs|runs|failures|graph|diff> [options]"],
|
|
2491
|
+
commands: [
|
|
2492
|
+
{ command: "logs --task <id>", description: "Legacy automation-only: latest old run log for a task.", primary: true },
|
|
2493
|
+
{ command: "run-logs --run <id>", description: "Legacy automation-only: log lines for a specific run.", primary: true },
|
|
2494
|
+
{ command: "runs", description: "Legacy automation-only: list projected runs." },
|
|
2495
|
+
{ command: "artifact --task <id> --file <name>", description: "Legacy automation-only: preview one completion artifact." },
|
|
2496
|
+
{ command: "artifacts --task <id>", description: "Legacy automation-only: list completion artifacts.", primary: true },
|
|
2497
|
+
{ command: "diff --task <id>", description: "Legacy automation-only: list task changed files." },
|
|
2498
|
+
{ command: "failures --task <id>", description: "Legacy automation-only: recorded failures for a task.", primary: true },
|
|
2499
|
+
{ command: "graph [--task <id>]", description: "Legacy automation-only: task dependency graph." }
|
|
2500
|
+
],
|
|
2501
|
+
next: ["For normal UX, use the OMP Runs screen and OMP session history."]
|
|
2502
|
+
}
|
|
2503
|
+
};
|
|
2504
|
+
var runReadModelPlugin = definePlugin({
|
|
2505
|
+
name: RUN_READ_MODEL_PLUGIN_NAME,
|
|
2506
|
+
version: "0.0.0-alpha.1",
|
|
2507
|
+
effects: { readsFiles: true, contributesCliCommands: true, contributesPanels: true },
|
|
2508
|
+
contributes: {
|
|
2509
|
+
capabilities: [
|
|
2510
|
+
RunReadModelCap3.provide(async () => (await Promise.resolve().then(() => (init_read_model_service(), exports_read_model_service))).runReadModelService, {
|
|
2511
|
+
title: "Run read-model service",
|
|
2512
|
+
description: "List, inspect, summarize, and classify canonical run session projections for operator surfaces."
|
|
2513
|
+
}),
|
|
2514
|
+
RunSessionJournalCap.provide(async () => (await Promise.resolve().then(() => (init_session_journal(), exports_session_journal))).runSessionJournalCodec, {
|
|
2515
|
+
title: "Run session-journal codec",
|
|
2516
|
+
description: "Fold run-session entries into projections, extract timelines, and parse control sentinels."
|
|
2517
|
+
})
|
|
2518
|
+
],
|
|
2519
|
+
cliCommands: [statsCommand, inspectCommand],
|
|
2520
|
+
panels: [
|
|
2521
|
+
{
|
|
2522
|
+
id: "runs",
|
|
2523
|
+
slot: RIG_COCKPIT_PANEL_SLOT,
|
|
2524
|
+
title: "Runs",
|
|
2525
|
+
description: "Dispatched Rig runs and live OMP collaborative sessions.",
|
|
2526
|
+
produceBoard: produceRunsBoard,
|
|
2527
|
+
createView: async (host) => {
|
|
2528
|
+
const { truncateToWidth, matchesKey } = await import("@oh-my-pi/pi-tui");
|
|
2529
|
+
return (await Promise.resolve().then(() => (init_runs_screen(), exports_runs_screen))).createRunsBoardView(host, { truncateToWidth, matchesKey });
|
|
2530
|
+
},
|
|
2531
|
+
screen: {
|
|
2532
|
+
title: "Runs",
|
|
2533
|
+
navOrder: 2,
|
|
2534
|
+
navLabel: "RUNS",
|
|
2535
|
+
navDescription: "attach to dispatched Rig runs and live OMP collaborative sessions",
|
|
2536
|
+
shortcutKey: "r",
|
|
2537
|
+
shortcutDescription: "Rig runs"
|
|
2538
|
+
}
|
|
2539
|
+
}
|
|
2540
|
+
]
|
|
2541
|
+
}
|
|
2542
|
+
});
|
|
2543
|
+
function createRunReadModelPlugin() {
|
|
2544
|
+
return runReadModelPlugin;
|
|
2545
|
+
}
|
|
2546
|
+
export {
|
|
2547
|
+
runReadModelPlugin,
|
|
2548
|
+
createRunReadModelPlugin,
|
|
2549
|
+
RUN_READ_MODEL_PLUGIN_NAME
|
|
2550
|
+
};
|