dsh-taskboard 0.2.1 → 0.3.3

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.
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Host git face (0.3.0): the ONLY place dsh-taskboard shells out to git.
3
+ * 0.3.1: per-repo serialization of structural operations, binary probing,
4
+ * no-op merge detection, worktree REUSE mode, and evidence size caps.
5
+ *
6
+ * Design invariants (plan §3.4/§3.5):
7
+ * - NARROW interface: detect / binaryAvailable / prepareWorktree / collect /
8
+ * merge / isAncestor / removeWorktree / deleteBranch — nothing else leaks
9
+ * into the plugin.
10
+ * - FAIL-SOFT: every call has a timeout and resolves to a benign result
11
+ * (false / undefined / empty facts) on ANY git failure — a missing git,
12
+ * a locked worktree, or a damaged repo degrades execution to the original
13
+ * directory and NEVER fails the ledger or the run pipeline. Only the
14
+ * explicit user actions (merge / remove / deleteBranch) throw, with a
15
+ * readable message the GUI surfaces as-is.
16
+ * - SERIALIZED structural ops: concurrent isolated executions on the SAME
17
+ * repository would race on git's index/worktree locks, so every structural
18
+ * operation (prepareWorktree / merge / removeWorktree / deleteBranch) runs
19
+ * inside a per-root in-process mutex. Read-only collects stay concurrent.
20
+ * - INJECTABLE runner: the exec layer is a single function so unit tests
21
+ * script every path without a real git.
22
+ *
23
+ * @module dsh-taskboard/host/git
24
+ */
25
+ import type { CommitInfo } from '../shared/protocol.ts'
26
+
27
+ /** Timeout for quick read-only queries (rev-parse / status / log / diff). */
28
+ const QUICK_TIMEOUT_MS = 2_000
29
+
30
+ /** Timeout for structural operations (worktree add/remove, merge, branch). */
31
+ const HEAVY_TIMEOUT_MS = 15_000
32
+
33
+ /** Directory under a workspace where task worktrees live. */
34
+ export const WORKTREE_DIR = '.dsh-worktrees'
35
+
36
+ /** Evidence caps: commits kept per execution record (newest first). */
37
+ export const MAX_COMMIT_EVIDENCE = 50
38
+
39
+ /** Evidence caps: uncommitted-change lines kept per execution record. */
40
+ export const MAX_DIRTY_EVIDENCE = 100
41
+
42
+ /** Result of one underlying exec: `ok` is exit-0, output never null. */
43
+ export interface ExecResult { ok: boolean; stdout: string; stderr: string }
44
+
45
+ /** The injectable exec layer: run `git <args>` under a cwd with a timeout. */
46
+ export type ExecFn = (args: string[], options: { cwd?: string; timeout?: number }) => Promise<ExecResult>
47
+
48
+ /** Facts needed to open an isolated execution. */
49
+ export interface WorktreeInfo {
50
+ /** Absolute worktree path (the session's cwd). */
51
+ path: string
52
+ /** The task branch checked out there. */
53
+ branch: string
54
+ /** Baseline for evidence collection: main HEAD (fresh) or worktree HEAD (reuse). */
55
+ baseCommit: string
56
+ /** True when an existing live worktree was kept as-is (续跑). */
57
+ reused?: boolean
58
+ }
59
+
60
+ /** Settlement facts collected from a worktree (partial on best-effort basis). */
61
+ export interface SettlementFacts {
62
+ headCommit?: string
63
+ commits: CommitInfo[]
64
+ /** Total commits before capping (equals commits.length when under the cap). */
65
+ commitsTotal: number
66
+ dirtyFiles: string[]
67
+ /** Total uncommitted lines before capping. */
68
+ dirtyFilesTotal: number
69
+ diffStat?: string
70
+ changedFiles: number
71
+ }
72
+
73
+ /** The narrow git face the rest of the plugin depends on. */
74
+ export interface GitFace {
75
+ /** Whether `root` sits inside a usable git work tree (fail-soft → false). */
76
+ detect(root: string): Promise<boolean>
77
+ /** Whether a usable git binary answers at all (distinguishes 未装 git vs 非 git 仓库). */
78
+ binaryAvailable(): Promise<boolean>
79
+ /**
80
+ * Ensure a worktree at `path` on `branch`. Default mode `'fresh'` resets to
81
+ * the main worktree's current HEAD (每次全新); mode `'reuse'` keeps a live
82
+ * worktree exactly as-is (续跑 — agent's commits and uncommitted changes
83
+ * survive) and falls back to a fresh creation when none is alive. Resolves
84
+ * undefined on any failure — callers degrade to the original directory.
85
+ */
86
+ prepareWorktree(root: string, path: string, branch: string, mode?: 'fresh' | 'reuse'): Promise<WorktreeInfo | undefined>
87
+ /** Collect settlement facts (never throws; missing pieces stay unset). */
88
+ collect(worktreePath: string, baseCommit: string): Promise<SettlementFacts>
89
+ /** Merge `branch` into the main worktree (`--no-ff`); THROWS with a readable reason. */
90
+ merge(root: string, branch: string): Promise<void>
91
+ /** Whether `branch` is already an ancestor of HEAD (a merge would be a no-op). */
92
+ isAncestor(root: string, branch: string): Promise<boolean>
93
+ /** Remove a worktree; THROWS when it still has uncommitted changes. */
94
+ removeWorktree(root: string, worktreePath: string): Promise<void>
95
+ /** Delete a branch; THROWS (e.g. still checked out in a worktree). */
96
+ deleteBranch(root: string, branch: string): Promise<void>
97
+ }
98
+
99
+ /**
100
+ * Build the task branch name `task/<标题>+<taskId>` (plan §9 拍板).
101
+ *
102
+ * Title sanitizing: whitespace runs collapse to `-`; git-illegal characters
103
+ * (`~ ^ : ? * [ \ / @ { }` and friends) are stripped; `..` collapses; the
104
+ * segment is trimmed of leading/trailing `.-` and truncated to ~20 code
105
+ * points; an empty result falls back to the bare `task/<taskId>`.
106
+ * @param title - the task title (already normalized 1..200 chars).
107
+ * @param taskId - the task id (stable suffix).
108
+ * @returns the branch name.
109
+ */
110
+ export function sanitizeBranchName(title: string, taskId: string): string {
111
+ const segment = title.trim()
112
+ .replace(/\s+/g, '-')
113
+ .replace(/[/\\~^:?*[\]@{}"'<>|#%&;$!`'=,;()]+/g, '')
114
+ .replace(/\.\.+/g, '.')
115
+ .replace(/^[-.\s]+|[-.\s]+$/g, '')
116
+ const head = Array.from(segment).slice(0, 20).join('').replace(/^[-.]+|[-.]+$/g, '')
117
+ return head.length === 0 ? `task/${taskId}` : `task/${head}+${taskId}`
118
+ }
119
+
120
+ /** The canonical worktree path of a task inside its workspace (forward slashes). */
121
+ export function worktreePathOf(workspacePath: string, taskId: string): string {
122
+ const root = workspacePath.replace(/[\\/]+$/, '').replaceAll('\\', '/')
123
+ return `${root}/${WORKTREE_DIR}/${taskId}`
124
+ }
125
+
126
+ /** Real exec layer over child_process.execFile (windowsHide, timeout, maxBuffer). */
127
+ const realExec: ExecFn = (args, options) => new Promise(resolve => {
128
+ void (async () => {
129
+ const { execFile } = await import('node:child_process')
130
+ execFile('git', args, {
131
+ cwd: options.cwd,
132
+ timeout: options.timeout ?? QUICK_TIMEOUT_MS,
133
+ windowsHide: true,
134
+ maxBuffer: 4 * 1024 * 1024,
135
+ encoding: 'utf8',
136
+ }, (error, stdout, stderr) => {
137
+ resolve({ ok: error === null, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })
138
+ })
139
+ })().catch(() => resolve({ ok: false, stdout: '', stderr: 'exec unavailable' }))
140
+ })
141
+
142
+ /**
143
+ * Build a {@link GitFace} over an injectable exec layer.
144
+ * @param exec - the exec function (real `git` when omitted).
145
+ */
146
+ export function createGitFace(exec: ExecFn = realExec): GitFace {
147
+ const quick = (args: string[], cwd?: string): Promise<ExecResult> => exec(args, { cwd, timeout: QUICK_TIMEOUT_MS })
148
+ const heavy = (args: string[], cwd?: string): Promise<ExecResult> => exec(args, { cwd, timeout: HEAVY_TIMEOUT_MS })
149
+
150
+ // Per-root mutex (0.3.1): structural git ops on the SAME repository run one
151
+ // at a time — concurrent isolated executions must not race on git's locks.
152
+ const locks = new Map<string, Promise<unknown>>()
153
+ const withRootLock = <T>(root: string, fn: () => Promise<T>): Promise<T> => {
154
+ const prev = locks.get(root) ?? Promise.resolve()
155
+ const next = prev.then(fn, fn)
156
+ locks.set(root, next.catch(() => { /* the chain never blocks later ops */ }))
157
+ return next
158
+ }
159
+
160
+ return {
161
+ async detect(root) {
162
+ const r = await quick(['rev-parse', '--is-inside-work-tree'], root)
163
+ return r.ok && r.stdout.trim() === 'true'
164
+ },
165
+
166
+ async binaryAvailable() {
167
+ const r = await quick(['--version'])
168
+ return r.ok && r.stdout.startsWith('git version')
169
+ },
170
+
171
+ prepareWorktree: (root, path, branch, mode = 'fresh') => withRootLock(root, async () => {
172
+ // 续跑: a live worktree at the path is kept EXACTLY as-is — the agent's
173
+ // commits and uncommitted changes survive; the baseline becomes the
174
+ // worktree's own HEAD so evidence covers only the new run.
175
+ if (mode === 'reuse') {
176
+ const wtHead = await quick(['rev-parse', 'HEAD'], path)
177
+ if (wtHead.ok && wtHead.stdout.trim().length > 0) {
178
+ return { path, branch, baseCommit: wtHead.stdout.trim(), reused: true }
179
+ }
180
+ // No live worktree → fall through to a fresh preparation.
181
+ }
182
+
183
+ // Baseline: the main worktree's current HEAD (also validates the repo).
184
+ const head = await quick(['rev-parse', 'HEAD'], root)
185
+ if (!head.ok) return undefined
186
+ const baseCommit = head.stdout.trim()
187
+
188
+ const exists = await quick(['show-ref', '--verify', `refs/heads/${branch}`], root)
189
+ if (exists.ok) {
190
+ // Reuse the fixed branch name, but guarantee a FRESH baseline: drop
191
+ // any stale worktree at the path, move the branch to the current
192
+ // HEAD, then check the branch out again (每次全新,复用仅作选项保留).
193
+ await heavy(['worktree', 'remove', '--force', path], root)
194
+ await heavy(['worktree', 'prune'], root)
195
+ const moved = await heavy(['branch', '-f', branch, 'HEAD'], root)
196
+ if (!moved.ok) return undefined
197
+ const added = await heavy(['worktree', 'add', path, branch], root)
198
+ if (!added.ok) return undefined
199
+ } else {
200
+ const added = await heavy(['worktree', 'add', '-b', branch, path], root)
201
+ if (!added.ok) return undefined
202
+ }
203
+ return { path, branch, baseCommit }
204
+ }),
205
+
206
+ async collect(worktreePath, baseCommit) {
207
+ const facts: SettlementFacts = { commits: [], commitsTotal: 0, dirtyFiles: [], dirtyFilesTotal: 0, changedFiles: 0 }
208
+ const range = `${baseCommit}..HEAD`
209
+
210
+ const head = await quick(['rev-parse', 'HEAD'], worktreePath)
211
+ if (head.ok) facts.headCommit = head.stdout.trim()
212
+
213
+ const log = await quick(['log', '--pretty=format:%h %s', range], worktreePath)
214
+ if (log.ok) {
215
+ const commits = log.stdout.split('\n')
216
+ .map(line => line.trim())
217
+ .filter(line => line.length > 0)
218
+ .map(line => {
219
+ const space = line.indexOf(' ')
220
+ return space === -1
221
+ ? { hash: line, subject: '' }
222
+ : { hash: line.slice(0, space), subject: line.slice(space + 1) }
223
+ })
224
+ // Evidence caps (0.3.1): the ledger is rewritten whole on every
225
+ // mutation — cap what a huge branch/status dump can add to it.
226
+ facts.commitsTotal = commits.length
227
+ facts.commits = commits.slice(0, MAX_COMMIT_EVIDENCE)
228
+ }
229
+
230
+ const status = await quick(['status', '--porcelain'], worktreePath)
231
+ if (status.ok) {
232
+ const dirty = status.stdout.split('\n').map(l => l.trim()).filter(l => l.length > 0)
233
+ facts.dirtyFilesTotal = dirty.length
234
+ facts.dirtyFiles = dirty.slice(0, MAX_DIRTY_EVIDENCE)
235
+ }
236
+
237
+ const shortstat = await quick(['diff', '--shortstat', range], worktreePath)
238
+ if (shortstat.ok && shortstat.stdout.trim().length > 0) facts.diffStat = shortstat.stdout.trim()
239
+
240
+ const names = await quick(['diff', '--name-only', range], worktreePath)
241
+ if (names.ok) facts.changedFiles = names.stdout.split('\n').filter(l => l.trim().length > 0).length
242
+
243
+ return facts
244
+ },
245
+
246
+ merge: (root, branch) => withRootLock(root, async () => {
247
+ // Main-clean check. The plugin's own worktree directory
248
+ // (<root>/.dsh-worktrees) shows up as untracked noise and is EXEMPT —
249
+ // otherwise merging would be impossible without gitignoring it first.
250
+ const status = await quick(['status', '--porcelain'], root)
251
+ if (status.ok) {
252
+ const dirtyLines = status.stdout.split('\n')
253
+ .map(l => l.trim())
254
+ .filter(l => {
255
+ if (l.length === 0) return false
256
+ const path = l.slice(3)
257
+ return path !== WORKTREE_DIR && !path.startsWith(`${WORKTREE_DIR}/`)
258
+ })
259
+ if (dirtyLines.length > 0) {
260
+ throw new Error(`主工作区有 ${dirtyLines.length} 处未提交修改,请先提交或暂存后再合并`)
261
+ }
262
+ }
263
+ const merged = await heavy(['merge', '--no-ff', '--no-edit', branch], root)
264
+ if (!merged.ok) {
265
+ // Roll the half-finished merge back so the main worktree stays usable;
266
+ // report the ORIGINAL failure verbatim (不自动解决冲突).
267
+ await heavy(['merge', '--abort'], root)
268
+ throw new Error(`合并失败:${merged.stderr.trim().slice(0, 300)}`)
269
+ }
270
+ }),
271
+
272
+ async isAncestor(root, branch) {
273
+ // exit 0 = branch is an ancestor of (or equal to) HEAD → merge no-op.
274
+ const r = await quick(['merge-base', '--is-ancestor', branch, 'HEAD'], root)
275
+ return r.ok
276
+ },
277
+
278
+ removeWorktree: (root, worktreePath) => withRootLock(root, async () => {
279
+ const status = await quick(['status', '--porcelain'], worktreePath)
280
+ if (status.ok && status.stdout.trim().length > 0) {
281
+ const lines = status.stdout.split('\n').map(l => l.trim()).filter(l => l.length > 0)
282
+ throw new Error(`worktree 有 ${lines.length} 处未提交修改,拒绝删除:\n${lines.slice(0, 10).join('\n')}`)
283
+ }
284
+ const removed = await heavy(['worktree', 'remove', worktreePath], root)
285
+ if (!removed.ok) throw new Error(`删除 worktree 失败:${(removed.stderr.trim() || removed.stdout.trim()).slice(0, 300)}`)
286
+ }),
287
+
288
+ deleteBranch: (root, branch) => withRootLock(root, async () => {
289
+ const deleted = await heavy(['branch', '-D', branch], root)
290
+ if (!deleted.ok) throw new Error(`删除分支失败:${deleted.stderr.trim().slice(0, 300)}`)
291
+ }),
292
+ }
293
+ }