dsh-git-assistant 0.0.0-stage → 0.4.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/index.js ADDED
@@ -0,0 +1,1854 @@
1
+ /**
2
+ * dsh-git-assistant — host half.
3
+ *
4
+ * Local Git workbench service for the browser panel. Runs `git` with argv arrays (never a shell string),
5
+ * pins the working directory to a registered DSH workspace / worktree, validates every path, and serves
6
+ * parsed JSON to the panel through a local same-origin API.
7
+ *
8
+ * Read: repository/worktree discovery, status, branches, unified diff, file listing, file text, raw file.
9
+ * Write: stage, unstage, discard, commit/amend, branch switch/create. All write routes require the same
10
+ * local same-origin guard as reads, and the client confirms destructive actions before calling them.
11
+ */
12
+
13
+ import { spawn } from 'node:child_process'
14
+ import { realpathSync, existsSync, lstatSync, readdirSync, readFileSync, rmSync, statSync, watch } from 'node:fs'
15
+ import { randomUUID } from 'node:crypto'
16
+ import { basename, dirname, extname, join, resolve, sep } from 'node:path'
17
+
18
+ export const name = 'dsh-git-assistant'
19
+ export const inject = ['webServer', 'workspaceRegistry', 'sessionController', 'sessionPersistence']
20
+
21
+ const PACKAGE_MANIFEST = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
22
+ const PLUGIN_VERSION = typeof PACKAGE_MANIFEST.version === 'string' ? PACKAGE_MANIFEST.version : '0.0.0'
23
+
24
+ const PREFIX = '/git-assistant/api'
25
+ const GIT_TIMEOUT_MS = 20000
26
+ const GIT_MAX_BUFFER = 8 * 1024 * 1024
27
+ const MAX_FILE_BYTES = 512 * 1024
28
+ const MAX_RAW_BYTES = 24 * 1024 * 1024
29
+ const MAX_UNTRACKED_ENTRIES = 500
30
+ const MAX_FILE_ENTRIES = 12000
31
+ const MAX_BODY_BYTES = 64 * 1024
32
+ const REPOSITORY_CACHE_MS = 2000
33
+
34
+ const GIT_ENV = (() => {
35
+ const env = {
36
+ ...process.env,
37
+ GIT_TERMINAL_PROMPT: '0',
38
+ GIT_OPTIONAL_LOCKS: '0',
39
+ GIT_PAGER: 'cat',
40
+ LC_ALL: 'C',
41
+ }
42
+ for (const key of [
43
+ 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY',
44
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_NAMESPACE', 'GIT_CEILING_DIRECTORIES',
45
+ ]) delete env[key]
46
+ return env
47
+ })()
48
+
49
+ const WORKTREES_CACHE_TTL = 30 * 1000
50
+ const worktreesCache = new Map()
51
+
52
+ function clearWorktreesCache(repoPath) {
53
+ worktreesCache.delete(repoPath)
54
+ }
55
+
56
+ const DIFF_CACHE_LIMIT = 300
57
+ const diffCache = new Map()
58
+ const headStamp = { path: undefined, at: 0, sha: '' }
59
+
60
+ function cacheGetDiff(key) {
61
+ const value = diffCache.get(key)
62
+ if (value === undefined) return undefined
63
+ diffCache.delete(key)
64
+ diffCache.set(key, value)
65
+ return value
66
+ }
67
+
68
+ function cacheSetDiff(key, value) {
69
+ if (diffCache.size >= DIFF_CACHE_LIMIT) {
70
+ const oldest = diffCache.keys().next().value
71
+ if (oldest !== undefined) diffCache.delete(oldest)
72
+ }
73
+ diffCache.set(key, value)
74
+ }
75
+
76
+ function clearDiffCache(repoPath) {
77
+ const prefix = `${repoPath}|`
78
+ for (const key of [...diffCache.keys()]) if (key.startsWith(prefix)) diffCache.delete(key)
79
+ }
80
+
81
+ async function headCommitOf(repoPath) {
82
+ const now = Date.now()
83
+ if (headStamp.path === repoPath && now - headStamp.at < 2000) return headStamp.sha
84
+ const raw = await gitOk(repoPath, ['rev-parse', 'HEAD'])
85
+ headStamp.path = repoPath
86
+ headStamp.at = now
87
+ headStamp.sha = (raw ?? '').trim()
88
+ return headStamp.sha
89
+ }
90
+
91
+ async function indexStampOf(repoPath, file) {
92
+ const raw = await gitOk(repoPath, ['ls-files', '-s', '--', file])
93
+ return (raw ?? '').trim() || 'missing'
94
+ }
95
+
96
+ const CONTENT_TYPES = {
97
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
98
+ '.webp': 'image/webp', '.svg': 'image/svg+xml', '.bmp': 'image/bmp', '.ico': 'image/x-icon',
99
+ '.pdf': 'application/pdf', '.md': 'text/markdown; charset=utf-8', '.txt': 'text/plain; charset=utf-8',
100
+ '.json': 'application/json; charset=utf-8', '.html': 'text/html; charset=utf-8',
101
+ }
102
+
103
+ /** Run git without a shell; resolve with { code, stdout, stderr, truncated }. */
104
+ function runGit(cwd, args, { timeout = GIT_TIMEOUT_MS, maxBuffer = GIT_MAX_BUFFER } = {}) {
105
+ return new Promise(done => {
106
+ let settled = false
107
+ let truncated = false
108
+ const out = []
109
+ const err = []
110
+ let size = 0
111
+ const child = spawn('git', ['-c', 'core.quotepath=false', ...args], {
112
+ cwd, env: GIT_ENV, stdio: ['ignore', 'pipe', 'pipe'],
113
+ })
114
+ const finish = result => {
115
+ if (settled) return
116
+ settled = true
117
+ clearTimeout(timer)
118
+ done(result)
119
+ }
120
+ const timer = setTimeout(() => {
121
+ truncated = true
122
+ child.kill('SIGKILL')
123
+ finish({ code: 124, stdout: Buffer.concat(out).toString('utf8'), stderr: 'git timed out', truncated: true })
124
+ }, timeout)
125
+ child.stdout.on('data', chunk => {
126
+ if (size + chunk.length > maxBuffer) {
127
+ truncated = true
128
+ child.kill('SIGKILL')
129
+ return
130
+ }
131
+ size += chunk.length
132
+ out.push(chunk)
133
+ })
134
+ child.stderr.on('data', chunk => {
135
+ if (err.length < 200) err.push(chunk)
136
+ })
137
+ child.on('error', error => finish({ code: -1, stdout: '', stderr: String(error), truncated }))
138
+ child.on('close', code => finish({
139
+ code: code ?? -1,
140
+ stdout: Buffer.concat(out).toString('utf8'),
141
+ stderr: Buffer.concat(err).toString('utf8'),
142
+ truncated,
143
+ }))
144
+ })
145
+ }
146
+
147
+ async function gitOk(cwd, args, options) {
148
+ const result = await runGit(cwd, args, options)
149
+ return result.code === 0 ? result.stdout : undefined
150
+ }
151
+
152
+ function json(res, status, body) {
153
+ res.writeHead(status, {
154
+ 'content-type': 'application/json; charset=utf-8',
155
+ 'cache-control': 'no-store',
156
+ 'x-content-type-options': 'nosniff',
157
+ })
158
+ res.end(JSON.stringify(body))
159
+ }
160
+
161
+ /** Accept only loopback, same-origin panel requests. */
162
+ function allowed(req) {
163
+ const host = req.headers.host
164
+ if (typeof host !== 'string') return false
165
+ if (!/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(host)) return false
166
+ const site = req.headers['sec-fetch-site']
167
+ if (site !== undefined && site !== 'same-origin' && site !== 'same-site') return false
168
+ return true
169
+ }
170
+
171
+ function inside(root, candidate) {
172
+ const a = resolve(root)
173
+ const b = resolve(candidate)
174
+ return b === a || b.startsWith(a + sep)
175
+ }
176
+
177
+ function safeRelativePath(file) {
178
+ return typeof file === 'string' && file.length > 0 && file.length < 4096 &&
179
+ !file.startsWith('/') && !file.split('/').includes('..') && !file.includes('\u0000')
180
+ }
181
+
182
+ function safeFileList(files) {
183
+ if (!Array.isArray(files) || files.length === 0 || files.length > 500) return undefined
184
+ if (!files.every(safeRelativePath)) return undefined
185
+ return files
186
+ }
187
+
188
+ function readJsonBody(req) {
189
+ return new Promise((resolvePromise, reject) => {
190
+ let size = 0
191
+ const chunks = []
192
+ req.on('data', chunk => {
193
+ size += chunk.length
194
+ if (size > MAX_BODY_BYTES) {
195
+ reject(new Error('request body too large'))
196
+ req.destroy()
197
+ return
198
+ }
199
+ chunks.push(chunk)
200
+ })
201
+ req.on('end', () => {
202
+ if (chunks.length === 0) { resolvePromise({}); return }
203
+ try { resolvePromise(JSON.parse(Buffer.concat(chunks).toString('utf8'))) }
204
+ catch { reject(new Error('request body is not JSON')) }
205
+ })
206
+ req.on('error', reject)
207
+ })
208
+ }
209
+
210
+ /* ── parsers ─────────────────────────────────────────────────────────── */
211
+
212
+ /** `git worktree list --porcelain` → [{ path, head, branch, detached, locked, bare }] */
213
+ function parseWorktrees(raw) {
214
+ const list = []
215
+ for (const block of raw.split('\n\n')) {
216
+ let current
217
+ for (const line of block.split('\n')) {
218
+ if (!line) continue
219
+ const index = line.indexOf(' ')
220
+ const key = index === -1 ? line : line.slice(0, index)
221
+ const value = index === -1 ? '' : line.slice(index + 1)
222
+ if (key === 'worktree') {
223
+ current = { path: value }
224
+ list.push(current)
225
+ } else if (current) {
226
+ if (key === 'HEAD') current.head = value
227
+ else if (key === 'branch') current.branch = value.replace(/^refs\/heads\//, '')
228
+ else if (key === 'bare') current.bare = true
229
+ else if (key === 'detached') current.detached = true
230
+ else if (key === 'locked') current.locked = value || true
231
+ else if (key === 'prunable') current.prunable = value || true
232
+ }
233
+ }
234
+ }
235
+ return list.filter(item => item.path)
236
+ }
237
+
238
+ /** Resolve symlinks when possible so paths from git (e.g. /private/var) compare with user paths. */
239
+ function canonicalPath(value) {
240
+ try { return realpathSync(value) } catch { return resolve(value) }
241
+ }
242
+
243
+ function unquotePath(value) {
244
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
245
+ try { return JSON.parse(value) } catch { return value.slice(1, -1) }
246
+ }
247
+ return value
248
+ }
249
+
250
+ /** `git status --porcelain=v2 --branch` → staged / unstaged / untracked + branch facts. */
251
+ function parseStatus(raw) {
252
+ const status = {
253
+ branch: undefined, detached: false, upstream: undefined, ahead: 0, behind: 0,
254
+ staged: [], unstaged: [], untracked: [], conflicted: [],
255
+ }
256
+ for (const line of raw.split('\n')) {
257
+ if (!line) continue
258
+ if (line.startsWith('# ')) {
259
+ const value = line.slice(2)
260
+ if (value.startsWith('branch.head ')) {
261
+ const head = value.slice('branch.head '.length)
262
+ if (head === '(detached)') status.detached = true
263
+ else status.branch = head
264
+ } else if (value.startsWith('branch.upstream ')) {
265
+ status.upstream = value.slice('branch.upstream '.length)
266
+ } else if (value.startsWith('branch.ab ')) {
267
+ const match = /\+(\d+) -(\d+)/.exec(value.slice('branch.ab '.length))
268
+ if (match) { status.ahead = Number(match[1]); status.behind = Number(match[2]) }
269
+ }
270
+ continue
271
+ }
272
+ const kind = line[0]
273
+ if (kind === '1') {
274
+ const parts = line.split(' ')
275
+ const xy = parts[1] ?? '..'
276
+ const path = unquotePath(parts.slice(8).join(' '))
277
+ if (xy[0] !== '.') status.staged.push({ path, status: xy[0] })
278
+ if (xy[1] !== '.') status.unstaged.push({ path, status: xy[1] })
279
+ } else if (kind === '2') {
280
+ const parts = line.split(' ')
281
+ const xy = parts[1] ?? '..'
282
+ const info = parts.slice(9).join(' ')
283
+ const [newPath, oldPath] = info.split('\t')
284
+ const path = unquotePath(newPath)
285
+ const entry = { path, status: 'R', oldPath: oldPath ? unquotePath(oldPath) : undefined }
286
+ if (xy[0] !== '.') status.staged.push(entry)
287
+ if (xy[1] !== '.') status.unstaged.push({ path, status: 'R' })
288
+ } else if (kind === 'u') {
289
+ const parts = line.split(' ')
290
+ const path = unquotePath(parts.slice(10).join(' '))
291
+ status.unstaged.push({ path, status: 'C' })
292
+ status.conflicted.push({ path })
293
+ } else if (kind === '?') {
294
+ status.untracked.push({ path: unquotePath(line.slice(2)), status: 'U' })
295
+ }
296
+ }
297
+ return status
298
+ }
299
+
300
+ /** Unified diff text → [{ path, oldPath, binary, newFile, deletedFile, additions, deletions, hunks }] */
301
+ function parseUnifiedDiff(raw) {
302
+ const files = []
303
+ let current
304
+ let hunk
305
+ for (const line of raw.split('\n')) {
306
+ if (line.startsWith('diff --git ')) {
307
+ current = { path: undefined, oldPath: undefined, binary: false, newFile: false, deletedFile: false, additions: 0, deletions: 0, hunks: [] }
308
+ files.push(current)
309
+ hunk = undefined
310
+ continue
311
+ }
312
+ if (!current) continue
313
+ if (line.startsWith('new file mode ')) { current.newFile = true; continue }
314
+ if (line.startsWith('deleted file mode ')) { current.deletedFile = true; continue }
315
+ if (line.startsWith('Binary files ') || line === 'GIT binary patch') { current.binary = true; continue }
316
+ if (line.startsWith('--- ')) {
317
+ const path = line.slice(4)
318
+ current.oldPath = path === '/dev/null' ? undefined : path.replace(/^[ab]\//, '')
319
+ continue
320
+ }
321
+ if (line.startsWith('+++ ')) {
322
+ const path = line.slice(4)
323
+ current.path = path === '/dev/null' ? current.oldPath : path.replace(/^[ab]\//, '')
324
+ continue
325
+ }
326
+ if (line.startsWith('@@')) {
327
+ const match = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/.exec(line)
328
+ if (!match) continue
329
+ hunk = {
330
+ header: line,
331
+ oldStart: Number(match[1]),
332
+ oldLines: match[2] === undefined ? 1 : Number(match[2]),
333
+ newStart: Number(match[3]),
334
+ newLines: match[4] === undefined ? 1 : Number(match[4]),
335
+ section: (match[5] ?? '').trim(),
336
+ lines: [],
337
+ }
338
+ current.hunks.push(hunk)
339
+ continue
340
+ }
341
+ if (!hunk) continue
342
+ if (line.startsWith('\\')) continue
343
+ const sign = line[0]
344
+ if (sign === ' ') hunk.lines.push({ kind: 'ctx', text: line.slice(1) })
345
+ else if (sign === '+') { hunk.lines.push({ kind: 'add', text: line.slice(1) }); current.additions += 1 }
346
+ else if (sign === '-') { hunk.lines.push({ kind: 'del', text: line.slice(1) }); current.deletions += 1 }
347
+ }
348
+ return files
349
+ }
350
+
351
+ /* ── discovery & queries ─────────────────────────────────────────────── */
352
+
353
+ let repositoryCache = { at: 0, value: undefined }
354
+
355
+ /** DSH workspaces that are Git checkouts, expanded to every linked worktree. */
356
+ async function discoverRepositories(ctx) {
357
+ const now = Date.now()
358
+ if (repositoryCache.value !== undefined && now - repositoryCache.at < REPOSITORY_CACHE_MS) return repositoryCache.value
359
+ const repositories = []
360
+ const seenRoots = new Set()
361
+ for (const workspace of ctx.workspaceRegistry.list()) {
362
+ const insideRepo = await gitOk(workspace.path, ['rev-parse', '--is-inside-work-tree'])
363
+ if (insideRepo === undefined || insideRepo.trim() !== 'true') continue
364
+ const root = (await gitOk(workspace.path, ['rev-parse', '--show-toplevel']) ?? '').trim() || workspace.path
365
+ if (seenRoots.has(root)) continue
366
+ seenRoots.add(root)
367
+ const worktrees = parseWorktrees(await gitOk(root, ['worktree', 'list', '--porcelain']) ?? '')
368
+ const entries = worktrees.length > 0 ? worktrees : [{ path: root }]
369
+ for (const worktree of entries) {
370
+ if (worktree.bare) continue
371
+ repositories.push({
372
+ id: worktree.path,
373
+ path: worktree.path,
374
+ repoRoot: root,
375
+ repoName: basename(root),
376
+ branch: worktree.branch ?? (worktree.detached && worktree.head ? worktree.head.slice(0, 8) : undefined),
377
+ isMain: resolve(worktree.path) === resolve(root),
378
+ locked: Boolean(worktree.locked),
379
+ })
380
+ }
381
+ }
382
+ repositories.sort((a, b) =>
383
+ a.repoName.localeCompare(b.repoName) ||
384
+ Number(b.isMain) - Number(a.isMain) ||
385
+ String(a.branch ?? '').localeCompare(String(b.branch ?? '')))
386
+ const value = { repositories, scannedAt: new Date().toISOString() }
387
+ repositoryCache = { at: now, value }
388
+ return value
389
+ }
390
+
391
+ /** Validate that `path` is one of the discovered checkouts (workspaces or their worktrees). */
392
+ async function knownCheckout(ctx, path) {
393
+ if (typeof path !== 'string' || path.length === 0) return undefined
394
+ const { repositories } = await discoverRepositories(ctx)
395
+ return repositories.find(repository => resolve(repository.path) === resolve(path))
396
+ }
397
+
398
+ async function statusOf(repoPath) {
399
+ // Background polling must never fight the user's own git over the index lock (git's own guidance for read-only probes).
400
+ const raw = await gitOk(repoPath, ['--no-optional-locks', 'status', '--porcelain=v2', '--branch', '--untracked-files=all', '--ignored=no'])
401
+ if (raw === undefined) throw new Error('not a git checkout')
402
+ const status = parseStatus(raw)
403
+ if (status.untracked.length > MAX_UNTRACKED_ENTRIES) {
404
+ status.untrackedOmitted = status.untracked.length - MAX_UNTRACKED_ENTRIES
405
+ status.untracked = status.untracked.slice(0, MAX_UNTRACKED_ENTRIES)
406
+ }
407
+ return status
408
+ }
409
+
410
+ /** Branches of one checkout, annotated with the worktree that holds each of them (git allows one). */
411
+ async function branchesOf(repoPath) {
412
+ const [raw, worktreeRaw] = await Promise.all([
413
+ gitOk(repoPath, ['for-each-ref', '--format=%(refname:short)%09%(HEAD)%09%(upstream:short)', 'refs/heads']),
414
+ gitOk(repoPath, ['worktree', 'list', '--porcelain']),
415
+ ])
416
+ const self = canonicalPath(repoPath)
417
+ const holders = new Map()
418
+ for (const worktree of parseWorktrees(worktreeRaw ?? '')) {
419
+ if (!worktree.branch || worktree.bare || worktree.prunable) continue
420
+ if (canonicalPath(worktree.path) === self) continue
421
+ holders.set(worktree.branch, worktree.path)
422
+ }
423
+ return (raw ?? '').split('\n').filter(Boolean).map(line => {
424
+ const [name, head, upstream] = line.split('\t')
425
+ const worktree = holders.get(name)
426
+ return {
427
+ name,
428
+ current: head === '*',
429
+ upstream: upstream || undefined,
430
+ worktree: worktree ?? null,
431
+ worktreeName: worktree ? basename(worktree) : undefined,
432
+ }
433
+ })
434
+ }
435
+
436
+ /** The path of a worktree that already has `branch` checked out, ignoring `repoPath` itself. */
437
+ async function branchHolderOf(repoPath, branch) {
438
+ const raw = await gitOk(repoPath, ['worktree', 'list', '--porcelain'])
439
+ const self = canonicalPath(repoPath)
440
+ for (const worktree of parseWorktrees(raw ?? '')) {
441
+ if (worktree.bare) continue
442
+ if (worktree.branch !== branch) continue
443
+ if (canonicalPath(worktree.path) === self) continue
444
+ return worktree.path
445
+ }
446
+ return undefined
447
+ }
448
+
449
+ function listDirectory(root, dir) {
450
+ const absolute = resolve(root, dir || '.')
451
+ if (!inside(root, absolute)) throw new Error('directory is outside the checkout')
452
+ const dirents = readdirSync(absolute, { withFileTypes: true })
453
+ const entries = []
454
+ for (const dirent of dirents) {
455
+ if (dirent.name === '.git') continue
456
+ const kind = dirent.isDirectory() ? 'dir' : dirent.isFile() ? 'file' : dirent.isSymbolicLink() ? 'link' : 'other'
457
+ entries.push({ name: dirent.name, path: dir ? `${dir}/${dirent.name}` : dirent.name, kind })
458
+ }
459
+ entries.sort((left, right) => {
460
+ if ((left.kind === 'dir') !== (right.kind === 'dir')) return left.kind === 'dir' ? -1 : 1
461
+ return left.name.localeCompare(right.name)
462
+ })
463
+ const truncated = entries.length > 2000
464
+ return { entries: truncated ? entries.slice(0, 2000) : entries, truncated }
465
+ }
466
+
467
+ async function filesOf(repoPath) {
468
+ const raw = await gitOk(repoPath, ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], { maxBuffer: 32 * 1024 * 1024 })
469
+ if (raw === undefined) throw new Error('not a git checkout')
470
+ const seen = new Set()
471
+ for (const path of raw.split('\u0000')) {
472
+ if (path) seen.add(path)
473
+ }
474
+ const files = [...seen].sort()
475
+ const truncated = files.length > MAX_FILE_ENTRIES
476
+ return { files: truncated ? files.slice(0, MAX_FILE_ENTRIES) : files, total: files.length, truncated }
477
+ }
478
+
479
+ async function commitOf(repoPath, hash) {
480
+ const metaRaw = await gitOk(repoPath, ['show', '-s', '--format=%H%x1f%an%x1f%ae%x1f%at%x1f%s%x1f%b', hash])
481
+ const [oid, author, email, timeRaw, subject, body] = (metaRaw ?? '').split('\x1f')
482
+ const parentsRaw = await gitOk(repoPath, ['rev-list', '--parents', '-n', '1', hash])
483
+ const parents = (parentsRaw ?? '').trim().split(' ').slice(1)
484
+ const numstatArgs = parents.length > 0
485
+ ? ['diff-tree', '-r', '--numstat', '--no-commit-id', '--find-renames', `${hash}^1`, hash]
486
+ : ['show', '--numstat', '--format=', '--root', '--find-renames', hash]
487
+ const nameArgs = parents.length > 0
488
+ ? ['diff-tree', '-r', '--name-status', '--no-commit-id', '--find-renames', `${hash}^1`, hash]
489
+ : ['show', '--name-status', '--format=', '--root', '--find-renames', hash]
490
+ const statRaw = await gitOk(repoPath, numstatArgs)
491
+ const nameRaw = await gitOk(repoPath, nameArgs)
492
+ const statusByPath = new Map()
493
+ for (const line of (nameRaw ?? '').split('\n')) {
494
+ if (!line.trim()) continue
495
+ const parts = line.split('\t')
496
+ const code = (parts[0] ?? '').charAt(0)
497
+ if (code === 'R' && parts[2]) statusByPath.set(parts[2], { status: 'R', oldPath: parts[1] })
498
+ else if (parts[1]) statusByPath.set(parts[1], { status: code || 'M' })
499
+ }
500
+ const files = []
501
+ let additions = 0
502
+ let deletions = 0
503
+ for (const line of (statRaw ?? '').split('\n')) {
504
+ if (!line.trim()) continue
505
+ const [addRaw, delRaw, pathRaw] = line.split('\t')
506
+ if (!pathRaw) continue
507
+ const info = statusByPath.get(pathRaw) ?? {}
508
+ const added = addRaw === '-' ? 0 : Number(addRaw)
509
+ const removed = delRaw === '-' ? 0 : Number(delRaw)
510
+ additions += added
511
+ deletions += removed
512
+ files.push({
513
+ path: pathRaw, oldPath: info.oldPath, status: info.status ?? 'M',
514
+ additions: added, deletions: removed, binary: addRaw === '-',
515
+ })
516
+ }
517
+ return {
518
+ commit: { hash: oid ?? hash, author: author ?? '', email: email ?? '', time: Number(timeRaw ?? 0), subject: subject ?? '', body: (body ?? '').trim() },
519
+ files,
520
+ stats: { files: files.length, additions, deletions },
521
+ }
522
+ }
523
+
524
+ const ISSUE_CACHE_TTL = 5 * 60 * 1000
525
+ const ISSUE_STORE_TTL = 5 * 60 * 1000
526
+ const ISSUE_STALE_AFTER = 5 * 60 * 1000
527
+ const ISSUE_POLL_MS = 2 * 60 * 1000
528
+ const ISSUE_ACCESS_TTL = 15 * 60 * 1000
529
+ const ISSUE_FULL_SYNC_MS = 30 * 60 * 1000
530
+ const issueCache = new Map()
531
+ const issueStores = new Map()
532
+
533
+ function issueCacheGet(key) {
534
+ const hit = issueCache.get(key)
535
+ if (!hit) return undefined
536
+ if (Date.now() - hit.at > ISSUE_CACHE_TTL) { issueCache.delete(key); return undefined }
537
+ return hit.value
538
+ }
539
+
540
+ function issueCacheSet(key, value) {
541
+ if (issueCache.size >= 300) {
542
+ const oldest = issueCache.keys().next().value
543
+ if (oldest !== undefined) issueCache.delete(oldest)
544
+ }
545
+ issueCache.set(key, { at: Date.now(), value })
546
+ }
547
+
548
+ function invalidateIssueEntry(repoPath, number) {
549
+ issueCache.delete(`issue|${repoPath}|${number}`)
550
+ issueCache.delete(`comments|${repoPath}|${number}`)
551
+ }
552
+
553
+ function issueFromRest(item) {
554
+ return {
555
+ number: item.number,
556
+ title: item.title ?? '',
557
+ state: String(item.state ?? '').toLowerCase(),
558
+ labels: (item.labels ?? []).map(label => ({ name: typeof label === 'string' ? label : label.name, color: typeof label === 'string' ? '' : label.color })),
559
+ assignees: (item.assignees ?? []).map(assignee => typeof assignee === 'string' ? assignee : assignee.login),
560
+ comments: item.comments ?? 0,
561
+ updatedAt: item.updated_at ?? item.updatedAt ?? '',
562
+ createdAt: item.created_at ?? item.createdAt ?? '',
563
+ url: item.html_url ?? item.url ?? '',
564
+ parent: null,
565
+ children: [],
566
+ }
567
+ }
568
+
569
+ function issueStoreOf(repoPath) {
570
+ let store = issueStores.get(repoPath)
571
+ if (!store) {
572
+ store = { repo: null, issues: new Map(), lastSyncAt: 0, fullSyncAt: 0, checkedAt: 0, syncing: null, refSignature: '', watching: false, etag: '', lastAccessAt: 0 }
573
+ issueStores.set(repoPath, store)
574
+ }
575
+ return store
576
+ }
577
+
578
+ async function issueRelationsFor(owner, name, numbers) {
579
+ const relations = new Map()
580
+ for (let offset = 0; offset < numbers.length; offset += 40) {
581
+ const chunk = numbers.slice(offset, offset + 40)
582
+ const part = await issueRelationsOf(owner, name, chunk)
583
+ for (const [number, value] of part) relations.set(number, value)
584
+ }
585
+ return relations
586
+ }
587
+
588
+ async function syncIssueStore(repoPath, { forceFull = false } = {}) {
589
+ const store = issueStoreOf(repoPath)
590
+ if (store.syncing) return store.syncing
591
+ store.syncing = (async () => {
592
+ try {
593
+ const repo = await githubRepoOf(repoPath)
594
+ store.repo = repo
595
+ const now = Date.now()
596
+ const full = forceFull || !store.fullSyncAt || now - store.fullSyncAt > ISSUE_FULL_SYNC_MS
597
+ const items = []
598
+ if (full) {
599
+ for (let page = 1; page <= 3; page += 1) {
600
+ const raw = await ghJson(['api', `repos/${repo.owner}/${repo.name}/issues?state=all&per_page=100&page=${page}`], 'gh issue sync failed')
601
+ const list = Array.isArray(raw) ? raw : []
602
+ items.push(...list.filter(item => !item.pull_request))
603
+ if (list.length < 100) break
604
+ }
605
+ } else {
606
+ const since = new Date(store.lastSyncAt - 60000).toISOString()
607
+ const raw = await ghJson(['api', `repos/${repo.owner}/${repo.name}/issues?state=all&since=${encodeURIComponent(since)}&per_page=100&sort=updated&direction=desc`], 'gh issue sync failed')
608
+ items.push(...(Array.isArray(raw) ? raw : []).filter(item => !item.pull_request))
609
+ }
610
+ const changed = []
611
+ for (const item of items) {
612
+ const issue = issueFromRest(item)
613
+ const previous = store.issues.get(issue.number)
614
+ if (!previous || previous.updatedAt !== issue.updatedAt) changed.push(issue.number)
615
+ store.issues.set(issue.number, issue)
616
+ }
617
+ if (changed.length > 0) {
618
+ const relationNumbers = full && changed.length > 40
619
+ ? changed
620
+ .map(number => store.issues.get(number))
621
+ .filter(Boolean)
622
+ .sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
623
+ .slice(0, 40)
624
+ .map(issue => issue.number)
625
+ : changed
626
+ const relations = await issueRelationsFor(repo.owner, repo.name, relationNumbers)
627
+ for (const number of changed) {
628
+ const issue = store.issues.get(number)
629
+ if (!issue) continue
630
+ const relation = relations.get(number)
631
+ issue.parent = relation?.parent ?? null
632
+ issue.children = relation?.children ?? []
633
+ if (relation?.comments !== undefined) issue.comments = relation.comments
634
+ invalidateIssueEntry(repoPath, number)
635
+ }
636
+ }
637
+ store.lastSyncAt = now
638
+ if (full) store.fullSyncAt = now
639
+ store.checkedAt = now
640
+ } finally {
641
+ store.syncing = null
642
+ }
643
+ })()
644
+ return store.syncing
645
+ }
646
+
647
+ function parseGhIncludedResponse(result) {
648
+ const text = String(result?.stdout ?? '')
649
+ const split = text.indexOf('\r\n\r\n') >= 0 ? text.indexOf('\r\n\r\n') : text.indexOf('\n\n')
650
+ const head = split >= 0 ? text.slice(0, split) : text
651
+ const body = split >= 0 ? text.slice(split + (text.includes('\r\n\r\n') ? 4 : 2)) : ''
652
+ const status = Number((/HTTP\/\S+\s+(\d{3})/.exec(head) ?? [])[1] ?? 0)
653
+ const etag = (/^etag:\s*(.+)$/im.exec(head) ?? [])[1]?.trim() ?? ''
654
+ return { status, etag, body }
655
+ }
656
+
657
+ async function pollIssueStore(repoPath) {
658
+ const store = issueStoreOf(repoPath)
659
+ if (store.syncing || !store.fullSyncAt) return
660
+ store.syncing = (async () => {
661
+ try {
662
+ const repo = store.repo ?? await githubRepoOf(repoPath)
663
+ store.repo = repo
664
+ const since = new Date(store.lastSyncAt - 60000).toISOString()
665
+ const args = ['api', '-i']
666
+ if (store.etag) args.push('-H', `If-None-Match: ${store.etag}`)
667
+ args.push(`repos/${repo.owner}/${repo.name}/issues?state=all&since=${encodeURIComponent(since)}&per_page=100&sort=updated&direction=desc`)
668
+ const result = await runProcess('gh', args)
669
+ const parsed = parseGhIncludedResponse(result)
670
+ if (parsed.status === 304) { store.checkedAt = Date.now(); return }
671
+ if (parsed.status < 200 || parsed.status >= 300) {
672
+ const message = String(result?.stderr || '').trim().split('\n')[0] || `HTTP ${parsed.status}`
673
+ throw new Error(message)
674
+ }
675
+ let items = []
676
+ try { items = JSON.parse(parsed.body) } catch { items = [] }
677
+ if (!Array.isArray(items)) items = []
678
+ items = items.filter(item => !item.pull_request)
679
+ const now = Date.now()
680
+ const changed = []
681
+ for (const item of items) {
682
+ const issue = issueFromRest(item)
683
+ const previous = store.issues.get(issue.number)
684
+ if (!previous || previous.updatedAt !== issue.updatedAt) changed.push(issue.number)
685
+ store.issues.set(issue.number, issue)
686
+ }
687
+ if (changed.length > 0) {
688
+ const relations = await issueRelationsFor(repo.owner, repo.name, changed)
689
+ for (const number of changed) {
690
+ const issue = store.issues.get(number)
691
+ if (!issue) continue
692
+ const relation = relations.get(number)
693
+ issue.parent = relation?.parent ?? null
694
+ issue.children = relation?.children ?? []
695
+ if (relation?.comments !== undefined) issue.comments = relation.comments
696
+ invalidateIssueEntry(repoPath, number)
697
+ }
698
+ }
699
+ if (parsed.etag) store.etag = parsed.etag
700
+ store.lastSyncAt = now
701
+ store.checkedAt = now
702
+ } finally {
703
+ store.syncing = null
704
+ }
705
+ })()
706
+ return store.syncing
707
+ }
708
+
709
+ let issuePoller = null
710
+
711
+ function ensureIssuePolling() {
712
+ if (issuePoller) return
713
+ issuePoller = setInterval(() => {
714
+ const now = Date.now()
715
+ for (const [repoPath, store] of issueStores) {
716
+ if (!store.lastAccessAt || now - store.lastAccessAt > ISSUE_ACCESS_TTL) continue
717
+ if (!store.fullSyncAt) continue
718
+ pollIssueStore(repoPath).catch(() => {})
719
+ }
720
+ }, ISSUE_POLL_MS)
721
+ issuePoller.unref?.()
722
+ }
723
+
724
+ function issueStoreResult(store, state, limit) {
725
+ const matching = [...store.issues.values()]
726
+ .filter(issue => state === 'all' || issue.state === state)
727
+ .sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
728
+ return {
729
+ repo: store.repo,
730
+ issues: matching.slice(0, limit),
731
+ total: matching.length,
732
+ stale: Date.now() - store.checkedAt > ISSUE_STORE_TTL,
733
+ }
734
+ }
735
+
736
+ function gitDirOf(repoPath) {
737
+ const dotGit = join(repoPath, '.git')
738
+ try {
739
+ const stat = statSync(dotGit)
740
+ if (stat.isFile()) {
741
+ const match = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, 'utf8'))
742
+ if (match) return resolve(repoPath, match[1].trim())
743
+ }
744
+ } catch { /* ignore */ }
745
+ return dotGit
746
+ }
747
+
748
+ function gitRefSignature(repoPath) {
749
+ const gitDir = gitDirOf(repoPath)
750
+ let signature = ''
751
+ const addPath = (target, depth) => {
752
+ let stat
753
+ try { stat = statSync(target) } catch { return }
754
+ if (stat.isDirectory()) {
755
+ if (depth > 4) return
756
+ let entries = []
757
+ try { entries = readdirSync(target, { withFileTypes: true }) } catch { return }
758
+ for (const entry of entries) addPath(join(target, entry.name), depth + 1)
759
+ return
760
+ }
761
+ signature += `${target}:${stat.mtimeMs}:${stat.size};`
762
+ }
763
+ addPath(join(gitDir, 'refs', 'remotes'), 0)
764
+ addPath(join(gitDir, 'packed-refs'), 0)
765
+ addPath(join(gitDir, 'FETCH_HEAD'), 0)
766
+ addPath(join(gitDir, 'logs', 'refs', 'remotes'), 0)
767
+ return signature
768
+ }
769
+
770
+ let issueWatcher = null
771
+
772
+ function ensureIssueWatcher() {
773
+ if (issueWatcher) return
774
+ issueWatcher = setInterval(() => {
775
+ for (const [repoPath, store] of issueStores) {
776
+ const signature = gitRefSignature(repoPath)
777
+ if (store.refSignature && signature !== store.refSignature) {
778
+ store.checkedAt = 0
779
+ syncIssueStore(repoPath).catch(() => {})
780
+ }
781
+ store.refSignature = signature
782
+ }
783
+ }, 8000)
784
+ issueWatcher.unref?.()
785
+ }
786
+
787
+ function streamRepoEvents(target, req, res) {
788
+ res.writeHead(200, {
789
+ 'Content-Type': 'text/event-stream; charset=utf-8',
790
+ 'Cache-Control': 'no-cache, no-transform',
791
+ Connection: 'keep-alive',
792
+ 'X-Accel-Buffering': 'no',
793
+ })
794
+ res.write('retry: 3000\n\n')
795
+ const gitDir = gitDirOf(target.path)
796
+ const watched = []
797
+ let debounceTimer = null
798
+ let closed = false
799
+ let heartbeat = null
800
+ const cleanup = () => {
801
+ if (closed) return
802
+ closed = true
803
+ if (debounceTimer) { clearTimeout(debounceTimer); debounceTimer = null }
804
+ if (heartbeat) { clearInterval(heartbeat); heartbeat = null }
805
+ for (const watcher of watched) { try { watcher.close() } catch { /* ignore */ } }
806
+ watched.length = 0
807
+ }
808
+ const send = () => {
809
+ if (closed || debounceTimer) return
810
+ debounceTimer = setTimeout(() => {
811
+ debounceTimer = null
812
+ if (closed) return
813
+ try {
814
+ res.write(`event: change\ndata: ${JSON.stringify({ path: target.path })}\n\n`)
815
+ } catch { cleanup() }
816
+ }, 180)
817
+ }
818
+ // Do not watch .git/index: `git status` can refresh it, which would echo back as a change
819
+ // event and make the client re-read status/diffs in a loop. Index changes are still picked
820
+ // up by the 5s status fallback, and staging from the UI refreshes explicitly.
821
+ const targets = [
822
+ join(gitDir, 'HEAD'), join(gitDir, 'packed-refs'),
823
+ join(gitDir, 'FETCH_HEAD'), join(gitDir, 'ORIG_HEAD'), join(gitDir, 'MERGE_HEAD'),
824
+ join(gitDir, 'refs'), join(gitDir, 'logs', 'refs'),
825
+ ]
826
+ for (const targetPath of targets) {
827
+ try {
828
+ if (!existsSync(targetPath)) continue
829
+ const isDirectory = statSync(targetPath).isDirectory()
830
+ const watcher = watch(targetPath, { recursive: isDirectory }, send)
831
+ watcher.on?.('error', () => { /* ignore watcher errors, polling remains a fallback */ })
832
+ watched.push(watcher)
833
+ } catch { /* unsupported target in this environment */ }
834
+ }
835
+ heartbeat = setInterval(() => {
836
+ if (closed) return
837
+ try { res.write(': ping\n\n') } catch { cleanup() }
838
+ }, 20000)
839
+ heartbeat.unref?.()
840
+ req.on('close', cleanup)
841
+ res.on('close', cleanup)
842
+ }
843
+
844
+ function runProcess(command, args, { timeout = 20000, maxBuffer = 8 * 1024 * 1024 } = {}) {
845
+ return new Promise(resolve => {
846
+ let stdout = ''
847
+ let stderr = ''
848
+ let child
849
+ try { child = spawn(command, args, { cwd: undefined, env: process.env }) } catch (error) { resolve({ code: 1, stdout, stderr: String(error?.message ?? error) }); return }
850
+ const timer = setTimeout(() => { try { child.kill('SIGKILL') } catch { /* ignore */ } }, timeout)
851
+ child.stdout?.on('data', chunk => { if (stdout.length < maxBuffer) stdout += chunk })
852
+ child.stderr?.on('data', chunk => { if (stderr.length < maxBuffer) stderr += chunk })
853
+ child.on('error', error => { clearTimeout(timer); resolve({ code: 1, stdout, stderr: String(error?.message ?? error) }) })
854
+ child.on('close', code => { clearTimeout(timer); resolve({ code: code ?? 1, stdout, stderr }) })
855
+ })
856
+ }
857
+
858
+ async function githubRepoOf(repoPath) {
859
+ const raw = await gitOk(repoPath, ['remote', 'get-url', 'origin'])
860
+ if (!raw) throw new Error('repository has no origin remote')
861
+ const match = raw.trim().match(/github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?$/)
862
+ if (!match) throw new Error('origin is not a GitHub repository')
863
+ return { owner: match[1], name: match[2] }
864
+ }
865
+
866
+ async function ghJson(args, errorPrefix) {
867
+ const result = await runProcess('gh', args)
868
+ if (result.code !== 0) {
869
+ const message = (result.stderr || result.stdout || '').trim().split('\n')[0] || 'gh command failed'
870
+ throw new Error(`${errorPrefix}: ${message}`)
871
+ }
872
+ try { return JSON.parse(result.stdout) } catch { throw new Error(`${errorPrefix}: invalid response`) }
873
+ }
874
+
875
+ async function issueRelationsOf(owner, name, numbers) {
876
+ const relations = new Map()
877
+ if (numbers.length === 0) return relations
878
+ const aliases = numbers.map((number, index) => `i${index}: issue(number: ${number}) { number state comments { totalCount } parent { number title state } subIssues(first: 30) { nodes { number title state } } }`).join('\n')
879
+ const query = `query { repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(name)}) { ${aliases} } }`
880
+ const result = await runProcess('gh', ['api', 'graphql', '-f', `query=${query}`])
881
+ if (result.code !== 0) return relations
882
+ try {
883
+ const data = JSON.parse(result.stdout)?.data?.repository ?? {}
884
+ for (const value of Object.values(data)) {
885
+ if (!value || typeof value.number !== 'number') continue
886
+ relations.set(value.number, {
887
+ comments: value.comments?.totalCount ?? 0,
888
+ parent: value.parent ? { number: value.parent.number, title: value.parent.title, state: value.parent.state } : null,
889
+ children: Array.isArray(value.subIssues?.nodes) ? value.subIssues.nodes.filter(Boolean).map(child => ({ number: child.number, title: child.title, state: child.state })) : [],
890
+ })
891
+ }
892
+ } catch { /* ignore */ }
893
+ return relations
894
+ }
895
+
896
+ async function issuesOf(repoPath, state, search, limit) {
897
+ const repo = await githubRepoOf(repoPath)
898
+ const args = ['issue', 'list', '--repo', `${repo.owner}/${repo.name}`, '--state', state, '--limit', String(limit), '--json', 'number,title,state,labels,assignees,comments,updatedAt,url']
899
+ if (search) args.push('--search', search)
900
+ const issues = await ghJson(args, 'gh issue list failed')
901
+ const relations = await issueRelationsOf(repo.owner, repo.name, issues.map(issue => issue.number))
902
+ return {
903
+ repo,
904
+ issues: issues.map(issue => ({
905
+ number: issue.number,
906
+ title: issue.title ?? '',
907
+ state: String(issue.state ?? '').toLowerCase(),
908
+ labels: (issue.labels ?? []).map(label => ({ name: label.name, color: label.color })),
909
+ assignees: (issue.assignees ?? []).map(assignee => assignee.login),
910
+ comments: issue.comments ?? 0,
911
+ updatedAt: issue.updatedAt ?? '',
912
+ url: issue.url ?? '',
913
+ parent: relations.get(issue.number)?.parent ?? null,
914
+ children: relations.get(issue.number)?.children ?? [],
915
+ })),
916
+ }
917
+ }
918
+
919
+ async function issueCommentsOf(repoPath, number) {
920
+ const repo = await githubRepoOf(repoPath)
921
+ const comments = await ghJson(['api', `repos/${repo.owner}/${repo.name}/issues/${number}/comments?per_page=50`], 'gh issue comments failed')
922
+ return {
923
+ comments: (Array.isArray(comments) ? comments : []).map(comment => ({
924
+ id: comment.id,
925
+ author: comment.user?.login ?? '',
926
+ body: comment.body ?? '',
927
+ createdAt: comment.created_at ?? '',
928
+ url: comment.html_url ?? '',
929
+ })),
930
+ }
931
+ }
932
+
933
+ /** Post one comment on an issue through the authenticated gh CLI (REST POST). */
934
+ async function issueCommentAdd(repoPath, number, body) {
935
+ if (typeof body !== 'string' || !body.trim()) throw new Error('comment body is empty')
936
+ const repo = await githubRepoOf(repoPath)
937
+ const result = await runProcess('gh', ['api', `repos/${repo.owner}/${repo.name}/issues/${number}/comments`, '-f', `body=${body}`], { timeout: 30000 })
938
+ if (result.code !== 0) {
939
+ throw new Error(`gh issue comment failed: ${(result.stderr || result.stdout || 'gh command failed').trim().split('\n')[0]}`)
940
+ }
941
+ }
942
+
943
+ /** Open or close one issue through the authenticated gh CLI. */
944
+ async function issueSetState(repoPath, number, state) {
945
+ if (state !== 'open' && state !== 'closed') throw new Error('invalid issue state')
946
+ const repo = await githubRepoOf(repoPath)
947
+ const result = await runProcess('gh', ['issue', state === 'closed' ? 'close' : 'reopen', String(number), '--repo', `${repo.owner}/${repo.name}`], { timeout: 30000 })
948
+ if (result.code !== 0) {
949
+ throw new Error(`gh issue ${state === 'closed' ? 'close' : 'reopen'} failed: ${(result.stderr || result.stdout || 'gh command failed').trim().split('\n')[0]}`)
950
+ }
951
+ }
952
+
953
+ /** Apply a local write to the cached board immediately: comment count and state stay honest until the next sync. */
954
+ function touchIssueStore(repoPath, number, patch) {
955
+ const store = issueStoreOf(repoPath)
956
+ const issue = store.issues.get(number)
957
+ if (!issue) return
958
+ Object.assign(issue, patch)
959
+ store.checkedAt = Date.now()
960
+ invalidateIssueEntry(repoPath, number)
961
+ }
962
+
963
+ async function issueDetailOf(repoPath, number) {
964
+ const repo = await githubRepoOf(repoPath)
965
+ const issue = await ghJson(['issue', 'view', String(number), '--repo', `${repo.owner}/${repo.name}`, '--json', 'number,title,state,body,labels,assignees,createdAt,updatedAt,url,author,milestone'], 'gh issue view failed')
966
+ const relations = await issueRelationsOf(repo.owner, repo.name, [number])
967
+ const relation = relations.get(number)
968
+ return {
969
+ repo,
970
+ issue: {
971
+ number: issue.number,
972
+ title: issue.title ?? '',
973
+ state: String(issue.state ?? '').toLowerCase(),
974
+ body: issue.body ?? '',
975
+ labels: (issue.labels ?? []).map(label => ({ name: label.name, color: label.color })),
976
+ assignees: (issue.assignees ?? []).map(assignee => assignee.login),
977
+ author: issue.author?.login ?? '',
978
+ comments: relation?.comments ?? 0,
979
+ createdAt: issue.createdAt ?? '',
980
+ updatedAt: issue.updatedAt ?? '',
981
+ url: issue.url ?? '',
982
+ milestone: issue.milestone?.title ?? null,
983
+ parent: relation?.parent ?? null,
984
+ children: relation?.children ?? [],
985
+ },
986
+ }
987
+ }
988
+
989
+ async function linesOf(repoPath, file, start, end, staged, hash) {
990
+ let content
991
+ if (hash) {
992
+ content = await gitOk(repoPath, ['show', `${hash}:${file}`])
993
+ } else if (staged) {
994
+ content = await gitOk(repoPath, ['show', `:${file}`])
995
+ } else {
996
+ const absolute = absoluteFile(repoPath, file)
997
+ const buffer = readFileSync(absolute)
998
+ if (buffer.includes(0)) throw new Error('binary file')
999
+ content = buffer.toString('utf8')
1000
+ }
1001
+ if (content === undefined) throw new Error('file not found')
1002
+ const lines = content.split('\n')
1003
+ const from = Math.max(1, Math.min(start, lines.length + 1))
1004
+ const to = Math.max(from, Math.min(end, from + 399))
1005
+ return { start: from, lines: lines.slice(from - 1, to) }
1006
+ }
1007
+
1008
+ async function localCommitsOf(repoPath, limit) {
1009
+ const raw = await gitOk(repoPath, [
1010
+ 'log', 'HEAD', '--not', '--remotes', `--max-count=${limit}`,
1011
+ '--pretty=format:%H%x1f%an%x1f%at%x1f%s',
1012
+ ])
1013
+ const commits = []
1014
+ for (const line of (raw ?? '').split('\n')) {
1015
+ if (!line.trim()) continue
1016
+ const [oid, author, timeRaw, subject] = line.split('\x1f')
1017
+ commits.push({ oid, author: author ?? '', time: Number(timeRaw ?? 0), subject: subject ?? '' })
1018
+ }
1019
+ return { commits }
1020
+ }
1021
+
1022
+ async function commitPatchOf(repoPath, hash) {
1023
+ const cacheKey = `${repoPath}|cp|${hash}`
1024
+ const cached = cacheGetDiff(cacheKey)
1025
+ if (cached !== undefined) return cached
1026
+ const meta = await commitOf(repoPath, hash)
1027
+ const parentsRaw = await gitOk(repoPath, ['rev-list', '--parents', '-n', '1', hash])
1028
+ const parents = (parentsRaw ?? '').trim().split(' ').slice(1)
1029
+ const raw = parents.length > 0
1030
+ ? await gitOk(repoPath, ['diff', '--find-renames', '--no-color', '--no-ext-diff', '--unified=3', `${hash}^1`, hash])
1031
+ : await gitOk(repoPath, ['show', '--format=', '--patch', '--root', '--find-renames', '--no-color', '--no-ext-diff', '--unified=3', hash])
1032
+ const files = parseUnifiedDiff(raw ?? '')
1033
+ const byPath = new Map(meta.files.map(file => [file.path, file]))
1034
+ for (const entry of files) {
1035
+ const info = byPath.get(entry.path)
1036
+ if (info) {
1037
+ entry.status = info.status
1038
+ entry.additions = info.additions
1039
+ entry.deletions = info.deletions
1040
+ } else if (!entry.status) {
1041
+ entry.status = entry.newFile ? 'A' : entry.deletedFile ? 'D' : 'M'
1042
+ }
1043
+ }
1044
+ const result = { commit: meta.commit, stats: meta.stats, files }
1045
+ cacheSetDiff(cacheKey, result)
1046
+ return result
1047
+ }
1048
+
1049
+ async function commitDiffOf(repoPath, hash, file) {
1050
+ const cacheKey = `${repoPath}|c|${hash}|${file}`
1051
+ const cached = cacheGetDiff(cacheKey)
1052
+ if (cached !== undefined) return cached
1053
+ const parentsRaw = await gitOk(repoPath, ['rev-list', '--parents', '-n', '1', hash])
1054
+ const parents = (parentsRaw ?? '').trim().split(' ').slice(1)
1055
+ const raw = parents.length > 0
1056
+ ? await gitOk(repoPath, ['diff', '--find-renames', `${hash}^1`, hash, '--', file])
1057
+ : await gitOk(repoPath, ['show', '--format=', '--patch', '--root', '--find-renames', hash, '--', file])
1058
+ const files = parseUnifiedDiff(raw ?? '')
1059
+ cacheSetDiff(cacheKey, files)
1060
+ return files
1061
+ }
1062
+
1063
+ async function graphOf(repoPath, limit, skip, scope) {
1064
+ const scopeArgs = scope === 'all' ? ['--all'] : []
1065
+ const raw = await gitOk(repoPath, [
1066
+ 'log', ...scopeArgs, '--topo-order',
1067
+ `--max-count=${limit}`, `--skip=${skip}`,
1068
+ '--pretty=format:%x00%H%x1f%P%x1f%an%x1f%at%x1f%s%x1f%D%x1f%b',
1069
+ ])
1070
+ const statsRaw = await gitOk(repoPath, [
1071
+ 'log', ...scopeArgs, '--topo-order',
1072
+ `--max-count=${limit}`, `--skip=${skip}`,
1073
+ '--numstat', '--format=%x00%H',
1074
+ ])
1075
+ const statsByHash = new Map()
1076
+ let currentHash = null
1077
+ for (const line of (statsRaw ?? '').split('\n')) {
1078
+ if (!line) continue
1079
+ if (line.startsWith('\x00')) {
1080
+ currentHash = line.slice(1).trim()
1081
+ statsByHash.set(currentHash, { files: 0, additions: 0, deletions: 0 })
1082
+ continue
1083
+ }
1084
+ if (!currentHash) continue
1085
+ const [addRaw, delRaw] = line.split('\t')
1086
+ if (delRaw === undefined) continue
1087
+ const entry = statsByHash.get(currentHash)
1088
+ if (!entry) continue
1089
+ entry.files += 1
1090
+ if (addRaw !== '-') entry.additions += Number(addRaw) || 0
1091
+ if (delRaw !== '-') entry.deletions += Number(delRaw) || 0
1092
+ }
1093
+ const commits = []
1094
+ for (const record of (raw ?? '').split('\x00')) {
1095
+ if (!record.trim()) continue
1096
+ const parts = record.split('\x1f')
1097
+ const [oid, parentsRaw, author, timeRaw, subject, decoration] = parts
1098
+ const bodyRaw = parts.slice(6).join('\x1f')
1099
+ const refs = (decoration ?? '').split(', ').map(part => part.replace(/^HEAD -> /, '').replace(/^tag: /, '').trim()).filter(name => name && name !== 'HEAD')
1100
+ commits.push({
1101
+ oid, parents: (parentsRaw ?? '').split(' ').filter(Boolean), author: author ?? '',
1102
+ time: Number(timeRaw ?? 0), subject: subject ?? '', body: (bodyRaw ?? '').trim().slice(0, 2000), refs,
1103
+ stats: statsByHash.get(oid) ?? { files: 0, additions: 0, deletions: 0 },
1104
+ })
1105
+ }
1106
+ return { commits, hasMore: commits.length >= limit }
1107
+ }
1108
+
1109
+ async function mapLimit(items, limit, worker) {
1110
+ const results = new Array(items.length)
1111
+ let cursor = 0
1112
+ const runners = Array.from({ length: Math.min(Math.max(1, limit), items.length) }, async () => {
1113
+ while (true) {
1114
+ const index = cursor
1115
+ cursor += 1
1116
+ if (index >= items.length) return
1117
+ results[index] = await worker(items[index], index)
1118
+ }
1119
+ })
1120
+ await Promise.all(runners)
1121
+ return results
1122
+ }
1123
+
1124
+ async function worktreesOf(repoPath) {
1125
+ const list = parseWorktrees(await gitOk(repoPath, ['worktree', 'list', '--porcelain']) ?? '')
1126
+ .filter(worktree => !worktree.bare && !worktree.prunable && existsSync(worktree.path))
1127
+ .slice(0, 40)
1128
+ const worktrees = await mapLimit(list, 8, async worktree => {
1129
+ const status = parseStatus(await gitOk(worktree.path, ['--no-optional-locks', 'status', '--porcelain=v2', '--branch', '--untracked-files=no'], { timeout: 2500 }) ?? '')
1130
+ const lastRaw = await gitOk(worktree.path, ['log', '-1', '--format=%at'], { timeout: 2500 })
1131
+ return {
1132
+ path: worktree.path,
1133
+ branch: status.branch ?? (worktree.detached ? 'detached' : undefined),
1134
+ ahead: status.ahead,
1135
+ behind: status.behind,
1136
+ changes: status.staged.length + status.unstaged.length,
1137
+ isMain: resolve(worktree.path) === resolve(repoPath),
1138
+ updatedAt: Number(lastRaw?.trim() ?? 0) || 0,
1139
+ }
1140
+ })
1141
+ worktrees.sort((left, right) => {
1142
+ if (left.isMain !== right.isMain) return left.isMain ? -1 : 1
1143
+ if ((left.changes > 0) !== (right.changes > 0)) return left.changes > 0 ? -1 : 1
1144
+ return right.updatedAt - left.updatedAt
1145
+ })
1146
+ return { worktrees }
1147
+ }
1148
+
1149
+ async function cachedWorktreesOf(repoPath) {
1150
+ const hit = worktreesCache.get(repoPath)
1151
+ if (hit) {
1152
+ if (hit.promise) return hit.promise
1153
+ if (Date.now() - hit.at < WORKTREES_CACHE_TTL) return hit.value
1154
+ }
1155
+ const promise = worktreesOf(repoPath)
1156
+ .then(value => {
1157
+ worktreesCache.set(repoPath, { at: Date.now(), value })
1158
+ return value
1159
+ })
1160
+ .catch(error => {
1161
+ worktreesCache.delete(repoPath)
1162
+ throw error
1163
+ })
1164
+ worktreesCache.set(repoPath, { at: 0, value: null, promise })
1165
+ return promise
1166
+ }
1167
+
1168
+ async function diffOf(repoPath, file, staged) {
1169
+ if (!safeRelativePath(file)) throw new Error('invalid file path')
1170
+ const absolute = resolve(repoPath, file)
1171
+ if (!inside(repoPath, absolute)) throw new Error('file is outside the checkout')
1172
+
1173
+ let cacheKey
1174
+ if (staged) {
1175
+ cacheKey = `${repoPath}|s|${file}|${await indexStampOf(repoPath, file)}`
1176
+ } else {
1177
+ let statKey = 'missing'
1178
+ try {
1179
+ const stat = statSync(absolute)
1180
+ statKey = `${stat.mtimeMs}:${stat.size}`
1181
+ } catch { /* missing file */ }
1182
+ cacheKey = `${repoPath}|w|${file}|${await headCommitOf(repoPath)}|${statKey}`
1183
+ }
1184
+ const cached = cacheGetDiff(cacheKey)
1185
+ if (cached !== undefined) return cached
1186
+
1187
+ let files
1188
+ if (staged) {
1189
+ const raw = await gitOk(repoPath, ['diff', '--cached', '--no-color', '--no-ext-diff', '--unified=3', '--', file])
1190
+ files = parseUnifiedDiff(raw ?? '')
1191
+ } else {
1192
+ const raw = await gitOk(repoPath, ['diff', '--no-color', '--no-ext-diff', '--unified=3', '--', file])
1193
+ if (raw !== undefined && raw.trim().length > 0) {
1194
+ files = parseUnifiedDiff(raw)
1195
+ } else {
1196
+ const tracked = await gitOk(repoPath, ['ls-files', '--error-unmatch', '--', file])
1197
+ if (tracked !== undefined) {
1198
+ files = []
1199
+ } else {
1200
+ const untracked = await runGit(repoPath, ['diff', '--no-color', '--no-ext-diff', '--unified=3', '--no-index', '--', '/dev/null', file])
1201
+ files = parseUnifiedDiff(untracked.stdout)
1202
+ for (const entry of files) {
1203
+ entry.path = file
1204
+ entry.newFile = true
1205
+ }
1206
+ }
1207
+ }
1208
+ }
1209
+ cacheSetDiff(cacheKey, files)
1210
+ return files
1211
+ }
1212
+
1213
+ function absoluteFile(repoPath, file) {
1214
+ if (!safeRelativePath(file)) throw new Error('invalid file path')
1215
+ const absolute = resolve(repoPath, file)
1216
+ if (!inside(repoPath, absolute)) throw new Error('file is outside the checkout')
1217
+ return absolute
1218
+ }
1219
+
1220
+ function readTextFile(repoPath, file) {
1221
+ const absolute = absoluteFile(repoPath, file)
1222
+ const stat = statSync(absolute)
1223
+ if (!stat.isFile()) throw new Error('not a file')
1224
+ const truncated = stat.size > MAX_FILE_BYTES
1225
+ const buffer = readFileSync(absolute)
1226
+ const slice = truncated ? buffer.subarray(0, MAX_FILE_BYTES) : buffer
1227
+ const binary = slice.includes(0)
1228
+ return {
1229
+ path: file,
1230
+ size: stat.size,
1231
+ truncated,
1232
+ binary,
1233
+ content: binary ? undefined : slice.toString('utf8'),
1234
+ }
1235
+ }
1236
+
1237
+ function spawnDetached(command) {
1238
+ try {
1239
+ const child = spawn(command[0], command.slice(1), { detached: true, stdio: 'ignore' })
1240
+ child.unref()
1241
+ } catch { /* best effort */ }
1242
+ }
1243
+
1244
+ /** Reveal a file or folder in the platform file manager. */
1245
+ function revealInFileManager(repoPath, file) {
1246
+ const absolute = absoluteFile(repoPath, file)
1247
+ const directory = statSync(absolute).isDirectory()
1248
+ if (process.platform === 'darwin') spawnDetached(['open', ...(directory ? [absolute] : ['-R', absolute])])
1249
+ else if (process.platform === 'win32') spawnDetached(['explorer', directory ? absolute : `/select,${absolute}`])
1250
+ else spawnDetached(['xdg-open', directory ? absolute : dirname(absolute)])
1251
+ }
1252
+
1253
+ /** Open a file or folder with the platform default application. */
1254
+ function openWithDefaultApp(repoPath, file) {
1255
+ const absolute = absoluteFile(repoPath, file)
1256
+ if (process.platform === 'darwin') spawnDetached(['open', absolute])
1257
+ else if (process.platform === 'win32') spawnDetached(['cmd', '/c', 'start', '', absolute])
1258
+ else spawnDetached(['xdg-open', absolute])
1259
+ }
1260
+
1261
+ function rawFile(repoPath, file, res, download = false) {
1262
+ const absolute = absoluteFile(repoPath, file)
1263
+ const stat = statSync(absolute)
1264
+ if (!stat.isFile()) throw new Error('not a file')
1265
+ if (stat.size > MAX_RAW_BYTES) throw new Error('file is too large to serve')
1266
+ const type = CONTENT_TYPES[extname(absolute).toLowerCase()] ?? 'application/octet-stream'
1267
+ const buffer = readFileSync(absolute)
1268
+ const headers = { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }
1269
+ if (download) headers['content-disposition'] = `attachment; filename="${basename(absolute).replace(/"/g, '')}"`
1270
+ res.writeHead(200, headers)
1271
+ res.end(buffer)
1272
+ }
1273
+
1274
+ /* ── write operations ────────────────────────────────────────────────── */
1275
+
1276
+ async function requireSuccess(repoPath, args) {
1277
+ const result = await runGit(repoPath, args)
1278
+ if (result.code !== 0) throw new Error((result.stderr || result.stdout || `git ${args[0]} failed`).trim().split('\n')[0])
1279
+ return result.stdout
1280
+ }
1281
+
1282
+ async function stageFiles(repoPath, files) {
1283
+ await requireSuccess(repoPath, ['add', '--', ...files])
1284
+ }
1285
+
1286
+ async function unstageFiles(repoPath, files) {
1287
+ const tracked = await gitOk(repoPath, ['rev-parse', '--verify', '--quiet', 'HEAD'])
1288
+ if (tracked === undefined) {
1289
+ // Unborn HEAD: remove the paths from the index instead of resetting against a missing commit.
1290
+ await requireSuccess(repoPath, ['rm', '--cached', '-r', '-q', '--', ...files])
1291
+ return
1292
+ }
1293
+ await requireSuccess(repoPath, ['reset', '-q', 'HEAD', '--', ...files])
1294
+ }
1295
+
1296
+ async function discardFiles(repoPath, files) {
1297
+ const tracked = []
1298
+ const untracked = []
1299
+ for (const file of files) {
1300
+ const result = await runGit(repoPath, ['ls-files', '--error-unmatch', '--', file])
1301
+ if (result.code === 0) tracked.push(file)
1302
+ else untracked.push(file)
1303
+ }
1304
+ if (tracked.length > 0) await requireSuccess(repoPath, ['restore', '--worktree', '--', ...tracked])
1305
+ for (const file of untracked) {
1306
+ const absolute = absoluteFile(repoPath, file)
1307
+ const info = lstatSync(absolute)
1308
+ if (!info.isFile()) throw new Error(`refusing to delete non-file ${file}`)
1309
+ rmSync(absolute, { force: true })
1310
+ }
1311
+ }
1312
+
1313
+ async function commitFiles(repoPath, message, action = 'commit') {
1314
+ const amend = action === 'amend'
1315
+ const args = ['commit']
1316
+ if (amend) args.push('--amend')
1317
+ if (message.trim().length > 0) args.push('-m', message)
1318
+ else if (amend) args.push('--no-edit')
1319
+ else throw new Error('commit message is empty')
1320
+ const output = await requireSuccess(repoPath, args)
1321
+ if (action === 'push') await requireSuccess(repoPath, ['push'])
1322
+ if (action === 'sync') {
1323
+ const pulled = await runGit(repoPath, ['pull', '--ff-only'])
1324
+ if (pulled.code !== 0) throw new Error((pulled.stderr || 'git pull failed').trim().split('\n')[0])
1325
+ await requireSuccess(repoPath, ['push'])
1326
+ }
1327
+ return { output: output.trim() }
1328
+ }
1329
+
1330
+ async function switchBranch(repoPath, branch) {
1331
+ if (typeof branch !== 'string' || branch.length === 0 || branch.startsWith('-')) throw new Error('invalid branch name')
1332
+ // A branch can only be checked out in one worktree; report the holder instead of leasing git's fatal text.
1333
+ const holder = await branchHolderOf(repoPath, branch)
1334
+ if (holder) {
1335
+ const error = new Error(`branch '${branch}' is already checked out in another worktree: ${holder}`)
1336
+ error.code = 'branch-in-worktree'
1337
+ error.worktree = holder
1338
+ throw error
1339
+ }
1340
+ await requireSuccess(repoPath, ['switch', branch])
1341
+ }
1342
+
1343
+ async function createBranch(repoPath, name, from) {
1344
+ if (typeof name !== 'string' || name.length === 0 || name.startsWith('-')) throw new Error('invalid branch name')
1345
+ const args = ['branch', name]
1346
+ if (typeof from === 'string' && from.length > 0 && !from.startsWith('-')) args.push(from)
1347
+ await requireSuccess(repoPath, args)
1348
+ }
1349
+
1350
+ /* ── stash operations ────────────────────────────────────────────────── */
1351
+
1352
+ async function stashesOf(repoPath) {
1353
+ const raw = await gitOk(repoPath, ['stash', 'list', '--format=%gd%x1f%ct%x1f%gs'])
1354
+ const stashes = []
1355
+ for (const line of (raw ?? '').split('\n')) {
1356
+ if (!line.trim()) continue
1357
+ const [selector, timeRaw, subject] = line.split('\x1f')
1358
+ const indexMatch = selector?.match(/stash@\{(\d+)\}/)
1359
+ if (!indexMatch) continue
1360
+ stashes.push({
1361
+ index: Number(indexMatch[1]),
1362
+ selector: selector.trim(),
1363
+ time: Number(timeRaw ?? 0) || 0,
1364
+ subject: (subject ?? '').trim(),
1365
+ })
1366
+ }
1367
+ return { stashes }
1368
+ }
1369
+
1370
+ async function stashPush(repoPath, message) {
1371
+ const args = ['stash', 'push', '-u']
1372
+ if (typeof message === 'string' && message.trim()) args.push('-m', message.trim())
1373
+ const result = await runGit(repoPath, args)
1374
+ if (result.code !== 0) throw new Error((result.stderr || result.stdout || 'git stash push failed').trim().split('\n')[0])
1375
+ if (/no local changes to save/i.test(result.stdout)) throw new Error('nothing to stash')
1376
+ }
1377
+
1378
+ async function stashPop(repoPath, index) {
1379
+ const safeIndex = Number.isInteger(index) && index >= 0 && index < 100 ? index : 0
1380
+ const result = await runGit(repoPath, ['stash', 'pop', `stash@{${safeIndex}}`])
1381
+ if (result.code !== 0) throw new Error((result.stderr || result.stdout || 'git stash pop failed').trim().split('\n')[0])
1382
+ }
1383
+
1384
+ /** Commit history for one file, newest first; --follow keeps renames on a single path. */
1385
+ async function fileHistoryOf(repoPath, file, limit = 40) {
1386
+ if (!safeRelativePath(file)) throw new Error('invalid file path')
1387
+ const raw = await gitOk(repoPath, ['log', '--follow', `--max-count=${limit}`, '--pretty=format:%H%x1f%an%x1f%at%x1f%s', '--', file])
1388
+ const commits = []
1389
+ for (const line of (raw ?? '').split('\n')) {
1390
+ if (!line.trim()) continue
1391
+ const [oid, author, timeRaw, subject] = line.split('\x1f')
1392
+ commits.push({ oid, author: author ?? '', time: Number(timeRaw ?? 0), subject: subject ?? '' })
1393
+ }
1394
+ return { file, commits }
1395
+ }
1396
+
1397
+ /* ── minimal chat bridge (B-route proof) ─────────────────────────────── */
1398
+
1399
+ /** Read the durable event log of one Session and reduce it to text messages. */
1400
+ async function chatHistory(ctx, sessionId, limit = 120) {
1401
+ const handle = await ctx.sessionPersistence.open(sessionId, 'read')
1402
+ let events
1403
+ try { events = (await handle.read()).events } finally { await handle.close() }
1404
+ const messages = []
1405
+ for (const event of events ?? []) {
1406
+ const type = event?.type
1407
+ const data = event?.data
1408
+ if (type === 'user/message') {
1409
+ const text = textOf(data?.content ?? data?.message?.content)
1410
+ if (text) messages.push({ role: 'user', text, seq: event.seq })
1411
+ } else if (type === 'assistant/message') {
1412
+ const text = textOf(data?.message?.content ?? data?.content)
1413
+ if (text) messages.push({ role: 'assistant', text, seq: event.seq })
1414
+ }
1415
+ }
1416
+ return messages.slice(-limit)
1417
+ }
1418
+
1419
+ function textOf(content) {
1420
+ if (!Array.isArray(content)) return ''
1421
+ return content.filter(part => part && part.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n').trim()
1422
+ }
1423
+
1424
+ async function chatSend(ctx, sessionId, text, mode) {
1425
+ if (typeof text !== 'string' || !text.trim()) throw new Error('empty message')
1426
+ await ctx.sessionController.prompt({
1427
+ requestId: randomUUID(), sessionId, mode: mode === 'steer' ? 'steer' : 'queue',
1428
+ content: [{ type: 'text', text: text.trim() }],
1429
+ clientTimeZone: 'Asia/Taipei',
1430
+ })
1431
+ }
1432
+
1433
+ async function syncWorktree(repoPath) {
1434
+ const output = await requireSuccess(repoPath, ['pull', '--ff-only'])
1435
+ return { output: output.trim() }
1436
+ }
1437
+
1438
+ async function chatNew(ctx, cwd) {
1439
+ const value = await ctx.sessionController.create({ cwd })
1440
+ return value.sessionId
1441
+ }
1442
+
1443
+ /* ── plugin entry ────────────────────────────────────────────────────── */
1444
+
1445
+ let toolSyncTimer = null
1446
+
1447
+ function markIssueStoresForSync() {
1448
+ if (issueStores.size === 0) return
1449
+ for (const store of issueStores.values()) store.checkedAt = 0
1450
+ if (toolSyncTimer) return
1451
+ toolSyncTimer = setTimeout(() => {
1452
+ toolSyncTimer = null
1453
+ for (const repoPath of issueStores.keys()) syncIssueStore(repoPath).catch(() => {})
1454
+ }, 5000)
1455
+ toolSyncTimer.unref?.()
1456
+ }
1457
+
1458
+ function watchToolEvents(ctx) {
1459
+ if (typeof ctx.on !== 'function') return
1460
+ const handler = event => {
1461
+ try {
1462
+ const data = event?.data ?? event
1463
+ const args = data?.arguments ?? data?.args ?? data?.input ?? ''
1464
+ const raw = typeof args === 'string' ? args : JSON.stringify(args)
1465
+ if (!/git\s+push|gh\s+(issue|pr)\b/.test(raw)) return
1466
+ markIssueStoresForSync()
1467
+ } catch { /* ignore malformed tool events */ }
1468
+ }
1469
+ ctx.on('tool/call', handler)
1470
+ ctx.on('tool/result', handler)
1471
+ }
1472
+
1473
+ export function apply(ctx) {
1474
+ watchToolEvents(ctx)
1475
+ ctx.effect(() => ctx.webServer.register({
1476
+ kind: 'prefix',
1477
+ path: PREFIX,
1478
+ handler: async (req, res) => {
1479
+ if (!allowed(req)) {
1480
+ json(res, 403, { error: 'the git-assistant API serves local same-origin requests only' })
1481
+ return
1482
+ }
1483
+ const url = new URL(req.url ?? '/', 'http://localhost')
1484
+ const route = url.pathname.slice(PREFIX.length).replace(/\/+$/, '') || '/'
1485
+ try {
1486
+ if (req.method === 'GET' && route === '/events') {
1487
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1488
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1489
+ streamRepoEvents(target, req, res)
1490
+ return
1491
+ }
1492
+ if (req.method === 'GET' && route === '/ping') {
1493
+ json(res, 200, { ok: true, version: PLUGIN_VERSION })
1494
+ return
1495
+ }
1496
+ if (req.method === 'GET' && route === '/repositories') {
1497
+ json(res, 200, await discoverRepositories(ctx))
1498
+ return
1499
+ }
1500
+
1501
+ if (req.method === 'GET' && route === '/issues/touch') {
1502
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1503
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1504
+ const store = issueStoreOf(target.path)
1505
+ store.lastAccessAt = Date.now()
1506
+ ensureIssueWatcher()
1507
+ ensureIssuePolling()
1508
+ json(res, 200, { ok: true })
1509
+ return
1510
+ }
1511
+ if (req.method === 'GET' && route === '/issues') {
1512
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1513
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1514
+ const state = ['open', 'closed', 'all'].includes(url.searchParams.get('state')) ? url.searchParams.get('state') : 'open'
1515
+ const search = (url.searchParams.get('search') ?? '').trim()
1516
+ const limit = Math.max(1, Math.min(300, Number(url.searchParams.get('limit')) || 50))
1517
+ const force = url.searchParams.get('refresh') === '1'
1518
+ const full = url.searchParams.get('full') === '1'
1519
+ try {
1520
+ if (search) {
1521
+ const cacheKey = `issues|${target.path}|${state}|${search}|${limit}`
1522
+ const cached = force ? undefined : issueCacheGet(cacheKey)
1523
+ if (cached !== undefined) { json(res, 200, cached); return }
1524
+ const result = await issuesOf(target.path, state, search, limit)
1525
+ result.total = (result.issues ?? []).length
1526
+ issueCacheSet(cacheKey, result)
1527
+ json(res, 200, result)
1528
+ return
1529
+ }
1530
+ ensureIssueWatcher()
1531
+ ensureIssuePolling()
1532
+ const store = issueStoreOf(target.path)
1533
+ store.lastAccessAt = Date.now()
1534
+ if (!force && store.issues.size > 0) {
1535
+ const payload = issueStoreResult(store, state, limit)
1536
+ const stale = !store.checkedAt || Date.now() - store.checkedAt > ISSUE_STALE_AFTER
1537
+ if (stale) {
1538
+ payload.stale = true
1539
+ syncIssueStore(target.path).catch(() => {})
1540
+ }
1541
+ json(res, 200, payload)
1542
+ return
1543
+ }
1544
+ await syncIssueStore(target.path, { forceFull: full || store.issues.size === 0 })
1545
+ json(res, 200, issueStoreResult(store, state, limit))
1546
+ } catch (error) { json(res, 400, { error: String(error?.message ?? error) }) }
1547
+ return
1548
+ }
1549
+ if (req.method === 'GET' && route === '/issue') {
1550
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1551
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1552
+ const number = Number(url.searchParams.get('number'))
1553
+ if (!Number.isInteger(number) || number <= 0) { json(res, 400, { error: 'invalid issue number' }); return }
1554
+ const cacheKey = `issue|${target.path}|${number}`
1555
+ const force = url.searchParams.get('refresh') === '1'
1556
+ const cached = force ? undefined : issueCacheGet(cacheKey)
1557
+ if (cached !== undefined) { json(res, 200, cached); return }
1558
+ try {
1559
+ const result = await issueDetailOf(target.path, number)
1560
+ issueCacheSet(cacheKey, result)
1561
+ json(res, 200, result)
1562
+ }
1563
+ catch (error) { json(res, 400, { error: String(error?.message ?? error) }) }
1564
+ return
1565
+ }
1566
+ if (req.method === 'GET' && route === '/issue-comments') {
1567
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1568
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1569
+ const number = Number(url.searchParams.get('number'))
1570
+ if (!Number.isInteger(number) || number <= 0) { json(res, 400, { error: 'invalid issue number' }); return }
1571
+ const cacheKey = `comments|${target.path}|${number}`
1572
+ const force = url.searchParams.get('refresh') === '1'
1573
+ const cached = force ? undefined : issueCacheGet(cacheKey)
1574
+ if (cached !== undefined) { json(res, 200, cached); return }
1575
+ try {
1576
+ const result = await issueCommentsOf(target.path, number)
1577
+ issueCacheSet(cacheKey, result)
1578
+ json(res, 200, result)
1579
+ }
1580
+ catch (error) { json(res, 400, { error: String(error?.message ?? error) }) }
1581
+ return
1582
+ }
1583
+ if (req.method === 'GET' && route === '/lines') {
1584
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1585
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1586
+ const file = url.searchParams.get('file')
1587
+ if (!file) { json(res, 400, { error: 'missing file' }); return }
1588
+ const start = Math.max(1, Number(url.searchParams.get('start')) || 1)
1589
+ const end = Math.max(start, Number(url.searchParams.get('end')) || start + 199)
1590
+ const staged = url.searchParams.get('staged') === '1'
1591
+ const hash = url.searchParams.get('hash') ?? ''
1592
+ try {
1593
+ json(res, 200, await linesOf(target.path, file, start, end, staged, hash))
1594
+ } catch (error) {
1595
+ json(res, 400, { error: String(error?.message ?? error) })
1596
+ }
1597
+ return
1598
+ }
1599
+ if (req.method === 'GET' && route === '/local-commits') {
1600
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1601
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1602
+ const limit = Math.max(1, Math.min(200, Number(url.searchParams.get('limit')) || 80))
1603
+ json(res, 200, await localCommitsOf(target.path, limit))
1604
+ return
1605
+ }
1606
+ if (req.method === 'GET' && route === '/stashes') {
1607
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1608
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1609
+ json(res, 200, await stashesOf(target.path))
1610
+ return
1611
+ }
1612
+ if (req.method === 'GET' && route === '/file-log') {
1613
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1614
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1615
+ const file = url.searchParams.get('file')
1616
+ if (!file) { json(res, 400, { error: 'missing file' }); return }
1617
+ const limit = Math.max(1, Math.min(100, Number(url.searchParams.get('limit')) || 40))
1618
+ try {
1619
+ json(res, 200, await fileHistoryOf(target.path, file, limit))
1620
+ } catch (error) {
1621
+ json(res, 400, { error: String(error?.message ?? error) })
1622
+ }
1623
+ return
1624
+ }
1625
+ if (req.method === 'GET' && route === '/commit-patch') {
1626
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1627
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1628
+ const hash = url.searchParams.get('hash')
1629
+ if (!hash || !/^[0-9a-f]{4,64}$/i.test(hash)) { json(res, 400, { error: 'invalid hash' }); return }
1630
+ json(res, 200, await commitPatchOf(target.path, hash))
1631
+ return
1632
+ }
1633
+ if (req.method === 'GET' && route === '/commit') {
1634
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1635
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1636
+ const hash = url.searchParams.get('hash')
1637
+ if (!hash || !/^[0-9a-f]{4,64}$/i.test(hash)) { json(res, 400, { error: 'invalid hash' }); return }
1638
+ json(res, 200, await commitOf(target.path, hash))
1639
+ return
1640
+ }
1641
+ if (req.method === 'GET' && route === '/commit-diff') {
1642
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1643
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1644
+ const hash = url.searchParams.get('hash')
1645
+ const file = url.searchParams.get('file')
1646
+ if (!hash || !/^[0-9a-f]{4,64}$/i.test(hash) || !file) { json(res, 400, { error: 'invalid commit diff request' }); return }
1647
+ json(res, 200, { file, hash, files: await commitDiffOf(target.path, hash, file) })
1648
+ return
1649
+ }
1650
+ if (req.method === 'GET' && route === '/fs/list') {
1651
+ const target = await knownCheckout(ctx, url.searchParams.get('path'))
1652
+ if (!target) { json(res, 400, { error: 'unknown checkout' }); return }
1653
+ json(res, 200, listDirectory(target.path, url.searchParams.get('dir') ?? ''))
1654
+ return
1655
+ }
1656
+ if (req.method === 'GET' && route === '/graph') {
1657
+ const path = url.searchParams.get('path')
1658
+ const checkout = await knownCheckout(ctx, path)
1659
+ if (!checkout) { json(res, 400, { error: 'unknown checkout' }); return }
1660
+ const limit = Math.max(20, Math.min(400, Number(url.searchParams.get('limit')) || 150))
1661
+ const skip = Math.max(0, Number(url.searchParams.get('skip')) || 0)
1662
+ const scope = url.searchParams.get('scope') === 'all' ? 'all' : 'branch'
1663
+ json(res, 200, await graphOf(checkout.path, limit, skip, scope))
1664
+ return
1665
+ }
1666
+ if (req.method === 'GET' && route === '/worktrees') {
1667
+ const path = url.searchParams.get('path')
1668
+ const checkout = await knownCheckout(ctx, path)
1669
+ if (!checkout) { json(res, 400, { error: 'unknown checkout' }); return }
1670
+ json(res, 200, await cachedWorktreesOf(checkout.path))
1671
+ return
1672
+ }
1673
+ if (req.method === 'GET' && route === '/chat/history') {
1674
+ const sessionId = url.searchParams.get('sessionId')
1675
+ if (!sessionId) { json(res, 400, { error: 'missing sessionId' }); return }
1676
+ json(res, 200, { messages: await chatHistory(ctx, sessionId) })
1677
+ return
1678
+ }
1679
+ if (req.method === 'GET' && ['/status', '/branches', '/diff', '/file', '/files', '/raw'].includes(route)) {
1680
+ const path = url.searchParams.get('path')
1681
+ const checkout = await knownCheckout(ctx, path)
1682
+ if (!checkout) { json(res, 400, { error: 'unknown checkout' }); return }
1683
+ if (route === '/status') { json(res, 200, await statusOf(checkout.path)); return }
1684
+ if (route === '/branches') { json(res, 200, { branches: await branchesOf(checkout.path) }); return }
1685
+ if (route === '/files') { json(res, 200, await filesOf(checkout.path)); return }
1686
+ const file = url.searchParams.get('file')
1687
+ if (!file) { json(res, 400, { error: 'missing file' }); return }
1688
+ if (route === '/diff') {
1689
+ const staged = url.searchParams.get('staged') === '1'
1690
+ json(res, 200, { file, staged, files: await diffOf(checkout.path, file, staged) })
1691
+ return
1692
+ }
1693
+ if (route === '/raw') { rawFile(checkout.path, file, res, url.searchParams.get('download') === '1'); return }
1694
+ json(res, 200, readTextFile(checkout.path, file))
1695
+ return
1696
+ }
1697
+
1698
+ if (req.method === 'POST') {
1699
+ const body = await readJsonBody(req)
1700
+ const checkout = await knownCheckout(ctx, body?.path)
1701
+ if (!checkout) { json(res, 400, { error: 'unknown checkout' }); return }
1702
+ if (route === '/reveal') {
1703
+ if (!body.file) { json(res, 400, { error: 'missing file' }); return }
1704
+ revealInFileManager(checkout.path, body.file)
1705
+ json(res, 200, { ok: true })
1706
+ return
1707
+ }
1708
+ if (route === '/open') {
1709
+ if (!body.file) { json(res, 400, { error: 'missing file' }); return }
1710
+ openWithDefaultApp(checkout.path, body.file)
1711
+ json(res, 200, { ok: true })
1712
+ return
1713
+ }
1714
+ if (route === '/sync') {
1715
+ await syncWorktree(checkout.path)
1716
+ clearDiffCache(checkout.path)
1717
+ clearWorktreesCache(checkout.path)
1718
+ json(res, 200, { ok: true })
1719
+ return
1720
+ }
1721
+ if (route === '/chat/send') {
1722
+ await chatSend(ctx, body.sessionId, body.text, body.mode)
1723
+ json(res, 200, { ok: true })
1724
+ return
1725
+ }
1726
+ if (route === '/chat/new') {
1727
+ const sessionId = await chatNew(ctx, body.path)
1728
+ json(res, 200, { ok: true, sessionId })
1729
+ return
1730
+ }
1731
+ if (route === '/stage') {
1732
+ const files = safeFileList(body.files)
1733
+ if (!files) { json(res, 400, { error: 'invalid file list' }); return }
1734
+ await stageFiles(checkout.path, files)
1735
+ clearDiffCache(checkout.path)
1736
+ json(res, 200, { ok: true })
1737
+ return
1738
+ }
1739
+ if (route === '/unstage') {
1740
+ const files = safeFileList(body.files)
1741
+ if (!files) { json(res, 400, { error: 'invalid file list' }); return }
1742
+ await unstageFiles(checkout.path, files)
1743
+ clearDiffCache(checkout.path)
1744
+ json(res, 200, { ok: true })
1745
+ return
1746
+ }
1747
+ if (route === '/discard') {
1748
+ const files = safeFileList(body.files)
1749
+ if (!files) { json(res, 400, { error: 'invalid file list' }); return }
1750
+ await discardFiles(checkout.path, files)
1751
+ clearDiffCache(checkout.path)
1752
+ json(res, 200, { ok: true })
1753
+ return
1754
+ }
1755
+ if (route === '/commit') {
1756
+ const message = typeof body.message === 'string' ? body.message : ''
1757
+ const action = typeof body.action === 'string' ? body.action : (body.amend ? 'amend' : 'commit')
1758
+ const result = await commitFiles(checkout.path, message, action)
1759
+ clearDiffCache(checkout.path)
1760
+ clearWorktreesCache(checkout.path)
1761
+ json(res, 200, { ok: true, ...result })
1762
+ return
1763
+ }
1764
+ if (route === '/stash-push') {
1765
+ await stashPush(checkout.path, body.message)
1766
+ clearDiffCache(checkout.path)
1767
+ clearWorktreesCache(checkout.path)
1768
+ json(res, 200, { ok: true, stashes: (await stashesOf(checkout.path)).stashes })
1769
+ return
1770
+ }
1771
+ if (route === '/stash-pop') {
1772
+ await stashPop(checkout.path, body.index)
1773
+ clearDiffCache(checkout.path)
1774
+ clearWorktreesCache(checkout.path)
1775
+ json(res, 200, { ok: true, stashes: (await stashesOf(checkout.path)).stashes })
1776
+ return
1777
+ }
1778
+ if (route === '/issue-comment') {
1779
+ const number = Number(body.number)
1780
+ if (!Number.isInteger(number) || number <= 0) { json(res, 400, { error: 'invalid issue number' }); return }
1781
+ const text = typeof body.body === 'string' ? body.body : ''
1782
+ if (!text.trim() || text.length > 65000) { json(res, 400, { error: 'invalid comment body' }); return }
1783
+ try {
1784
+ await issueCommentAdd(checkout.path, number, text.trim())
1785
+ touchIssueStore(checkout.path, number, {
1786
+ comments: (issueStoreOf(checkout.path).issues.get(number)?.comments ?? 0) + 1,
1787
+ updatedAt: new Date().toISOString(),
1788
+ })
1789
+ json(res, 200, { ok: true })
1790
+ } catch (error) {
1791
+ json(res, 400, { error: String(error?.message ?? error) })
1792
+ }
1793
+ return
1794
+ }
1795
+ if (route === '/issue-state') {
1796
+ const number = Number(body.number)
1797
+ if (!Number.isInteger(number) || number <= 0) { json(res, 400, { error: 'invalid issue number' }); return }
1798
+ const state = body.state === 'open' || body.state === 'closed' ? body.state : null
1799
+ if (!state) { json(res, 400, { error: 'invalid issue state' }); return }
1800
+ try {
1801
+ await issueSetState(checkout.path, number, state)
1802
+ touchIssueStore(checkout.path, number, { state, updatedAt: new Date().toISOString() })
1803
+ json(res, 200, { ok: true, state })
1804
+ } catch (error) {
1805
+ json(res, 400, { error: String(error?.message ?? error) })
1806
+ }
1807
+ return
1808
+ }
1809
+ if (route === '/switch') {
1810
+ try {
1811
+ await switchBranch(checkout.path, body.branch)
1812
+ } catch (error) {
1813
+ json(res, error?.code === 'branch-in-worktree' ? 409 : 400, {
1814
+ error: error instanceof Error ? error.message : String(error),
1815
+ code: error?.code,
1816
+ worktree: error?.worktree,
1817
+ })
1818
+ return
1819
+ }
1820
+ clearDiffCache(checkout.path)
1821
+ clearWorktreesCache(checkout.path)
1822
+ json(res, 200, { ok: true })
1823
+ return
1824
+ }
1825
+ if (route === '/branch/create') {
1826
+ await createBranch(checkout.path, body.name, body.from)
1827
+ clearDiffCache(checkout.path)
1828
+ clearWorktreesCache(checkout.path)
1829
+ json(res, 200, { ok: true })
1830
+ return
1831
+ }
1832
+ json(res, 404, { error: `unknown route ${route}` })
1833
+ return
1834
+ }
1835
+
1836
+ json(res, 404, { error: `unknown route ${req.method ?? 'GET'} ${route}` })
1837
+ } catch (error) {
1838
+ ctx.logger.warn('dsh-git-assistant: %s', error instanceof Error ? error.stack ?? error.message : error)
1839
+ json(res, 500, { error: error instanceof Error ? error.message : String(error) })
1840
+ }
1841
+ },
1842
+ }), 'dsh-git-assistant: git API')
1843
+ }
1844
+
1845
+ /** Exposed for local parser checks only; not part of the plugin surface. */
1846
+ export const internals = {
1847
+ parseWorktrees, parseStatus, parseUnifiedDiff, safeRelativePath, safeFileList,
1848
+ filesOf: (repoPath) => filesOf(repoPath),
1849
+ diffOf: (repoPath, file, staged) => diffOf(repoPath, file, staged),
1850
+ clearDiffCache, diffCacheSize: () => diffCache.size,
1851
+ stageFiles, unstageFiles, discardFiles, commitFiles, switchBranch, createBranch,
1852
+ stashesOf, stashPush, stashPop, fileHistoryOf, issueCommentAdd, issueSetState, touchIssueStore,
1853
+ branchesOf, branchHolderOf,
1854
+ }