@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.
Files changed (70) hide show
  1. package/README.md +1 -0
  2. package/dist/src/plugin.d.ts +4 -0
  3. package/dist/src/plugin.js +4319 -0
  4. package/dist/src/read-model/inspect-command.d.ts +19 -0
  5. package/dist/src/read-model/inspect-command.js +341 -0
  6. package/dist/src/read-model/plugin.d.ts +4 -0
  7. package/dist/src/read-model/plugin.js +2550 -0
  8. package/dist/src/read-model/read-model-backend/diagnostics.d.ts +9 -0
  9. package/dist/src/read-model/read-model-backend/diagnostics.js +51 -0
  10. package/dist/src/read-model/read-model-backend/guard.d.ts +4 -0
  11. package/dist/src/read-model/read-model-backend/guard.js +25 -0
  12. package/dist/src/read-model/read-model-backend/inbox.d.ts +23 -0
  13. package/dist/src/read-model/read-model-backend/inbox.js +669 -0
  14. package/dist/src/read-model/read-model-backend/index.d.ts +8 -0
  15. package/dist/src/read-model/read-model-backend/index.js +1163 -0
  16. package/dist/src/read-model/read-model-backend/inspect.d.ts +26 -0
  17. package/dist/src/read-model/read-model-backend/inspect.js +770 -0
  18. package/dist/src/read-model/read-model-backend/projection.d.ts +39 -0
  19. package/dist/src/read-model/read-model-backend/projection.js +669 -0
  20. package/dist/src/read-model/read-model-backend/run-status.d.ts +27 -0
  21. package/dist/src/read-model/read-model-backend/run-status.js +237 -0
  22. package/dist/src/read-model/read-model-backend/stats.d.ts +12 -0
  23. package/dist/src/read-model/read-model-backend/stats.js +800 -0
  24. package/dist/src/read-model/read-model-service.d.ts +2 -0
  25. package/dist/src/read-model/read-model-service.js +1725 -0
  26. package/dist/src/read-model/reconcile.d.ts +23 -0
  27. package/dist/src/read-model/reconcile.js +306 -0
  28. package/dist/src/read-model/run-format.d.ts +23 -0
  29. package/dist/src/read-model/run-format.js +202 -0
  30. package/dist/src/read-model/runs-screen.d.ts +14 -0
  31. package/dist/src/read-model/runs-screen.js +217 -0
  32. package/dist/src/read-model/session-journal.d.ts +26 -0
  33. package/dist/src/read-model/session-journal.js +355 -0
  34. package/dist/src/read-model/stats-command.d.ts +16 -0
  35. package/dist/src/read-model/stats-command.js +88 -0
  36. package/dist/src/read-model/stats-format.d.ts +1 -0
  37. package/dist/src/read-model/stats-format.js +8 -0
  38. package/dist/src/worker/autohost.d.ts +11 -0
  39. package/dist/src/worker/autohost.js +858 -0
  40. package/dist/src/worker/constants.d.ts +3 -0
  41. package/dist/src/worker/constants.js +10 -0
  42. package/dist/src/worker/extension.d.ts +14 -0
  43. package/dist/src/worker/extension.js +881 -0
  44. package/dist/src/worker/host.d.ts +1 -0
  45. package/dist/src/worker/host.js +1 -0
  46. package/dist/src/worker/inbox-command.d.ts +23 -0
  47. package/dist/src/worker/inbox-command.js +163 -0
  48. package/dist/src/worker/index.d.ts +2 -0
  49. package/dist/src/worker/index.js +1767 -0
  50. package/dist/src/worker/local-run-changes.d.ts +3 -0
  51. package/dist/src/worker/local-run-changes.js +65 -0
  52. package/dist/src/worker/notifications.d.ts +1 -0
  53. package/dist/src/worker/notifications.js +27 -0
  54. package/dist/src/worker/notify-cap.d.ts +11 -0
  55. package/dist/src/worker/notify-cap.js +13 -0
  56. package/dist/src/worker/panel-plugin.d.ts +11 -0
  57. package/dist/src/worker/panel-plugin.js +37 -0
  58. package/dist/src/worker/plugin.d.ts +3 -0
  59. package/dist/src/worker/plugin.js +1761 -0
  60. package/dist/src/worker/run-control-service.d.ts +2 -0
  61. package/dist/src/worker/run-control-service.js +210 -0
  62. package/dist/src/worker/session-journal-writer.d.ts +4 -0
  63. package/dist/src/worker/session-journal-writer.js +184 -0
  64. package/dist/src/worker/stall.d.ts +21 -0
  65. package/dist/src/worker/stall.js +55 -0
  66. package/dist/src/worker/utils.d.ts +21 -0
  67. package/dist/src/worker/utils.js +29 -0
  68. package/dist/src/worker/workflow-journal-writer.d.ts +7 -0
  69. package/dist/src/worker/workflow-journal-writer.js +76 -0
  70. package/package.json +47 -0
@@ -0,0 +1,1163 @@
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
+
18
+ // packages/run-plugin/src/read-model/session-journal.ts
19
+ import { Schema } from "effect";
20
+ import {
21
+ CUSTOM_TYPE_FOR,
22
+ RIG_CONTROL_SENTINEL_END,
23
+ RIG_INBOX_RESOLUTION_SENTINEL,
24
+ RIG_PAUSE_SENTINEL,
25
+ RIG_RESUME_SENTINEL,
26
+ RIG_STOP_SENTINEL,
27
+ RIG_STOP_SENTINEL_END,
28
+ RunJournalEvent,
29
+ TYPE_FOR_CUSTOM
30
+ } from "@rig/contracts";
31
+ function isTerminalRunStatus(status) {
32
+ return TERMINAL_RUN_STATUSES.includes(status);
33
+ }
34
+ function canTransitionRunStatus(from, to) {
35
+ if (from === null)
36
+ return true;
37
+ if (from === to)
38
+ return true;
39
+ return RUN_STATUS_TRANSITIONS[from].includes(to);
40
+ }
41
+ function reduceRunJournal(events, runId = null) {
42
+ let record = {};
43
+ let status = null;
44
+ const statusHistory = [];
45
+ const pendingApprovals = new Map;
46
+ const resolvedApprovals = [];
47
+ const pendingUserInputs = new Map;
48
+ const resolvedUserInputs = [];
49
+ const closeoutPhases = [];
50
+ let resolvedPipeline = null;
51
+ const stageOutcomes = [];
52
+ const anomalies = [];
53
+ let steeringCount = 0;
54
+ let stallCount = 0;
55
+ let lastSeq = 0;
56
+ let lastEventAt = null;
57
+ const projectedRunId = runId ?? events[0]?.runId ?? null;
58
+ for (const event of events) {
59
+ lastSeq = event.seq;
60
+ lastEventAt = event.at;
61
+ switch (event.type) {
62
+ case "status-changed": {
63
+ if (!canTransitionRunStatus(status, event.to)) {
64
+ anomalies.push({ seq: event.seq, kind: "illegal-transition", detail: `${status ?? "(none)"} -> ${event.to}` });
65
+ }
66
+ statusHistory.push({ seq: event.seq, at: event.at, from: status, to: event.to, reason: event.reason ?? null });
67
+ const wasTerminal = status !== null && isTerminalRunStatus(status);
68
+ status = event.to;
69
+ record = { ...record, updatedAt: event.at };
70
+ if (isTerminalRunStatus(event.to) && !record.completedAt)
71
+ record = { ...record, completedAt: event.at };
72
+ if (!isTerminalRunStatus(event.to) && wasTerminal)
73
+ record = { ...record, completedAt: null };
74
+ if (event.to === "running" && !record.startedAt)
75
+ record = { ...record, startedAt: event.at };
76
+ break;
77
+ }
78
+ case "record-patch": {
79
+ const next = { ...record };
80
+ for (const [key, value] of Object.entries(event.patch)) {
81
+ if (value !== undefined)
82
+ next[key] = value;
83
+ }
84
+ next.updatedAt = event.patch.updatedAt ?? event.at;
85
+ record = next;
86
+ break;
87
+ }
88
+ case "approval-requested": {
89
+ pendingApprovals.set(event.requestId, {
90
+ requestId: event.requestId,
91
+ requestKind: event.requestKind,
92
+ actionId: event.actionId ?? null,
93
+ payload: event.payload,
94
+ requestedAt: event.at
95
+ });
96
+ break;
97
+ }
98
+ case "approval-resolved": {
99
+ const pending = pendingApprovals.get(event.requestId);
100
+ if (!pending) {
101
+ const alreadyResolved = resolvedApprovals.some((entry) => entry.requestId === event.requestId);
102
+ anomalies.push({ seq: event.seq, kind: alreadyResolved ? "duplicate-resolution" : "unknown-request", detail: `approval ${event.requestId}` });
103
+ break;
104
+ }
105
+ pendingApprovals.delete(event.requestId);
106
+ resolvedApprovals.push({ ...pending, decision: event.decision, note: event.note ?? null, actor: event.actor, resolvedAt: event.at });
107
+ break;
108
+ }
109
+ case "input-requested": {
110
+ pendingUserInputs.set(event.requestId, {
111
+ requestId: event.requestId,
112
+ requestKind: "user-input",
113
+ actionId: null,
114
+ payload: event.payload,
115
+ requestedAt: event.at
116
+ });
117
+ break;
118
+ }
119
+ case "input-resolved": {
120
+ const pending = pendingUserInputs.get(event.requestId);
121
+ if (!pending) {
122
+ const alreadyResolved = resolvedUserInputs.some((entry) => entry.requestId === event.requestId);
123
+ anomalies.push({ seq: event.seq, kind: alreadyResolved ? "duplicate-resolution" : "unknown-request", detail: `user-input ${event.requestId}` });
124
+ break;
125
+ }
126
+ pendingUserInputs.delete(event.requestId);
127
+ resolvedUserInputs.push({ ...pending, answers: event.answers, actor: event.actor, resolvedAt: event.at });
128
+ break;
129
+ }
130
+ case "steering":
131
+ steeringCount += 1;
132
+ break;
133
+ case "adopted":
134
+ record = { ...record, pid: event.pid, updatedAt: event.at };
135
+ break;
136
+ case "stall-detected":
137
+ stallCount += 1;
138
+ break;
139
+ case "closeout-phase":
140
+ closeoutPhases.push({ seq: event.seq, at: event.at, phase: event.phase, outcome: event.outcome, detail: event.detail ?? null });
141
+ break;
142
+ case "pipeline-resolved":
143
+ resolvedPipeline = event.pipeline;
144
+ break;
145
+ case "stage-outcome":
146
+ stageOutcomes.push({ seq: event.seq, at: event.at, outcome: event.outcome });
147
+ break;
148
+ case "timeline-entry":
149
+ case "log-entry":
150
+ break;
151
+ }
152
+ }
153
+ return {
154
+ runId: projectedRunId,
155
+ record,
156
+ status,
157
+ statusHistory,
158
+ pendingApprovals: [...pendingApprovals.values()],
159
+ resolvedApprovals,
160
+ pendingUserInputs: [...pendingUserInputs.values()],
161
+ resolvedUserInputs,
162
+ steeringCount,
163
+ stallCount,
164
+ closeoutPhases,
165
+ resolvedPipeline,
166
+ stageOutcomes,
167
+ lastSeq,
168
+ lastEventAt,
169
+ anomalies
170
+ };
171
+ }
172
+ function isRunSessionCustomType(customType) {
173
+ return customType !== undefined && Object.hasOwn(TYPE_FOR_CUSTOM, customType);
174
+ }
175
+ function foldRunSessionEntries(entries, runId) {
176
+ const events = [];
177
+ entries.forEach((entry, index) => {
178
+ if (entry.type !== "custom" || !isRunSessionCustomType(entry.customType))
179
+ return;
180
+ const data = entry.data !== null && typeof entry.data === "object" ? entry.data : {};
181
+ const stamped = {
182
+ v: 1,
183
+ seq: index + 1,
184
+ at: typeof data.at === "string" ? data.at : new Date(0).toISOString(),
185
+ runId,
186
+ ...data,
187
+ type: TYPE_FOR_CUSTOM[entry.customType]
188
+ };
189
+ try {
190
+ events.push(decodeRunJournalEvent(stamped));
191
+ } catch {}
192
+ });
193
+ return reduceRunJournal(events, runId);
194
+ }
195
+ function isRecord(value) {
196
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
197
+ }
198
+ function timelineEntryFromCustomEntry(entry) {
199
+ if (entry.customType !== CUSTOM_TYPE_FOR["timeline-entry"] || !isRecord(entry.data))
200
+ return null;
201
+ const payload = isRecord(entry.data.payload) ? entry.data.payload : entry.data;
202
+ const type = typeof payload.type === "string" ? payload.type : "timeline";
203
+ const stage = typeof payload.stage === "string" ? payload.stage : typeof payload.name === "string" ? payload.name : null;
204
+ const status = typeof payload.status === "string" ? payload.status : typeof payload.outcome === "string" ? payload.outcome : null;
205
+ const detail = typeof payload.detail === "string" ? payload.detail : typeof payload.message === "string" ? payload.message : null;
206
+ const at = typeof entry.data.at === "string" ? entry.data.at : typeof payload.at === "string" ? payload.at : null;
207
+ return { at, type, stage, status, detail };
208
+ }
209
+ function timelineEntriesFromCustomEntries(entries) {
210
+ return entries.flatMap((entry) => {
211
+ const timelineEntry = timelineEntryFromCustomEntry(entry);
212
+ return timelineEntry ? [timelineEntry] : [];
213
+ });
214
+ }
215
+ var decodeRunJournalEvent = (value) => Schema.decodeUnknownSync(RunJournalEvent)(value), RUN_STATUS_TRANSITIONS, TERMINAL_RUN_STATUSES;
216
+ var init_session_journal = __esm(() => {
217
+ RUN_STATUS_TRANSITIONS = {
218
+ created: ["queued", "preparing", "running", "failed", "stopped"],
219
+ queued: ["preparing", "running", "failed", "stopped"],
220
+ preparing: ["queued", "running", "needs-attention", "failed", "stopped"],
221
+ running: [
222
+ "queued",
223
+ "waiting-approval",
224
+ "waiting-user-input",
225
+ "paused",
226
+ "validating",
227
+ "reviewing",
228
+ "closing-out",
229
+ "needs-attention",
230
+ "completed",
231
+ "failed",
232
+ "stopped"
233
+ ],
234
+ "waiting-approval": ["running", "needs-attention", "failed", "stopped"],
235
+ "waiting-user-input": ["running", "needs-attention", "failed", "stopped"],
236
+ paused: ["running", "failed", "stopped"],
237
+ validating: ["running", "reviewing", "closing-out", "needs-attention", "completed", "failed", "stopped"],
238
+ reviewing: ["running", "validating", "closing-out", "needs-attention", "completed", "failed", "stopped"],
239
+ "closing-out": ["running", "needs-attention", "completed", "failed", "stopped"],
240
+ "needs-attention": ["queued", "preparing", "running", "closing-out", "completed", "failed", "stopped"],
241
+ completed: [],
242
+ failed: ["queued", "preparing", "running", "closing-out"],
243
+ stopped: ["queued", "preparing", "running", "closing-out"]
244
+ };
245
+ TERMINAL_RUN_STATUSES = ["completed", "failed", "stopped"];
246
+ });
247
+
248
+ // packages/run-plugin/src/read-model/read-model-backend/run-status.ts
249
+ function isTerminalRunStatus2(status) {
250
+ return TERMINAL_RUN_STATUSES2.includes(status);
251
+ }
252
+ function isActiveRunStatus(status) {
253
+ return !isTerminalRunStatus2(status);
254
+ }
255
+ function isRuntimeActiveStatus(status) {
256
+ return RUNTIME_ACTIVE_STATUSES.has(normalizeRunStatusToken(status));
257
+ }
258
+ function normalizeRunStatusToken(status) {
259
+ return String(status ?? "").trim().toLowerCase().replace(/[\s_]+/g, "-");
260
+ }
261
+ function isOperatorActiveRunStatus(status) {
262
+ const normalized = normalizeRunStatusToken(status);
263
+ if (!normalized)
264
+ return false;
265
+ return !OPERATOR_INACTIVE_RUN_STATUSES.has(normalized);
266
+ }
267
+ function canonicalStatusToken(status) {
268
+ const normalized = normalizeRunStatusToken(status);
269
+ if (normalized === "waiting-input")
270
+ return "waiting-user-input";
271
+ return normalized;
272
+ }
273
+ function asRunStatus(status) {
274
+ return KNOWN_RUN_STATUS[status] ? status : null;
275
+ }
276
+ function statusColorRole(status) {
277
+ switch (canonicalStatusToken(status)) {
278
+ case "done":
279
+ case "completed":
280
+ case "ready":
281
+ case "healthy":
282
+ case "approved":
283
+ case "merged":
284
+ return "success";
285
+ case "needs-attention":
286
+ case "waiting-approval":
287
+ case "waiting-user-input":
288
+ case "blocked":
289
+ case "paused":
290
+ return "action-yellow";
291
+ case "running":
292
+ case "adopted":
293
+ case "preparing":
294
+ case "created":
295
+ case "queued":
296
+ case "starting":
297
+ case "pending":
298
+ case "in-progress":
299
+ case "active":
300
+ case "booting":
301
+ case "validating":
302
+ case "reviewing":
303
+ case "closing-out":
304
+ return "active-cyan";
305
+ case "failed":
306
+ case "error":
307
+ case "rejected":
308
+ return "failure";
309
+ case "stopped":
310
+ case "cancelled":
311
+ case "canceled":
312
+ case "stale":
313
+ return "muted";
314
+ default:
315
+ return "neutral";
316
+ }
317
+ }
318
+ function isNeedsAttention(run) {
319
+ return canonicalStatusToken(run.status) === "needs-attention" || run.pendingApprovals + run.pendingInputs > 0 || run.stallCount > 0;
320
+ }
321
+ function phaseForStatus(status, runStatus, needsAttention) {
322
+ if (runStatus && isTerminalRunStatus2(runStatus))
323
+ return runStatus === "completed" || runStatus === "failed" || runStatus === "stopped" ? runStatus : "stopped";
324
+ if (needsAttention)
325
+ return "needs-attention";
326
+ switch (status) {
327
+ case "created":
328
+ case "queued":
329
+ case "preparing":
330
+ case "starting":
331
+ case "booting":
332
+ return "starting";
333
+ case "waiting-approval":
334
+ case "waiting-user-input":
335
+ return "waiting";
336
+ case "paused":
337
+ return "paused";
338
+ case "running":
339
+ case "validating":
340
+ case "reviewing":
341
+ case "closing-out":
342
+ return "active";
343
+ default:
344
+ return runStatus && isActiveRunStatus(runStatus) ? "active" : "unknown";
345
+ }
346
+ }
347
+ function classifyRun(run) {
348
+ const status = canonicalStatusToken(run.status) || (run.live && !run.stale ? "starting" : "unknown");
349
+ const runStatus = asRunStatus(status);
350
+ const isTerminal = runStatus ? isTerminalRunStatus2(runStatus) : false;
351
+ const isNeedsAttentionValue = isNeedsAttention(run);
352
+ const phase = phaseForStatus(status, runStatus, isNeedsAttentionValue);
353
+ return {
354
+ status,
355
+ runStatus: runStatus ?? "needs-attention",
356
+ phase,
357
+ isActive: runStatus ? isActiveRunStatus(runStatus) : !isTerminal && status !== "unknown",
358
+ isTerminal,
359
+ isNeedsAttention: isNeedsAttentionValue,
360
+ offersRecovery: phase === "failed"
361
+ };
362
+ }
363
+ function runStatusText(run) {
364
+ return classifyRun(run).status;
365
+ }
366
+ function runStatusColorRole(run) {
367
+ const classification = classifyRun(run);
368
+ return classification.isNeedsAttention && !classification.isTerminal ? "action-yellow" : statusColorRole(classification.status);
369
+ }
370
+ function statusRank(run) {
371
+ const classification = classifyRun(run);
372
+ if (classification.isNeedsAttention)
373
+ return 0;
374
+ switch (classification.phase) {
375
+ case "needs-attention":
376
+ return 0;
377
+ case "active":
378
+ case "waiting":
379
+ case "paused":
380
+ return 1;
381
+ case "starting":
382
+ return 2;
383
+ case "completed":
384
+ return 3;
385
+ case "failed":
386
+ return 4;
387
+ case "stopped":
388
+ return 5;
389
+ case "unknown":
390
+ return 6;
391
+ }
392
+ }
393
+ function isSteerableStatus(status) {
394
+ switch (status) {
395
+ case "needs-attention":
396
+ case "waiting-approval":
397
+ case "waiting-user-input":
398
+ case "paused":
399
+ return false;
400
+ default: {
401
+ const runStatus = asRunStatus(status);
402
+ return runStatus ? isActiveRunStatus(runStatus) : false;
403
+ }
404
+ }
405
+ }
406
+ function canSteer(run) {
407
+ const classification = classifyRun(run);
408
+ if (classification.phase === "active" || classification.phase === "starting")
409
+ return true;
410
+ return classification.isNeedsAttention && isSteerableStatus(classification.status);
411
+ }
412
+ function canStop(run) {
413
+ const classification = classifyRun(run);
414
+ return classification.isActive && !classification.isTerminal;
415
+ }
416
+ function canPause(run) {
417
+ const phase = classifyRun(run).phase;
418
+ return phase === "active" || phase === "starting";
419
+ }
420
+ function canResume(run) {
421
+ return classifyRun(run).phase === "paused";
422
+ }
423
+ var OPERATOR_INACTIVE_RUN_STATUSES, TERMINAL_RUN_STATUSES2, RUNTIME_ACTIVE_STATUSES, ACTIVE_RUN_STATUSES, KNOWN_RUN_STATUS;
424
+ var init_run_status = __esm(() => {
425
+ OPERATOR_INACTIVE_RUN_STATUSES = new Set([
426
+ "completed",
427
+ "complete",
428
+ "done",
429
+ "success",
430
+ "succeeded",
431
+ "passed",
432
+ "failed",
433
+ "failure",
434
+ "error",
435
+ "errored",
436
+ "stopped",
437
+ "cancelled",
438
+ "canceled",
439
+ "aborted",
440
+ "abort",
441
+ "merged",
442
+ "closed",
443
+ "skipped",
444
+ "needs-attention",
445
+ "needs_attention"
446
+ ]);
447
+ TERMINAL_RUN_STATUSES2 = ["completed", "failed", "stopped"];
448
+ RUNTIME_ACTIVE_STATUSES = new Set([
449
+ "created",
450
+ "preparing",
451
+ "running",
452
+ "validating",
453
+ "reviewing",
454
+ "closing-out"
455
+ ]);
456
+ ACTIVE_RUN_STATUSES = [
457
+ "created",
458
+ "queued",
459
+ "preparing",
460
+ "running",
461
+ "waiting-approval",
462
+ "waiting-user-input",
463
+ "paused",
464
+ "validating",
465
+ "reviewing",
466
+ "closing-out",
467
+ "needs-attention"
468
+ ];
469
+ KNOWN_RUN_STATUS = Object.fromEntries([...ACTIVE_RUN_STATUSES, ...TERMINAL_RUN_STATUSES2].map((status) => [status, true]));
470
+ });
471
+
472
+ // packages/run-plugin/src/read-model/read-model-backend/diagnostics.ts
473
+ function normalizeString(value) {
474
+ if (typeof value !== "string")
475
+ return null;
476
+ const normalized = value.replace(/\s+/g, " ").trim();
477
+ return normalized.length > 0 ? normalized : null;
478
+ }
479
+ function isGenericRunFailure(value) {
480
+ const text = normalizeString(value);
481
+ return Boolean(text && /^Task run failed \([^)]*\)$/i.test(text));
482
+ }
483
+ function appendCandidate(candidates, value) {
484
+ const text = normalizeString(value);
485
+ if (text && !candidates.includes(text))
486
+ candidates.push(text);
487
+ }
488
+ function categorizeUsefulRunError(lines) {
489
+ const taskSourceFailure = lines.find((line) => /failed to update task source/i.test(line));
490
+ if (taskSourceFailure)
491
+ return `Task source update failed: ${taskSourceFailure}`;
492
+ const moduleFailure = lines.find((line) => /cannot find module/i.test(line));
493
+ if (moduleFailure)
494
+ return `Runtime module resolution failed: ${moduleFailure}`;
495
+ const providerFailure = lines.find((line) => /no api key found|unauthorized|authentication failed|invalid api key/i.test(line));
496
+ if (providerFailure)
497
+ return `Provider authentication failed: ${providerFailure}`;
498
+ return null;
499
+ }
500
+ function summarizeRunError(projection) {
501
+ if (projection.status !== "failed")
502
+ return null;
503
+ const candidates = [];
504
+ for (const anomaly of projection.anomalies) {
505
+ appendCandidate(candidates, `Journal anomaly (${anomaly.kind}): ${anomaly.detail}`);
506
+ }
507
+ for (const phase of projection.closeoutPhases) {
508
+ if (phase.outcome === "failed")
509
+ appendCandidate(candidates, phase.detail);
510
+ }
511
+ for (const entry of projection.statusHistory) {
512
+ appendCandidate(candidates, entry.reason);
513
+ }
514
+ appendCandidate(candidates, projection.record.statusDetail);
515
+ appendCandidate(candidates, projection.record.errorText);
516
+ const nonGeneric = candidates.filter((candidate) => !isGenericRunFailure(candidate));
517
+ return categorizeUsefulRunError(nonGeneric) ?? nonGeneric.at(-1) ?? normalizeString(projection.record.errorText);
518
+ }
519
+
520
+ // packages/run-plugin/src/read-model/read-model-backend/projection.ts
521
+ var exports_projection = {};
522
+ __export(exports_projection, {
523
+ selectRunProjection: () => selectRunProjection,
524
+ runRecordsFromCollab: () => runRecordsFromCollab,
525
+ runRecordFromRegistryEntry: () => runRecordFromRegistryEntry,
526
+ resolveRunJoinTarget: () => resolveRunJoinTarget,
527
+ resolveJoinTarget: () => resolveJoinTarget,
528
+ readSessionRunEntries: () => readSessionRunEntries,
529
+ listRuns: () => listRuns,
530
+ listRunProjections: () => listRunProjections,
531
+ getRunProjection: () => getRunProjection,
532
+ getRun: () => getRun,
533
+ discoveryDiagnosticRunRecord: () => discoveryDiagnosticRunRecord
534
+ });
535
+ import { existsSync, readFileSync } from "fs";
536
+ import { isAbsolute, relative, resolve } from "path";
537
+ import { RUN_DISCOVERY, RUN_REGISTRY_BACKBONE } from "@rig/contracts";
538
+ import { loadCapabilityForRoot } from "@rig/core/capability-loaders";
539
+ import { defineCapability } from "@rig/core/capability";
540
+ function registryEntryFromCollab(collab) {
541
+ const record = collab;
542
+ return {
543
+ roomId: collab.sessionId,
544
+ title: collab.title,
545
+ status: record.registryStatus ?? (collab.stale ? "stale" : "running"),
546
+ startedAt: collab.startedAt ?? null,
547
+ heartbeatAt: collab.updatedAt ?? null,
548
+ sessionPath: collab.sessionPath ?? null,
549
+ cwd: collab.cwd ?? null,
550
+ joinLink: collab.joinLink ?? null,
551
+ webLink: collab.webLink ?? null,
552
+ relayUrl: collab.relayUrl ?? null,
553
+ stale: collab.stale,
554
+ repo: collab.selectedRepo ?? null,
555
+ ...collab.pid === undefined ? {} : { pid: collab.pid },
556
+ projection: record.registryProjection ?? null
557
+ };
558
+ }
559
+ function readSessionRunEntries(sessionPath) {
560
+ if (!sessionPath || !existsSync(sessionPath))
561
+ return [];
562
+ try {
563
+ return parseSessionRunEntries(readFileSync(sessionPath, "utf8"));
564
+ } catch {
565
+ return [];
566
+ }
567
+ }
568
+ function parseSessionRunEntries(raw) {
569
+ const entries = [];
570
+ for (const line of raw.split(`
571
+ `)) {
572
+ if (!line.trim())
573
+ continue;
574
+ try {
575
+ const parsed = JSON.parse(line);
576
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
577
+ continue;
578
+ entries.push({
579
+ type: "type" in parsed && typeof parsed.type === "string" ? parsed.type : "",
580
+ ..."customType" in parsed && typeof parsed.customType === "string" ? { customType: parsed.customType } : {},
581
+ ..."data" in parsed ? { data: parsed.data } : {}
582
+ });
583
+ } catch {
584
+ continue;
585
+ }
586
+ }
587
+ return entries;
588
+ }
589
+ function stringOrNull(value) {
590
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
591
+ }
592
+ function numberOrNull(value) {
593
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
594
+ }
595
+ function objectRecord(value) {
596
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
597
+ }
598
+ function payloadString(payload, keys) {
599
+ if (!payload || typeof payload !== "object")
600
+ return null;
601
+ const record = payload;
602
+ for (const key of keys) {
603
+ const value = record[key];
604
+ if (typeof value === "string" && value.trim())
605
+ return value.trim();
606
+ }
607
+ return null;
608
+ }
609
+ function payloadOptions(payload) {
610
+ if (!payload || typeof payload !== "object")
611
+ return;
612
+ const record = payload;
613
+ const options = Array.isArray(record.options) ? record.options : Array.isArray(record.choices) ? record.choices : null;
614
+ const values = options?.filter((value) => typeof value === "string" && value.trim().length > 0) ?? [];
615
+ return values.length > 0 ? values : undefined;
616
+ }
617
+ function inboxRequest(request, kind) {
618
+ const fallback = kind === "approval" ? "Approval requested" : "Input requested";
619
+ const body = payloadString(request.payload, ["body", "description", "detail", "details"]);
620
+ const options = payloadOptions(request.payload);
621
+ return {
622
+ requestId: request.requestId,
623
+ kind,
624
+ title: payloadString(request.payload, ["title", "message", "reason", "prompt", "summary"]) ?? fallback,
625
+ ...body !== undefined ? { body } : {},
626
+ ...options ? { options } : {},
627
+ requestedAt: request.requestedAt ?? null,
628
+ source: "run"
629
+ };
630
+ }
631
+ function inboxFromProjection(projection) {
632
+ return [
633
+ ...projection.pendingApprovals.map((request) => inboxRequest(request, "approval")),
634
+ ...projection.pendingUserInputs.map((request) => inboxRequest(request, "input"))
635
+ ].sort((a, b) => (Date.parse(a.requestedAt ?? "") || 0) - (Date.parse(b.requestedAt ?? "") || 0));
636
+ }
637
+ function isProjectPath(projectRoot, cwd) {
638
+ const root = resolve(projectRoot);
639
+ const candidate = resolve(cwd);
640
+ const pathFromRoot = relative(root, candidate);
641
+ return pathFromRoot === "" || !pathFromRoot.startsWith("../") && pathFromRoot !== ".." && !isAbsolute(pathFromRoot);
642
+ }
643
+ function sourceFromEntry(projectRoot, projection, entry) {
644
+ const candidates = [
645
+ stringOrNull(projection.collabCwd),
646
+ stringOrNull(projection.cwd),
647
+ stringOrNull(entry.cwd),
648
+ stringOrNull(projection.worktreePath)
649
+ ].filter((cwd) => cwd !== null);
650
+ return candidates.some((cwd) => isProjectPath(projectRoot, cwd)) ? "local" : "remote";
651
+ }
652
+ function pendingRequests(value, fallbackKind) {
653
+ if (!Array.isArray(value))
654
+ return [];
655
+ return value.flatMap((item) => {
656
+ const record = objectRecord(item);
657
+ const requestId = stringOrNull(record?.requestId) ?? stringOrNull(record?.id);
658
+ if (!record || !requestId)
659
+ return [];
660
+ return [{
661
+ requestId,
662
+ requestKind: stringOrNull(record.requestKind) ?? stringOrNull(record.kind) ?? fallbackKind,
663
+ actionId: stringOrNull(record.actionId),
664
+ payload: "payload" in record ? record.payload : record,
665
+ requestedAt: stringOrNull(record.requestedAt) ?? stringOrNull(record.at) ?? ""
666
+ }];
667
+ });
668
+ }
669
+ function emptyFoldedProjection(runId, projection, toRunStatus) {
670
+ const projectionRecord = projection;
671
+ const nestedProjection = objectRecord(projectionRecord.projection);
672
+ const pendingApprovals = pendingRequests(nestedProjection?.pendingApprovals ?? projectionRecord.pendingApprovals, "approval");
673
+ const pendingUserInputs = pendingRequests(nestedProjection?.pendingUserInputs ?? nestedProjection?.pendingInputs ?? projectionRecord.pendingUserInputs ?? (Array.isArray(projectionRecord.pendingInputs) ? projectionRecord.pendingInputs : undefined), "user-input");
674
+ const nestedRecord = objectRecord(nestedProjection?.record);
675
+ const nestedFolded = nestedProjection;
676
+ return {
677
+ ...EMPTY_PROJECTION,
678
+ ...nestedFolded ?? {},
679
+ record: {
680
+ ...nestedRecord ?? {},
681
+ runId,
682
+ ...projection.taskId ? { taskId: projection.taskId } : {},
683
+ ...projection.title ? { title: projection.title } : {},
684
+ ...projection.startedAt ? { startedAt: projection.startedAt } : {},
685
+ ...projection.updatedAt ? { updatedAt: projection.updatedAt } : {},
686
+ ...projection.completedAt ? { completedAt: projection.completedAt } : {},
687
+ ...projection.sessionPath ? { sessionPath: projection.sessionPath } : {},
688
+ ...projection.worktreePath ? { worktreePath: projection.worktreePath } : {},
689
+ ...projection.prUrl ? { prUrl: projection.prUrl } : {}
690
+ },
691
+ status: toRunStatus(projection.status) ?? toRunStatus(nestedProjection?.status),
692
+ pendingApprovals,
693
+ pendingUserInputs,
694
+ steeringCount: projection.steeringCount ?? numberOrNull(nestedProjection?.steeringCount) ?? 0,
695
+ stallCount: projection.stallCount ?? numberOrNull(nestedProjection?.stallCount) ?? 0,
696
+ lastEventAt: projection.updatedAt ?? stringOrNull(nestedProjection?.lastEventAt)
697
+ };
698
+ }
699
+ function foldedProjectionForRun(runId, projection, sessionPath, toRunStatus) {
700
+ const registryFolded = emptyFoldedProjection(runId, projection, toRunStatus);
701
+ const sessionEntries = readSessionRunEntries(sessionPath);
702
+ if (sessionEntries.length === 0)
703
+ return { projection: registryFolded, hasSessionEntries: false };
704
+ const sessionFolded = foldRunSessionEntries(sessionEntries, runId);
705
+ if (sessionFolded.lastSeq === 0)
706
+ return { projection: registryFolded, hasSessionEntries: false };
707
+ return {
708
+ projection: {
709
+ ...registryFolded,
710
+ ...sessionFolded,
711
+ record: {
712
+ ...registryFolded.record,
713
+ ...sessionFolded.record,
714
+ runId
715
+ },
716
+ status: sessionFolded.status ?? registryFolded.status,
717
+ lastEventAt: sessionFolded.lastEventAt ?? registryFolded.lastEventAt
718
+ },
719
+ hasSessionEntries: true
720
+ };
721
+ }
722
+ function runRecordFromRegistryEntry(projectRoot, entry, toRunStatus) {
723
+ const projection = entry.projection && typeof entry.projection === "object" ? entry.projection : {};
724
+ const projectionRecord = projection;
725
+ const runId = stringOrNull(projection.runId) ?? entry.roomId;
726
+ const sessionPath = stringOrNull(projection.sessionPath) ?? stringOrNull(entry.sessionPath) ?? null;
727
+ const foldedResult = foldedProjectionForRun(runId, projection, sessionPath, toRunStatus);
728
+ const folded = foldedResult.projection;
729
+ const pushedStatus = folded.status ?? toRunStatus(projection.status) ?? toRunStatus(entry.status);
730
+ const status = entry.stale ? pushedStatus && isTerminalRunStatus(pushedStatus) ? pushedStatus : "stale" : pushedStatus ?? "running";
731
+ const collabCwd = stringOrNull(projection.collabCwd) ?? stringOrNull(projection.cwd) ?? stringOrNull(entry.cwd) ?? stringOrNull(projection.worktreePath);
732
+ const pendingApprovals = foldedResult.hasSessionEntries ? folded.pendingApprovals.length : numberOrNull(projectionRecord.pendingApprovals) ?? folded.pendingApprovals.length;
733
+ const pendingInputs = foldedResult.hasSessionEntries ? folded.pendingUserInputs.length : numberOrNull(projectionRecord.pendingInputs) ?? folded.pendingUserInputs.length;
734
+ return {
735
+ runId,
736
+ taskId: stringOrNull(projection.taskId),
737
+ title: stringOrNull(projection.title) ?? entry.title,
738
+ status,
739
+ source: sourceFromEntry(projectRoot, projection, entry),
740
+ live: !entry.stale,
741
+ stale: entry.stale,
742
+ startedAt: stringOrNull(projection.startedAt) ?? entry.startedAt ?? null,
743
+ updatedAt: stringOrNull(projection.updatedAt) ?? entry.heartbeatAt ?? null,
744
+ completedAt: stringOrNull(projection.completedAt),
745
+ joinLink: stringOrNull(projection.joinLink) ?? entry.joinLink ?? null,
746
+ webLink: stringOrNull(projection.webLink) ?? entry.webLink ?? null,
747
+ relayUrl: stringOrNull(projection.relayUrl) ?? entry.relayUrl ?? null,
748
+ sessionPath,
749
+ prUrl: stringOrNull(projection.prUrl),
750
+ worktreePath: stringOrNull(projection.worktreePath) ?? collabCwd,
751
+ pendingApprovals,
752
+ pendingInputs,
753
+ steeringCount: projection.steeringCount ?? folded.steeringCount ?? 0,
754
+ stallCount: projection.stallCount ?? folded.stallCount ?? 0,
755
+ errorSummary: stringOrNull(projection.errorSummary) ?? summarizeRunError(folded),
756
+ timeline: Array.isArray(projection.timeline) ? [...projection.timeline] : [...timelineEntriesFromCustomEntries([])],
757
+ inbox: inboxFromProjection(folded),
758
+ collabCwd: collabCwd ?? null,
759
+ projection: folded
760
+ };
761
+ }
762
+ function runRecordsFromCollab(projectRoot, collabs, toRunStatus) {
763
+ return sortByRecency(collabs.map((collab) => runRecordFromRegistryEntry(projectRoot, registryEntryFromCollab(collab), toRunStatus)).filter((record) => record !== null));
764
+ }
765
+ function sortByRecency(records) {
766
+ return [...records].sort((a, b) => {
767
+ const at = Date.parse(b.updatedAt ?? b.startedAt ?? "") || 0;
768
+ const bt = Date.parse(a.updatedAt ?? a.startedAt ?? "") || 0;
769
+ return at - bt;
770
+ });
771
+ }
772
+ function discoveryDiagnosticRunRecord(projectRoot, error) {
773
+ const detail = error instanceof Error ? error.message : String(error);
774
+ const runId = DISCOVERY_DIAGNOSTIC_RUN_ID;
775
+ const projection = {
776
+ ...EMPTY_PROJECTION,
777
+ record: { runId, title: "Registry discovery unavailable" },
778
+ status: "needs-attention",
779
+ stallCount: 1
780
+ };
781
+ return {
782
+ runId,
783
+ taskId: null,
784
+ title: "Registry discovery unavailable",
785
+ status: "needs-attention",
786
+ source: "remote",
787
+ live: false,
788
+ stale: true,
789
+ startedAt: null,
790
+ updatedAt: null,
791
+ completedAt: null,
792
+ joinLink: null,
793
+ webLink: null,
794
+ relayUrl: null,
795
+ sessionPath: null,
796
+ prUrl: null,
797
+ worktreePath: null,
798
+ pendingApprovals: 0,
799
+ pendingInputs: 0,
800
+ steeringCount: 0,
801
+ stallCount: 1,
802
+ errorSummary: `registry discovery unavailable: ${detail}`,
803
+ timeline: [],
804
+ inbox: [],
805
+ collabCwd: null,
806
+ projection
807
+ };
808
+ }
809
+ async function listRunProjections(projectRoot, filter = {}) {
810
+ try {
811
+ const discovery = await loadCapabilityForRoot(projectRoot, RunDiscoveryCap);
812
+ if (!discovery)
813
+ return [discoveryDiagnosticRunRecord(projectRoot, "run discovery capability unavailable")];
814
+ const backbone = await loadCapabilityForRoot(projectRoot, RunRegistryBackboneCap);
815
+ if (!backbone)
816
+ return [discoveryDiagnosticRunRecord(projectRoot, "run registry backbone capability unavailable")];
817
+ const collabs = await discovery.listActiveRunCollab(projectRoot, filter, { isRuntimeActiveStatus });
818
+ return runRecordsFromCollab(projectRoot, collabs, backbone.registryStatusToRunStatus);
819
+ } catch (error) {
820
+ return [discoveryDiagnosticRunRecord(projectRoot, error)];
821
+ }
822
+ }
823
+ function selectRunProjection(runs, runId) {
824
+ const exactRun = runs.find((run) => run.runId === runId);
825
+ if (exactRun)
826
+ return exactRun;
827
+ const exactTask = runs.find((run) => run.taskId === runId);
828
+ if (exactTask)
829
+ return exactTask;
830
+ const prefixMatches = runs.filter((run) => run.runId.startsWith(runId));
831
+ if (prefixMatches.length === 1)
832
+ return prefixMatches[0] ?? null;
833
+ if (prefixMatches.length > 1) {
834
+ const matches = prefixMatches.map((run) => run.runId).join(", ");
835
+ throw new Error(`Ambiguous run id prefix "${runId}" matched ${prefixMatches.length} runs: ${matches}`);
836
+ }
837
+ return runs.find((run) => run.runId === DISCOVERY_DIAGNOSTIC_RUN_ID) ?? null;
838
+ }
839
+ async function getRunProjection(projectRoot, runId, filter = {}) {
840
+ const runs = await listRunProjections(projectRoot, filter);
841
+ return selectRunProjection(runs, runId);
842
+ }
843
+ async function resolveRunJoinTarget(projectRoot, runId, filter = {}) {
844
+ const run = await getRunProjection(projectRoot, runId, filter);
845
+ if (!run || !run.joinLink)
846
+ return null;
847
+ return { runId: run.runId, taskId: run.taskId, joinLink: run.joinLink, cwd: run.collabCwd ?? run.sessionPath, stale: run.stale };
848
+ }
849
+ var RunDiscoveryCap, RunRegistryBackboneCap, EMPTY_PROJECTION, DISCOVERY_DIAGNOSTIC_RUN_ID = "__registry_discovery_error__", listRuns, getRun, resolveJoinTarget;
850
+ var init_projection = __esm(() => {
851
+ init_session_journal();
852
+ init_run_status();
853
+ RunDiscoveryCap = defineCapability(RUN_DISCOVERY);
854
+ RunRegistryBackboneCap = defineCapability(RUN_REGISTRY_BACKBONE);
855
+ EMPTY_PROJECTION = foldRunSessionEntries([], "");
856
+ listRuns = listRunProjections;
857
+ getRun = getRunProjection;
858
+ resolveJoinTarget = resolveRunJoinTarget;
859
+ });
860
+
861
+ // packages/run-plugin/src/read-model/read-model-backend/guard.ts
862
+ var TERMINAL = new Set(["completed", "failed", "stopped"]);
863
+ function runBlocksNewRunForTask(run) {
864
+ return run.live && !run.stale && !TERMINAL.has(run.status) && run.status !== "needs-attention" && run.status !== "needs_attention";
865
+ }
866
+ async function activeRunByTaskId(listRuns, projectRoot) {
867
+ const active = new Map;
868
+ for (const run of await listRuns(projectRoot)) {
869
+ if (run.taskId && runBlocksNewRunForTask(run) && !active.has(run.taskId))
870
+ active.set(run.taskId, run.runId);
871
+ }
872
+ return active;
873
+ }
874
+ async function assertNoActiveRunForTask(listRuns, projectRoot, taskId) {
875
+ const existing = (await activeRunByTaskId(listRuns, projectRoot)).get(taskId);
876
+ if (existing) {
877
+ throw new Error(`Task ${taskId} already has an active run: ${existing}. Attach instead: rig run attach ${existing} \u2014 or re-dispatch anyway with --force.`);
878
+ }
879
+ }
880
+ // packages/run-plugin/src/read-model/read-model-backend/inbox.ts
881
+ init_projection();
882
+ function promptFromPayload(payload, fallback) {
883
+ if (payload && typeof payload === "object") {
884
+ const record = payload;
885
+ for (const key of ["title", "message", "reason", "prompt", "summary"]) {
886
+ const value = record[key];
887
+ if (typeof value === "string" && value.trim().length > 0)
888
+ return value.trim();
889
+ }
890
+ }
891
+ return fallback;
892
+ }
893
+ function recordsFromRun(run, kind) {
894
+ const pending = kind === "approvals" ? run.projection.pendingApprovals : run.projection.pendingUserInputs;
895
+ return pending.map((request) => ({
896
+ runId: run.runId,
897
+ taskId: run.taskId,
898
+ requestId: request.requestId,
899
+ status: "pending",
900
+ prompt: promptFromPayload(request.payload, kind === "approvals" ? "Approval requested" : "Input requested"),
901
+ requestedAt: request.requestedAt,
902
+ payload: request.payload,
903
+ kind: kind === "approvals" ? "approval" : "input"
904
+ }));
905
+ }
906
+ function matchesFilters(run, filters) {
907
+ if (filters.run && run.runId !== filters.run)
908
+ return false;
909
+ if (filters.task && run.taskId !== filters.task && run.runId !== filters.task)
910
+ return false;
911
+ return true;
912
+ }
913
+ async function listInboxRecords(input, kind, filters = {}, deps = {}) {
914
+ const runs = await (deps.listRuns ?? listRuns)(input.projectRoot);
915
+ return runs.filter((run) => matchesFilters(run, filters)).flatMap((run) => recordsFromRun(run, kind));
916
+ }
917
+ // packages/run-plugin/src/read-model/read-model-backend/inspect.ts
918
+ init_projection();
919
+ import { RIG_RUN_LOG_ENTRY } from "@rig/contracts";
920
+ function asRecord(value) {
921
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
922
+ }
923
+ function firstString(record, keys) {
924
+ for (const key of keys) {
925
+ const value = record[key];
926
+ if (typeof value === "string" && value.trim().length > 0)
927
+ return value;
928
+ }
929
+ return null;
930
+ }
931
+ function stringifyLogPayload(value) {
932
+ if (typeof value === "string")
933
+ return value;
934
+ if (typeof value === "number" || typeof value === "boolean")
935
+ return String(value);
936
+ const record = asRecord(value);
937
+ if (!record)
938
+ return null;
939
+ const direct = firstString(record, ["line", "message", "text", "content", "output", "summary", "detail"]);
940
+ if (direct)
941
+ return direct;
942
+ try {
943
+ return JSON.stringify(record);
944
+ } catch {
945
+ return String(record);
946
+ }
947
+ }
948
+ function logLineFromValue(value) {
949
+ const record = asRecord(value);
950
+ if (!record)
951
+ return stringifyLogPayload(value);
952
+ const direct = firstString(record, ["line", "message", "text", "content", "output", "summary", "detail"]);
953
+ if (direct)
954
+ return direct;
955
+ if ("payload" in record)
956
+ return stringifyLogPayload(record.payload);
957
+ if ("data" in record)
958
+ return stringifyLogPayload(record.data);
959
+ return stringifyLogPayload(record);
960
+ }
961
+ function logLineFromSessionEntry(entry) {
962
+ if (entry.type !== "custom" || entry.customType !== RIG_RUN_LOG_ENTRY)
963
+ return null;
964
+ return logLineFromValue(entry.data);
965
+ }
966
+ function logLinesFromProjection(projection) {
967
+ const projected = projection;
968
+ const lines = [];
969
+ for (const key of ["logs", "logEntries", "journalLogs", "runLogs"]) {
970
+ const entries = projected[key];
971
+ if (!Array.isArray(entries))
972
+ continue;
973
+ for (const entry of entries) {
974
+ const line = logLineFromValue(entry);
975
+ if (line !== null)
976
+ lines.push(line);
977
+ }
978
+ }
979
+ return lines;
980
+ }
981
+ function extractRunLogs(run, deps = {}) {
982
+ const projectedLines = logLinesFromProjection(run.projection);
983
+ if (projectedLines.length > 0)
984
+ return projectedLines;
985
+ return (deps.readSessionRunEntries ?? readSessionRunEntries)(run.sessionPath).map(logLineFromSessionEntry).filter((line) => line !== null);
986
+ }
987
+ function summarizeRunFailures(run) {
988
+ const failures = [];
989
+ const useful = summarizeRunError(run.projection);
990
+ if (useful)
991
+ failures.push(`${run.runId}: ${useful}`);
992
+ if (run.status === "failed" || run.projection.status === "failed")
993
+ failures.push(`${run.runId}: run status failed`);
994
+ for (const phase of run.projection.closeoutPhases) {
995
+ if (phase.outcome === "failed")
996
+ failures.push(`${run.runId}: closeout ${phase.phase} failed${phase.detail ? ` \u2014 ${phase.detail}` : ""}`);
997
+ }
998
+ for (const anomaly of run.projection.anomalies) {
999
+ failures.push(`${run.runId}: anomaly ${anomaly.kind}${anomaly.detail ? ` \u2014 ${anomaly.detail}` : ""}`);
1000
+ }
1001
+ return failures;
1002
+ }
1003
+ async function runsForTask(projectRoot, taskId, deps = {}) {
1004
+ const list = deps.listRuns ?? listRuns;
1005
+ try {
1006
+ const runs = await list(projectRoot);
1007
+ const filtered = runs.filter((run2) => run2.taskId === taskId || run2.runId === taskId);
1008
+ if (filtered.length > 0)
1009
+ return [...filtered];
1010
+ } catch {}
1011
+ const run = await (deps.getRun ?? getRun)(projectRoot, taskId);
1012
+ return run ? [run] : [];
1013
+ }
1014
+ function runInspectSummaryRows(runs, options = {}) {
1015
+ const attachable = runs.filter((run) => Boolean(run.joinLink && !run.stale)).length;
1016
+ const pendingInbox = options.pendingInbox ?? runs.reduce((total, run) => total + run.pendingApprovals + run.pendingInputs, 0);
1017
+ return [
1018
+ { id: "title", label: "Inspect", currentValue: "runtime", heading: true, description: "session/runtime inspection rows from @rig/client" },
1019
+ { id: "inspect:sessions", label: "RUNS", currentValue: String(runs.length), heading: true, description: `${attachable} attachable OMP collab links` },
1020
+ { id: "inspect:cwd", label: "PROJECT ROOT", currentValue: options.projectRoot ?? "", heading: true, description: "selected target/project root used by Rig chrome" },
1021
+ { id: "inspect:inbox", label: "INBOX", currentValue: String(pendingInbox), values: ["open"], description: "pending run gates; open Inbox to resolve" },
1022
+ { id: "inspect:runs", label: "RUNS", currentValue: String(runs.length), values: ["open"], description: "open Runs to inspect individual run detail, logs, and attach controls" },
1023
+ { id: "inspect:audit", label: "AUDIT", currentValue: "unavailable", heading: true, description: "CLI inspect audit has no cockpit equivalent; use rig inspect audit" }
1024
+ ];
1025
+ }
1026
+
1027
+ // packages/run-plugin/src/read-model/read-model-backend/index.ts
1028
+ init_run_status();
1029
+
1030
+ // packages/run-plugin/src/read-model/read-model-backend/stats.ts
1031
+ init_run_status();
1032
+ init_run_status();
1033
+ function parseTimestamp(value) {
1034
+ if (!value)
1035
+ return null;
1036
+ const parsed = Date.parse(value);
1037
+ return Number.isFinite(parsed) ? parsed : null;
1038
+ }
1039
+ function median(values) {
1040
+ if (values.length === 0)
1041
+ return null;
1042
+ const sorted = [...values].sort((left, right) => left - right);
1043
+ const middle = Math.floor(sorted.length / 2);
1044
+ return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
1045
+ }
1046
+ function rate(part, total) {
1047
+ return total === 0 ? null : part / total;
1048
+ }
1049
+ function completedDuration(run) {
1050
+ if (run.status !== "completed")
1051
+ return null;
1052
+ const startedAt = parseTimestamp(run.startedAt);
1053
+ const completedAt = parseTimestamp(run.completedAt);
1054
+ if (startedAt === null || completedAt === null || completedAt < startedAt)
1055
+ return null;
1056
+ return completedAt - startedAt;
1057
+ }
1058
+ async function computeStats(projectRootOrRuns, options = {}) {
1059
+ const sinceMs = options.since ? options.since.getTime() : null;
1060
+ const allRuns = typeof projectRootOrRuns === "string" ? await (options.listRuns ?? (await Promise.resolve().then(() => (init_projection(), exports_projection))).listRuns)(projectRootOrRuns) : projectRootOrRuns;
1061
+ const runs = allRuns.filter((run) => {
1062
+ if (sinceMs === null)
1063
+ return true;
1064
+ const startedAt = parseTimestamp(run.startedAt);
1065
+ return startedAt !== null && startedAt >= sinceMs;
1066
+ });
1067
+ const statusCounts = {};
1068
+ const completionDurations = [];
1069
+ let completedRuns = 0;
1070
+ let failedRuns = 0;
1071
+ let needsAttentionRuns = 0;
1072
+ let steeringTotal = 0;
1073
+ let stallTotal = 0;
1074
+ let approvalsPending = 0;
1075
+ let approvalsApproved = 0;
1076
+ let approvalsRejected = 0;
1077
+ for (const run of runs) {
1078
+ const status = run.status || "unknown";
1079
+ statusCounts[status] = (statusCounts[status] ?? 0) + 1;
1080
+ if (status === "completed")
1081
+ completedRuns += 1;
1082
+ if (status === "failed")
1083
+ failedRuns += 1;
1084
+ if (isNeedsAttention(run))
1085
+ needsAttentionRuns += 1;
1086
+ const duration = completedDuration(run);
1087
+ if (duration !== null)
1088
+ completionDurations.push(duration);
1089
+ steeringTotal += run.steeringCount;
1090
+ stallTotal += run.stallCount;
1091
+ approvalsPending += run.projection.pendingApprovals.length;
1092
+ for (const approval of run.projection.resolvedApprovals) {
1093
+ if (approval.decision === "approve")
1094
+ approvalsApproved += 1;
1095
+ if (approval.decision === "reject")
1096
+ approvalsRejected += 1;
1097
+ }
1098
+ }
1099
+ const approvalsRequested = approvalsPending + approvalsApproved + approvalsRejected;
1100
+ const totalRuns = runs.length;
1101
+ return {
1102
+ since: options.since ? options.since.toISOString() : null,
1103
+ totalRuns,
1104
+ statusCounts,
1105
+ completedRuns,
1106
+ failedRuns,
1107
+ needsAttentionRuns,
1108
+ completionRate: rate(completedRuns, totalRuns),
1109
+ failureRate: rate(failedRuns, totalRuns),
1110
+ needsAttentionRate: rate(needsAttentionRuns, totalRuns),
1111
+ medianCompletionMs: median(completionDurations),
1112
+ steeringTotal,
1113
+ steeringPerRun: totalRuns === 0 ? null : steeringTotal / totalRuns,
1114
+ stallTotal,
1115
+ approvalsRequested,
1116
+ approvalsApproved,
1117
+ approvalsRejected,
1118
+ approvalsPending
1119
+ };
1120
+ }
1121
+
1122
+ // packages/run-plugin/src/read-model/read-model-backend/index.ts
1123
+ init_projection();
1124
+ export {
1125
+ summarizeRunFailures,
1126
+ summarizeRunError,
1127
+ stringifyLogPayload,
1128
+ statusRank,
1129
+ statusColorRole,
1130
+ runsForTask,
1131
+ runStatusText,
1132
+ runStatusColorRole,
1133
+ runInspectSummaryRows,
1134
+ runBlocksNewRunForTask,
1135
+ resolveRunJoinTarget,
1136
+ resolveJoinTarget,
1137
+ recordsFromRun,
1138
+ readSessionRunEntries,
1139
+ rate,
1140
+ parseTimestamp,
1141
+ normalizeRunStatusToken,
1142
+ median,
1143
+ logLinesFromProjection,
1144
+ logLineFromValue,
1145
+ logLineFromSessionEntry,
1146
+ listRuns,
1147
+ listInboxRecords,
1148
+ isRuntimeActiveStatus,
1149
+ isOperatorActiveRunStatus,
1150
+ isNeedsAttention,
1151
+ getRun,
1152
+ extractRunLogs,
1153
+ computeStats,
1154
+ completedDuration,
1155
+ classifyRun,
1156
+ canStop,
1157
+ canSteer,
1158
+ canResume,
1159
+ canPause,
1160
+ assertNoActiveRunForTask,
1161
+ asRunStatus,
1162
+ activeRunByTaskId
1163
+ };