@yanauto/broco 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.
Files changed (70) hide show
  1. package/CHANGELOG.md +209 -0
  2. package/LICENSE +202 -0
  3. package/README.md +188 -2
  4. package/README.zh-CN.md +187 -0
  5. package/assets/broco-board-icon-128.png +0 -0
  6. package/assets/broco-favicon-192.png +0 -0
  7. package/assets/broco-favicon-32.png +0 -0
  8. package/assets/broco-favicon-64.png +0 -0
  9. package/assets/broco-foreman-256.png +0 -0
  10. package/assets/broco-hero-1024.png +0 -0
  11. package/assets/broco-icon-512.png +0 -0
  12. package/assets/broco-readme-logo-dark.png +0 -0
  13. package/assets/broco-readme-logo-light.png +0 -0
  14. package/assets/broco-social-preview-1280x640.png +0 -0
  15. package/assets/favicon.ico +0 -0
  16. package/bin/broco +1077 -0
  17. package/bundle/board/assets/index-Bue0HpFh.css +1 -0
  18. package/bundle/board/assets/index-DTqMQtD9.js +16 -0
  19. package/bundle/board/broco-board-icon-128.png +0 -0
  20. package/bundle/board/broco-favicon-32.png +0 -0
  21. package/bundle/board/broco-favicon-64.png +0 -0
  22. package/bundle/board/broco-foreman-256.png +0 -0
  23. package/bundle/board/favicon.ico +0 -0
  24. package/bundle/board/fonts/instrument-sans-latin.woff2 +0 -0
  25. package/bundle/board/fonts/jetbrains-mono-latin.woff2 +0 -0
  26. package/bundle/board/index.html +18 -0
  27. package/lib/attachments.mjs +104 -0
  28. package/lib/claude-md.mjs +132 -0
  29. package/lib/cli-args.mjs +292 -0
  30. package/lib/cli-process.mjs +75 -0
  31. package/lib/client.mjs +198 -0
  32. package/lib/credential-proxy.mjs +165 -0
  33. package/lib/credential-source.mjs +23 -0
  34. package/lib/crew.mjs +947 -0
  35. package/lib/detect.mjs +279 -0
  36. package/lib/directories.mjs +32 -0
  37. package/lib/map.mjs +336 -0
  38. package/lib/model-catalog.json +864 -0
  39. package/lib/model-catalog.mjs +138 -0
  40. package/lib/model-env.mjs +11 -0
  41. package/lib/native.mjs +228 -0
  42. package/lib/paths.mjs +63 -0
  43. package/lib/pi-profile.mjs +29 -0
  44. package/lib/pi-secrets.mjs +48 -0
  45. package/lib/pi.mjs +232 -0
  46. package/lib/platform/index.mjs +13 -0
  47. package/lib/platform/launchd.mjs +138 -0
  48. package/lib/platform/linux.mjs +168 -0
  49. package/lib/platform/macos.mjs +29 -0
  50. package/lib/platform/processes.mjs +102 -0
  51. package/lib/problems.mjs +50 -0
  52. package/lib/projects.mjs +530 -0
  53. package/lib/quota.mjs +132 -0
  54. package/lib/roster-output.mjs +136 -0
  55. package/lib/roster.mjs +913 -0
  56. package/lib/runner.mjs +403 -0
  57. package/lib/settings-audit.mjs +104 -0
  58. package/lib/setup.mjs +416 -0
  59. package/lib/slots.mjs +177 -0
  60. package/lib/stats.mjs +92 -0
  61. package/lib/store.mjs +737 -0
  62. package/lib/stream-workers.mjs +464 -0
  63. package/lib/templates.mjs +173 -0
  64. package/lib/time.mjs +25 -0
  65. package/lib/web.mjs +260 -0
  66. package/lib/worker-policy.mjs +17 -0
  67. package/lib/worktree.mjs +269 -0
  68. package/package.json +50 -4
  69. package/scripts/package-board.mjs +53 -0
  70. package/skills/broco/SKILL.md +59 -0
package/lib/runner.mjs ADDED
@@ -0,0 +1,403 @@
1
+ import { mkdirSync, rmSync } from 'node:fs'
2
+ import { createServer } from 'node:http'
3
+ import { join } from 'node:path'
4
+ import { DatabaseSync } from 'node:sqlite'
5
+ import { home, socketPath } from './paths.mjs'
6
+ import { Slots } from './slots.mjs'
7
+ import { Projects } from './projects.mjs'
8
+ import { Web } from './web.mjs'
9
+ import { CredentialProxies } from './credential-proxy.mjs'
10
+ import { batchDetail, dispatchMap, doneBatch, isBatch, retryBatch, stopBatch } from './map.mjs'
11
+ import { cleanWorktrees, diffWorktree } from './worktree.mjs'
12
+ import { gcAttachments } from './attachments.mjs'
13
+ import { summarize, ticketRecords } from './stats.mjs'
14
+ import { formatDateTime } from './time.mjs'
15
+ import { supportedWorker } from './worker-policy.mjs'
16
+
17
+ const RUNNER_PROTOCOL = 15
18
+ const MAX_RPC_BODY = 2 * 1024 * 1024
19
+
20
+ process.umask(0o077)
21
+ mkdirSync(home, { recursive: true })
22
+ const lease = new DatabaseSync(join(home, 'runner.lock'))
23
+ try { lease.exec('BEGIN EXCLUSIVE') }
24
+ catch (err) {
25
+ if ((err.errcode & 0xff) !== 5) throw err
26
+ process.exit(0)
27
+ }
28
+
29
+ const slots = new Slots(Number(process.env.BROCO_CONCURRENCY ?? 3))
30
+ const waiters = new Set()
31
+ let web
32
+ const publish = event => web?.publish(event)
33
+ const projects = new Projects(slots, publish, () => Boolean(web?.hasSubscribers()) || waiters.size > 0)
34
+ web = new Web(projects)
35
+ const proxies = new CredentialProxies()
36
+
37
+ function wakeWaiters(projectId = null, forceRetry = false) {
38
+ for (const w of [...waiters]) {
39
+ if (projectId === null || w.projectId === projectId) {
40
+ try { w.check(forceRetry) } catch {}
41
+ }
42
+ }
43
+ }
44
+
45
+ projects.onTicketChange = projectId => wakeWaiters(projectId)
46
+
47
+ projects.db.exec('CREATE TABLE IF NOT EXISTS runner_state (id INTEGER PRIMARY KEY CHECK (id=1), pid INTEGER, ppid INTEGER, started INTEGER, stop_reason TEXT, stopped INTEGER, web_port INTEGER)')
48
+ const prevRunner = projects.db.prepare('SELECT * FROM runner_state WHERE id=1').get() ?? null
49
+ projects.db.prepare('INSERT INTO runner_state(id,pid,ppid,started,stop_reason,stopped) VALUES (1,?,?,?,NULL,NULL) ON CONFLICT(id) DO UPDATE SET pid=excluded.pid,ppid=excluded.ppid,started=excluded.started,stop_reason=NULL,stopped=NULL').run(process.pid, process.ppid, Date.now())
50
+
51
+ function recoverReason() {
52
+ if (!prevRunner) return 'Runner interrupted; inspect work before resuming'
53
+ const nowText = formatDateTime()
54
+ if (prevRunner.stop_reason) {
55
+ return 'Runner interrupted (' + prevRunner.stop_reason + ', runner pid ' + prevRunner.pid + '); recovered by pid ' + process.pid + ' at ' + nowText + '; inspect work before resuming'
56
+ }
57
+ return 'Runner interrupted: previous runner (pid ' + prevRunner.pid + ') exited unexpectedly without shutdown; recovered by pid ' + process.pid + ' at ' + nowText + '; inspect work before resuming'
58
+ }
59
+
60
+ await projects.recover(recoverReason())
61
+ projects.startReconciler()
62
+
63
+ const savedWebPort = projects.readWebPort()
64
+ if (savedWebPort) {
65
+ web.port = savedWebPort
66
+ await web.start().then(() => {
67
+ if (web.boundPort) projects.saveWebPort(web.boundPort)
68
+ }).catch(() => {})
69
+ }
70
+
71
+ async function readRpcBody(req) {
72
+ const chunks = []
73
+ let bytes = 0
74
+ for await (const part of req) {
75
+ const buf = Buffer.isBuffer(part) ? part : Buffer.from(part)
76
+ bytes += buf.length
77
+ if (bytes > MAX_RPC_BODY) throw new Error('RPC request exceeds 2 MiB')
78
+ chunks.push(buf)
79
+ }
80
+ const text = chunks.length ? Buffer.concat(chunks, bytes).toString('utf8') : '{}'
81
+ return JSON.parse(text)
82
+ }
83
+
84
+ function requireCrew(crew) {
85
+ if (!crew) throw new Error('Project ID is required')
86
+ return crew
87
+ }
88
+
89
+ function evaluateWait(crew, { name, turn, number }) {
90
+ const store = crew.store
91
+ if (isBatch(store, name)) {
92
+ if (turn !== undefined && turn !== null) {
93
+ throw new Error('Batch wait does not take a turn number; use broco wait ' + name)
94
+ }
95
+ const detail = batchDetail(store, name)
96
+ if (!detail) throw new Error('Unknown batch: ' + name)
97
+ if (!detail.finished) return { done: false }
98
+ return { done: true, value: detail }
99
+ }
100
+ const c = store.byName(name)
101
+ if (!c) throw new Error('Unknown conversation: ' + name)
102
+ let targetTurn
103
+ if (turn === undefined || turn === null) {
104
+ if (c.turn < 1) throw new Error('Conversation has no turns yet: ' + name)
105
+ targetTurn = c.turn
106
+ } else {
107
+ targetTurn = Number(turn)
108
+ }
109
+ if (!Number.isSafeInteger(targetTurn) || targetTurn < 1) throw new Error('Expected a positive turn number')
110
+ if (number) {
111
+ const msg = store.stmt('SELECT error FROM messages WHERE cid=? AND number=?').get(c.id, number)
112
+ if (msg?.error) throw new Error(msg.error)
113
+ }
114
+ const result = store.result(c.id, targetTurn)
115
+ if (['running', 'queued'].includes(result.status)) return { done: false }
116
+ const taskRow = store.tasks(c.id).find(tk => targetTurn >= tk.startTurn && targetTurn <= tk.endTurn) ?? store.currentTask(c.id)
117
+ const meta = store.meta(c.id)
118
+ return {
119
+ done: true,
120
+ value: {
121
+ name: c.name,
122
+ task: taskRow?.task ?? null,
123
+ worker: c.provider,
124
+ model: c.model,
125
+ cwd: crew.workingDirectory(c, meta),
126
+ worktree: meta?.worktree ?? null,
127
+ branch: meta?.branch ?? null,
128
+ changedFiles: JSON.parse(meta?.files ?? 'null'),
129
+ ...result
130
+ }
131
+ }
132
+ }
133
+
134
+ function waitForOutcome(projectId, crew, input, req) {
135
+ const first = evaluateWait(crew, input)
136
+ if (first.done) return Promise.resolve(first.value)
137
+ const holdMs = Math.min(Math.max(500, Number(input.timeoutMs) || 25000), 30000)
138
+ return new Promise((resolve, reject) => {
139
+ let settled = false
140
+ let timer = null
141
+ const waiter = {
142
+ projectId,
143
+ check(forceRetry = false) {
144
+ if (settled) return
145
+ if (forceRetry || closing) {
146
+ cleanup()
147
+ resolve({ waiting: true })
148
+ return
149
+ }
150
+ try {
151
+ const outcome = evaluateWait(crew, input)
152
+ if (outcome.done) {
153
+ cleanup()
154
+ resolve(outcome.value)
155
+ }
156
+ } catch (err) {
157
+ cleanup()
158
+ reject(err)
159
+ }
160
+ }
161
+ }
162
+ const onClose = () => {
163
+ if (settled) return
164
+ cleanup()
165
+ resolve({ waiting: true })
166
+ }
167
+ function cleanup() {
168
+ settled = true
169
+ if (timer) clearTimeout(timer)
170
+ waiters.delete(waiter)
171
+ req.off('close', onClose)
172
+ }
173
+ timer = setTimeout(() => {
174
+ if (settled) return
175
+ cleanup()
176
+ resolve({ waiting: true })
177
+ }, holdMs)
178
+ timer.unref?.()
179
+ req.once('close', onClose)
180
+ waiters.add(waiter)
181
+ })
182
+ }
183
+
184
+ rmSync(socketPath, { force: true })
185
+ let closing = false
186
+ const server = createServer(async (req, res) => {
187
+ res.setHeader('Content-Type', 'application/json')
188
+ try {
189
+ if (closing) throw new Error('Runner is shutting down')
190
+ if (req.url === '/ready' && req.method === 'GET') {
191
+ res.end(JSON.stringify({ pid: process.pid, protocol: RUNNER_PROTOCOL, credentialProxy: true }))
192
+ return
193
+ }
194
+ if (req.method !== 'POST') throw new Error('Expected POST')
195
+ const input = await readRpcBody(req)
196
+ const crew = input.projectId ? projects.get(input.projectId).crew : null
197
+ let reply
198
+ if (req.url === '/ui') {
199
+ const url = await web.start()
200
+ if (web.boundPort) projects.saveWebPort(web.boundPort)
201
+ reply = { url }
202
+ } else if (req.url === '/status') {
203
+ const snap = projects.statusSnapshot({ projectId: input.projectId ?? null, cwd: input.cwd ?? null, all: !!input.all })
204
+ const proxyList = proxies.list()
205
+ const startedMs = snap.runnerState?.startedAt ? Date.parse(snap.runnerState.startedAt) : null
206
+ reply = {
207
+ runner: {
208
+ online: true,
209
+ compatible: true,
210
+ pid: process.pid,
211
+ protocol: RUNNER_PROTOCOL,
212
+ startedAt: snap.runnerState?.startedAt ?? null,
213
+ startedLocal: snap.runnerState?.startedLocal ?? null,
214
+ uptimeSec: startedMs ? Math.max(0, Math.floor((Date.now() - startedMs) / 1000)) : 0,
215
+ lastStopReason: snap.runnerState?.lastStopReason ?? null,
216
+ webUrl: web.origin ?? null,
217
+ activeProxies: proxyList.length,
218
+ proxies: proxyList
219
+ },
220
+ project: snap.project,
221
+ projects: snap.projects,
222
+ totals: snap.totals
223
+ }
224
+ } else if (req.url === '/proxy-open') reply = await proxies.open(input)
225
+ else if (req.url === '/proxy-list') reply = proxies.list()
226
+ else if (req.url === '/proxy-close') reply = await proxies.close(input.id)
227
+ else if (req.url === '/register') reply = projects.register(input.cwd, input.allow, input.worker, { agentsMd: input.agentsMd, claudeMd: input.claudeMd, host: input.host, managerMode: input.managerMode, concurrency: input.concurrency })
228
+ else if (req.url === '/unregister') reply = await projects.uninit(input.cwd, { agentsMd: input.agentsMd, claudeMd: input.claudeMd, host: input.host })
229
+ else if (req.url === '/context') reply = projects.context(input.cwd, { createImplicit: input.createImplicit !== false, optional: !!input.optional })
230
+ else if (req.url === '/roster') {
231
+ if (input.global) {
232
+ const globalCfg = projects.roster.read('global')
233
+ const unconfigured = !(globalCfg.allow?.length)
234
+ const raw = await projects.roster.list('global', unconfigured ? true : Boolean(input.all), { refresh: !!input.refresh })
235
+ if (unconfigured) {
236
+ raw.globalAllowConfigured = false
237
+ raw.workers = raw.workers
238
+ .filter(w => w.installed)
239
+ .map(w => ({
240
+ ...w,
241
+ allowed: false,
242
+ models: ['ready', 'not-required'].includes(w.loginStatus) ? w.models : []
243
+ }))
244
+ raw.warnings = [
245
+ ...(raw.warnings ?? []),
246
+ 'Global allowlist is not configured yet. Run broco setup or broco allow <ids> --global.'
247
+ ]
248
+ }
249
+ reply = raw
250
+ } else {
251
+ if (!input.projectId) throw new Error('Project ID is required')
252
+ reply = await projects.roster.list(input.projectId, Boolean(input.all), { refresh: !!input.refresh })
253
+ }
254
+ } else if (req.url === '/stats') {
255
+ reply = input.projectId ? summarize(ticketRecords(requireCrew(crew).store)) : projects.roster.records()
256
+ } else if (req.url === '/defaults-proposal') reply = projects.roster.proposeDefaults(input.projectId, input.worker, input)
257
+ else if (req.url === '/note-proposal') reply = projects.roster.propose(input.projectId, input.worker, input.note)
258
+ else if (req.url === '/defaults-set') reply = projects.roster.setDefaults(input.scope, input.worker, { model: input.model, effort: input.effort, clear: !!input.clear }, input.actor ?? 'agent')
259
+ else if (req.url === '/note-set') reply = projects.roster.setNote(input.scope, input.worker, input.note, input.actor ?? 'agent')
260
+ else if (req.url === '/concurrency-set') reply = projects.roster.setConcurrency(input.scope, input.concurrency, input.actor ?? 'agent')
261
+ else if (req.url === '/allow-set') reply = projects.roster.setAllow(input.scope, { allow: input.allow, add: input.add, remove: input.remove, defaultWorker: input.defaultWorker, inheritPolicy: input.inheritPolicy }, input.actor ?? 'agent')
262
+ else if (req.url === '/rules-get') {
263
+ if (input.worker && !supportedWorker(input.worker)) throw new Error('Unknown worker: ' + input.worker)
264
+ const cfg = projects.roster.config(input.scope)
265
+ const eff = cfg.effective
266
+ reply = {
267
+ scope: cfg.scope,
268
+ rules: eff.rules ?? [],
269
+ scopeRules: cfg.rules ?? [],
270
+ rulesOverride: !!cfg.rulesOverride,
271
+ ...(input.worker
272
+ ? { worker: input.worker, workerRules: eff.entries?.[input.worker]?.rules ?? [] }
273
+ : { workerRules: Object.fromEntries(Object.entries(eff.entries ?? {}).filter(([, e]) => e.rules?.length).map(([k, e]) => [k, e.rules])) })
274
+ }
275
+ }
276
+ else if (req.url === '/rules-set') reply = projects.roster.setRules(input.scope, { add: input.add, remove: input.remove, clear: !!input.clear, worker: input.worker, rulesOverride: input.rulesOverride }, input.actor ?? 'agent')
277
+ else if (req.url === '/hidden-models-set') reply = projects.roster.setHiddenModels(input.scope, input.worker, { hide: input.hide, unhide: input.unhide, clear: !!input.clear }, input.actor ?? 'agent')
278
+ else if (req.url === '/audit-list') reply = projects.roster.auditList(input.scope, input.limit)
279
+ else if (req.url === '/audit-undo') reply = projects.roster.undoAudit(input.id, { scope: input.scope, actor: input.actor ?? 'agent' })
280
+ else if (req.url === '/say') {
281
+ requireCrew(crew)
282
+ input.defaultCwd = projects.get(input.projectId).repoPath
283
+ reply = await crew.serial(input.name, () => crew.say(input))
284
+ if (reply.delivery) reply = await reply.delivery
285
+ } else if (req.url === '/retry') {
286
+ requireCrew(crew)
287
+ if (isBatch(crew.store, input.name)) {
288
+ reply = await retryBatch(crew, input.name, { model: input.model, effort: input.effort, worker: input.worker, env: input.env })
289
+ } else {
290
+ reply = await crew.serial(input.name, () => crew.retry(input.name, { model: input.model, effort: input.effort, worker: input.worker, env: input.env }))
291
+ if (reply.delivery) reply = await reply.delivery
292
+ }
293
+ } else if (req.url === '/map') {
294
+ requireCrew(crew)
295
+ input.defaultCwd = projects.get(input.projectId).repoPath
296
+ reply = await dispatchMap(crew, input)
297
+ } else if (req.url === '/review') {
298
+ requireCrew(crew)
299
+ reply = await crew.serial(input.name, () => crew.review({ ...input, by: input.by ?? null }))
300
+ } else if (req.url === '/stop') {
301
+ requireCrew(crew)
302
+ reply = isBatch(crew.store, input.name)
303
+ ? await stopBatch(crew, input.name)
304
+ : await crew.serial(input.name, () => crew.stop(input.name))
305
+ } else if (req.url === '/done') {
306
+ requireCrew(crew)
307
+ if (isBatch(crew.store, input.name)) {
308
+ if (input.task !== undefined) throw new Error('--task applies to a single session, not a batch prefix')
309
+ reply = doneBatch(crew.store, input.name, { result: input.result, why: input.why })
310
+ } else {
311
+ reply = await crew.serial(input.name, () => crew.store.done(input.name, { result: input.result, why: input.why, task: input.task }))
312
+ }
313
+ } else if (req.url === '/wait') {
314
+ requireCrew(crew)
315
+ reply = await waitForOutcome(input.projectId, crew, input, req)
316
+ } else if (req.url === '/diff') {
317
+ requireCrew(crew)
318
+ const c = crew.store.byName(input.name)
319
+ if (!c) throw new Error('Unknown conversation: ' + input.name)
320
+ const meta = crew.store.meta(c.id)
321
+ const targetCwd = crew.workingDirectory(c, meta)
322
+ const diff = diffWorktree(targetCwd, meta?.baseline ?? null, { statOnly: !!input.statOnly })
323
+ reply = {
324
+ name: c.name,
325
+ cwd: targetCwd,
326
+ worktree: meta?.worktree ?? null,
327
+ branch: meta?.branch ?? null,
328
+ ...diff
329
+ }
330
+ } else if (req.url === '/clean') {
331
+ requireCrew(crew)
332
+ const proj = projects.get(input.projectId)
333
+ const worktrees = cleanWorktrees(crew.store, proj.repoPath, {
334
+ target: input.name ?? null,
335
+ dryRun: !!input.dryRun,
336
+ deleteBranch: !!input.deleteBranch,
337
+ force: !!input.force
338
+ })
339
+ const attachments = input.name ? { removed: 0, freedBytes: 0, files: [] } : gcAttachments(crew.store, { dryRun: !!input.dryRun })
340
+ reply = { ...worktrees, attachments }
341
+ } else if (req.url === '/shutdown') {
342
+ closing = true
343
+ wakeWaiters(null, true)
344
+ try { await stopWorkers({ callerPid: input.callerPid }) } catch (err) { closing = false; proxies.closed = false; slots.paused = false; slots.drain(); throw err }
345
+ reply = { status: 'offline' }
346
+ res.once('finish', () => server.close())
347
+ } else throw new Error('Unknown command')
348
+ if (!res.writableEnded) res.end(JSON.stringify(reply))
349
+ } catch (err) {
350
+ if (!res.headersSent) res.statusCode = 400
351
+ if (!res.writableEnded) res.end(JSON.stringify({ error: err.message }))
352
+ }
353
+ })
354
+
355
+ async function stopWorkers({ preserveQueued = false, signal, callerPid } = {}) {
356
+ slots.paused = true
357
+ projects.stopReconciler()
358
+ wakeWaiters(null, true)
359
+ const nowText = formatDateTime()
360
+ const reason = signal
361
+ ? 'Runner interrupted by ' + signal + ' (runner pid ' + process.pid + ' at ' + nowText + '); inspect work before resuming'
362
+ : 'Stopped by manager'
363
+ if (signal) {
364
+ try { projects.db.prepare('UPDATE runner_state SET stop_reason=?,stopped=? WHERE id=1').run('signal:' + signal, Date.now()) } catch {}
365
+ } else if (callerPid) {
366
+ try { projects.db.prepare('UPDATE runner_state SET stop_reason=?,stopped=? WHERE id=1').run('shutdown-rpc:caller=' + callerPid, Date.now()) } catch {}
367
+ } else {
368
+ try { projects.db.prepare('UPDATE runner_state SET stop_reason=?,stopped=? WHERE id=1').run('shutdown-rpc', Date.now()) } catch {}
369
+ }
370
+ await proxies.closeAll()
371
+ await web.close()
372
+ for (const crew of projects.crews()) {
373
+ if (preserveQueued && typeof crew.interruptRunning === 'function') {
374
+ await crew.interruptRunning(reason)
375
+ continue
376
+ }
377
+ await Promise.allSettled([...crew.queues.values()])
378
+ for (const c of crew.store.stmt("SELECT * FROM conversations WHERE status IN ('queued','running')").all()) {
379
+ if (preserveQueued && c.status === 'queued') continue
380
+ await crew.stop(c.name)
381
+ }
382
+ if (typeof crew.releaseAll === 'function') await crew.releaseAll()
383
+ }
384
+ }
385
+
386
+ async function shutdown(sig) {
387
+ if (closing) return
388
+ closing = true
389
+ wakeWaiters(null, true)
390
+ try { await stopWorkers({ preserveQueued: true, signal: sig }) }
391
+ catch { process.exitCode = 1 }
392
+ finally { server.close() }
393
+ }
394
+
395
+ server.on('close', () => {
396
+ projects.stopReconciler()
397
+ for (const crew of projects.crews()) crew.store.db.close()
398
+ projects.db.close()
399
+ lease.close()
400
+ })
401
+ server.listen(socketPath)
402
+ process.once('SIGTERM', () => shutdown('SIGTERM'))
403
+ process.once('SIGINT', () => shutdown('SIGINT'))
@@ -0,0 +1,104 @@
1
+ import { formatDateTime } from './time.mjs'
2
+
3
+ export const localTime = formatDateTime
4
+
5
+ function hydrate(row) {
6
+ if (!row) return null
7
+ const atLocal = formatDateTime(row.at)
8
+ const revertedAtLocal = row.revertedAt ? formatDateTime(row.revertedAt) : null
9
+ return {
10
+ id: Number(row.id),
11
+ at: row.at,
12
+ atLocal,
13
+ atAsia: atLocal,
14
+ scope: row.scope,
15
+ scopeName: row.scopeName,
16
+ actor: row.actor,
17
+ action: row.action,
18
+ summary: row.summary,
19
+ beforeJson: row.beforeJson,
20
+ afterJson: row.afterJson,
21
+ before: JSON.parse(row.beforeJson),
22
+ after: JSON.parse(row.afterJson),
23
+ revertedAt: row.revertedAt ?? null,
24
+ revertedAtLocal,
25
+ revertedAtAsia: revertedAtLocal
26
+ }
27
+ }
28
+
29
+ export class SettingsAudit {
30
+ constructor(db) {
31
+ this.db = db
32
+ this.db.exec(
33
+ 'CREATE TABLE IF NOT EXISTS settings_audit(' +
34
+ 'id INTEGER PRIMARY KEY AUTOINCREMENT,' +
35
+ 'at INTEGER NOT NULL,' +
36
+ 'atAsia TEXT NOT NULL,' +
37
+ 'scope TEXT NOT NULL,' +
38
+ 'scopeName TEXT NOT NULL,' +
39
+ 'actor TEXT NOT NULL,' +
40
+ 'action TEXT NOT NULL,' +
41
+ 'summary TEXT NOT NULL,' +
42
+ 'beforeJson TEXT NOT NULL,' +
43
+ 'afterJson TEXT NOT NULL,' +
44
+ 'revertedAt INTEGER' +
45
+ ');' +
46
+ 'CREATE INDEX IF NOT EXISTS idx_settings_audit_scope ON settings_audit(scope, id DESC)'
47
+ )
48
+ }
49
+
50
+ record({ scope, scopeName, actor = 'agent', action, summary, before, after, at = Date.now() }) {
51
+ const atLocal = formatDateTime(at)
52
+ const beforeJson = JSON.stringify(before ?? {})
53
+ const afterJson = JSON.stringify(after ?? {})
54
+ const res = this.db.prepare(
55
+ 'INSERT INTO settings_audit (at,atAsia,scope,scopeName,actor,action,summary,beforeJson,afterJson,revertedAt) VALUES (?,?,?,?,?,?,?,?,?,NULL)'
56
+ ).run(at, atLocal, scope, scopeName || scope, actor || 'agent', action, summary, beforeJson, afterJson)
57
+ return hydrate({
58
+ id: Number(res.lastInsertRowid),
59
+ at,
60
+ atAsia: atLocal,
61
+ scope,
62
+ scopeName: scopeName || scope,
63
+ actor: actor || 'agent',
64
+ action,
65
+ summary,
66
+ beforeJson,
67
+ afterJson,
68
+ revertedAt: null
69
+ })
70
+ }
71
+
72
+ get(id) {
73
+ if (!Number.isSafeInteger(Number(id)) || Number(id) < 1) return null
74
+ return hydrate(this.db.prepare('SELECT * FROM settings_audit WHERE id=?').get(Number(id)))
75
+ }
76
+
77
+ list(scope = null, limit = 30) {
78
+ const max = Math.max(1, Math.min(500, Math.trunc(Number(limit) || 30)))
79
+ const rows = scope && scope !== 'all'
80
+ ? this.db.prepare('SELECT * FROM settings_audit WHERE scope=? ORDER BY id DESC LIMIT ?').all(scope, max)
81
+ : this.db.prepare('SELECT * FROM settings_audit ORDER BY id DESC LIMIT ?').all(max)
82
+ return rows.map(hydrate)
83
+ }
84
+
85
+ latestUndoable(scope = null) {
86
+ if (scope && scope !== 'all') {
87
+ const row = this.db.prepare("SELECT * FROM settings_audit WHERE scope=? AND revertedAt IS NULL AND action!='undo' ORDER BY id DESC LIMIT 1").get(scope)
88
+ return hydrate(row)
89
+ }
90
+ const hasProjects = Boolean(this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='projects'").get())
91
+ const sql = hasProjects
92
+ ? "SELECT * FROM settings_audit WHERE revertedAt IS NULL AND action!='undo' AND (scope='global' OR EXISTS (SELECT 1 FROM projects WHERE id=settings_audit.scope)) ORDER BY id DESC LIMIT 1"
93
+ : "SELECT * FROM settings_audit WHERE revertedAt IS NULL AND action!='undo' ORDER BY id DESC LIMIT 1"
94
+ return hydrate(this.db.prepare(sql).get())
95
+ }
96
+
97
+ markReverted(id, at = Date.now()) {
98
+ this.db.prepare('UPDATE settings_audit SET revertedAt=? WHERE id=?').run(at, Number(id))
99
+ }
100
+
101
+ archiveScope(scope, at = Date.now()) {
102
+ this.db.prepare('UPDATE settings_audit SET revertedAt=? WHERE scope=? AND revertedAt IS NULL').run(at, scope)
103
+ }
104
+ }