@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/store.ts ADDED
@@ -0,0 +1,300 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { readLimits } from './config.ts'
3
+ import type { Plugin } from '@opencode/plugin'
4
+ type Context = Plugin.Context
5
+
6
+ import { statuses, transitions, isApproved, checkScope, type RecordInfo, type Op, type Phase, type PhaseAction, type RunInfo, type Check, type Evidence } from './model.ts'
7
+ import { validateAllowedPaths } from './scope.ts'
8
+ export { statuses, phases, transitions, phaseActions, isApproved, type RecordInfo, type Op, type Status, type Phase, type PhaseAction, type Owner } from './model.ts'
9
+ export class StoreError extends Error {
10
+ code: 'stale_revision' | 'not_found' | 'approval_denied' | 'approval_withdrawn' | 'approval_required' | 'invalid_op' | 'approval_pending' | 'storage_inconsistent' | 'limit_exceeded' | 'verification_incomplete'
11
+ currentRevision?: number
12
+ constructor(code: StoreError['code'], currentRevision?: number, message?: string) {
13
+ super(message ?? code); this.code = code; this.currentRevision = currentRevision
14
+ }
15
+ }
16
+ export function migrate(value: unknown): RecordInfo {
17
+ let record = structuredClone(value) as RecordInfo
18
+ if ((record.schemaVersion as number) === 1) {
19
+ const approved = isApproved(record, 'plan')
20
+ const planRevision = approved ? record.approvals.at(-1)!.revision : record.revision
21
+ record = { ...record, schemaVersion: 2 as 3, planRevision, phase: approved ? 'approved' : 'draft', tasks: record.tasks.map(task => ({ ...task, fixCycles: 0 })), approvals: record.approvals.map(approval => ({ ...approval, planRevision: approval.revision })) }
22
+ }
23
+ if ((record.schemaVersion as number) === 2) record = { ...record, schemaVersion: 3, checks: [] }
24
+ return record
25
+ }
26
+ export function validateCheck(check: Check) {
27
+ if (!check || typeof check !== 'object' || Object.keys(check).some(key => !['id', 'name', 'adapter', 'command', 'policy', 'scope', 'reason', 'screenshotDir', 'timeoutMs'].includes(key))) throw new StoreError('invalid_op')
28
+ for (const [key, max] of [['id', 200], ['name', 120], ['command', 160]] as const) if (typeof check[key] !== 'string' || !check[key].trim() || Array.from(check[key]).length > max) throw new StoreError('invalid_op')
29
+ for (const value of [check.name, check.command, check.reason, check.screenshotDir]) if (typeof value === 'string' && /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\u{e0000}-\u{e007f}]/u.test(value)) throw new StoreError('invalid_op')
30
+ if (!['command', 'playwright'].includes(check.adapter) || !['automated-required', 'manual-allowed', 'not-applicable'].includes(check.policy)) throw new StoreError('invalid_op')
31
+ if (check.scope !== undefined && !['task', 'final'].includes(check.scope)) throw new StoreError('invalid_op')
32
+ if (check.reason !== undefined && (typeof check.reason !== 'string' || Array.from(check.reason).length > 500) || check.policy === 'not-applicable' && !check.reason?.trim()) throw new StoreError('invalid_op')
33
+ if (check.screenshotDir !== undefined && (check.adapter !== 'playwright' || typeof check.screenshotDir !== 'string' || !check.screenshotDir.trim() || /^(?:[a-z]:|[\\/])/i.test(check.screenshotDir) || check.screenshotDir.split(/[\\/]/).includes('..'))) throw new StoreError('invalid_op')
34
+ if (check.timeoutMs !== undefined && (!Number.isSafeInteger(check.timeoutMs) || check.timeoutMs <= 0 || check.timeoutMs > 1800000)) throw new StoreError('invalid_op')
35
+ }
36
+
37
+ // One writer for every store instance in this module, including different locations.
38
+ let queue: Promise<unknown> = Promise.resolve()
39
+ function serialize<T>(work: () => Promise<T>): Promise<T> {
40
+ const next = queue.then(work)
41
+ queue = next.catch(() => {})
42
+ return next
43
+ }
44
+
45
+ export function createStore(storage: Context['storage'], location: RecordInfo['location'], limits: { maxRunningTasks?: unknown; maxFixCycles?: unknown } = {}) {
46
+ let { maxRunningTasks, maxFixCycles } = readLimits(limits)
47
+ const prefix = `relay/records/${encodeURIComponent(location.projectID)}/`
48
+ const runPrefix = `relay/runs/${encodeURIComponent(location.projectID)}/`
49
+ const evidencePrefix = `relay/evidence/${encodeURIComponent(location.projectID)}/`
50
+ async function listEvidence(id: string): Promise<Evidence[]> {
51
+ await get(id)
52
+ const evidence: Evidence[] = []; let after: string | undefined
53
+ do {
54
+ const page = await storage.scan({ prefix: `${evidencePrefix}${id}/`, after, limit: 100 })
55
+ evidence.push(...page.entries.map(entry => entry.value as Evidence)); after = page.next
56
+ } while (after)
57
+ const order = { unverified: 0, failed: 1, passed: 2, 'manually verified': 3 }
58
+ return evidence.sort((a, b) => a.endedAt - b.endedAt || a.startedAt - b.startedAt || order[a.result] - order[b.result] || a.id.localeCompare(b.id))
59
+ }
60
+ async function saveEvidence(input: Omit<Evidence, 'id'>) {
61
+ const evidence = { ...input, id: randomUUID() }
62
+ await storage.set(`${evidencePrefix}${input.recordID}/${evidence.id}`, evidence)
63
+ return evidence
64
+ }
65
+ async function verification(record: RecordInfo) {
66
+ const checks = record.checks.filter(check => check.policy !== 'not-applicable')
67
+ if (!checks.length) return
68
+ const taskChecks = checks.filter(check => checkScope(check) === 'task')
69
+ const finalChecks = checks.filter(check => checkScope(check) === 'final')
70
+ const runs = await listRuns(record.id); const evidence = await listEvidence(record.id)
71
+ const valid = (item: Evidence | undefined, check: Check) => Boolean(item && (item.result === 'passed' || item.result === 'manually verified' && check.policy === 'manual-allowed'))
72
+ const entries = record.tasks.map(task => {
73
+ const build = runs.findLast(run => run.taskID === task.id && run.stage === 'build' && run.status === 'reported')
74
+ const review = runs.findLast(run => run.taskID === task.id && run.stage === 'review' && run.status === 'reported' && run.report && 'verdict' in run.report && run.report.verdict === 'approve')
75
+ return { task, build, review }
76
+ })
77
+ let finalSatisfied = !finalChecks.length
78
+ for (const { task, build, review } of entries) {
79
+ if (!build || !review || review.startedAt < build.startedAt || !review.evidenceIDs) throw new StoreError('verification_incomplete')
80
+ const taskCurrent = taskChecks.map(check => evidence.findLast(item => item.taskID === task.id && item.checkID === check.id && item.buildRunID === build.id))
81
+ if (taskCurrent.some((item, index) => !valid(item, taskChecks[index])) || taskCurrent.some(item => !review.evidenceIDs!.includes(item!.id))) throw new StoreError('verification_incomplete')
82
+ const finalCurrent = finalChecks.map(check => evidence.findLast(item => item.taskID === task.id && item.checkID === check.id && item.buildRunID === build.id))
83
+ const hasFinalEvidence = finalChecks.length > 0 && finalCurrent.every((item, index) => valid(item, finalChecks[index])) && finalCurrent.every(item => review.evidenceIDs!.includes(item!.id))
84
+ const expectedLength = hasFinalEvidence ? taskCurrent.length + finalCurrent.length : taskCurrent.length
85
+ if (review.evidenceIDs.length !== expectedLength) throw new StoreError('verification_incomplete')
86
+ if (hasFinalEvidence && entries.every(other => other.build && review.startedAt >= other.build.startedAt && (!other.build.endedAt || review.startedAt >= other.build.endedAt))) finalSatisfied = true
87
+ }
88
+ if (!finalSatisfied) throw new StoreError('verification_incomplete')
89
+ }
90
+ async function listRuns(recordID: string): Promise<RunInfo[]> {
91
+ await get(recordID)
92
+ const runs: RunInfo[] = []; let after: string | undefined
93
+ do {
94
+ const page = await storage.scan({ prefix: `${runPrefix}${recordID}/`, after, limit: 100 })
95
+ runs.push(...page.entries.map(entry => entry.value as RunInfo)); after = page.next
96
+ } while (after)
97
+ return runs.sort((a, b) => a.startedAt.localeCompare(b.startedAt) || a.attempt - b.attempt || (a.stage === b.stage ? 0 : a.stage === 'build' ? -1 : 1) || a.id.localeCompare(b.id))
98
+ }
99
+ async function get(id: string): Promise<RecordInfo> {
100
+ const value = await storage.get(prefix + id)
101
+ if (!value) throw new StoreError('not_found')
102
+ return migrate(value)
103
+ }
104
+ async function persist(record: RecordInfo) {
105
+ await storage.set(prefix + record.id, JSON.parse(JSON.stringify(record)))
106
+ const saved = await get(record.id)
107
+ if (saved.revision !== record.revision) throw new StoreError('storage_inconsistent')
108
+ return saved
109
+ }
110
+ function write(id: string, revision: number, apply: (record: RecordInfo) => void | Promise<void>, planRevision?: number) {
111
+ return serialize(async () => {
112
+ const record = await get(id)
113
+ if (planRevision === undefined ? record.revision !== revision : record.planRevision !== planRevision) throw new StoreError('stale_revision', record.revision)
114
+ await apply(record)
115
+ record.revision++
116
+ record.updatedAt = new Date().toISOString()
117
+ return persist(record)
118
+ })
119
+ }
120
+ async function list() {
121
+ const records: RecordInfo[] = []
122
+ let after: string | undefined
123
+ do {
124
+ const page = await storage.scan({ prefix, after, limit: 100 })
125
+ records.push(...page.entries.map(entry => migrate(entry.value)))
126
+ after = page.next
127
+ } while (after)
128
+ return records.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
129
+ }
130
+ return {
131
+ limits(values: { maxRunningTasks: number; maxFixCycles: number }) { maxRunningTasks = values.maxRunningTasks; maxFixCycles = values.maxFixCycles },
132
+ get,
133
+ write,
134
+ updatePlanner(id: string, apply: (planner: NonNullable<RecordInfo['plannerSession']>) => void) {
135
+ return serialize(async () => {
136
+ const record = await get(id)
137
+ if (!record.plannerSession) return record
138
+ apply(record.plannerSession)
139
+ return persist(record)
140
+ })
141
+ },
142
+ listRuns,
143
+ listEvidence,
144
+ createEvidence(input: Omit<Evidence, 'id'>) {
145
+ return serialize(async () => { await get(input.recordID); return saveEvidence(input) })
146
+ },
147
+ async recordManual(id: string, revision: number, taskID: string, checkID: string, note: string, permission: () => Promise<void>, guard?: () => void) {
148
+ function eligible(record: RecordInfo) {
149
+ const check = record.checks.find(check => check.id === checkID)
150
+ const task = record.tasks.find(task => task.id === taskID)
151
+ if (!check || check.policy !== 'manual-allowed' || record.phase !== 'interrupted' || record.interruptReason !== `manual verification required: ${check.name}` || task?.status !== 'running' || task.owner?.role !== 'reviewer' || typeof note !== 'string' || !note.trim() || Array.from(note).length > 1000) throw new StoreError('invalid_op')
152
+ }
153
+ const before = await get(id)
154
+ if (before.revision !== revision) throw new StoreError('stale_revision', before.revision)
155
+ eligible(before)
156
+ const runs = await listRuns(id)
157
+ const build = runs.findLast(run => run.taskID === taskID && run.stage === 'build' && run.status === 'reported')
158
+ const latest = (await listEvidence(id)).findLast(item => item.taskID === taskID && item.checkID === checkID && item.buildRunID === build?.id)
159
+ if (!build || latest?.result !== 'unverified') throw new StoreError('invalid_op')
160
+ await permission()
161
+ return serialize(async () => {
162
+ const record = await get(id)
163
+ if (record.revision !== revision) throw new StoreError('stale_revision', record.revision)
164
+ eligible(record)
165
+ const currentBuild = (await listRuns(id)).findLast(run => run.taskID === taskID && run.stage === 'build' && run.status === 'reported')
166
+ if (currentBuild?.id !== build.id) throw new StoreError('verification_incomplete')
167
+ guard?.()
168
+ const now = Date.now()
169
+ await saveEvidence({ recordID: id, taskID, checkID, buildRunID: build.id, result: 'manually verified', source: 'permission-assert', note: note.trim(), screenshots: [], startedAt: now, endedAt: now, durationMs: 0 })
170
+ record.revision++; record.updatedAt = new Date().toISOString()
171
+ return persist(record)
172
+ })
173
+ },
174
+ createRun(input: Omit<RunInfo, 'id'>) {
175
+ return serialize(async () => {
176
+ await get(input.recordID)
177
+ const run = { ...input, id: randomUUID() }
178
+ await storage.set(`${runPrefix}${run.recordID}/${run.id}`, run)
179
+ return run
180
+ })
181
+ },
182
+ updateRun(recordID: string, runID: string, apply: (run: RunInfo) => void) {
183
+ return serialize(async () => {
184
+ const key = `${runPrefix}${recordID}/${runID}`
185
+ const run = await storage.get(key) as RunInfo | undefined
186
+ if (!run) throw new StoreError('not_found')
187
+ apply(run)
188
+ await storage.set(key, JSON.parse(JSON.stringify(run)))
189
+ return run
190
+ })
191
+ },
192
+ create(title: string, sessionID?: string, plannerSession?: RecordInfo['plannerSession']) {
193
+ return serialize(async () => {
194
+ title = title.trim()
195
+ if (!title) throw new StoreError('invalid_op')
196
+ if (Array.from(title).length > 500) throw new StoreError('limit_exceeded')
197
+ const now = new Date().toISOString()
198
+ return persist({ schemaVersion: 3, id: randomUUID(), revision: 1, planRevision: 1, phase: 'draft', title: title.trim(), location,
199
+ ...(sessionID ? { sessionID } : {}), ...(plannerSession ? { plannerSession } : {}), createdAt: now, updatedAt: now, tasks: [], checks: [], approvals: [] })
200
+ })
201
+ },
202
+ list,
203
+ async reconcile() {
204
+ const changed: RecordInfo[] = []
205
+ for (const record of await list()) {
206
+ if (record.phase !== 'running') continue
207
+ try { changed.push(await write(record.id, record.revision, current => { current.phase = 'interrupted'; current.interruptReason = 'server_restart' })) }
208
+ catch (failure) { if (!(failure instanceof StoreError) || failure.code !== 'stale_revision') console.error('Relay record reconciliation failed', record.id, failure) }
209
+ }
210
+ return changed
211
+ },
212
+ mutate(id: string, revision: number, op: Op) {
213
+ return write(id, revision, record => {
214
+ if (record.phase === 'completed' || record.phase === 'cancelled') throw new StoreError('invalid_op')
215
+ if (op.type === 'addCheck' || op.type === 'removeCheck') {
216
+ if (record.phase !== 'draft') throw new StoreError('invalid_op')
217
+ if (op.type === 'addCheck') {
218
+ validateCheck(op.check)
219
+ if (record.checks.some(check => check.id === op.check.id || check.name.trim() === op.check.name.trim())) throw new StoreError('invalid_op')
220
+ if (record.checks.length >= 20) throw new StoreError('limit_exceeded')
221
+ record.checks.push(structuredClone(op.check))
222
+ } else {
223
+ const index = record.checks.findIndex(check => check.id === op.checkID)
224
+ if (index < 0) throw new StoreError('invalid_op')
225
+ record.checks.splice(index, 1)
226
+ }
227
+ record.planRevision++
228
+ } else if (op.type === 'addTask' && typeof op.title === 'string' && op.title.trim()) {
229
+ if (!['draft', 'approved', 'interrupted'].includes(record.phase)) throw new StoreError('invalid_op')
230
+ if (Array.from(op.title.trim()).length > 2000 || record.tasks.length >= 200) throw new StoreError('limit_exceeded')
231
+ const scoped = validateAllowedPaths(op.allowedPaths)
232
+ if (!scoped.ok) throw new StoreError(scoped.code, undefined, scoped.message)
233
+ record.tasks.push({ id: randomUUID(), title: op.title.trim(), status: 'pending', fixCycles: 0, ...(scoped.paths ? { allowedPaths: scoped.paths } : {}), updatedAt: new Date().toISOString() })
234
+ record.planRevision++; record.phase = 'draft'; delete record.interruptReason
235
+ } else if (op.type === 'setTaskStatus' && statuses.includes(op.status)) {
236
+ if (['running'].includes(record.phase)) throw new StoreError('invalid_op')
237
+ const task = record.tasks.find(task => task.id === op.taskID)
238
+ if (!task) throw new StoreError('invalid_op')
239
+ if (op.status === 'running') {
240
+ if (record.phase !== 'running' || !task.owner || task.status === 'running') throw new StoreError('invalid_op')
241
+ if (record.tasks.filter(task => task.status === 'running').length >= maxRunningTasks) throw new StoreError('limit_exceeded')
242
+ }
243
+ if (task.status === 'running' && op.status === 'pending') {
244
+ if (task.fixCycles >= maxFixCycles) throw new StoreError('limit_exceeded')
245
+ task.fixCycles++
246
+ }
247
+ task.status = op.status; task.updatedAt = new Date().toISOString()
248
+ } else if (op.type === 'assignTask') {
249
+ if (record.phase === 'running') throw new StoreError('invalid_op')
250
+ const task = record.tasks.find(task => task.id === op.taskID)
251
+ if (!task || task.status === 'running' || !op.owner || !['planner', 'builder', 'reviewer'].includes(op.owner.role) || (op.owner.sessionID !== undefined && (typeof op.owner.sessionID !== 'string' || !op.owner.sessionID.trim()))) throw new StoreError('invalid_op')
252
+ if (op.owner.sessionID !== undefined && Array.from(op.owner.sessionID.trim()).length > 200) throw new StoreError('limit_exceeded')
253
+ task.owner = { role: op.owner.role, ...(op.owner.sessionID ? { sessionID: op.owner.sessionID.trim() } : {}) }; task.updatedAt = new Date().toISOString()
254
+ } else if (Object.hasOwn(transitions, op.type)) {
255
+ const action = op.type as PhaseAction
256
+ if (!(transitions[action] as readonly Phase[]).includes(record.phase)) throw new StoreError('invalid_op')
257
+ if ((action === 'start' || action === 'resume') && !isApproved(record, 'plan')) throw new StoreError('approval_required')
258
+ if (action === 'complete' && (!record.tasks.length || !record.tasks.every(task => task.status === 'completed'))) throw new StoreError('invalid_op')
259
+ if (['complete'].includes(action)) throw new StoreError('approval_required')
260
+ if (op.type === 'cancel' && op.cancelReason !== undefined) {
261
+ if (record.phase !== 'draft' || !op.cancelReason.trim()) throw new StoreError('invalid_op')
262
+ if (Array.from(op.cancelReason.trim()).length > 500) throw new StoreError('limit_exceeded')
263
+ record.cancelReason = op.cancelReason.trim()
264
+ }
265
+ if (op.type === 'interrupt') {
266
+ if (typeof op.reason !== 'string' || !op.reason.trim()) throw new StoreError('invalid_op')
267
+ if (Array.from(op.reason.trim()).length > 500) throw new StoreError('limit_exceeded')
268
+ record.interruptReason = op.reason.trim()
269
+ } else delete record.interruptReason
270
+ record.phase = action === 'start' || action === 'resume' ? 'running' : action === 'interrupt' ? 'interrupted' : action === 'complete' ? 'completed' : 'cancelled'
271
+ } else throw new StoreError('invalid_op')
272
+ })
273
+ },
274
+ async signOff(id: string, revision: number, permission: () => Promise<void>, guard?: () => void) {
275
+ const before = await get(id)
276
+ if (before.revision !== revision) throw new StoreError('stale_revision', before.revision)
277
+ if (before.phase !== 'running' || !before.tasks.length || !before.tasks.every(task => task.status === 'completed')) throw new StoreError('invalid_op')
278
+ await verification(before)
279
+ await permission()
280
+ return write(id, revision, async record => {
281
+ if (record.phase !== 'running' || !record.tasks.length || !record.tasks.every(task => task.status === 'completed')) throw new StoreError('invalid_op')
282
+ await verification(record)
283
+ guard?.()
284
+ record.phase = 'completed'
285
+ })
286
+ },
287
+ async approve(id: string, revision: number, permission: () => Promise<void>, guard?: () => void) {
288
+ const before = await get(id)
289
+ if (before.phase !== 'draft') throw new StoreError('invalid_op')
290
+ if (before.revision !== revision) throw new StoreError('stale_revision', before.revision)
291
+ await permission()
292
+ return write(id, revision, record => {
293
+ if (record.phase !== 'draft') throw new StoreError('invalid_op')
294
+ guard?.()
295
+ record.approvals.push({ kind: 'plan', revision, planRevision: record.planRevision, approvedAt: new Date().toISOString(), source: 'permission-assert' })
296
+ if (record.phase === 'draft') record.phase = 'approved'
297
+ }, before.planRevision)
298
+ },
299
+ }
300
+ }