@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/setup.mjs ADDED
@@ -0,0 +1,416 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { chmodSync, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
3
+ import { homedir } from 'node:os'
4
+ import { basename, delimiter, dirname, join, resolve, sep } from 'node:path'
5
+ import { DatabaseSync } from 'node:sqlite'
6
+ import { call, probeReady } from './client.mjs'
7
+ import { detectCli, discoverPi } from './detect.mjs'
8
+ import { canonical, home, isolated, legacyCcBroHome, repo, socketFor } from './paths.mjs'
9
+ import { windowLabel } from './quota.mjs'
10
+ import { SettingsAudit } from './settings-audit.mjs'
11
+ import { supportedWorker } from './worker-policy.mjs'
12
+
13
+ const quote = value => "'" + value.replaceAll("'", "'\\''") + "'"
14
+ const EPHEMERAL_DIR = /^(?:\/private)?\/(?:tmp|var\/folders)(?:\/|$)/
15
+ const NPM_SHIM_DIR = /\/(?:node_modules\/\.bin|\.npm\/_npx)(?:\/|$)/
16
+ const TEST_SANDBOX_DIR = /\/(?:\.sandbox|test\/fixtures)(?:\/|$)/
17
+ const TRANSIENT_NAMES = new Set(['runner.lock', 'runner.lock-wal', 'runner.lock-shm', 'runner.pid', 'runner.plist'])
18
+
19
+ export const FIRST_RUN_PROMPT = 'Check my broco roster and ask a different model to review my latest commit.'
20
+
21
+ function isDir(path) {
22
+ try {
23
+ return existsSync(path) && statSync(path).isDirectory()
24
+ } catch {
25
+ return false
26
+ }
27
+ }
28
+
29
+ function writeAtomic(file, content, mode) {
30
+ const tmp = file + '.' + randomUUID()
31
+ writeFileSync(tmp, content, { mode, flag: 'wx' })
32
+ chmodSync(tmp, mode)
33
+ renameSync(tmp, file)
34
+ }
35
+
36
+ export function sanitizeSetupPath(rawPath = process.env.PATH ?? '', { nodeDir = dirname(realpathSync(process.execPath)), isIsolated = isolated } = {}) {
37
+ const allowedIsolatedDirs = new Set()
38
+ if (isIsolated) {
39
+ const fixturePath = join(repo, 'test', 'fixtures')
40
+ allowedIsolatedDirs.add(fixturePath)
41
+ if (existsSync(fixturePath)) allowedIsolatedDirs.add(realpathSync(fixturePath))
42
+ }
43
+ const entries = [nodeDir, ...String(rawPath).split(delimiter)]
44
+ const seen = new Set()
45
+ const kept = []
46
+ for (const raw of entries) {
47
+ const entry = raw.trim()
48
+ if (!entry.startsWith('/') || seen.has(entry)) continue
49
+ if (entry !== nodeDir && !allowedIsolatedDirs.has(entry)) {
50
+ if (EPHEMERAL_DIR.test(entry) || NPM_SHIM_DIR.test(entry)) continue
51
+ if (!isIsolated && TEST_SANDBOX_DIR.test(entry)) continue
52
+ if (!existsSync(entry)) continue
53
+ } else if (entry !== nodeDir && !existsSync(entry)) {
54
+ continue
55
+ }
56
+ seen.add(entry)
57
+ kept.push(entry)
58
+ }
59
+ return kept.join(':')
60
+ }
61
+
62
+ export function skillHostTargets({ homeDir, skillsHome, env = process.env } = {}) {
63
+ const effectiveHome = resolve(homeDir ?? env.BROCO_HOST_HOME ?? homedir())
64
+ const universalRoot = resolve(skillsHome ?? env.BROCO_SKILLS_HOME ?? join(effectiveHome, '.agents', 'skills'))
65
+ const universalDir = join(universalRoot, 'broco')
66
+ const claudeParent = env.CLAUDE_CONFIG_DIR ? resolve(env.CLAUDE_CONFIG_DIR) : join(effectiveHome, '.claude')
67
+ const codexParent = env.CODEX_HOME ? resolve(env.CODEX_HOME) : join(effectiveHome, '.codex')
68
+ const piParent = env.PI_CODING_AGENT_DIR ? resolve(env.PI_CODING_AGENT_DIR) : join(effectiveHome, '.pi', 'agent')
69
+ const hostCandidates = [
70
+ { id: 'claude', parent: claudeParent, dir: join(claudeParent, 'skills', 'broco'), explicit: Boolean(env.CLAUDE_CONFIG_DIR) },
71
+ { id: 'codex', parent: codexParent, dir: join(codexParent, 'skills', 'broco'), explicit: Boolean(env.CODEX_HOME) },
72
+ { id: 'gemini', parent: join(effectiveHome, '.gemini', 'config'), dir: join(effectiveHome, '.gemini', 'config', 'skills', 'broco'), explicit: false },
73
+ { id: 'cursor', parent: join(effectiveHome, '.cursor'), dir: join(effectiveHome, '.cursor', 'skills', 'broco'), explicit: false },
74
+ { id: 'opencode', parent: join(effectiveHome, '.config', 'opencode'), dir: join(effectiveHome, '.config', 'opencode', 'skills', 'broco'), explicit: false },
75
+ { id: 'pi', parent: piParent, dir: join(piParent, 'skills', 'broco'), explicit: Boolean(env.PI_CODING_AGENT_DIR), symlink: true }
76
+ ]
77
+ return { effectiveHome, universalDir, hostCandidates }
78
+ }
79
+
80
+ export function setupInfo(opts = {}) {
81
+ const env = opts.env ?? process.env
82
+ const { universalDir, hostCandidates } = skillHostTargets({
83
+ homeDir: opts.homeDir,
84
+ skillsHome: opts.skillsHome,
85
+ env
86
+ })
87
+ mkdirSync(universalDir, { recursive: true })
88
+ const launcher = join(universalDir, 'broco')
89
+ const skillPath = join(universalDir, 'SKILL.md')
90
+ const node = realpathSync(process.execPath)
91
+ const cli = realpathSync(join(repo, 'bin', 'broco'))
92
+ const path = sanitizeSetupPath(env.PATH ?? '', { nodeDir: dirname(node), isIsolated: isolated })
93
+ const script = [
94
+ '#!/bin/sh',
95
+ 'export PATH=' + quote(path) + ':"$PATH"',
96
+ 'if [ -z "$BROCO_HOME" ]; then export BROCO_HOME=' + quote(home) + '; fi',
97
+ 'exec ' + quote(node) + ' ' + quote(cli) + ' "$@"',
98
+ ''
99
+ ].join('\n')
100
+ const skillTemplate = readFileSync(join(repo, 'skills', 'broco', 'SKILL.md'), 'utf8')
101
+ const skill = skillTemplate.replaceAll('{{launcher}}', () => quote(launcher))
102
+ writeAtomic(launcher, script, 0o755)
103
+ writeAtomic(skillPath, skill, 0o644)
104
+
105
+ const universalCanonical = canonical(universalDir)
106
+ const seenDirs = new Set([universalCanonical])
107
+ const hosts = [{ id: 'agents', dir: universalDir, skillPath, launcher }]
108
+ const skippedHosts = []
109
+
110
+ for (const target of hostCandidates) {
111
+ if (!target.explicit && !isDir(target.parent)) {
112
+ skippedHosts.push(target.id)
113
+ continue
114
+ }
115
+ const resolvedTarget = canonical(target.dir)
116
+ if (target.symlink) {
117
+ if (resolvedTarget === universalCanonical) {
118
+ hosts.push({ id: target.id, dir: target.dir, skillPath: join(target.dir, 'SKILL.md'), launcher })
119
+ continue
120
+ }
121
+ if (universalCanonical.startsWith(resolvedTarget + sep)) {
122
+ skippedHosts.push(target.id)
123
+ continue
124
+ }
125
+ mkdirSync(dirname(target.dir), { recursive: true })
126
+ if (lstatSync(target.dir, { throwIfNoEntry: false })) {
127
+ rmSync(target.dir, { recursive: true, force: true })
128
+ }
129
+ symlinkSync(universalDir, target.dir, 'dir')
130
+ hosts.push({ id: target.id, dir: target.dir, skillPath: join(target.dir, 'SKILL.md'), launcher })
131
+ continue
132
+ }
133
+ if (seenDirs.has(resolvedTarget)) {
134
+ hosts.push({ id: target.id, dir: target.dir, skillPath: join(target.dir, 'SKILL.md'), launcher })
135
+ continue
136
+ }
137
+ mkdirSync(target.dir, { recursive: true })
138
+ const targetSkill = join(target.dir, 'SKILL.md')
139
+ writeAtomic(targetSkill, skill, 0o644)
140
+ seenDirs.add(resolvedTarget)
141
+ hosts.push({ id: target.id, dir: target.dir, skillPath: targetSkill })
142
+ }
143
+
144
+ return {
145
+ launcher,
146
+ skillPath,
147
+ universal: { dir: universalDir, launcher, skillPath },
148
+ hosts,
149
+ skippedHosts
150
+ }
151
+ }
152
+
153
+ export function setup(opts) {
154
+ return setupInfo(opts).launcher
155
+ }
156
+
157
+ export function formatQuotaBar(quota) {
158
+ if (!quota) return 'quota: unreported'
159
+ if (quota.source === 'observed') {
160
+ return 'quota: observed ' + quota.class + ' (avoid)'
161
+ }
162
+ const wins = Array.isArray(quota.windows) ? quota.windows : []
163
+ if (!wins.length) return 'quota: no windows'
164
+ const parts = wins.map(w => {
165
+ const used = Math.max(0, Math.min(100, Math.round(Number(w.usedPercent) || 0)))
166
+ const left = 100 - used
167
+ const filled = Math.round(left / 10)
168
+ const bar = '[' + '█'.repeat(filled) + '░'.repeat(10 - filled) + ']'
169
+ return windowLabel(w.minutes) + ' ' + bar + ' ' + left + '% left' + (used >= 90 ? ' (tight)' : '')
170
+ })
171
+ const tightExtra = Array.isArray(quota.tightGroups) && quota.tightGroups.length
172
+ ? ' · tight: ' + quota.tightGroups.map(g => g.name).join(', ')
173
+ : ''
174
+ return parts.join(' ') + tightExtra
175
+ }
176
+
177
+ export async function probeSetupWorkers({ cwd = process.cwd() } = {}) {
178
+ const builtins = ['codex', 'agy', 'cursor-agent', 'claude'].filter(supportedWorker)
179
+ const discoveredPi = await discoverPi(cwd, { refresh: true }).catch(() => [])
180
+ const ids = [...new Set([...builtins, ...discoveredPi.filter(supportedWorker)])]
181
+ const rows = await Promise.all(ids.map(async id => {
182
+ try {
183
+ const detected = await detectCli(id, cwd, { refresh: true })
184
+ const installed = Boolean(detected.installed)
185
+ const loginStatus = detected.loginStatus || 'unknown'
186
+ const loggedIn = Boolean(installed && ['ready', 'not-required'].includes(loginStatus))
187
+ return {
188
+ id,
189
+ cli: detected.cli || id,
190
+ installed,
191
+ loginStatus,
192
+ loggedIn,
193
+ defaultModel: detected.defaultModel || detected.models?.[0]?.id || null,
194
+ modelCount: detected.models?.length ?? 0,
195
+ quota: detected.quota ?? null,
196
+ quotaBar: formatQuotaBar(detected.quota ?? null),
197
+ install: detected.install ?? null,
198
+ login: detected.login ?? null
199
+ }
200
+ } catch {
201
+ return {
202
+ id,
203
+ cli: id.startsWith('pi:') ? 'pi' : id,
204
+ installed: false,
205
+ loginStatus: 'unavailable',
206
+ loggedIn: false,
207
+ defaultModel: null,
208
+ modelCount: 0,
209
+ quota: null,
210
+ quotaBar: 'quota: unreported',
211
+ install: null,
212
+ login: null
213
+ }
214
+ }
215
+ }))
216
+ return rows
217
+ }
218
+
219
+ export function formatSetupRoster(detected, currentAllow = [], defaultWorker = '') {
220
+ if (!detected.length) return 'No supported worker CLIs detected.'
221
+ const allowedSet = new Set(currentAllow)
222
+ return detected.map(w => {
223
+ const tag = allowedSet.has(w.id)
224
+ ? (w.id === defaultWorker ? '[allowed*]' : '[allowed]')
225
+ : w.loggedIn ? '[ready]' : w.installed ? '[' + w.loginStatus + ']' : '[missing]'
226
+ const model = w.defaultModel ? 'model=' + w.defaultModel : (w.modelCount ? w.modelCount + ' models' : 'no models')
227
+ const detail = w.loggedIn
228
+ ? model + ' ' + w.quotaBar
229
+ : w.installed
230
+ ? (w.login ? 'login: ' + w.login : w.loginStatus)
231
+ : (w.install ? 'install: ' + w.install : 'not installed')
232
+ return ' ' + tag.padEnd(11) + ' ' + w.id.padEnd(16) + ' ' + detail
233
+ }).join('\n')
234
+ }
235
+
236
+ export function readGlobalPolicy(brocoHome = home) {
237
+ const regPath = join(brocoHome, 'registry-v2.sqlite')
238
+ if (!existsSync(regPath)) return { configured: false, allow: [], defaultWorker: '', revision: 0 }
239
+ const db = new DatabaseSync(regPath, { readOnly: true })
240
+ try {
241
+ const hasTable = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='roster_settings'").get())
242
+ if (!hasTable) return { configured: false, allow: [], defaultWorker: '', revision: 0 }
243
+ const row = db.prepare("SELECT revision, data FROM roster_settings WHERE scope='global'").get()
244
+ if (!row) return { configured: false, allow: [], defaultWorker: '', revision: 0 }
245
+ const data = JSON.parse(row.data || '{}')
246
+ const allow = Array.isArray(data.allow) ? data.allow.filter(supportedWorker) : []
247
+ const defaultWorker = allow.includes(data.worker) ? data.worker : (allow[0] ?? '')
248
+ return { configured: allow.length > 0, allow, defaultWorker, revision: row.revision }
249
+ } finally {
250
+ db.close()
251
+ }
252
+ }
253
+
254
+ export async function saveGlobalAllowlist(allowInput, { defaultWorker, brocoHome = home } = {}) {
255
+ const rawList = Array.isArray(allowInput)
256
+ ? allowInput
257
+ : String(allowInput ?? '').split(',')
258
+ const allow = [...new Set(rawList.map(s => String(s).trim()).filter(Boolean))]
259
+ if (!allow.length) throw new Error('Specify at least one worker to allow globally')
260
+ if (allow.some(id => !supportedWorker(id))) {
261
+ throw new Error('Expected supported workers (claude, codex, agy, cursor-agent, pi:<provider>, or custom:<name>): ' + allow.filter(id => !supportedWorker(id)).join(', '))
262
+ }
263
+ const existing = readGlobalPolicy(brocoHome)
264
+ let nextWorker = defaultWorker
265
+ if (nextWorker !== undefined && nextWorker !== null && nextWorker !== '') {
266
+ if (!allow.includes(nextWorker)) throw new Error('Default worker must be in the allowed list: ' + nextWorker)
267
+ } else {
268
+ nextWorker = allow.includes(existing.defaultWorker) ? existing.defaultWorker : allow[0]
269
+ }
270
+ const sock = socketFor(brocoHome)
271
+ const probe = await probeReady(sock).catch(() => ({ online: false, compatible: false }))
272
+ if (probe.online && probe.compatible) {
273
+ const res = await call('/allow-set', { scope: 'global', allow, defaultWorker: nextWorker, actor: 'user' }, sock)
274
+ return { allow: res.allow, defaultWorker: res.defaultWorker, auditId: res.auditId, via: 'runner' }
275
+ }
276
+ mkdirSync(brocoHome, { recursive: true })
277
+ const db = new DatabaseSync(join(brocoHome, 'registry-v2.sqlite'))
278
+ try {
279
+ db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON')
280
+ db.exec('CREATE TABLE IF NOT EXISTS roster_settings(scope TEXT PRIMARY KEY,revision INTEGER NOT NULL,data TEXT NOT NULL)')
281
+ const audit = new SettingsAudit(db)
282
+ const row = db.prepare("SELECT revision, data FROM roster_settings WHERE scope='global'").get()
283
+ const oldRev = row ? row.revision : 0
284
+ const oldData = row ? JSON.parse(row.data || '{}') : { entries: {}, rules: [] }
285
+ const nextData = {
286
+ ...oldData,
287
+ entries: oldData.entries ?? {},
288
+ rules: oldData.rules ?? [],
289
+ allow,
290
+ worker: nextWorker
291
+ }
292
+ const before = { kind: 'allow', allow: oldData.allow ?? [], worker: oldData.worker ?? '', inheritPolicy: false }
293
+ const after = { kind: 'allow', allow, worker: nextWorker, inheritPolicy: false }
294
+ const summary = 'Set allowlist=[' + allow.join(', ') + ']' + (nextWorker ? ', default=' + nextWorker : '')
295
+ let auditRow
296
+ db.exec('BEGIN IMMEDIATE')
297
+ try {
298
+ db.prepare('INSERT INTO roster_settings VALUES (?,?,?) ON CONFLICT(scope) DO UPDATE SET revision=excluded.revision,data=excluded.data').run(
299
+ 'global', oldRev + 1, JSON.stringify(nextData)
300
+ )
301
+ auditRow = audit.record({ scope: 'global', scopeName: 'Global', actor: 'user', action: 'allow', summary, before, after })
302
+ db.exec('COMMIT')
303
+ } catch (err) {
304
+ db.exec('ROLLBACK')
305
+ throw err
306
+ }
307
+ return { allow, defaultWorker: nextWorker, auditId: auditRow.id, via: 'sqlite' }
308
+ } finally {
309
+ db.close()
310
+ }
311
+ }
312
+
313
+ export function resolveLegacyHome(env = process.env) {
314
+ if (!env?.CC_BRO_HOME && env?.BROCO_HOST_HOME) {
315
+ return legacyCcBroHome({ ...env, CC_BRO_HOME: join(env.BROCO_HOST_HOME, '.cc-bro') })
316
+ }
317
+ return legacyCcBroHome(env)
318
+ }
319
+
320
+ export function isBrocoHomeEmpty(brocoHome = home) {
321
+ if (!existsSync(brocoHome)) return true
322
+ if (existsSync(join(brocoHome, 'registry-v2.sqlite'))) return false
323
+ const projectsDir = join(brocoHome, 'projects')
324
+ if (existsSync(projectsDir) && isDir(projectsDir)) {
325
+ if (readdirSync(projectsDir).length > 0) return false
326
+ }
327
+ return true
328
+ }
329
+
330
+ export function detectLegacyMigration({ brocoHome = home, env = process.env } = {}) {
331
+ const legacyDir = resolveLegacyHome(env)
332
+ const targetDir = canonical(resolve(brocoHome))
333
+ if (legacyDir === targetDir || !existsSync(legacyDir) || !isDir(legacyDir)) {
334
+ return { available: false, legacyDir, targetDir, legacyHasData: false, targetEmpty: isBrocoHomeEmpty(targetDir), command: 'broco setup --migrate-cc-bro' }
335
+ }
336
+ const hasRegistry = existsSync(join(legacyDir, 'registry-v2.sqlite'))
337
+ const legacyProjects = join(legacyDir, 'projects')
338
+ const hasProjects = isDir(legacyProjects) && readdirSync(legacyProjects).length > 0
339
+ const legacyHasData = hasRegistry || hasProjects
340
+ const targetEmpty = isBrocoHomeEmpty(targetDir)
341
+ return {
342
+ available: legacyHasData && targetEmpty,
343
+ legacyDir,
344
+ targetDir,
345
+ legacyHasData,
346
+ targetEmpty,
347
+ command: 'broco setup --migrate-cc-bro'
348
+ }
349
+ }
350
+
351
+ async function detectActiveRunner(dir) {
352
+ const probe = await probeReady(socketFor(dir)).catch(() => ({ online: false, runner: null }))
353
+ if (probe.online) return { running: true, pid: probe.runner?.pid ?? null }
354
+ const pidPath = join(dir, 'runner.pid')
355
+ if (existsSync(pidPath)) {
356
+ const raw = readFileSync(pidPath, 'utf8').trim()
357
+ const pid = Number(raw)
358
+ if (Number.isSafeInteger(pid) && pid > 1) {
359
+ try {
360
+ process.kill(pid, 0)
361
+ return { running: true, pid }
362
+ } catch {}
363
+ }
364
+ }
365
+ return { running: false, pid: null }
366
+ }
367
+
368
+ function shouldCopyMigrationPath(src) {
369
+ const name = basename(src)
370
+ if (TRANSIENT_NAMES.has(name) || name.endsWith('.sock') || name.endsWith('.service')) return false
371
+ const st = lstatSync(src, { throwIfNoEntry: false })
372
+ if (!st || st.isSocket() || st.isFIFO()) return false
373
+ return true
374
+ }
375
+
376
+ export async function migrateLegacyCcBro({ brocoHome = home, env = process.env } = {}) {
377
+ const status = detectLegacyMigration({ brocoHome, env })
378
+ if (!status.legacyHasData) {
379
+ throw new Error('No legacy ~/.cc-bro data found to migrate at ' + status.legacyDir)
380
+ }
381
+ if (!status.targetEmpty) {
382
+ throw new Error('Target broco home already contains data (' + status.targetDir + '); refusing to overwrite existing data.')
383
+ }
384
+ const legacyRunner = await detectActiveRunner(status.legacyDir)
385
+ if (legacyRunner.running) {
386
+ throw new Error(
387
+ 'A legacy runner is currently active for ' + status.legacyDir +
388
+ (legacyRunner.pid ? ' (pid ' + legacyRunner.pid + ')' : '') +
389
+ '. Stop it first with broco shutdown (or cc-bro shutdown) before running broco setup --migrate-cc-bro.'
390
+ )
391
+ }
392
+ const targetRunner = await detectActiveRunner(status.targetDir)
393
+ if (targetRunner.running) {
394
+ throw new Error(
395
+ 'A broco runner is currently active for ' + status.targetDir +
396
+ (targetRunner.pid ? ' (pid ' + targetRunner.pid + ')' : '') +
397
+ '. Run broco shutdown first before running broco setup --migrate-cc-bro.'
398
+ )
399
+ }
400
+ mkdirSync(status.targetDir, { recursive: true })
401
+ const copied = []
402
+ for (const name of readdirSync(status.legacyDir)) {
403
+ const src = join(status.legacyDir, name)
404
+ if (!shouldCopyMigrationPath(src)) continue
405
+ const dst = join(status.targetDir, name)
406
+ cpSync(src, dst, { recursive: true, filter: shouldCopyMigrationPath })
407
+ copied.push(name)
408
+ }
409
+ return {
410
+ migrated: true,
411
+ legacyDir: status.legacyDir,
412
+ targetDir: status.targetDir,
413
+ copied,
414
+ preservedLegacy: true
415
+ }
416
+ }
package/lib/slots.mjs ADDED
@@ -0,0 +1,177 @@
1
+ function validLimit(n) {
2
+ return Number.isSafeInteger(n) && n >= 1
3
+ }
4
+
5
+ export class Slots {
6
+ constructor(defaultLimit = 3) {
7
+ if (!validLimit(defaultLimit)) throw new Error('BROCO_CONCURRENCY must be a positive integer')
8
+ this.defaultLimit = defaultLimit
9
+ this.limits = new Map()
10
+ this.pools = new Map()
11
+ this.paused = false
12
+ this.suppressNotify = false
13
+ this.dirtyPools = new Set()
14
+ this.notifyScheduled = false
15
+ }
16
+
17
+ get limit() {
18
+ return this.defaultLimit
19
+ }
20
+
21
+ set limit(n) {
22
+ if (!validLimit(n)) throw new Error('BROCO_CONCURRENCY must be a positive integer')
23
+ this.defaultLimit = n
24
+ }
25
+
26
+ scopeOf(crew) {
27
+ return crew?.workerSettings?.()?.id || crew?.projectId || 'default'
28
+ }
29
+
30
+ pool(scope, crew) {
31
+ let p = this.pools.get(scope)
32
+ if (!p) {
33
+ p = { active: new Map(), queue: new Map(), crew: null }
34
+ this.pools.set(scope, p)
35
+ }
36
+ if (crew) p.crew = crew
37
+ return p
38
+ }
39
+
40
+ limitFor(scope = 'default', crew = this.pools.get(scope)?.crew) {
41
+ const configured = crew?.workerSettings?.()?.concurrency
42
+ if (validLimit(configured)) return configured
43
+ const override = this.limits.get(scope)
44
+ if (validLimit(override)) return override
45
+ return this.defaultLimit
46
+ }
47
+
48
+ setLimit(scope, n) {
49
+ const key = !scope || scope === 'global' || scope === 'default' ? 'default' : scope
50
+ if (n === null) {
51
+ if (key !== 'default') this.limits.delete(key)
52
+ } else {
53
+ if (!validLimit(n)) throw new Error('BROCO_CONCURRENCY must be a positive integer')
54
+ if (key === 'default') this.defaultLimit = n
55
+ else this.limits.set(key, n)
56
+ }
57
+ for (const [poolScope, p] of this.pools) {
58
+ if (key === 'default' || poolScope === key) p.crew?.syncConcurrency?.(this.limitFor(poolScope, p.crew))
59
+ }
60
+ this.drain()
61
+ return this.limitFor(key)
62
+ }
63
+
64
+ queueInfo(cid) {
65
+ for (const [scope, p] of this.pools) {
66
+ if (!p.queue.has(cid)) continue
67
+ const ids = [...p.queue.keys()]
68
+ const crew = p.queue.get(cid)?.crew ?? p.crew
69
+ return {
70
+ position: ids.indexOf(cid) + 1,
71
+ totalQueued: ids.length,
72
+ limit: this.limitFor(scope, crew),
73
+ scope,
74
+ activeNames: [...p.active.values()].map(a => a.name)
75
+ }
76
+ }
77
+ return null
78
+ }
79
+
80
+ scheduleNotify() {
81
+ if (this.notifyScheduled || !this.dirtyPools.size) return
82
+ this.notifyScheduled = true
83
+ queueMicrotask(() => {
84
+ this.notifyScheduled = false
85
+ if (this.suppressNotify) return
86
+ const pools = [...this.dirtyPools]
87
+ this.dirtyPools.clear()
88
+ for (const p of pools) {
89
+ for (const [id, item] of p.queue) item.crew?.onQueueChange?.(id)
90
+ }
91
+ })
92
+ }
93
+
94
+ notifyQueue(p) {
95
+ this.dirtyPools.add(p)
96
+ if (!this.suppressNotify) this.scheduleNotify()
97
+ }
98
+
99
+ flushNotifications() {
100
+ this.suppressNotify = false
101
+ this.scheduleNotify()
102
+ }
103
+
104
+ reserve(crew, c) {
105
+ const scope = this.scopeOf(crew)
106
+ const p = this.pool(scope, crew)
107
+ const limit = this.limitFor(scope, crew)
108
+ crew?.syncConcurrency?.(limit)
109
+ if (!this.paused && p.queue.size && p.active.size < limit) this.drainPool(scope, p)
110
+ if (!this.paused && p.active.size < limit && !p.queue.size) {
111
+ p.active.set(c.id, { scope, crew, name: c.name, turn: c.turn, startedAt: Date.now() })
112
+ return true
113
+ }
114
+ const existing = p.queue.get(c.id)
115
+ p.queue.set(c.id, { scope, crew, name: c.name, turn: c.turn, queuedAt: existing?.queuedAt ?? Date.now() })
116
+ this.notifyQueue(p)
117
+ return false
118
+ }
119
+
120
+ release(id, turn) {
121
+ let changed = false
122
+ for (const p of this.pools.values()) {
123
+ const activeItem = p.active.get(id)
124
+ if (activeItem && (turn === undefined || activeItem.turn === turn)) {
125
+ p.active.delete(id)
126
+ changed = true
127
+ }
128
+ const queuedItem = p.queue.get(id)
129
+ if (queuedItem && (turn === undefined || queuedItem.turn === turn)) {
130
+ p.queue.delete(id)
131
+ queuedItem.crew?.clearEnvFor?.(id, turn)
132
+ changed = true
133
+ this.notifyQueue(p)
134
+ }
135
+ }
136
+ this.drain()
137
+ return changed
138
+ }
139
+
140
+ drainPool(scope, p) {
141
+ if (!p.queue.size || this.paused) return
142
+ let cachedCrew = p.crew
143
+ let limit = this.limitFor(scope, cachedCrew)
144
+ cachedCrew?.syncConcurrency?.(limit)
145
+ for (const [id, item] of p.queue) {
146
+ const { crew, name, turn } = item
147
+ if (crew !== cachedCrew) {
148
+ cachedCrew = crew
149
+ limit = this.limitFor(scope, crew)
150
+ crew?.syncConcurrency?.(limit)
151
+ }
152
+ if (this.paused || p.active.size >= limit) break
153
+ p.queue.delete(id)
154
+ if (crew.closing) {
155
+ crew?.clearEnvFor?.(id, turn)
156
+ continue
157
+ }
158
+ p.active.set(id, { scope, crew, name, turn, startedAt: Date.now() })
159
+ crew.serial(name, async () => {
160
+ const c = crew.store.byName(name)
161
+ if (!crew.closing && c && c.turn === turn && c.status === 'queued') await crew.dispatch(c)
162
+ else {
163
+ crew?.clearEnvFor?.(id, turn)
164
+ this.release(id, turn)
165
+ }
166
+ }).catch(() => {
167
+ this.release(id, turn)
168
+ })
169
+ }
170
+ if (p.queue.size) this.notifyQueue(p)
171
+ }
172
+
173
+ drain() {
174
+ if (this.paused) return
175
+ for (const [scope, p] of this.pools) this.drainPool(scope, p)
176
+ }
177
+ }
package/lib/stats.mjs ADDED
@@ -0,0 +1,92 @@
1
+ import { infra } from './problems.mjs'
2
+
3
+ const median = values => {
4
+ if (!values.length) return null
5
+ const sorted = [...values].sort((a, b) => a - b), mid = sorted.length >> 1
6
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2
7
+ }
8
+
9
+ function computeWeekSpent(quotaRows) {
10
+ if (!quotaRows || !quotaRows.length) return null
11
+ const first = quotaRows[0], last = quotaRows.at(-1)
12
+ const w = (last.windows ?? []).find(win => win.minutes === 10080)
13
+ if (!w) return null
14
+ const before = (first.windows ?? []).find(b => b.minutes === 10080)
15
+ if (!before || before.resetsAt !== w.resetsAt) return null
16
+ const pct = Math.max(0, w.usedPercent - before.usedPercent)
17
+ return Number.isFinite(pct) ? pct : null
18
+ }
19
+
20
+ export function ticketRecords(store) {
21
+ const tickets = store.stmt("SELECT c.id,c.provider,t.model,t.thinking,t.start_turn,t.end_turn,t.outcome,(SELECT parent FROM collaboration WHERE cid=c.id) AS parent FROM tasks t JOIN conversations c ON c.id=t.cid WHERE t.outcome IS NOT NULL").all()
22
+ if (!tickets.length) return []
23
+
24
+ const cidsJson = JSON.stringify([...new Set(tickets.map(t => t.id))])
25
+ const turnsByCid = new Map()
26
+ for (const r of store.stmt('SELECT cid,turn,status,started,finished,problem FROM turns WHERE cid IN (SELECT value FROM json_each(?)) ORDER BY cid,turn').all(cidsJson)) {
27
+ let arr = turnsByCid.get(r.cid)
28
+ if (!arr) { arr = []; turnsByCid.set(r.cid, arr) }
29
+ arr.push(r)
30
+ }
31
+
32
+ const quotaByKey = new Map()
33
+ for (const e of store.stmt("SELECT cid,turn,raw FROM events WHERE kind='quota' AND cid IN (SELECT value FROM json_each(?)) ORDER BY id").all(cidsJson)) {
34
+ const key = e.cid + ':' + e.turn
35
+ let arr = quotaByKey.get(key)
36
+ if (!arr) { arr = []; quotaByKey.set(key, arr) }
37
+ arr.push(JSON.parse(e.raw))
38
+ }
39
+
40
+ return tickets.map(t => {
41
+ const allTurns = turnsByCid.get(t.id) ?? []
42
+ const turns = allTurns.filter(r => r.turn >= t.start_turn && r.turn <= t.end_turn)
43
+ const week = turns.map(r => computeWeekSpent(quotaByKey.get(t.id + ':' + r.turn))).filter(Number.isFinite)
44
+ const done = turns.filter(r => r.status === 'done').length
45
+ const infraFailures = turns.filter(r => r.problem && infra.includes(JSON.parse(r.problem).class)).length
46
+ const last = turns.at(-1)?.problem
47
+ const outcome = t.outcome === 'fail' && last && infra.includes(JSON.parse(last).class) ? 'blocked' : t.outcome
48
+ return {
49
+ worker: t.provider,
50
+ model: t.model,
51
+ effort: t.thinking,
52
+ role: t.parent ? 'review' : 'write',
53
+ outcome,
54
+ turns: done,
55
+ minutes: turns.reduce((sum, r) => sum + (r.finished && r.started ? (r.finished - r.started) / 60000 : 0), 0),
56
+ infraFailures,
57
+ weekQuota: week.length ? week.reduce((a, b) => a + b, 0) : null
58
+ }
59
+ })
60
+ }
61
+
62
+ export function summarize(records) {
63
+ const groups = new Map()
64
+ for (const r of records) {
65
+ const key = [r.worker, r.model, r.role].join('\0')
66
+ if (!groups.has(key)) groups.set(key, { worker: r.worker, model: r.model, role: r.role, tickets: 0, pass: 0, rework: 0, fail: 0, blocked: 0, infraFailures: 0, minutes: [], quota: [], efforts: new Set() })
67
+ const g = groups.get(key)
68
+ g[r.outcome]++
69
+ if (r.outcome === 'blocked') { g.infraFailures += r.infraFailures; continue }
70
+ g.tickets++
71
+ g.infraFailures += r.infraFailures
72
+ g.minutes.push(r.minutes)
73
+ if (r.weekQuota !== null) g.quota.push(r.weekQuota)
74
+ if (r.effort) g.efforts.add(r.effort)
75
+ }
76
+ return [...groups.values()].map(({ minutes, quota, efforts, ...g }) => ({
77
+ ...g,
78
+ passRate: g.tickets ? g.pass / g.tickets : null,
79
+ medianMinutes: minutes.length ? Math.round(median(minutes) * 10) / 10 : null,
80
+ weekQuotaPerTicket: quota.length ? Math.round(quota.reduce((a, b) => a + b, 0) / quota.length * 10) / 10 : null,
81
+ efforts: [...efforts]
82
+ })).sort((a, b) => b.tickets - a.tickets)
83
+ }
84
+
85
+ export const minimumTickets = 3
86
+
87
+ export function statsText(groups) {
88
+ if (!groups.length) return 'No accepted tickets with an outcome yet. Record one with: broco done <name> --result pass|rework|fail|blocked'
89
+ return ['BRO\tMODEL\tROLE\tTICKETS\tPASS\tREWORK\tFAIL\tBLOCKED\tMEDIAN_MIN\tWEEK_QUOTA/TICKET\tINFRA_FAILURES', ...groups.map(g =>
90
+ [g.worker, g.model, g.role, g.tickets, g.pass, g.rework, g.fail, g.blocked, g.medianMinutes ?? '-', g.weekQuotaPerTicket ?? '-', g.infraFailures].join('\t')),
91
+ 'BLOCKED = closed with --result blocked, or failed on its last turn because of quota, region, policy, network or auth; excluded from TICKETS and pass rates.'].join('\n')
92
+ }