@nandoblanco/opencode-relay-orchestration 0.0.0-stage → 1.0.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/view.ts ADDED
@@ -0,0 +1,124 @@
1
+ import type { RecordInfo, RunInfo, Check, Evidence } from './model.ts'
2
+ import { statuses, phaseActions, checkScope, isFinalTask } from './model.ts'
3
+ export function approvalMessage(record?: RecordInfo) {
4
+ const result = record?.approvalResult
5
+ if (!result) return ''
6
+ if (record?.pendingApproval?.revision === record?.revision) return ''
7
+ if ((record!.schemaVersion as number) >= 2 && result.outcome === 'approved') {
8
+ if (record!.phase !== 'approved') return ''
9
+ if (!record!.approvals.some(approval => approval.revision === result.revision && approval.planRevision === record!.planRevision)) return ''
10
+ } else if (record!.revision !== result.revision + (result.outcome === 'approved' ? 1 : 0)) return ''
11
+ return result.outcome === 'approved' ? `Plan approved for revision ${result.revision}` : result.outcome === 'withdrawn' ? 'Approval request withdrawn' : result.outcome === 'rejected' ? 'Approval rejected' : 'Plan changed; approval not recorded'
12
+ }
13
+ export function pendingMessage(record?: RecordInfo) {
14
+ return record?.pendingApproval ? `Waiting for approval of revision ${record.pendingApproval.revision}` : ''
15
+ }
16
+ export function failureMessage(failure: unknown) {
17
+ const messages: Record<string, string> = { stale_revision: 'This record changed. Review the refreshed snapshot and retry.', approval_pending: 'An approval request is already waiting in the session prompt.', approval_denied: 'The approval request was denied.', invalid_op: 'This action is not available for the selected record or session.', not_found: 'This record could not be found. Refresh to choose another.', storage_inconsistent: 'Storage verification failed. Stop making changes and check the server.' }
18
+ // SDK Rpc.Failure is a plain object, not necessarily an Error instance.
19
+ const rpc = failure as { type: string; message: string; data?: { currentRevision: number } }
20
+ const code = failure instanceof Error ? failure.message : typeof failure === 'string' ? failure : rpc?.type
21
+ const detail = failure instanceof Error ? failure.message : rpc?.message
22
+ if (rpc?.type === 'invalid_op' && typeof detail === 'string' && /^Check "[^\r\n]*" contains unsupported characters or settings; remove and re-add it\.$/.test(detail)) return detail
23
+ if (rpc?.type === 'invalid_op' && detail === 'Could not write report file.') return detail
24
+ if (code === 'approval_required') return 'Approve the current plan before starting or resuming work.'
25
+ if (code === 'approval_withdrawn') return 'Approval request withdrawn'
26
+ if (code === 'verification_incomplete') return 'Verification is incomplete. Run the current checks and independent review before sign-off.'
27
+ if (code === 'limit_exceeded') return 'A record limit was exceeded. Check title, task text, owner session and interrupt reason lengths, task count, running tasks and fix cycles.'
28
+ if (Object.hasOwn(messages, code)) return messages[code]
29
+ return 'This action could not be completed. Refresh and try again.'
30
+ }
31
+ export function formatTimestamp(value: string) { return new Date(value).toLocaleString() }
32
+ export function visibleError(failure: unknown, record?: RecordInfo, requestApproval = false) {
33
+ const code = failure instanceof Error ? failure.message : typeof failure === 'string' ? failure : (failure as { type?: string })?.type
34
+ const matching = code === 'stale_revision' && record?.approvalResult?.outcome === 'stale' || code === 'approval_denied' && record?.approvalResult?.outcome === 'rejected' || code === 'approval_withdrawn' && record?.approvalResult?.outcome === 'withdrawn'
35
+ return requestApproval && matching && approvalMessage(record) ? '' : failureMessage(failure)
36
+ }
37
+ export function signOffMessage(revision: number) { return `Waiting for sign-off of revision ${revision}` }
38
+ export function signOffError(failure: unknown) {
39
+ const code = failure instanceof Error ? failure.message : typeof failure === 'string' ? failure : (failure as { type?: string })?.type
40
+ return code === 'approval_denied' ? 'Sign-off was denied. The record is still running.' : failureMessage(failure)
41
+ }
42
+ export function tokenTotals(runs: RunInfo[]) {
43
+ const total = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }
44
+ for (const run of runs) if (run.tokens) {
45
+ total.input += run.tokens.input; total.output += run.tokens.output; total.reasoning += run.tokens.reasoning
46
+ total.cache.read += run.tokens.cache.read; total.cache.write += run.tokens.cache.write
47
+ }
48
+ return total
49
+ }
50
+ export function tokensMessage(runs: RunInfo[]) {
51
+ const total = tokenTotals(runs)
52
+ return `Tokens: input ${total.input}, output ${total.output}, reasoning ${total.reasoning}, cache read ${total.cache.read}, cache write ${total.cache.write}`
53
+ }
54
+ export function plannerTokensMessage(record?: RecordInfo) {
55
+ const tracking = record?.plannerSession
56
+ if (!tracking) return ''
57
+ const end = tracking.tokensAtEnd; const start = tracking.tokensAtStart
58
+ if (!end) return `Planner session tokens: ${record && ['completed', 'cancelled'].includes(record.phase) ? 'unavailable' : 'tracking'}`
59
+ if (end.input < start.input || end.output < start.output || end.reasoning < start.reasoning || end.cache.read < start.cache.read || end.cache.write < start.cache.write) return 'Planner session tokens: unavailable (session total decreased)'
60
+ return `Planner session tokens: input +${end.input - start.input}, output +${end.output - start.output}, reasoning +${end.reasoning - start.reasoning}, cache read +${end.cache.read - start.cache.read}`
61
+ }
62
+ export function interruptionMessage(reason?: string) {
63
+ if (!reason) return ''
64
+ if (reason === 'server_restart') return 'Interrupted: server restarted. Resume explicitly to continue.'
65
+ if (reason === 'escalated: screenshot inspection incomplete') return 'Screenshot inspection incomplete. The reviewer must inspect and list every attached screenshot by its exact name. Resolve the blocked task, then resume.'
66
+ if (reason === 'escalated: screenshot review unavailable') return 'Screenshot review unavailable. Configure a reviewer model with image input and validate it or run the image probe, then resolve the blocked task and resume.'
67
+ if (reason === 'escalated: screenshot changed after check') return 'Screenshot changed after check. Restore the verification output, resolve the blocked task and resume to recheck the screenshot before review.'
68
+ if (reason.startsWith('verification unavailable: ')) return `Verification unavailable: ${reason.slice(26)}. Configure the environment, then resume.`
69
+ if (reason.startsWith('manual verification required: ')) return `Manual verification required: ${reason.slice(30)}. Record your verification, then resume.`
70
+ return reason.startsWith('escalated:') ? `Needs your attention: ${reason.slice(10).trim()}. Resolve the blocked task, then resume.` : `Interrupted: ${reason}`
71
+ }
72
+ export function evidenceTitle(title: string, limit = 40) {
73
+ const clean = title.replace(/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069]/g, ' ').replace(/\s+/g, ' ').trim().replace(/[.\s]+$/, '')
74
+ const points = Array.from(clean)
75
+ return points.length > limit ? points.slice(0, limit - 1).join('').replace(/[.\s]+$/, '') + '…' : clean
76
+ }
77
+ export function checkView(check: Check) {
78
+ return { ...check, label: check.policy === 'not-applicable' ? `Not applicable: ${check.reason}` : `${check.name} (${check.policy}${checkScope(check) === 'final' ? ', final gate' : ''})` }
79
+ }
80
+ export function canRecordManual(record: RecordInfo, taskID: string, check: Check, evidence: Evidence[], runs: RunInfo[]) {
81
+ const task = record.tasks.find(task => task.id === taskID)
82
+ const build = runs.findLast(run => run.taskID === taskID && run.stage === 'build' && run.status === 'reported')
83
+ const latest = evidence.findLast(item => item.taskID === taskID && item.checkID === check.id && item.buildRunID === build?.id)
84
+ return check.policy === 'manual-allowed' && record.phase === 'interrupted' && record.interruptReason === `manual verification required: ${check.name}` && task?.status === 'running' && task.owner?.role === 'reviewer' && latest?.result === 'unverified'
85
+ }
86
+ export function evidenceView(check: Check, evidence: Evidence | undefined, runs: RunInfo[], deferred = false) {
87
+ const build = evidence && runs.findLast(run => run.taskID === evidence.taskID && run.stage === 'build' && run.status === 'reported')
88
+ const stale = Boolean(evidence && evidence.buildRunID !== build?.id)
89
+ const label = check.policy === 'not-applicable' ? `Not applicable: ${check.reason}` : !evidence ? (deferred ? 'Deferred to final gate' : 'Unverified: no evidence') : evidence.result === 'passed' ? 'Passed (plugin-run)' : evidence.result === 'failed' ? 'Failed (plugin-run)' : evidence.result === 'manually verified' ? `Manually verified by user: ${evidence.note}` : `Unverified: ${evidence.reason}`
90
+ return { label: label + (stale ? ' (stale)' : ''), stale, screenshots: evidence?.screenshots.length ? `${evidence.screenshots.length} screenshot(s)` : '', manual: evidence?.result === 'manually verified' }
91
+ }
92
+ export function taskView(task: RecordInfo['tasks'][number], runs: RunInfo[]) {
93
+ const latest = runs.findLast(run => run.taskID === task.id)
94
+ const report = runs.findLast(run => run.taskID === task.id && run.report)?.report
95
+ const review = runs.findLast(run => run.taskID === task.id && run.report && 'findings' in run.report)?.report
96
+ const build = runs.findLast(run => run.taskID === task.id && run.report && 'checks' in run.report)?.report
97
+ const findings = review && 'findings' in review ? review.findings : []
98
+ const failed = build && 'checks' in build ? build.checks.filter(check => check.result === 'failed').length : 0
99
+ const stage = task.status === 'completed' ? 'Done' : task.status === 'blocked' ? 'Blocked' : task.status === 'running' ? task.owner?.role === 'reviewer' ? 'Reviewing' : 'Building' : task.status === 'pending' ? 'Pending' : 'Awaiting approval'
100
+ return { id: task.id, title: task.title, status: task.status, label: task.status.replaceAll('_', ' '), owner: task.owner, fixCycles: task.fixCycles,
101
+ scope: task.allowedPaths?.length ? `Scope: ${task.allowedPaths.join(', ')}` : '',
102
+ stage, attempt: latest?.attempt, summary: report?.summary ?? '', findings: review ? `${findings.length} finding${findings.length === 1 ? '' : 's'} (${findings.filter(item => item.severity === 'major').length} major)` : '',
103
+ checks: build && 'checks' in build ? failed ? `Builder self-checks: ${build.checks.length - failed} passed, ${failed} failed (self-reported, unverified)` : `${build.checks.length} builder check${build.checks.length === 1 ? '' : 's'} (self-reported, unverified)` : '' }
104
+ }
105
+ export function recordView(record?: RecordInfo, runs: RunInfo[] = []) {
106
+ return record ? {
107
+ title: record.title, revision: `Revision ${record.revision}`, location: record.location.directory,
108
+ phase: `Phase: ${record.phase}`, reason: record.phase === 'cancelled' && record.cancelReason ? `Cancelled: ${record.cancelReason}` : record.phase === 'approved' ? 'Plan approved. Choose Start in the panel or TUI to begin work.' : interruptionMessage(record.interruptReason), actions: phaseActions(record), canAdd: ['draft', 'approved', 'interrupted'].includes(record.phase), canEdit: !['running', 'completed', 'cancelled'].includes(record.phase), canApprove: record.phase === 'draft',
109
+ canSignOff: record.phase === 'running' && record.tasks.length > 0 && record.tasks.every(task => task.status === 'completed'), tokens: tokensMessage(runs), plannerTokens: plannerTokensMessage(record),
110
+ tasks: record.tasks.map(task => taskView(task, runs)),
111
+ approvals: [...(record.approvals.length > 3 ? [`(${record.approvals.length - 3} earlier)`] : []), ...record.approvals.slice(-3).map(approval => `Plan approved for revision ${approval.revision} at ${formatTimestamp(approval.approvedAt)} (permission assert)`)],
112
+ } : { title: 'No relay record', revision: '', location: '', phase: '', reason: '', actions: [], canAdd: false, canEdit: false, canApprove: false, canSignOff: false, tokens: '', plannerTokens: '', tasks: [], approvals: [] }
113
+ }
114
+ export function renderStatus(record?: RecordInfo, runs: RunInfo[] = [], evidence: Evidence[] = []) {
115
+ const view = recordView(record, runs)
116
+ const counts = statuses.map(status => { const count = view.tasks.filter(task => task.status === status).length; return count ? `${count} ${status.replaceAll('_', ' ')}` : '' }).filter(Boolean).join(', ')
117
+ const tasks = ['Tasks', counts || 'No tasks yet', ...view.tasks.slice(0, 12).map(task => {
118
+ const summary = Array.from(task.summary.replace(/\s+/g, ' ').trim())
119
+ const shown = summary.length > 157 ? summary.slice(0, 157).join('').replace(/[.\s]+$/, '') + '...' : summary.join('')
120
+ return `${task.label}: ${task.title}\n ${task.stage}${task.attempt ? `, attempt ${task.attempt}` : ''}${task.owner ? `, owner ${task.owner.role}` : ''}${task.scope ? `\n ${task.scope}` : ''}${shown ? `\n ${shown}` : ''}${task.findings ? `\n ${task.findings}` : ''}${task.checks ? `\n ${task.checks}` : ''}`
121
+ }), ...(view.tasks.length > 12 ? [`(+${view.tasks.length - 12} more tasks)`] : [])].join('\n')
122
+ const verification = record?.checks.length ? ['Verification', ...record.checks.slice(0, 12).flatMap(check => [checkView(check).label, ` Command: ${check.command}`, ...(check.policy === 'not-applicable' ? [] : record.tasks.slice(0, 12).map(task => { const latest = evidence.findLast(item => item.taskID === task.id && item.checkID === check.id); const item = evidenceView(check, latest, runs, checkScope(check) === 'final' && !isFinalTask(record, task.id)); return ` ${evidenceTitle(task.title)}: ${item.label}${item.screenshots ? `; ${item.screenshots}` : ''}` }))]), ...(record.checks.length > 12 ? [`(+${record.checks.length - 12} more checks)`] : [])].join('\n') : ''
123
+ return [[view.title, view.revision, view.location, view.phase, view.reason, view.tokens, view.plannerTokens].filter(Boolean).join('\n'), tasks, ...(verification ? [verification] : []), ...(view.approvals.length ? [['Approvals', ...view.approvals].join('\n')] : []), ...(view.actions.length ? [`Actions:\n${view.actions.map(action => `relay-${action === 'complete' ? 'signoff' : action}`).join('\n')}`] : [])].join('\n\n')
124
+ }