@nandoblanco/opencode-relay-orchestration 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tui.ts ADDED
@@ -0,0 +1,413 @@
1
+ import { Plugin } from '@opencode/plugin/tui'
2
+ import { RGBA, TextAttributes } from '@opentui/core'
3
+ import { createElement, createTextNode, insert, insertNode, setProp, effect, type JSX } from '@opentui/solid'
4
+ import { createSignal, createEffect, createRoot } from 'solid-js'
5
+ import { RelayRpc, type RelayApi } from './rpc.ts'
6
+ import { phaseActions, isFinalTask, checkScope, type RecordInfo, type PhaseAction, type Owner, type RunInfo, type Evidence, type Check } from './model.ts'
7
+ import { canRecordManual, checkView, evidenceView, evidenceTitle } from './view.ts'
8
+ import { renderStatus, recordView, failureMessage, visibleError, approvalMessage, pendingMessage, signOffMessage, signOffError } from './view.ts'
9
+ import { type ConfigReport, type RoleCheck } from './config.ts'
10
+ import { auditSummary } from './report.ts'
11
+ import { validateAllowedPaths } from './scope.ts'
12
+
13
+ const FALLBACK = {
14
+ bg: RGBA.fromInts(20, 22, 26),
15
+ raised: RGBA.fromInts(27, 30, 36),
16
+ border: RGBA.fromInts(56, 62, 74),
17
+ text: RGBA.fromInts(235, 238, 244),
18
+ muted: RGBA.fromInts(156, 163, 175),
19
+ subtle: RGBA.fromInts(114, 122, 136),
20
+ accent: RGBA.fromInts(88, 166, 255),
21
+ ok: RGBA.fromInts(63, 185, 80),
22
+ warn: RGBA.fromInts(210, 153, 34),
23
+ err: RGBA.fromInts(248, 81, 73),
24
+ }
25
+
26
+ function palette(ctx: unknown) {
27
+ const theme = (ctx as { theme?: any })?.theme
28
+ return {
29
+ bg: theme?.background?.base ?? FALLBACK.bg,
30
+ raised: theme?.background?.raised?.base ?? FALLBACK.raised,
31
+ border: theme?.border?.base ?? FALLBACK.border,
32
+ text: theme?.text?.base ?? FALLBACK.text,
33
+ muted: theme?.text?.muted ?? FALLBACK.muted,
34
+ subtle: theme?.text?.faint ?? theme?.text?.subtle ?? FALLBACK.subtle,
35
+ accent: theme?.text?.action?.primary?.base ?? FALLBACK.accent,
36
+ ok: theme?.text?.feedback?.success?.base ?? FALLBACK.ok,
37
+ warn: theme?.text?.feedback?.warning?.base ?? FALLBACK.warn,
38
+ err: theme?.text?.feedback?.error?.base ?? FALLBACK.err,
39
+ }
40
+ }
41
+
42
+ type TuiPalette = ReturnType<typeof palette>
43
+
44
+ function el(tag: string, props: Record<string, any> = {}, ...children: any[]) {
45
+ const node = createElement(tag)
46
+ for (const key of Object.keys(props)) {
47
+ const desc = Object.getOwnPropertyDescriptor(props, key)
48
+ if (desc?.get) effect(() => setProp(node, key, desc.get!()))
49
+ else setProp(node, key, props[key])
50
+ }
51
+ for (const child of children) {
52
+ if (child == null || child === false) continue
53
+ if (typeof child === 'function') insert(node, child)
54
+ else if (typeof child === 'string' || typeof child === 'number') insertNode(node, createTextNode(String(child)))
55
+ else insertNode(node, child)
56
+ }
57
+ return node
58
+ }
59
+
60
+ function line(content: string, fg: RGBA, attributes?: number) {
61
+ return el('text', attributes === undefined ? { content, fg } : { content, fg, attributes })
62
+ }
63
+
64
+ function clip(text: string, max: number) {
65
+ const clean = text.replace(/\s+/g, ' ').trim()
66
+ return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean
67
+ }
68
+
69
+ function phaseColor(phase: RecordInfo['phase'], p: TuiPalette) {
70
+ if (phase === 'completed' || phase === 'approved') return p.ok
71
+ if (phase === 'running') return p.accent
72
+ if (phase === 'interrupted') return p.warn
73
+ if (phase === 'cancelled') return p.err
74
+ return p.muted
75
+ }
76
+
77
+ function taskTone(status: string, p: TuiPalette) {
78
+ if (status === 'completed') return { color: p.ok, icon: '✓' }
79
+ if (status === 'running') return { color: p.accent, icon: '●' }
80
+ if (status === 'blocked') return { color: p.err, icon: '✕' }
81
+ if (status === 'awaiting_approval') return { color: p.warn, icon: '◈' }
82
+ return { color: p.muted, icon: '○' }
83
+ }
84
+
85
+ function evidenceTone(label: string, manual: boolean | undefined, p: TuiPalette) {
86
+ if (manual) return { color: p.warn, icon: '◆' }
87
+ if (label.startsWith('Passed')) return { color: p.ok, icon: '✓' }
88
+ if (label.startsWith('Failed')) return { color: p.err, icon: '✕' }
89
+ if (label.startsWith('Deferred') || label.startsWith('Not applicable')) return { color: p.subtle, icon: '·' }
90
+ return { color: p.warn, icon: '◌' }
91
+ }
92
+
93
+ function roleRow(role: RoleCheck, p: TuiPalette) {
94
+ const invalid = role.errors.length > 0 || role.image === 'failed' || role.image === 'error'
95
+ const color = invalid ? p.err : role.model ? p.ok : p.warn
96
+ const icon = invalid ? '✕' : role.model ? '●' : '○'
97
+ const label = role.role.padEnd(9, ' ')
98
+ const model = role.model
99
+ ? `${role.model.providerID}/${role.model.id}${role.model.variant ? ` (${role.model.variant})` : ''}${role.role === 'reviewer' ? ` · image: ${role.image}` : ''}`
100
+ : 'not configured'
101
+ const nodes = [line(`${icon} ${label} ${model}`, color)]
102
+ for (const issue of role.errors) nodes.push(line(` ${issue}`, p.err))
103
+ if (role.probe) {
104
+ nodes.push(line(` ${role.probe.status === 'error' ? `Probe error (not cached): ${role.probe.answer}` : `Probe answer: ${role.probe.answer}`}`, role.probe.status === 'error' ? p.err : p.muted))
105
+ nodes.push(line(` Probe tokens: input ${role.probe.tokens.input}, output ${role.probe.tokens.output}, reasoning ${role.probe.tokens.reasoning}, cache read ${role.probe.tokens.cache.read}, cache write ${role.probe.tokens.cache.write}`, p.subtle))
106
+ }
107
+ return el('box', { flexDirection: 'column', width: '100%' }, ...nodes)
108
+ }
109
+
110
+ function taskSummaryCounts(tasks: ReturnType<typeof recordView>['tasks']) {
111
+ const counts = new Map<string, number>()
112
+ for (const task of tasks) counts.set(task.status, (counts.get(task.status) ?? 0) + 1)
113
+ return [...counts.entries()].map(([status, count]) => `${count} ${status.replaceAll('_', ' ')}`).join(' · ')
114
+ }
115
+
116
+ export default Plugin.define({ id: 'opencode-relay-orchestration', setup(ctx) {
117
+ const [record, setRecord] = createSignal<RecordInfo>()
118
+ const [runs, setRuns] = createSignal<RunInfo[]>([])
119
+ const [evidence, setEvidence] = createSignal<Evidence[]>([])
120
+ const [signingRevision, setSigningRevision] = createSignal<number>()
121
+ const [error, setError] = createSignal('')
122
+ const [config, setConfig] = createSignal<ConfigReport>()
123
+ async function checkConfig(probe = false) {
124
+ try {
125
+ const id = sessionID()
126
+ if (probe && !id) { ctx.ui.toast.show({ message: 'Select a session before running an image probe.', variant: 'error' }); return }
127
+ const result = probe ? await api().probeImage({ parentSessionID: id! }, options()) : await api().validateConfig({}, options())
128
+ setConfig(result)
129
+ const reviewer = result.roles.find(role => role.role === 'reviewer')
130
+ if (probe && (reviewer?.image === 'error' || reviewer?.image === 'failed')) ctx.ui.toast.show({ message: reviewer.image === 'error' ? 'The image probe encountered a host error. No vision verdict was cached.' : 'The image probe answer did not match the expected color.', variant: 'error' })
131
+ }
132
+ catch { ctx.ui.toast.show({ message: probe ? 'Could not run the image probe. Check the reviewer configuration and probe setting.' : 'Could not validate role configuration. Use Relay validate config to retry.', variant: 'error' }) }
133
+ }
134
+ const [panelFocused, setPanelFocused] = createSignal(false)
135
+ let generation = 0
136
+ const lastResults = new Map<string, string>()
137
+ const api = () => { if (!ctx.location) throw new Error('Select a session location before using Relay.'); return ctx.client.rpc(RelayRpc) as unknown as RelayApi }
138
+ const options = () => ({ location: ctx.location })
139
+ function sessionID() { const route = ctx.ui.router.current(); return route.type === 'session' ? route.sessionID : undefined }
140
+ async function refresh() {
141
+ if (!ctx.location) return
142
+ const token = ++generation
143
+ try {
144
+ setConfig(await api().validateConfig({}, options()))
145
+ const records = (await api().listRecords({}, options())).filter(item => item.location.directory === ctx.location?.directory)
146
+ const selected = records.find(item => item.id === record()?.id) ?? records.find(item => item.sessionID === sessionID()) ?? records[0]
147
+ const snapshot = selected ? await api().getSnapshot({ recordID: selected.id }, options()) : undefined
148
+ const runList = snapshot ? await api().listRuns({ recordID: snapshot.id }, options()) : []
149
+ const evidenceList = snapshot ? await api().listEvidence({ id: snapshot.id }, options()) : []
150
+ if (token === generation) {
151
+ setRecord(snapshot); setRuns(runList); setEvidence(evidenceList); setError('')
152
+ const resultKey = snapshot?.approvalResult ? JSON.stringify(snapshot.approvalResult) : ''
153
+ if (snapshot) {
154
+ if (lastResults.has(snapshot.id) && resultKey && resultKey !== lastResults.get(snapshot.id) && approvalMessage(snapshot)) ctx.ui.toast.show({ message: approvalMessage(snapshot), variant: snapshot?.approvalResult?.outcome === 'approved' ? 'success' : 'warning' })
155
+ lastResults.set(snapshot.id, resultKey)
156
+ }
157
+ }
158
+ } catch (failure) { if (token === generation) setError(failureMessage(failure)) }
159
+ }
160
+ async function run(work: () => Promise<RecordInfo>, requestApproval = false) {
161
+ setError('')
162
+ try { setRecord(await work()); await refresh() } catch (failure) { await refresh(); const message = visibleError(failure, record(), requestApproval); setError(message); if (message) ctx.ui.toast.show({ message, variant: 'error' }) }
163
+ }
164
+ const disposeWatch = createRoot(dispose => {
165
+ createEffect(() => { ctx.location; sessionID(); setRecord(undefined); setRuns([]); setEvidence([]); setSigningRevision(undefined); setConfig(undefined); void refresh() })
166
+ return dispose
167
+ })
168
+ const off = ctx.client.rpc(RelayRpc).events.on('changed', event => {
169
+ if (event.location.directory === ctx.location?.directory) void refresh()
170
+ })
171
+ const reconnect = ctx.data.on('server.connected', () => { void refresh() })
172
+ const slot = ctx.ui.slot({ append: 'session.panel', render(input) {
173
+ if (input.name !== 'opencode-relay-orchestration:status') { setPanelFocused(false); return null }
174
+ setPanelFocused(input.focused)
175
+ createEffect(() => setPanelFocused(input.focused))
176
+ createEffect(() => { input.sessionID; void refresh() })
177
+ const p = palette(ctx)
178
+ const header = el('box', { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: '100%' },
179
+ line('Relay', p.text, TextAttributes.BOLD),
180
+ el('text', {
181
+ get content() {
182
+ const current = record()
183
+ if (!current) return 'Idle'
184
+ const done = current.tasks.filter(task => task.status === 'completed').length
185
+ const progress = current.tasks.length ? ` · ${done}/${current.tasks.length}` : ''
186
+ return `● ${current.phase.toUpperCase()} · r${current.revision}${progress}`
187
+ },
188
+ get fg() {
189
+ const current = record()
190
+ return current ? phaseColor(current.phase, p) : p.subtle
191
+ },
192
+ attributes: TextAttributes.BOLD,
193
+ }),
194
+ )
195
+ const buildBody = () => {
196
+ const current = record()
197
+ const view = recordView(current, runs())
198
+ const cfg = config()
199
+ const sections: any[] = []
200
+
201
+ const err = error()
202
+ if (err) {
203
+ sections.push(el('box', { flexDirection: 'column', width: '100%', border: true, borderStyle: 'rounded', borderColor: p.err, paddingLeft: 1, paddingRight: 1 },
204
+ line(err, p.err),
205
+ ))
206
+ }
207
+
208
+ const pending = pendingMessage(current)
209
+ const approval = approvalMessage(current)
210
+ const signOff = signingRevision() !== undefined ? signOffMessage(signingRevision()!) : ''
211
+ if (pending) {
212
+ sections.push(el('box', { flexDirection: 'column', width: '100%', border: true, borderStyle: 'rounded', borderColor: p.warn, paddingLeft: 1, paddingRight: 1 },
213
+ line(`◌ ${pending}`, p.warn),
214
+ ))
215
+ }
216
+ if (approval) {
217
+ const ok = current?.approvalResult?.outcome === 'approved'
218
+ sections.push(el('box', { flexDirection: 'column', width: '100%', border: true, borderStyle: 'rounded', borderColor: ok ? p.ok : p.warn, paddingLeft: 1, paddingRight: 1 },
219
+ line(`${ok ? '✓' : '✕'} ${approval}`, ok ? p.ok : p.warn),
220
+ ))
221
+ }
222
+ if (signOff) {
223
+ sections.push(el('box', { flexDirection: 'column', width: '100%', border: true, borderStyle: 'rounded', borderColor: p.warn, paddingLeft: 1, paddingRight: 1 },
224
+ line(`◌ ${signOff}`, p.warn),
225
+ ))
226
+ }
227
+
228
+ if (!current) {
229
+ sections.push(el('box', { flexDirection: 'column', width: '100%', border: true, borderStyle: 'rounded', borderColor: p.border, backgroundColor: p.raised, paddingLeft: 1, paddingRight: 1 },
230
+ line(view.title, p.text, TextAttributes.BOLD),
231
+ line('Run /relay <task> or /relay-new to create a record.', p.muted),
232
+ ))
233
+ } else {
234
+ const heroNodes: any[] = [
235
+ line(clip(view.title, 200), p.text, TextAttributes.BOLD),
236
+ line(view.revision, p.subtle),
237
+ line(view.location, p.subtle),
238
+ line(view.phase, phaseColor(current.phase, p), TextAttributes.BOLD),
239
+ ]
240
+ if (view.reason) heroNodes.push(line(view.reason, p.warn))
241
+ heroNodes.push(line(view.tokens, p.muted))
242
+ if (view.plannerTokens) heroNodes.push(line(view.plannerTokens, p.muted))
243
+ sections.push(el('box', { flexDirection: 'column', width: '100%', border: true, borderStyle: 'rounded', borderColor: p.border, backgroundColor: p.raised, paddingLeft: 1, paddingRight: 1 }, ...heroNodes))
244
+
245
+ const taskHeader = el('box', { flexDirection: 'row', justifyContent: 'space-between', width: '100%' },
246
+ line(`Tasks (${view.tasks.length})`, p.accent, TextAttributes.BOLD),
247
+ line(view.tasks.length ? taskSummaryCounts(view.tasks) : 'None', p.subtle),
248
+ )
249
+ const taskCards = view.tasks.map(task => {
250
+ const tone = taskTone(task.status, p)
251
+ const stageLabel = task.attempt ? `${task.stage}, attempt ${task.attempt}` : task.stage
252
+ const ownerLabel = task.owner ? `owner ${task.owner.role}` : 'unassigned'
253
+ const cardNodes: any[] = [
254
+ el('box', { flexDirection: 'row', justifyContent: 'space-between', width: '100%' },
255
+ line(`${tone.icon} ${stageLabel}`, tone.color, TextAttributes.BOLD),
256
+ line(`${ownerLabel} · fixes ${task.fixCycles}`, p.subtle),
257
+ ),
258
+ line(clip(task.title, 220), p.text),
259
+ ]
260
+ if (task.scope) cardNodes.push(line(task.scope, p.subtle))
261
+ if (task.summary) cardNodes.push(line(clip(task.summary, 200), p.muted))
262
+ if (task.findings) cardNodes.push(line(task.findings, task.findings.includes('(0 major)') ? p.muted : p.warn))
263
+ if (task.checks) cardNodes.push(line(task.checks, task.checks.includes('failed') ? p.warn : p.muted))
264
+ return el('box', { flexDirection: 'column', width: '100%', border: true, borderStyle: 'rounded', borderColor: task.status === 'pending' ? p.border : tone.color, paddingLeft: 1, paddingRight: 1 }, ...cardNodes)
265
+ })
266
+ sections.push(el('box', { flexDirection: 'column', width: '100%', gap: 1 }, taskHeader, ...(taskCards.length ? taskCards : [line('No tasks yet.', p.subtle)])))
267
+
268
+ if (current.checks.length) {
269
+ const checkCards = current.checks.map(check => {
270
+ const policyText = check.policy === 'not-applicable' ? checkView(check).label : `${check.policy}${checkScope(check) === 'final' ? ' · Final gate' : ''}`
271
+ const checkNodes: any[] = [
272
+ el('box', { flexDirection: 'row', justifyContent: 'space-between', width: '100%' },
273
+ line(check.name, p.text, TextAttributes.BOLD),
274
+ line(policyText, p.subtle),
275
+ ),
276
+ line(`${check.adapter}: ${check.command}`, p.muted),
277
+ ]
278
+ if (check.policy !== 'not-applicable') {
279
+ for (const task of current.tasks) {
280
+ const latest = evidence().findLast(item => item.taskID === task.id && item.checkID === check.id)
281
+ const item = evidenceView(check, latest, runs(), checkScope(check) === 'final' && !isFinalTask(current, task.id))
282
+ const ev = evidenceTone(item.label, item.manual, p)
283
+ const shots = item.screenshots ? ` (${item.screenshots})` : ''
284
+ checkNodes.push(line(` ${ev.icon} ${evidenceTitle(task.title)}: ${item.label}${shots}`, ev.color))
285
+ }
286
+ }
287
+ return el('box', { flexDirection: 'column', width: '100%', border: true, borderStyle: 'rounded', borderColor: p.border, paddingLeft: 1, paddingRight: 1 }, ...checkNodes)
288
+ })
289
+ sections.push(el('box', { flexDirection: 'column', width: '100%', gap: 1 },
290
+ line(`Verification (${current.checks.length})`, p.accent, TextAttributes.BOLD),
291
+ ...checkCards,
292
+ ))
293
+ }
294
+
295
+ if (view.approvals.length) {
296
+ sections.push(el('box', { flexDirection: 'column', width: '100%' },
297
+ line('Approvals', p.accent, TextAttributes.BOLD),
298
+ ...view.approvals.map(item => line(`· ${item}`, p.muted)),
299
+ ))
300
+ }
301
+ }
302
+
303
+ if (cfg) {
304
+ const cfgNodes: any[] = [
305
+ line('Role configuration', p.accent, TextAttributes.BOLD),
306
+ ...(cfg.summary ? [line(cfg.summary, p.subtle)] : []),
307
+ line(`Limits: ${cfg.limits.maxRunningTasks} running tasks, ${cfg.limits.maxFixCycles} fix cycles`, p.subtle),
308
+ ...cfg.roles.map(role => roleRow(role, p)),
309
+ ...cfg.errors.map(issue => line(issue, p.err)),
310
+ ]
311
+ sections.push(el('box', { flexDirection: 'column', width: '100%', border: true, borderStyle: 'rounded', borderColor: p.border, paddingLeft: 1, paddingRight: 1 }, ...cfgNodes))
312
+ }
313
+
314
+ return el('box', { flexDirection: 'column', width: '100%', gap: 1 }, ...sections)
315
+ }
316
+
317
+ const scroll = el('scrollbox', { flexGrow: 1, width: '100%', flexDirection: 'column' }, () => buildBody())
318
+ const footer = el('box', { flexDirection: 'row', justifyContent: 'space-between', width: '100%' },
319
+ line('Esc: close Relay panel', p.subtle),
320
+ line('Ctrl+P: relay commands', p.subtle),
321
+ )
322
+ const root = el('box', { flexDirection: 'column', width: '100%', height: '100%', paddingLeft: 1, paddingRight: 1, paddingTop: 1, gap: 1, focusable: false, backgroundColor: p.bg }, header, scroll, footer)
323
+ return root as unknown as JSX.Element
324
+ } })
325
+ let layerRegistered = false
326
+ const appSlot = ctx.ui.slot({ append: 'app', render() {
327
+ if (!layerRegistered) {
328
+ layerRegistered = true
329
+ ctx.keymap.layer(() => ({ mode: 'global', enabled: () => panelFocused() && ctx.ui.panel.current()?.name === 'opencode-relay-orchestration:status', commands: [{ id: 'relay-panel-escape', bind: 'escape', title: 'Close Relay panel', run: () => { if (!panelFocused() || ctx.ui.panel.current()?.name !== 'opencode-relay-orchestration:status') return false; ctx.ui.panel.close(); setPanelFocused(false) } }] }))
330
+ ctx.keymap.layer(() => ({ mode: 'global', commands: [
331
+ { id: 'relay-validate-config', title: 'Relay validate config', description: 'Validate configured role models without prompting.', palette: true, slash: { name: 'relay-validate-config' }, run: () => checkConfig() },
332
+ { id: 'relay-probe-image', title: 'Relay run image probe', description: 'Explicitly probe the configured reviewer image input.', enabled: () => config()?.enableProbe === true && Boolean(config()?.roles.some(role => role.role === 'reviewer' && role.model && !role.errors.length)), palette: true, slash: { name: 'relay-probe-image' }, run: () => { if (config()?.enableProbe) return checkConfig(true) } },
333
+ { id: 'relay-status', title: 'Relay status', description: 'Open record status and approvals.', palette: true, slash: { name: 'relay-status' }, run: async () => { await refresh(); if (!ctx.ui.panel.open('opencode-relay-orchestration:status')) await ctx.ui.dialog.alert({ title: 'Relay', message: renderStatus(record(), runs(), evidence()) + '\n' + error() }) } },
334
+ { id: 'relay-audit', title: 'Relay audit', description: 'Show related records and worker summaries.', palette: true, slash: { name: 'relay-audit' }, run: async () => {
335
+ await refresh(); const current = record(); if (!current) { ctx.ui.toast.show({ message: 'No Relay record selected.', variant: 'error' }); return }
336
+ try {
337
+ const all = await api().listRecords({}, options())
338
+ const related = current.sessionID ? all.filter(item => item.sessionID === current.sessionID) : [current]
339
+ const summaries = await Promise.all((related.length ? related : [current]).map(async item => auditSummary(item, await api().listRuns({ recordID: item.id }, options()))))
340
+ await ctx.ui.dialog.alert({ title: 'Relay audit', message: summaries.join('\n\n') })
341
+ } catch { ctx.ui.toast.show({ message: 'Could not load Relay audit.', variant: 'error' }) }
342
+ } },
343
+ { id: 'relay-export', title: 'Relay export Markdown', description: 'Write the selected report to .relay/reports.', palette: true, slash: { name: 'relay-export' }, run: async () => {
344
+ const current = record(); if (!current) { ctx.ui.toast.show({ message: 'No Relay record selected.', variant: 'error' }); return }
345
+ try { const report = await api().exportReport({ recordID: current.id, write: true }, options()); ctx.ui.toast.show({ message: `Report written: ${report.path!}`, variant: 'success' }) }
346
+ catch (failure) { ctx.ui.toast.show({ message: failureMessage(failure) === 'Could not write report file.' ? 'Could not write report file.' : 'Could not export Relay report.', variant: 'error' }) }
347
+ } },
348
+ { id: 'relay-add-check', title: 'Add relay check', description: 'Add a verification check in draft.', enabled: () => record()?.phase === 'draft', palette: true, slash: { name: 'relay-add-check' }, run: async () => {
349
+ const current = record(); if (!current || current.phase !== 'draft') return
350
+ const name = await ctx.ui.dialog.prompt({ title: 'Check name' }); if (!name?.trim()) return
351
+ const command = await ctx.ui.dialog.prompt({ title: 'Check command' }); if (!command?.trim()) return
352
+ const adapter = await ctx.ui.dialog.prompt({ title: 'Adapter: command or playwright' }); if (!adapter) return
353
+ const policy = await ctx.ui.dialog.prompt({ title: 'Policy: automated-required, manual-allowed or not-applicable' }); if (!policy) return
354
+ const scopeInput = await ctx.ui.dialog.prompt({ title: 'Scope: task or final (blank for task)' })
355
+ const scope = scopeInput?.trim() || 'task'
356
+ const reason = policy === 'not-applicable' ? await ctx.ui.dialog.prompt({ title: 'Not applicable reason' }) : undefined
357
+ if (!['command', 'playwright'].includes(adapter) || !['automated-required', 'manual-allowed', 'not-applicable'].includes(policy) || !['task', 'final'].includes(scope) || policy === 'not-applicable' && !reason?.trim()) { ctx.ui.toast.show({ message: 'Choose a listed adapter, policy and scope (task or final), with a reason when not applicable.', variant: 'error' }); return }
358
+ await run(() => api().mutate({ recordID: current.id, expectedRevision: current.revision, op: { type: 'addCheck', check: { id: crypto.randomUUID(), name: name.trim(), command: command.trim(), adapter: adapter as Check['adapter'], policy: policy as Check['policy'], ...(scope === 'final' ? { scope: 'final' } : {}), ...(reason ? { reason: reason.trim() } : {}) } } }, options()))
359
+ } },
360
+ { id: 'relay-remove-check', title: 'Remove relay check', description: 'Remove a verification check in draft.', enabled: () => record()?.phase === 'draft', palette: true, slash: { name: 'relay-remove-check' }, run: async () => {
361
+ const current = record(); if (!current || current.phase !== 'draft') return
362
+ const number = await ctx.ui.dialog.prompt({ title: 'Check number', description: current.checks.map((check, index) => `${index + 1}: ${check.name}`).join('\n') })
363
+ const check = current.checks[Number(number) - 1]; if (!number || !check) return
364
+ await run(() => api().mutate({ recordID: current.id, expectedRevision: current.revision, op: { type: 'removeCheck', checkID: check.id } }, options()))
365
+ } },
366
+ { id: 'relay-manual-verify', title: 'Record manual relay verification', description: 'Request permission to record your manual verification.', enabled: () => record()?.phase === 'interrupted', palette: true, slash: { name: 'relay-manual-verify' }, run: async () => {
367
+ const current = record(); if (!current) return
368
+ const choices = current.tasks.flatMap(task => current.checks.filter(check => canRecordManual(current, task.id, check, evidence(), runs())).map(check => ({ task, check })))
369
+ if (!choices.length) return
370
+ const number = await ctx.ui.dialog.prompt({ title: 'Verification number', description: choices.map((item, index) => `${index + 1}: ${item.task.title}: ${item.check.name}`).join('\n') })
371
+ const selected = choices[Number(number) - 1]; if (!number || !selected) return
372
+ const note = await ctx.ui.dialog.prompt({ title: 'Manual verification note' }); if (!note?.trim()) return
373
+ await run(() => api().recordManual({ id: current.id, revision: current.revision, taskID: selected.task.id, checkID: selected.check.id, note: note.trim(), sessionID: sessionID() }, options()))
374
+ } },
375
+ { id: 'relay-close', title: 'Close relay panel', description: 'Close the Relay panel and return to the composer.', palette: true, slash: { name: 'relay-close' }, run: () => { setPanelFocused(false); ctx.ui.panel.close() } },
376
+ { id: 'relay-withdraw', title: 'Withdraw approval request', description: 'Withdraw the pending Relay approval request.', enabled: () => Boolean(record()?.pendingApproval), palette: true, slash: { name: 'relay-withdraw' }, run: async () => { const current = record(); if (!current?.pendingApproval) return; await run(() => api().withdrawApproval({ recordID: current.id, key: current.pendingApproval!.key }, options())) } },
377
+ { id: 'relay-new', title: 'New relay record', description: 'Create a record without starting work.', palette: true, slash: { name: 'relay-new' }, run: async () => { const title = await ctx.ui.dialog.prompt({ title: 'Record title' }); if (title) await run(() => api().createRecord({ title, sessionID: sessionID() }, options())) } },
378
+ { id: 'relay-add-task', title: 'Add relay task', description: 'Add a pending task to the selected record.', enabled: () => recordView(record()).canAdd, palette: true, slash: { name: 'relay-add-task' }, run: async () => { const current = record(); if (!ctx.location || !current) { ctx.ui.toast.show({ message: 'Select a session location and create a relay record first.', variant: 'error' }); return }; if (!recordView(current).canAdd) { ctx.ui.toast.show({ message: 'Plan edits are not available in this phase.', variant: 'error' }); return }; const title = await ctx.ui.dialog.prompt({ title: 'Task title' }); if (!title) return; const rawScope = await ctx.ui.dialog.prompt({ title: 'Allowed paths (optional, comma-separated; blank for unrestricted)' }); const entries = rawScope?.split(',').map(item => item.trim()).filter(Boolean) ?? []; const scoped = entries.length ? validateAllowedPaths(entries) : { ok: true as const, paths: undefined }; if (!scoped.ok) { ctx.ui.toast.show({ message: scoped.message, variant: 'error' }); return }; await run(() => api().mutate({ recordID: current.id, expectedRevision: current.revision, op: { type: 'addTask', title, ...(scoped.paths ? { allowedPaths: scoped.paths } : {}) } }, options())) } },
379
+ { id: 'relay-approve', title: 'Approve relay plan', description: 'Request approval in the record session.', enabled: () => recordView(record()).canApprove, palette: true, slash: { name: 'relay-approve' }, run: async () => { const current = record(); const id = sessionID(); if (!ctx.location || !current || !id) { ctx.ui.toast.show({ message: 'Select a session location and create a relay record first.', variant: 'error' }); return }; if (!recordView(current).canApprove) { ctx.ui.toast.show({ message: 'Plan approval is available only in draft.', variant: 'error' }); return }; await run(() => api().requestApproval({ recordID: current.id, expectedRevision: current.revision, kind: 'plan', sessionID: id }, options()), true) } },
380
+ { id: 'relay-signoff', title: 'Sign off relay record', description: 'Request human sign-off after every task is done.', enabled: () => recordView(record()).canSignOff && signingRevision() === undefined, palette: true, slash: { name: 'relay-signoff' }, run: async () => {
381
+ const current = record(); const id = sessionID()
382
+ if (!current || !id || !recordView(current).canSignOff || signingRevision() !== undefined) return
383
+ const token = generation
384
+ setSigningRevision(current.revision); setError('')
385
+ try { const result = await api().signOff({ recordID: current.id, expectedRevision: current.revision, sessionID: id }, options()); if (id === sessionID() && current.id === record()?.id) { setRecord(result); await refresh() } }
386
+ catch (failure) { if (id === sessionID() && current.id === record()?.id) { await refresh(); const message = signOffError(failure); setError(message); ctx.ui.toast.show({ message, variant: 'error' }) } }
387
+ finally { if (id === sessionID() && token <= generation) setSigningRevision(undefined) }
388
+ } },
389
+ ...(['start', 'interrupt', 'resume', 'complete', 'cancel'] as PhaseAction[]).map(action => ({ id: `relay-${action}`, title: `${action[0].toUpperCase() + action.slice(1)} relay record`, description: `Explicitly ${action} the selected relay record.`, enabled: () => Boolean(record() && phaseActions(record()!).includes(action)), palette: true as const, slash: { name: `relay-${action}` }, run: async () => {
390
+ const current = record()
391
+ if (!current || !phaseActions(current).includes(action)) { ctx.ui.toast.show({ message: 'This transition is not available. Check the phase and current plan approval.', variant: 'error' }); return }
392
+ const reason = action === 'interrupt' ? await ctx.ui.dialog.prompt({ title: 'Interrupt reason' }) : undefined
393
+ if (action === 'interrupt' && !reason?.trim()) return
394
+ await run(() => action === 'complete' ? api().signOff({ recordID: current.id, expectedRevision: current.revision, sessionID: sessionID() }, options()) : api().mutate({ recordID: current.id, expectedRevision: current.revision, op: action === 'interrupt' ? { type: action, reason: reason!.trim() } : { type: action } }, options()))
395
+ } })),
396
+ { id: 'relay-assign-task', title: 'Assign relay task owner', description: 'Assign a role and optional session to a task.', enabled: () => recordView(record()).canEdit, palette: true, slash: { name: 'relay-assign-task' }, run: async () => {
397
+ const current = record(); if (!current || !recordView(current).canEdit) return
398
+ const taskNumber = await ctx.ui.dialog.prompt({ title: 'Task number', description: current.tasks.map((task, index) => `${index + 1}: ${task.title}`).join('\n') })
399
+ if (!taskNumber) return
400
+ const task = current.tasks[Number(taskNumber) - 1]
401
+ if (!task || task.status === 'running') { ctx.ui.toast.show({ message: 'Choose a task that is not running.', variant: 'error' }); return }
402
+ const role = await ctx.ui.dialog.prompt({ title: 'Owner role: planner, builder or reviewer' })
403
+ if (!role) return
404
+ if (!['planner', 'builder', 'reviewer'].includes(role)) { ctx.ui.toast.show({ message: 'Choose planner, builder or reviewer.', variant: 'error' }); return }
405
+ const ownerSession = await ctx.ui.dialog.prompt({ title: 'Owner session ID (optional)' })
406
+ await run(() => api().mutate({ recordID: current.id, expectedRevision: current.revision, op: { type: 'assignTask', taskID: task.id, owner: { role: role as Owner['role'], ...(ownerSession?.trim() ? { sessionID: ownerSession.trim() } : {}) } } }, options()))
407
+ } },
408
+ ] }))
409
+ }
410
+ return null
411
+ } })
412
+ return () => { generation++; disposeWatch(); off(); reconnect(); slot(); appSlot() }
413
+ } })
package/src/verify.ts ADDED
@@ -0,0 +1,82 @@
1
+ import { stat, readdir, readFile } from 'node:fs/promises'
2
+ import { resolve, join } from 'node:path'
3
+ import { createRequire } from 'node:module'
4
+ import { createHash } from 'node:crypto'
5
+ import type { Check, Evidence } from './model.ts'
6
+
7
+ export type Preflight = { childProcess: boolean; checks: { checkID: string; available: boolean; reason?: string }[] }
8
+ export type CheckResult = Omit<Evidence, 'id' | 'recordID' | 'taskID' | 'checkID' | 'buildRunID'>
9
+ export const MAX_SCREENSHOT_COUNT = 8
10
+ export const MAX_SCREENSHOT_BYTES = 12 * 1024 * 1024
11
+ const childProcess = () => import('node:child_process')
12
+ export async function preflight(directory: string, checks: Check[], importer = childProcess, requireFrom = createRequire): Promise<Preflight> {
13
+ let available = false
14
+ try { await importer(); available = true } catch {}
15
+ let exists = false
16
+ try { exists = (await stat(directory)).isDirectory() } catch {}
17
+ const results = checks.map(check => {
18
+ let reason = !available ? 'child_process unavailable' : !exists ? 'directory unavailable' : ''
19
+ if (!reason && check.adapter === 'playwright') {
20
+ const require = requireFrom(resolve(directory, 'package.json'))
21
+ let found = false
22
+ for (const name of ['playwright', '@playwright/test']) { try { require.resolve(name); found = true; break } catch {} }
23
+ if (!found) reason = 'Playwright package unavailable'
24
+ }
25
+ return { checkID: check.id, available: !reason, ...(reason ? { reason } : {}) }
26
+ })
27
+ return { childProcess: available, checks: results }
28
+ }
29
+ export async function runCheck(directory: string, check: Check, signal?: AbortSignal, importer = childProcess): Promise<CheckResult> {
30
+ const startedAt = Date.now(); let output = ''; let timedOut = false
31
+ const { spawn } = await importer()
32
+ signal?.throwIfAborted()
33
+ const exitCode = await new Promise<number>((done, reject) => {
34
+ const child = spawn(check.command, { shell: true, cwd: directory, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], ...(process.platform !== 'win32' ? { detached: true } : {}) })
35
+ const append = (data: Buffer) => { output = (output + data.toString()).slice(-4000) }
36
+ child.stdout?.on('data', append); child.stderr?.on('data', append)
37
+ function kill() {
38
+ if (process.platform === 'win32' && child.pid) {
39
+ const kill = spawn('taskkill', ['/T', '/F', '/PID', String(child.pid)], { windowsHide: true })
40
+ kill.on('error', reject)
41
+ } else {
42
+ try { if (!child.pid) throw Error('missing pid'); process.kill(-child.pid, 'SIGKILL') }
43
+ catch { child.kill('SIGKILL') }
44
+ }
45
+ }
46
+ const timer = setTimeout(() => { timedOut = true; kill() }, check.timeoutMs ?? 300000)
47
+ const abort = () => { kill() }
48
+ signal?.addEventListener('abort', abort, { once: true })
49
+ let exitTimer: ReturnType<typeof setTimeout> | undefined
50
+ function cleanup() { clearTimeout(timer); clearTimeout(exitTimer); signal?.removeEventListener('abort', abort) }
51
+ child.on('error', error => { cleanup(); reject(error) })
52
+ child.on('exit', code => { exitTimer = setTimeout(() => { cleanup(); done(code ?? -1) }, 2000) })
53
+ child.on('close', code => { cleanup(); done(code ?? -1) })
54
+ })
55
+ signal?.throwIfAborted()
56
+ const screenshots: Evidence['screenshots'] = []
57
+ let capReason: string | undefined
58
+ if (check.adapter === 'playwright' && exitCode === 0 && !timedOut) {
59
+ const found: { path: string; bytes: number }[] = []
60
+ async function collect(path: string) {
61
+ let entries
62
+ try { entries = await readdir(path, { withFileTypes: true }) } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error }
63
+ for (const entry of entries) {
64
+ const file = join(path, entry.name)
65
+ if (entry.isDirectory()) await collect(file)
66
+ else if (entry.isFile() && /\.png$/i.test(entry.name)) {
67
+ const info = await stat(file)
68
+ if (info.mtimeMs >= startedAt) found.push({ path: file, bytes: info.size })
69
+ }
70
+ }
71
+ }
72
+ await collect(resolve(directory, check.screenshotDir ?? '.screenshots'))
73
+ found.sort((a, b) => a.path.localeCompare(b.path))
74
+ const totalBytes = found.reduce((sum, item) => sum + item.bytes, 0)
75
+ if (found.length > MAX_SCREENSHOT_COUNT) capReason = `screenshot cap exceeded: ${found.length} files exceeds limit ${MAX_SCREENSHOT_COUNT}`
76
+ else if (totalBytes > MAX_SCREENSHOT_BYTES) capReason = `screenshot cap exceeded: ${totalBytes} bytes exceeds limit ${MAX_SCREENSHOT_BYTES}`
77
+ else for (const item of found) screenshots.push({ path: item.path, sha256: createHash('sha256').update(await readFile(item.path)).digest('hex'), bytes: item.bytes })
78
+ }
79
+ const endedAt = Date.now()
80
+ return { result: exitCode !== 0 || timedOut || capReason ? 'failed' : check.adapter === 'playwright' && !screenshots.length ? 'unverified' : 'passed', source: 'adapter', exitCode, output, screenshots,
81
+ ...(timedOut ? { reason: 'check timed out' } : capReason ? { reason: capReason } : check.adapter === 'playwright' && !screenshots.length && exitCode === 0 ? { reason: 'no screenshots produced' } : {}), startedAt, endedAt, durationMs: endedAt - startedAt }
82
+ }