@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/web.mjs ADDED
@@ -0,0 +1,260 @@
1
+ import { createReadStream, existsSync } from 'node:fs'
2
+ import { realpath, stat } from 'node:fs/promises'
3
+ import { createServer } from 'node:http'
4
+ import { extname, join, resolve, sep } from 'node:path'
5
+ import { batchDetail, listBatches } from './map.mjs'
6
+ import { checkout, home, repo } from './paths.mjs'
7
+
8
+ const mime = {
9
+ '.html': 'text/html; charset=utf-8',
10
+ '.js': 'text/javascript; charset=utf-8',
11
+ '.css': 'text/css; charset=utf-8',
12
+ '.json': 'application/json; charset=utf-8',
13
+ '.webmanifest': 'application/manifest+json; charset=utf-8',
14
+ '.svg': 'image/svg+xml; charset=utf-8',
15
+ '.png': 'image/png',
16
+ '.ico': 'image/x-icon',
17
+ '.woff2': 'font/woff2',
18
+ '.webp': 'image/webp'
19
+ }
20
+
21
+ function defaultDist() {
22
+ const devDist = join(repo, 'ui', 'dist')
23
+ const bundled = join(repo, 'bundle', 'board')
24
+ if (checkout) return existsSync(devDist) ? devDist : (existsSync(bundled) ? bundled : devDist)
25
+ return bundled
26
+ }
27
+
28
+ function fail(status, code, message) {
29
+ throw Object.assign(new Error(message), { status, code })
30
+ }
31
+
32
+ function decode(value) {
33
+ try {
34
+ return decodeURIComponent(value)
35
+ } catch {
36
+ fail(400, 'INVALID_PATH', 'Invalid URL encoding')
37
+ }
38
+ }
39
+
40
+ function projectOf(projects, id) {
41
+ try {
42
+ return projects.get(id)
43
+ } catch (err) {
44
+ if (/^Unknown project\b/i.test(err?.message || '')) fail(404, 'PROJECT_NOT_FOUND', err.message)
45
+ throw err
46
+ }
47
+ }
48
+
49
+ function json(res, value, status = 200) {
50
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' })
51
+ res.end(JSON.stringify(value))
52
+ }
53
+
54
+ async function body(req) {
55
+ const chunks = []
56
+ let bytes = 0
57
+ for await (const part of req) {
58
+ const buf = Buffer.isBuffer(part) ? part : Buffer.from(part)
59
+ bytes += buf.length
60
+ if (bytes > 256 * 1024) fail(413, 'BODY_TOO_LARGE', 'Settings exceed 256 KiB')
61
+ chunks.push(buf)
62
+ }
63
+ const text = chunks.length ? Buffer.concat(chunks, bytes).toString('utf8') : ''
64
+ try {
65
+ return JSON.parse(text || '{}')
66
+ } catch {
67
+ fail(400, 'INVALID_JSON', 'Invalid JSON body')
68
+ }
69
+ }
70
+
71
+ export class Web {
72
+ constructor(projects, { dist = defaultDist(), port = Number(process.env.BROCO_PORT ?? 4517) } = {}) {
73
+ this.projects = projects
74
+ this.dist = dist
75
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Invalid BROCO_PORT')
76
+ this.port = port
77
+ this.boundPort = null
78
+ this.streams = new Set()
79
+ this.server = createServer((req, res) => {
80
+ this.route(req, res).catch(err => {
81
+ if (res.headersSent) return res.destroy()
82
+ const missingProject = !err.status && /^Unknown project\b/i.test(err?.message || '')
83
+ const status = missingProject ? 404 : (err.status || 400)
84
+ const code = missingProject ? 'PROJECT_NOT_FOUND' : (err.code || 'REQUEST_FAILED')
85
+ json(res, { error: { code, message: err.message } }, status)
86
+ })
87
+ })
88
+ }
89
+
90
+ hasSubscribers() {
91
+ return this.streams.size > 0
92
+ }
93
+
94
+ start() {
95
+ this.starting ??= this.listen().catch(err => { this.starting = null; throw err })
96
+ return this.starting
97
+ }
98
+
99
+ async listen() {
100
+ for (let port = this.port; port <= 65535; port++) {
101
+ try {
102
+ await new Promise((ok, bad) => {
103
+ const error = err => { this.server.off('listening', listening); bad(err) }
104
+ const listening = () => { this.server.off('error', error); ok() }
105
+ this.server.once('error', error).once('listening', listening).listen(port, '127.0.0.1')
106
+ })
107
+ this.boundPort = this.server.address().port
108
+ this.origin = 'http://127.0.0.1:' + this.boundPort
109
+ return this.origin
110
+ } catch (err) { if (err.code !== 'EADDRINUSE') throw err }
111
+ }
112
+ throw new Error('No available loopback port')
113
+ }
114
+
115
+ validHost(host) {
116
+ if (!host || this.boundPort === null) return false
117
+ return host === '127.0.0.1:' + this.boundPort || host === 'localhost:' + this.boundPort
118
+ }
119
+
120
+ validOrigin(origin) {
121
+ if (!origin || this.boundPort === null) return false
122
+ return origin === 'http://127.0.0.1:' + this.boundPort || origin === 'http://localhost:' + this.boundPort
123
+ }
124
+
125
+ publish(event) {
126
+ if (!this.streams.size) return
127
+ const frame = 'data: ' + JSON.stringify(event) + '\n\n'
128
+ for (const res of this.streams) {
129
+ if (res.destroyed || res.writableEnded) {
130
+ this.streams.delete(res)
131
+ continue
132
+ }
133
+ if (res.writableLength > 1024 * 1024) {
134
+ this.streams.delete(res)
135
+ res.destroy()
136
+ } else {
137
+ res.write(frame)
138
+ }
139
+ }
140
+ }
141
+
142
+ stream(res) {
143
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' })
144
+ res.write('data: ' + JSON.stringify({ type: 'hello', projects: this.projects.list() }) + '\n\n')
145
+ this.streams.add(res)
146
+ const heartbeat = setInterval(() => {
147
+ if (!res.destroyed && !res.writableEnded) res.write(': keepalive\n\n')
148
+ }, 15000)
149
+ heartbeat.unref?.()
150
+ res.on('close', () => { clearInterval(heartbeat); this.streams.delete(res) })
151
+ }
152
+
153
+ async route(req, res) {
154
+ if (!this.validHost(req.headers.host)) fail(403, 'INVALID_HOST', 'Use the local broco address')
155
+ const method = req.method
156
+ if (['POST', 'DELETE'].includes(method) && !this.validOrigin(req.headers.origin)) {
157
+ fail(403, 'INVALID_ORIGIN', 'This action must come from this broco page')
158
+ }
159
+ const url = new URL(req.url, this.origin)
160
+ const path = url.pathname
161
+ if (!path.startsWith('/api/')) {
162
+ if (!['HEAD', 'GET'].includes(method)) fail(405, 'METHOD_NOT_ALLOWED', 'Unsupported method')
163
+ return this.static(req, res, path)
164
+ }
165
+ const [, , group, rawId, rawResource, rawTicket, ...extra] = path.split('/')
166
+ if (extra.length) fail(404, 'NOT_FOUND', 'Unknown endpoint')
167
+ if (path === '/api/stream' && method === 'GET') return this.stream(res)
168
+ if (path === '/api/projects' && method === 'GET') return json(res, this.projects.list())
169
+ const roster = this.projects.roster
170
+ const scope = rawId ? decode(rawId) : ''
171
+ const resource = rawResource ? decode(rawResource) : ''
172
+ if (group === 'settings' && scope && !resource) {
173
+ if (scope !== 'global') projectOf(this.projects, scope)
174
+ if (method === 'GET') return json(res, roster.config(scope))
175
+ if (method === 'POST') return json(res, roster.save(scope, await body(req), 'user'))
176
+ }
177
+ if (group === 'roster' && scope && !resource && method === 'GET') {
178
+ if (scope !== 'global') projectOf(this.projects, scope)
179
+ return json(res, await roster.list(scope, true, { refresh: url.searchParams.get('refresh') === '1' }))
180
+ }
181
+ if (group === 'audit' && scope && !resource && method === 'GET') {
182
+ if (scope !== 'global' && scope !== 'all') projectOf(this.projects, scope)
183
+ return json(res, roster.auditList(scope, Number(url.searchParams.get('limit') || 30)))
184
+ }
185
+ if (group === 'audit' && scope && resource === 'undo' && !rawTicket && method === 'POST') {
186
+ if (scope !== 'global' && scope !== 'all') projectOf(this.projects, scope)
187
+ const input = await body(req)
188
+ return json(res, roster.undoAudit(input.id ?? input.auditId ?? null, { scope, actor: input.actor || 'user' }))
189
+ }
190
+ if (group === 'templates' && scope && resource === 'test' && !rawTicket && method === 'POST') {
191
+ if (scope !== 'global') projectOf(this.projects, scope)
192
+ const input = await body(req)
193
+ return json(res, await roster.trial(scope, input.template, input.model, input.effort))
194
+ }
195
+ if (group === 'notes' && scope && resource && !rawTicket && method === 'POST') {
196
+ const input = await body(req)
197
+ if (typeof input.accept !== 'boolean') fail(400, 'INVALID_INPUT', 'Expected accept: true or false')
198
+ return json(res, roster.resolveProposal(scope, resource, input.accept))
199
+ }
200
+ if (group === 'cli' && scope && resource && !rawTicket && method === 'POST') {
201
+ const input = await body(req)
202
+ const cwd = input.projectId ? projectOf(this.projects, input.projectId).repoPath : home
203
+ return json(res, await roster.terminal(scope, resource, cwd, input.projectId ?? 'global'))
204
+ }
205
+ if (group === 'projects' && scope) {
206
+ const p = projectOf(this.projects, scope)
207
+ if (resource === 'tickets' && method === 'GET') {
208
+ if (!rawTicket) return json(res, p.crew.store.ticketRows())
209
+ const ticket = p.crew.store.detail(decode(rawTicket))
210
+ if (!ticket) fail(404, 'TICKET_NOT_FOUND', 'Ticket not found')
211
+ return json(res, ticket)
212
+ }
213
+ if (resource === 'batches' && method === 'GET') {
214
+ if (!rawTicket) return json(res, listBatches(p.crew.store))
215
+ const batch = batchDetail(p.crew.store, decode(rawTicket))
216
+ if (!batch) fail(404, 'BATCH_NOT_FOUND', 'Batch not found')
217
+ return json(res, batch)
218
+ }
219
+ }
220
+ fail(404, 'NOT_FOUND', 'Unknown endpoint')
221
+ }
222
+
223
+ async static(req, res, path) {
224
+ let root
225
+ try { root = await realpath(this.dist) }
226
+ catch (err) {
227
+ if (err.code !== 'ENOENT') throw err
228
+ res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-cache' })
229
+ return res.end('broco is running. Build ui/dist to open the board.')
230
+ }
231
+ const decoded = decode(path)
232
+ let file = resolve(root, '.' + decoded)
233
+ if (file !== root && !file.startsWith(root + sep)) fail(404, 'NOT_FOUND', 'File not found')
234
+ const isSpaEntry = file === root || !extname(file)
235
+ if (isSpaEntry) file = join(root, 'index.html')
236
+ try { file = await realpath(file) } catch { fail(404, 'NOT_FOUND', 'File not found') }
237
+ const info = await stat(file)
238
+ if (!file.startsWith(root + sep) || !info.isFile()) fail(404, 'NOT_FOUND', 'File not found')
239
+ const ext = extname(file).toLowerCase()
240
+ const cacheControl = !isSpaEntry && ext !== '.html' && decoded.startsWith('/assets/')
241
+ ? 'public, max-age=31536000, immutable'
242
+ : 'no-cache'
243
+ res.writeHead(200, {
244
+ 'Content-Type': mime[ext] || 'application/octet-stream',
245
+ 'Content-Length': info.size,
246
+ 'Cache-Control': cacheControl,
247
+ 'X-Content-Type-Options': 'nosniff'
248
+ })
249
+ if (req.method === 'HEAD') return res.end()
250
+ createReadStream(file).on('error', () => res.destroy()).pipe(res)
251
+ }
252
+
253
+ async close() {
254
+ this.starting = null
255
+ this.boundPort = null
256
+ for (const stream of this.streams) stream.end()
257
+ this.streams.clear()
258
+ if (this.server.listening) await new Promise(ok => this.server.close(ok))
259
+ }
260
+ }
@@ -0,0 +1,17 @@
1
+ export function supportedWorker(id) {
2
+ return typeof id === 'string' && /^(codex|claude|agy|cursor-agent|(?:pi|custom):[a-z0-9][a-z0-9_.-]*)$/.test(id)
3
+ }
4
+
5
+ export const chooseAllow = 'Choose allowed workers with --allow codex,claude,pi:<provider>,agy,cursor-agent,custom:<name> (or a single worker)'
6
+ export const chooseDefault = 'Choose a default from the allowed workers with --default-worker'
7
+
8
+ export function workerPolicy(allow, worker, current) {
9
+ if (allow === undefined && !current?.allow.length) throw new Error(chooseAllow)
10
+ const providers = allow === undefined ? current.allow : [...new Set(allow.split(',').map(v => v.trim()).filter(Boolean))]
11
+ if (!providers.length) throw new Error(chooseAllow)
12
+ if (!providers.every(supportedWorker)) throw new Error('Expected codex, claude, pi:<provider>, agy, cursor-agent or custom:<name>')
13
+ const selected = worker ?? (providers.includes(current?.worker) ? current.worker : providers.length === 1 ? providers[0] : null)
14
+ if (!selected) throw new Error(chooseDefault)
15
+ if (!providers.includes(selected)) throw new Error('Default worker must be allowed')
16
+ return { allow: providers, worker: selected }
17
+ }
@@ -0,0 +1,269 @@
1
+ import { execFile, execFileSync } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { existsSync, lstatSync, mkdirSync } from 'node:fs'
4
+ import { lstat as lstatAsync } from 'node:fs/promises'
5
+ import { join } from 'node:path'
6
+ import { promisify } from 'node:util'
7
+
8
+ const exec = promisify(execFile)
9
+
10
+ function git(cwd, ...args) {
11
+ return execFileSync('git', ['--no-optional-locks', '-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 })
12
+ }
13
+
14
+ async function gitAsync(cwd, ...args) {
15
+ const { stdout } = await exec('git', ['--no-optional-locks', '-C', cwd, ...args], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 })
16
+ return stdout
17
+ }
18
+
19
+ export function createTree(cwd, directory, name) {
20
+ const prefix = git(cwd, 'rev-parse', '--show-prefix').trimEnd()
21
+ if (prefix) git(cwd, 'cat-file', '-e', 'HEAD:' + prefix.slice(0, -1))
22
+ const id = randomUUID()
23
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 40).replace(/^-|-$/g, '') || 'ticket'
24
+ const branch = 'broco/' + slug + '-' + id.slice(0, 8)
25
+ mkdirSync(join(directory, 'worktrees'), { recursive: true })
26
+ const worktree = join(directory, 'worktrees', id)
27
+ git(cwd, 'worktree', 'add', '-q', '-b', branch, worktree, 'HEAD')
28
+ return { branch, worktree, cwd: join(worktree, prefix) }
29
+ }
30
+
31
+ export function verifyTree(cwd, branch) {
32
+ if (git(cwd, 'symbolic-ref', '--short', 'HEAD').trimEnd() !== branch) throw new Error('Ticket worktree is no longer on ' + branch)
33
+ }
34
+
35
+ function buildFileMap(trackedOut, stagedOut, untrackedOut) {
36
+ const files = new Map()
37
+ const tracked = trackedOut.split('\0')
38
+ for (let i = 0; i + 1 < tracked.length; i += 2) files.set(tracked[i + 1], [tracked[i], null])
39
+ const staged = stagedOut.split('\0')
40
+ for (let i = 0; i + 1 < staged.length; i += 2) {
41
+ const path = staged[i + 1], entry = staged[i]
42
+ files.set(path, [files.get(path)?.[0] ?? entry.split(' ').at(-1), entry])
43
+ }
44
+ for (const p of untrackedOut.split('\0').filter(Boolean)) files.set(p, ['A', files.get(p)?.[1] ?? null])
45
+ return files
46
+ }
47
+
48
+ function snapshot(cwd, base) {
49
+ const diff = (...args) => git(cwd, 'diff', '--no-ext-diff', '--relative', '--no-renames', '-z', ...args, base, '--', '.')
50
+ const files = buildFileMap(
51
+ diff('--name-status'),
52
+ diff('--cached', '--raw', '--no-abbrev'),
53
+ git(cwd, 'ls-files', '--others', '--exclude-standard', '-z', '--', '.')
54
+ )
55
+ return Object.fromEntries([...files].map(([p, [status, index]]) => {
56
+ const s = lstatSync(join(cwd, p), { bigint: true, throwIfNoEntry: false })
57
+ return [p, [status, s ? String(s.ctimeNs) : null, index]]
58
+ }))
59
+ }
60
+
61
+ async function snapshotAsync(cwd, base) {
62
+ const diff = (...args) => gitAsync(cwd, 'diff', '--no-ext-diff', '--relative', '--no-renames', '-z', ...args, base, '--', '.')
63
+ const [trackedOut, stagedOut, untrackedOut] = await Promise.all([
64
+ diff('--name-status'),
65
+ diff('--cached', '--raw', '--no-abbrev'),
66
+ gitAsync(cwd, 'ls-files', '--others', '--exclude-standard', '-z', '--', '.')
67
+ ])
68
+ const files = buildFileMap(trackedOut, stagedOut, untrackedOut)
69
+ const entries = await Promise.all([...files].map(async ([p, [status, index]]) => {
70
+ let ctime = null
71
+ try {
72
+ const s = await lstatAsync(join(cwd, p), { bigint: true })
73
+ ctime = String(s.ctimeNs)
74
+ } catch {}
75
+ return [p, [status, ctime, index]]
76
+ }))
77
+ return Object.fromEntries(entries)
78
+ }
79
+
80
+ export function baseline(cwd) {
81
+ try {
82
+ let head
83
+ try { head = git(cwd, 'rev-parse', '--verify', 'HEAD').trimEnd() }
84
+ catch { head = git(cwd, 'hash-object', '-t', 'tree', '--stdin').trimEnd() }
85
+ const branch = git(cwd, 'branch', '--show-current').trimEnd() || null
86
+ return { head, branch, files: snapshot(cwd, head) }
87
+ } catch { return null }
88
+ }
89
+
90
+ export function changes(cwd, before) {
91
+ if (!before) return null
92
+ try {
93
+ const now = snapshot(cwd, before.head)
94
+ return [...new Set([...Object.keys(before.files), ...Object.keys(now)])].sort()
95
+ .filter(p => JSON.stringify(Object.hasOwn(now, p) ? now[p] : null) !== JSON.stringify(Object.hasOwn(before.files, p) ? before.files[p] : null))
96
+ .map(path => {
97
+ if (Object.hasOwn(now, path)) return { path, status: now[path][0] }
98
+ const exists = lstatSync(join(cwd, path), { throwIfNoEntry: false })
99
+ return { path, status: !exists ? 'D' : before.files[path][0] === 'D' ? 'A' : 'M' }
100
+ })
101
+ } catch { return null }
102
+ }
103
+
104
+ export async function changesAsync(cwd, before) {
105
+ if (!before) return null
106
+ try {
107
+ const now = await snapshotAsync(cwd, before.head)
108
+ const keys = [...new Set([...Object.keys(before.files), ...Object.keys(now)])].sort()
109
+ .filter(p => JSON.stringify(Object.hasOwn(now, p) ? now[p] : null) !== JSON.stringify(Object.hasOwn(before.files, p) ? before.files[p] : null))
110
+ return Promise.all(keys.map(async path => {
111
+ if (Object.hasOwn(now, path)) return { path, status: now[path][0] }
112
+ let exists = false
113
+ try { await lstatAsync(join(cwd, path)); exists = true } catch {}
114
+ return { path, status: !exists ? 'D' : before.files[path][0] === 'D' ? 'A' : 'M' }
115
+ }))
116
+ } catch { return null }
117
+ }
118
+
119
+ function untrackedPatch(cwd, relPath) {
120
+ try {
121
+ return execFileSync('git', ['--no-optional-locks', '-C', cwd, 'diff', '--no-ext-diff', '--no-index', '--', '/dev/null', relPath], {
122
+ encoding: 'utf8',
123
+ stdio: ['ignore', 'pipe', 'pipe'],
124
+ maxBuffer: 4 * 1024 * 1024
125
+ })
126
+ } catch (err) {
127
+ if (err.status === 1 && typeof err.stdout === 'string') return err.stdout
128
+ return ''
129
+ }
130
+ }
131
+
132
+ export function diffWorktree(cwd, before, { statOnly = false } = {}) {
133
+ const parsed = typeof before === 'string' ? JSON.parse(before) : before
134
+ let ref = parsed
135
+ if (!ref) {
136
+ try {
137
+ const head = git(cwd, 'rev-parse', '--verify', 'HEAD').trimEnd()
138
+ ref = { head, files: {} }
139
+ } catch {
140
+ return { baseHead: null, changedFiles: [], stat: '', patch: statOnly ? null : '' }
141
+ }
142
+ }
143
+ const changedFiles = changes(cwd, ref) ?? []
144
+ if (!changedFiles.length) {
145
+ return { baseHead: ref.head, changedFiles: [], stat: '', patch: statOnly ? null : '' }
146
+ }
147
+ const untrackedSet = new Set(git(cwd, 'ls-files', '--others', '--exclude-standard', '-z', '--', '.').split('\0').filter(Boolean))
148
+ const trackedPaths = changedFiles.map(f => f.path).filter(p => !untrackedSet.has(p))
149
+ const untrackedPaths = changedFiles.map(f => f.path).filter(p => untrackedSet.has(p))
150
+
151
+ const statParts = []
152
+ if (trackedPaths.length) {
153
+ const trackedStat = git(cwd, 'diff', '--no-ext-diff', '--relative', '--stat', ref.head, '--', ...trackedPaths).trimEnd()
154
+ if (trackedStat) statParts.push(trackedStat)
155
+ }
156
+ for (const p of untrackedPaths) statParts.push(' ' + p + ' | new untracked file')
157
+ const stat = statParts.join('\n')
158
+
159
+ if (statOnly) return { baseHead: ref.head, changedFiles, stat, patch: null }
160
+
161
+ const patchParts = []
162
+ if (trackedPaths.length) {
163
+ const trackedPatch = git(cwd, 'diff', '--no-ext-diff', '--relative', ref.head, '--', ...trackedPaths)
164
+ if (trackedPatch) patchParts.push(trackedPatch.trimEnd())
165
+ }
166
+ for (const p of untrackedPaths) {
167
+ const uPatch = untrackedPatch(cwd, p)
168
+ if (uPatch) patchParts.push(uPatch.trimEnd())
169
+ }
170
+ const combined = patchParts.join('\n')
171
+ const maxChars = 2 * 1024 * 1024
172
+ const patch = combined.length > maxChars ? combined.slice(0, maxChars) + '\n... [diff truncated at 2 MiB]' : combined
173
+ return { baseHead: ref.head, changedFiles, stat, patch }
174
+ }
175
+
176
+ export function cleanWorktrees(store, repoPath, { target = null, dryRun = false, deleteBranch = false, force = false } = {}) {
177
+ let targetNames = null
178
+ if (target !== null && target !== undefined) {
179
+ const trimmed = String(target).trim()
180
+ if (!trimmed) throw new Error('Invalid clean target')
181
+ if (store.hasTable?.('batches')) {
182
+ const batchRow = store.stmt('SELECT shards FROM batches WHERE prefix=?').get(trimmed)
183
+ if (batchRow) targetNames = new Set(JSON.parse(batchRow.shards).map(s => s.name))
184
+ }
185
+ if (!targetNames) {
186
+ const single = store.stmt('SELECT c.name, m.worktree FROM conversations c LEFT JOIN collaboration m ON m.cid=c.id WHERE c.name=?').get(trimmed)
187
+ if (!single || !single.worktree) throw new Error('No worktree found for: ' + trimmed)
188
+ targetNames = new Set([trimmed])
189
+ }
190
+ }
191
+
192
+ const rows = store.stmt(`
193
+ SELECT c.id AS cid, c.name, c.status AS conversationStatus, t.stage AS ticketStatus,
194
+ m.worktree, m.branch
195
+ FROM collaboration m
196
+ JOIN conversations c ON c.id = m.cid
197
+ JOIN tickets t ON t.cid = c.id
198
+ WHERE m.worktree IS NOT NULL AND m.parent IS NULL
199
+ ORDER BY t.created ASC, c.name ASC
200
+ `).all()
201
+
202
+ const cleaned = []
203
+ const skipped = []
204
+
205
+ for (const row of rows) {
206
+ if (targetNames && !targetNames.has(row.name)) continue
207
+ const activeSharing = store.stmt("SELECT c.name FROM collaboration m JOIN conversations c ON c.id=m.cid WHERE m.worktree=? AND c.status IN ('queued','running') LIMIT 1").get(row.worktree)
208
+ if (['queued', 'running'].includes(row.conversationStatus) || activeSharing) {
209
+ skipped.push({ name: row.name, worktree: row.worktree, branch: row.branch, reason: 'Ticket has active or queued work' })
210
+ continue
211
+ }
212
+ if (!targetNames && !force && row.ticketStatus !== 'done') {
213
+ skipped.push({ name: row.name, worktree: row.worktree, branch: row.branch, reason: 'Ticket is not closed with done (pass --force or name explicitly)' })
214
+ continue
215
+ }
216
+ const exists = existsSync(row.worktree)
217
+ if (exists && !force) {
218
+ try {
219
+ const dirty = git(row.worktree, 'status', '--porcelain').trim()
220
+ if (dirty) {
221
+ skipped.push({ name: row.name, worktree: row.worktree, branch: row.branch, reason: 'Worktree has uncommitted changes (pass --force to remove)' })
222
+ continue
223
+ }
224
+ } catch {
225
+ skipped.push({ name: row.name, worktree: row.worktree, branch: row.branch, reason: 'Could not inspect worktree git status (pass --force to remove)' })
226
+ continue
227
+ }
228
+ }
229
+ if (dryRun) {
230
+ cleaned.push({ name: row.name, worktree: row.worktree, branch: row.branch, branchDeleted: Boolean(deleteBranch && row.branch), dryRun: true })
231
+ continue
232
+ }
233
+ if (exists) {
234
+ try {
235
+ git(repoPath, 'worktree', 'remove', ...(force ? ['--force'] : []), row.worktree)
236
+ } catch (err) {
237
+ skipped.push({ name: row.name, worktree: row.worktree, branch: row.branch, reason: err.message.trim() })
238
+ continue
239
+ }
240
+ } else {
241
+ try { git(repoPath, 'worktree', 'prune') } catch {}
242
+ }
243
+ let branchDeleted = false
244
+ let branchRetainedReason = null
245
+ if (deleteBranch && row.branch) {
246
+ try {
247
+ git(repoPath, 'branch', force ? '-D' : '-d', row.branch)
248
+ branchDeleted = true
249
+ } catch {
250
+ branchRetainedReason = 'Branch is not merged (pass --force to delete)'
251
+ }
252
+ }
253
+ store.transaction(() => {
254
+ if (branchDeleted) store.stmt('UPDATE collaboration SET worktree=NULL,branch=NULL WHERE worktree=?').run(row.worktree)
255
+ else store.stmt('UPDATE collaboration SET worktree=NULL WHERE worktree=?').run(row.worktree)
256
+ store.changed(row.cid)
257
+ })
258
+ cleaned.push({
259
+ name: row.name,
260
+ worktree: row.worktree,
261
+ branch: row.branch,
262
+ branchDeleted,
263
+ ...(branchRetainedReason ? { branchRetainedReason } : {}),
264
+ dryRun: false
265
+ })
266
+ }
267
+
268
+ return { cleaned, skipped }
269
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@yanauto/broco",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Let your AI coding harnesses work together — Claude Code, Codex, Cursor, Antigravity, OpenCode, and Pi.",
5
+ "license": "Apache-2.0",
6
+ "author": "yanauto",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/yanauto/broco.git"
10
+ },
11
+ "keywords": [
12
+ "agent-harness",
13
+ "claude-code",
14
+ "codex",
15
+ "gemini",
16
+ "cursor",
17
+ "opencode",
18
+ "pi",
19
+ "agents-md",
20
+ "multi-agent",
21
+ "worktree",
22
+ "code-review",
23
+ "kanban"
24
+ ],
25
+ "files": [
26
+ "bin",
27
+ "lib",
28
+ "skills",
29
+ "assets",
30
+ "bundle/board",
31
+ "scripts/package-board.mjs",
32
+ "CHANGELOG.md",
33
+ "README.md",
34
+ "README.zh-CN.md",
35
+ "LICENSE"
36
+ ],
37
+ "type": "module",
38
+ "bin": {
39
+ "broco": "bin/broco"
40
+ },
41
+ "engines": {
42
+ "node": ">=24"
43
+ },
44
+ "scripts": {
45
+ "test": "node --test test/offline.test.mjs test/m1.test.mjs test/m2.test.mjs test/pi-profile.test.mjs test/plugin.test.mjs test/protocol.test.mjs test/upgrade.test.mjs test/roster.test.mjs test/models.test.mjs test/roster-output.test.mjs test/visibility.test.mjs test/tasks.test.mjs test/directories.test.mjs test/credential-proxy.test.mjs test/agy-quota.test.mjs test/adapters.test.mjs test/config-audit.test.mjs test/queue-map.test.mjs test/cli-v040.test.mjs test/r2-engine.test.mjs test/r2-roster-proj.test.mjs test/r2-web.test.mjs test/r2-cli.test.mjs test/claude-worker.test.mjs test/l0-setup.test.mjs",
46
+ "test:plugin": "node --test test/plugin.test.mjs",
47
+ "sync:models": "node scripts/sync-model-catalog.mjs",
48
+ "prepack": "node scripts/package-board.mjs",
49
+ "install:local": "sh scripts/install-local.sh"
50
+ },
51
+ "homepage": "https://broco.yanauto.me"
52
+ }
@@ -0,0 +1,53 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'node:fs'
3
+ import { join, resolve } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ const defaultRoot = fileURLToPath(new URL('../', import.meta.url))
7
+
8
+ export function newestMtime(path) {
9
+ if (!existsSync(path)) return 0
10
+ const st = statSync(path)
11
+ if (!st.isDirectory()) return st.mtimeMs
12
+ let latest = st.mtimeMs
13
+ for (const entry of readdirSync(path, { withFileTypes: true })) {
14
+ if (entry.name === 'node_modules' || entry.name === 'dist') continue
15
+ latest = Math.max(latest, newestMtime(join(path, entry.name)))
16
+ }
17
+ return latest
18
+ }
19
+
20
+ export function packageBoard({
21
+ root = defaultRoot,
22
+ build = cwd => execFileSync('npm', ['--prefix', 'ui', 'run', 'build'], { cwd, stdio: 'inherit' })
23
+ } = {}) {
24
+ const uiDir = join(root, 'ui')
25
+ const uiSrc = join(uiDir, 'src')
26
+ const source = join(uiDir, 'dist')
27
+ const distIndex = join(source, 'index.html')
28
+ const target = join(root, 'bundle', 'board')
29
+ if (existsSync(uiSrc)) {
30
+ const srcTime = Math.max(
31
+ newestMtime(uiSrc),
32
+ newestMtime(join(uiDir, 'public')),
33
+ newestMtime(join(uiDir, 'index.html')),
34
+ newestMtime(join(uiDir, 'vite.config.js'))
35
+ )
36
+ const distTime = existsSync(distIndex) ? statSync(distIndex).mtimeMs : 0
37
+ if (!distTime || srcTime > distTime) {
38
+ build(root)
39
+ }
40
+ }
41
+ if (existsSync(distIndex)) {
42
+ rmSync(target, { recursive: true, force: true })
43
+ mkdirSync(target, { recursive: true })
44
+ cpSync(source, target, { recursive: true })
45
+ } else if (!existsSync(join(target, 'index.html'))) {
46
+ throw new Error('Build the board with npm run build --prefix ui before packing broco')
47
+ }
48
+ return target
49
+ }
50
+
51
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
52
+ packageBoard()
53
+ }