dsh-git-bugfix 0.0.0-stage → 0.1.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/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.en.md +152 -0
- package/README.md +162 -2
- package/client.js +2681 -0
- package/cordis.patch.yml +6 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +62 -0
- package/icon.svg +28 -0
- package/index.js +278 -0
- package/lib/fixer.js +2184 -0
- package/lib/git.js +728 -0
- package/lib/skills.js +173 -0
- package/lib/state.js +681 -0
- package/lib/xlsx.js +526 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +69 -4
package/lib/state.js
ADDED
|
@@ -0,0 +1,681 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-repository defect-fix state for the bug fixer.
|
|
3
|
+
*
|
|
4
|
+
* The state lives in `<repo>/.dsh-git-bugfix/state.json`, hidden from `git status`
|
|
5
|
+
* through the repository's local exclude file, so an imported defect list and
|
|
6
|
+
* every fix result survive a page reload and a DSH restart without touching a
|
|
7
|
+
* tracked file or a remote. Worktrees stay under `<repo>/.dsh-git-bugfix/worktrees/`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
|
|
13
|
+
import { ensureLocalExclude, listLocalBranches, listWorktrees, resolveRepo } from './git.js'
|
|
14
|
+
import { scanRepoSkills } from './skills.js'
|
|
15
|
+
|
|
16
|
+
/** Current persisted schema version. */
|
|
17
|
+
const STATE_VERSION = 1
|
|
18
|
+
|
|
19
|
+
/** Directory the plugin owns inside a repository. */
|
|
20
|
+
export const STATE_DIR = '.dsh-git-bugfix'
|
|
21
|
+
|
|
22
|
+
/** Default per-repository settings. */
|
|
23
|
+
const DEFAULT_COMMIT_TEMPLATE = 'fix(bug-{id}): {title}'
|
|
24
|
+
const DEFAULT_SETTINGS = {
|
|
25
|
+
parallel: 1,
|
|
26
|
+
verify: false,
|
|
27
|
+
skillPath: '',
|
|
28
|
+
baseBranch: '',
|
|
29
|
+
commitTemplate: '',
|
|
30
|
+
autoApply: true,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Placeholders a commit-message template may use. */
|
|
34
|
+
export const COMMIT_TEMPLATE_PLACEHOLDERS = ['id', 'title', 'summary', 'severity', 'state', 'link', 'date']
|
|
35
|
+
|
|
36
|
+
/** The built-in commit template used when the user leaves the field empty. */
|
|
37
|
+
export const DEFAULT_COMMIT_MESSAGE_TEMPLATE = DEFAULT_COMMIT_TEMPLATE
|
|
38
|
+
|
|
39
|
+
/** Defect fix lifecycle: what the UI draws for one defect block. */
|
|
40
|
+
export const FIX_STATUSES = new Set([
|
|
41
|
+
'idle', 'preparing', 'running', 'question', 'done', 'applied', 'merged',
|
|
42
|
+
'conflict', 'pending', 'failed', 'stopped', 'discarded',
|
|
43
|
+
])
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Clamp the requested parallel fix count.
|
|
47
|
+
* @param {unknown} value - user-supplied number.
|
|
48
|
+
* @returns {number} an integer between 1 and 8.
|
|
49
|
+
*/
|
|
50
|
+
export function clampParallel(value) {
|
|
51
|
+
const number = Number(value)
|
|
52
|
+
if (!Number.isFinite(number)) return 1
|
|
53
|
+
return Math.min(8, Math.max(1, Math.floor(number)))
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Render a commit message template for one defect.
|
|
58
|
+
* @param {string} template - user template with `{placeholder}` tokens.
|
|
59
|
+
* @param {object} bug - the defect.
|
|
60
|
+
* @param {string} [summary] - AI fix summary.
|
|
61
|
+
* @returns {string} the rendered message.
|
|
62
|
+
*/
|
|
63
|
+
export function renderCommitMessage(template, bug, summary = '') {
|
|
64
|
+
const today = new Date()
|
|
65
|
+
const pad = value => String(value).padStart(2, '0')
|
|
66
|
+
const values = {
|
|
67
|
+
id: bug.id !== '' ? bug.id : bug.key,
|
|
68
|
+
title: bug.title,
|
|
69
|
+
summary: summary === '' ? (bug.title === '' ? bug.key : bug.title) : summary,
|
|
70
|
+
severity: bug.severity,
|
|
71
|
+
state: bug.state,
|
|
72
|
+
link: bug.url,
|
|
73
|
+
date: `${today.getFullYear()}-${pad(today.getMonth() + 1)}-${pad(today.getDate())}`,
|
|
74
|
+
}
|
|
75
|
+
let message = template
|
|
76
|
+
for (const [name, value] of Object.entries(values)) {
|
|
77
|
+
message = message.split(`{${name}}`).join(String(value ?? ''))
|
|
78
|
+
}
|
|
79
|
+
return message
|
|
80
|
+
.replace(/[ \t]+\n/g, '\n')
|
|
81
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
82
|
+
.trim()
|
|
83
|
+
.slice(0, 4000)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Read the template actually used for commits: the configured one, or the
|
|
88
|
+
* built-in git-flow default when the field is empty.
|
|
89
|
+
* @param {Record<string, unknown>} settings - repository settings.
|
|
90
|
+
* @returns {string} the effective template.
|
|
91
|
+
*/
|
|
92
|
+
export function effectiveCommitTemplate(settings) {
|
|
93
|
+
const configured = typeof settings?.commitTemplate === 'string' ? settings.commitTemplate.trim() : ''
|
|
94
|
+
return configured === '' ? DEFAULT_COMMIT_TEMPLATE : configured
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Read the settings that must be present before a fix may start.
|
|
99
|
+
* @param {Record<string, unknown>} settings - repository settings.
|
|
100
|
+
* @param {string[]} branchNames - currently existing local branch names.
|
|
101
|
+
* @returns {{ complete: boolean, missing: string[] }} readiness facts.
|
|
102
|
+
*/
|
|
103
|
+
export function settingsReadiness(settings, branchNames) {
|
|
104
|
+
const missing = []
|
|
105
|
+
const baseBranch = typeof settings?.baseBranch === 'string' ? settings.baseBranch : ''
|
|
106
|
+
if (baseBranch === '' || !branchNames.includes(baseBranch)) missing.push('baseBranch')
|
|
107
|
+
return { complete: missing.length === 0, missing }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Read a defect's numeric sequence when the export has one.
|
|
112
|
+
* @param {object} bug - defect fields.
|
|
113
|
+
* @returns {number | null} the numeric sequence, or null.
|
|
114
|
+
*/
|
|
115
|
+
function defectNumericId(bug) {
|
|
116
|
+
const id = String(bug?.id ?? '').trim()
|
|
117
|
+
return /^\d+$/.test(id) ? Number(id) : null
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Order imported defects: numeric sequences ascending first, then source rows.
|
|
122
|
+
* @param {object} left - first defect.
|
|
123
|
+
* @param {object} right - second defect.
|
|
124
|
+
* @returns {number} sort order.
|
|
125
|
+
*/
|
|
126
|
+
export function compareDefectOrder(left, right) {
|
|
127
|
+
const leftId = defectNumericId(left)
|
|
128
|
+
const rightId = defectNumericId(right)
|
|
129
|
+
if (leftId !== null && rightId !== null) return leftId - rightId || (left.row ?? 0) - (right.row ?? 0)
|
|
130
|
+
if (leftId !== null) return -1
|
|
131
|
+
if (rightId !== null) return 1
|
|
132
|
+
return (left.row ?? 0) - (right.row ?? 0)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Create a fresh fix record for one imported defect.
|
|
137
|
+
* @param {object} defect - parsed defect fields from `lib/xlsx.js`.
|
|
138
|
+
* @returns {object} the defect plus its initial fix facts.
|
|
139
|
+
*/
|
|
140
|
+
function initialFix(defect) {
|
|
141
|
+
return {
|
|
142
|
+
...defect,
|
|
143
|
+
fix: {
|
|
144
|
+
status: 'idle',
|
|
145
|
+
summary: '',
|
|
146
|
+
detail: '',
|
|
147
|
+
verification: '',
|
|
148
|
+
verificationVerdict: 'none',
|
|
149
|
+
files: [],
|
|
150
|
+
branch: '',
|
|
151
|
+
worktree: '',
|
|
152
|
+
baseBranch: '',
|
|
153
|
+
baseSha: '',
|
|
154
|
+
commitSha: '',
|
|
155
|
+
appliedCommitSha: '',
|
|
156
|
+
appliedWithoutCommit: false,
|
|
157
|
+
childSessionId: '',
|
|
158
|
+
childName: '',
|
|
159
|
+
error: '',
|
|
160
|
+
startedAt: 0,
|
|
161
|
+
endedAt: 0,
|
|
162
|
+
pausedAt: 0,
|
|
163
|
+
appliedAt: 0,
|
|
164
|
+
mergedAt: 0,
|
|
165
|
+
discardedAt: 0,
|
|
166
|
+
appliedBy: '',
|
|
167
|
+
attempt: 0,
|
|
168
|
+
guidance: [],
|
|
169
|
+
attachments: [],
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Rebuild a bug's fix record from persisted JSON, tolerating older or partial data.
|
|
176
|
+
* @param {object} stored - persisted bug entry.
|
|
177
|
+
* @returns {object} normalized bug entry.
|
|
178
|
+
*/
|
|
179
|
+
function normalizeBug(stored) {
|
|
180
|
+
const base = initialFix({
|
|
181
|
+
key: String(stored?.key ?? ''),
|
|
182
|
+
row: Number(stored?.row) || 0,
|
|
183
|
+
id: String(stored?.id ?? ''),
|
|
184
|
+
title: String(stored?.title ?? ''),
|
|
185
|
+
analysis: String(stored?.analysis ?? ''),
|
|
186
|
+
severity: String(stored?.severity ?? ''),
|
|
187
|
+
state: String(stored?.state ?? ''),
|
|
188
|
+
tags: String(stored?.tags ?? ''),
|
|
189
|
+
note: String(stored?.note ?? ''),
|
|
190
|
+
url: String(stored?.url ?? ''),
|
|
191
|
+
plan: String(stored?.plan ?? ''),
|
|
192
|
+
creator: String(stored?.creator ?? ''),
|
|
193
|
+
fixer: String(stored?.fixer ?? ''),
|
|
194
|
+
registeredAt: String(stored?.registeredAt ?? ''),
|
|
195
|
+
requirement: String(stored?.requirement ?? ''),
|
|
196
|
+
reopenCount: String(stored?.reopenCount ?? ''),
|
|
197
|
+
standardStatus: String(stored?.standardStatus ?? ''),
|
|
198
|
+
standardOwner: String(stored?.standardOwner ?? ''),
|
|
199
|
+
platform: String(stored?.platform ?? ''),
|
|
200
|
+
version: String(stored?.version ?? ''),
|
|
201
|
+
})
|
|
202
|
+
const fix = stored?.fix ?? {}
|
|
203
|
+
const status = FIX_STATUSES.has(fix.status) ? fix.status : 'idle'
|
|
204
|
+
return {
|
|
205
|
+
...base,
|
|
206
|
+
fix: {
|
|
207
|
+
...base.fix,
|
|
208
|
+
status,
|
|
209
|
+
summary: String(fix.summary ?? ''),
|
|
210
|
+
detail: String(fix.detail ?? ''),
|
|
211
|
+
verification: String(fix.verification ?? ''),
|
|
212
|
+
verificationVerdict: fix.verificationVerdict === 'pass' || fix.verificationVerdict === 'fail'
|
|
213
|
+
? fix.verificationVerdict
|
|
214
|
+
: 'none',
|
|
215
|
+
files: Array.isArray(fix.files)
|
|
216
|
+
? fix.files
|
|
217
|
+
.filter(file => file !== null && typeof file === 'object' && typeof file.path === 'string')
|
|
218
|
+
.map(file => ({
|
|
219
|
+
path: file.path,
|
|
220
|
+
display: String(file.display ?? file.path),
|
|
221
|
+
added: Number(file.added) || 0,
|
|
222
|
+
deleted: Number(file.deleted) || 0,
|
|
223
|
+
binary: file.binary === true,
|
|
224
|
+
untracked: file.untracked === true,
|
|
225
|
+
}))
|
|
226
|
+
: [],
|
|
227
|
+
branch: String(fix.branch ?? ''),
|
|
228
|
+
worktree: String(fix.worktree ?? ''),
|
|
229
|
+
baseBranch: String(fix.baseBranch ?? ''),
|
|
230
|
+
baseSha: String(fix.baseSha ?? ''),
|
|
231
|
+
commitSha: String(fix.commitSha ?? ''),
|
|
232
|
+
appliedCommitSha: String(fix.appliedCommitSha ?? ''),
|
|
233
|
+
appliedWithoutCommit: fix.appliedWithoutCommit === true,
|
|
234
|
+
childSessionId: String(fix.childSessionId ?? ''),
|
|
235
|
+
childName: String(fix.childName ?? ''),
|
|
236
|
+
error: String(fix.error ?? ''),
|
|
237
|
+
startedAt: Number(fix.startedAt) || 0,
|
|
238
|
+
endedAt: Number(fix.endedAt) || 0,
|
|
239
|
+
pausedAt: Number(fix.pausedAt) || 0,
|
|
240
|
+
appliedAt: Number(fix.appliedAt) || 0,
|
|
241
|
+
mergedAt: Number(fix.mergedAt) || 0,
|
|
242
|
+
discardedAt: Number(fix.discardedAt) || 0,
|
|
243
|
+
appliedBy: fix.appliedBy === 'auto' ? 'auto' : (fix.appliedBy === 'manual' ? 'manual' : ''),
|
|
244
|
+
attempt: Number(fix.attempt) || 0,
|
|
245
|
+
guidance: Array.isArray(fix.guidance)
|
|
246
|
+
? fix.guidance
|
|
247
|
+
.filter(item => item !== null && typeof item === 'object' && typeof item.text === 'string')
|
|
248
|
+
.map(item => ({ at: Number(item.at) || 0, text: String(item.text).slice(0, 4000) }))
|
|
249
|
+
.slice(-20)
|
|
250
|
+
: [],
|
|
251
|
+
attachments: Array.isArray(fix.attachments)
|
|
252
|
+
? fix.attachments
|
|
253
|
+
.filter(item => item !== null && typeof item === 'object' && typeof item.path === 'string')
|
|
254
|
+
.map(item => ({
|
|
255
|
+
name: String(item.name ?? 'image'),
|
|
256
|
+
path: item.path,
|
|
257
|
+
mime: String(item.mime ?? 'image/png'),
|
|
258
|
+
}))
|
|
259
|
+
.slice(0, 4)
|
|
260
|
+
: [],
|
|
261
|
+
},
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Build the client-facing snapshot of one repository record.
|
|
267
|
+
* @param {object} record - the in-memory record.
|
|
268
|
+
* @returns {object} JSON-safe snapshot.
|
|
269
|
+
*/
|
|
270
|
+
export function snapshot(record) {
|
|
271
|
+
const counts = {
|
|
272
|
+
idle: 0, preparing: 0, running: 0, question: 0, done: 0, applied: 0, merged: 0,
|
|
273
|
+
conflict: 0, pending: 0, failed: 0, stopped: 0, discarded: 0,
|
|
274
|
+
}
|
|
275
|
+
for (const bug of record.bugs) counts[bug.fix.status] = (counts[bug.fix.status] ?? 0) + 1
|
|
276
|
+
const appliedCount = record.bugs.filter(bug => bug.fix.status === 'applied' || bug.fix.status === 'merged').length
|
|
277
|
+
const branchNames = (record.branches ?? []).map(branch => branch.name)
|
|
278
|
+
const allBranchNames = Array.isArray(record.allBranchNames) ? record.allBranchNames : branchNames
|
|
279
|
+
const readiness = settingsReadiness(record.settings, branchNames)
|
|
280
|
+
const template = effectiveCommitTemplate(record.settings)
|
|
281
|
+
const sample = record.bugs.find(bug => bug.fix.status === 'idle') ?? record.bugs[0]
|
|
282
|
+
const commitPreview = sample === undefined
|
|
283
|
+
? renderCommitMessage(template, { key: 'bug-123', id: '123', title: '修改某某问题', severity: '', state: '', url: '' }, '')
|
|
284
|
+
: renderCommitMessage(template, sample, sample.fix.summary)
|
|
285
|
+
return {
|
|
286
|
+
ok: true,
|
|
287
|
+
repo: {
|
|
288
|
+
isGit: true,
|
|
289
|
+
root: record.root,
|
|
290
|
+
branch: record.branch,
|
|
291
|
+
detached: record.detached,
|
|
292
|
+
headShort: record.headShort,
|
|
293
|
+
stateDir: path.join(record.root, STATE_DIR),
|
|
294
|
+
},
|
|
295
|
+
settings: {
|
|
296
|
+
parallel: record.settings.parallel,
|
|
297
|
+
verify: record.settings.verify,
|
|
298
|
+
skillPath: record.settings.skillPath,
|
|
299
|
+
baseBranch: record.settings.baseBranch,
|
|
300
|
+
commitTemplate: record.settings.commitTemplate,
|
|
301
|
+
autoApply: record.settings.autoApply,
|
|
302
|
+
},
|
|
303
|
+
settingsComplete: readiness.complete,
|
|
304
|
+
settingsMissing: readiness.missing,
|
|
305
|
+
commitPreview,
|
|
306
|
+
defaultCommitTemplate: DEFAULT_COMMIT_TEMPLATE,
|
|
307
|
+
branches: record.branches ?? [],
|
|
308
|
+
skills: record.skills.map(skill => ({
|
|
309
|
+
name: skill.name,
|
|
310
|
+
description: skill.description,
|
|
311
|
+
path: skill.path,
|
|
312
|
+
source: skill.source,
|
|
313
|
+
score: skill.score,
|
|
314
|
+
selected: skill.path === record.settings.skillPath,
|
|
315
|
+
})),
|
|
316
|
+
integration: record.integration === null || record.integration === undefined
|
|
317
|
+
? null
|
|
318
|
+
: {
|
|
319
|
+
...record.integration,
|
|
320
|
+
appliedCount,
|
|
321
|
+
activeBranchExists: allBranchNames.includes(record.integration.branch),
|
|
322
|
+
},
|
|
323
|
+
batch: {
|
|
324
|
+
running: record.batch.running === true,
|
|
325
|
+
aborted: record.batch.aborted === true,
|
|
326
|
+
activeKeys: [...record.runtime.active.keys()],
|
|
327
|
+
total: record.batch.total ?? 0,
|
|
328
|
+
done: record.batch.done ?? 0,
|
|
329
|
+
startedAt: record.batch.startedAt ?? 0,
|
|
330
|
+
finishedAt: record.batch.finishedAt ?? 0,
|
|
331
|
+
},
|
|
332
|
+
merge: record.merge ?? null,
|
|
333
|
+
model: record.model ?? null,
|
|
334
|
+
counts,
|
|
335
|
+
bugs: record.bugs,
|
|
336
|
+
updatedAt: record.updatedAt ?? 0,
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* The in-process store of repository records plus their durable state file.
|
|
342
|
+
*/
|
|
343
|
+
export class RepoStore {
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* @param {object} options - dependencies.
|
|
347
|
+
* @param {object} options.ctx - Host Cordis context.
|
|
348
|
+
* @param {object} [options.logger] - optional logger (ctx.logger).
|
|
349
|
+
*/
|
|
350
|
+
constructor({ ctx, logger }) {
|
|
351
|
+
/** @type {Map<string, object>} root to record. */
|
|
352
|
+
this.records = new Map()
|
|
353
|
+
this.ctx = ctx
|
|
354
|
+
this.logger = logger
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Resolve the repository record for a session directory, loading it once.
|
|
359
|
+
* @param {string} cwd - directory to resolve from (Session working directory).
|
|
360
|
+
* @param {AbortSignal} [signal] - caller cancellation.
|
|
361
|
+
* @returns {Promise<{ record: object } | { error: string, cwd: string }>} the record or a failure.
|
|
362
|
+
*/
|
|
363
|
+
async ensure(cwd, signal) {
|
|
364
|
+
const repo = await resolveRepo(cwd, signal)
|
|
365
|
+
if (repo === null) return { error: 'not-git-repository', cwd: path.resolve(cwd) }
|
|
366
|
+
const cached = this.records.get(repo.root)
|
|
367
|
+
if (cached !== undefined) {
|
|
368
|
+
cached.branch = repo.branch
|
|
369
|
+
cached.detached = repo.detached
|
|
370
|
+
cached.head = repo.head
|
|
371
|
+
cached.headShort = repo.headShort
|
|
372
|
+
return { record: cached }
|
|
373
|
+
}
|
|
374
|
+
await ensureLocalExclude(repo)
|
|
375
|
+
const record = await this.load(repo)
|
|
376
|
+
this.records.set(repo.root, record)
|
|
377
|
+
return { record }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Load (or initialize) one repository record and reconcile it with git.
|
|
382
|
+
* @param {{ root: string, gitDir: string, branch: string, detached: boolean, head: string, headShort: string }} repo - repository facts.
|
|
383
|
+
* @returns {Promise<object>} the record.
|
|
384
|
+
*/
|
|
385
|
+
async load(repo) {
|
|
386
|
+
const statePath = path.join(repo.root, STATE_DIR, 'state.json')
|
|
387
|
+
let stored = undefined
|
|
388
|
+
try {
|
|
389
|
+
const text = await readFile(statePath, 'utf8')
|
|
390
|
+
if (text.length < 32 * 1024 * 1024) stored = JSON.parse(text)
|
|
391
|
+
} catch {
|
|
392
|
+
stored = undefined
|
|
393
|
+
}
|
|
394
|
+
const settings = {
|
|
395
|
+
parallel: clampParallel(stored?.settings?.parallel ?? DEFAULT_SETTINGS.parallel),
|
|
396
|
+
verify: stored?.settings?.verify === true,
|
|
397
|
+
skillPath: typeof stored?.settings?.skillPath === 'string' ? stored.settings.skillPath : '',
|
|
398
|
+
baseBranch: typeof stored?.settings?.baseBranch === 'string' ? stored.settings.baseBranch : DEFAULT_SETTINGS.baseBranch,
|
|
399
|
+
commitTemplate: typeof stored?.settings?.commitTemplate === 'string' ? stored.settings.commitTemplate : '',
|
|
400
|
+
autoApply: stored?.settings?.autoApply !== false,
|
|
401
|
+
}
|
|
402
|
+
const bugs = Array.isArray(stored?.bugs)
|
|
403
|
+
? stored.bugs.filter(bug => bug !== null && typeof bug === 'object' && typeof bug.key === 'string').map(normalizeBug)
|
|
404
|
+
: []
|
|
405
|
+
for (const bug of bugs) {
|
|
406
|
+
if (bug.fix.status === 'running' || bug.fix.status === 'preparing') {
|
|
407
|
+
bug.fix.status = 'failed'
|
|
408
|
+
bug.fix.error = '进程中断(DSH 已重启或页面重新打开),可重新修复'
|
|
409
|
+
bug.fix.endedAt = bug.fix.endedAt || Date.now()
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
const skills = await scanRepoSkills(repo.root)
|
|
413
|
+
const skillExists = skills.some(skill => skill.path === settings.skillPath)
|
|
414
|
+
if (!skillExists) {
|
|
415
|
+
const preferred = skills.find(skill => skill.score > 0) ?? skills[0]
|
|
416
|
+
settings.skillPath = preferred?.path ?? ''
|
|
417
|
+
}
|
|
418
|
+
const storedMerge = stored?.merge !== null && typeof stored?.merge === 'object'
|
|
419
|
+
&& typeof stored.merge?.key === 'string'
|
|
420
|
+
&& typeof stored.merge?.dir === 'string'
|
|
421
|
+
? {
|
|
422
|
+
kind: stored.merge.kind === 'integration-merge' ? 'integration-merge' : 'fix-apply',
|
|
423
|
+
key: stored.merge.key,
|
|
424
|
+
dir: stored.merge.dir,
|
|
425
|
+
files: Array.isArray(stored.merge.files) ? stored.merge.files.filter(file => typeof file === 'string') : [],
|
|
426
|
+
branch: typeof stored.merge.branch === 'string' ? stored.merge.branch : '',
|
|
427
|
+
mode: stored.merge.mode === 'auto' ? 'auto' : 'manual',
|
|
428
|
+
temp: stored.merge.temp === true,
|
|
429
|
+
message: typeof stored.merge.message === 'string' ? stored.merge.message : '',
|
|
430
|
+
startedAt: Number(stored.merge.startedAt) || 0,
|
|
431
|
+
}
|
|
432
|
+
: null
|
|
433
|
+
const storedIntegration = stored?.integration !== null && typeof stored?.integration === 'object'
|
|
434
|
+
&& typeof stored.integration?.branch === 'string'
|
|
435
|
+
&& typeof stored.integration?.baseBranch === 'string'
|
|
436
|
+
? {
|
|
437
|
+
branch: stored.integration.branch,
|
|
438
|
+
baseBranch: stored.integration.baseBranch,
|
|
439
|
+
baseSha: typeof stored.integration.baseSha === 'string' ? stored.integration.baseSha : '',
|
|
440
|
+
worktree: typeof stored.integration.worktree === 'string' ? stored.integration.worktree : '',
|
|
441
|
+
createdAt: Number(stored.integration.createdAt) || 0,
|
|
442
|
+
mergedAt: Number(stored.integration.mergedAt) || 0,
|
|
443
|
+
status: stored.integration.status === 'merged' ? 'merged' : 'active',
|
|
444
|
+
}
|
|
445
|
+
: null
|
|
446
|
+
const record = {
|
|
447
|
+
version: STATE_VERSION,
|
|
448
|
+
root: repo.root,
|
|
449
|
+
gitDir: repo.gitDir,
|
|
450
|
+
branch: repo.branch,
|
|
451
|
+
detached: repo.detached,
|
|
452
|
+
head: repo.head,
|
|
453
|
+
headShort: repo.headShort,
|
|
454
|
+
settings,
|
|
455
|
+
skills,
|
|
456
|
+
branches: [],
|
|
457
|
+
bugs,
|
|
458
|
+
model: null,
|
|
459
|
+
batch: { running: false, aborted: false, total: 0, done: 0, startedAt: 0, finishedAt: 0 },
|
|
460
|
+
merge: storedMerge,
|
|
461
|
+
integration: storedIntegration,
|
|
462
|
+
runtime: {
|
|
463
|
+
active: new Map(),
|
|
464
|
+
queue: [],
|
|
465
|
+
abort: null,
|
|
466
|
+
batchPromise: null,
|
|
467
|
+
applyChain: Promise.resolve(),
|
|
468
|
+
},
|
|
469
|
+
saveChain: Promise.resolve(),
|
|
470
|
+
updatedAt: Date.now(),
|
|
471
|
+
}
|
|
472
|
+
await this.refreshBranches(record)
|
|
473
|
+
return record
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Persist one record to its repository state file.
|
|
478
|
+
* @param {object} record - the record.
|
|
479
|
+
* @returns {Promise<void>} after persistence succeeds; rejects on failure.
|
|
480
|
+
*/
|
|
481
|
+
async save(record) {
|
|
482
|
+
record.updatedAt = Date.now()
|
|
483
|
+
const saving = record.saveChain.then(async () => {
|
|
484
|
+
const directory = path.join(record.root, STATE_DIR)
|
|
485
|
+
const target = path.join(directory, 'state.json')
|
|
486
|
+
const temporary = `${target}.${process.pid}.tmp`
|
|
487
|
+
const payload = {
|
|
488
|
+
version: STATE_VERSION,
|
|
489
|
+
updatedAt: record.updatedAt,
|
|
490
|
+
settings: record.settings,
|
|
491
|
+
bugs: record.bugs,
|
|
492
|
+
merge: record.merge,
|
|
493
|
+
integration: record.integration,
|
|
494
|
+
}
|
|
495
|
+
try {
|
|
496
|
+
await mkdir(directory, { recursive: true })
|
|
497
|
+
await writeFile(temporary, JSON.stringify(payload), 'utf8')
|
|
498
|
+
await rename(temporary, target)
|
|
499
|
+
} catch (error) {
|
|
500
|
+
this.logger?.warn?.(`[dsh-git-bugfix] 状态保存失败:${String(error)}`)
|
|
501
|
+
throw error
|
|
502
|
+
}
|
|
503
|
+
})
|
|
504
|
+
record.saveChain = saving.catch(() => {})
|
|
505
|
+
return saving
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Import parsed defects into a record, either replacing the list or appending
|
|
510
|
+
* to existing defects, while keeping the fix history of matching keys.
|
|
511
|
+
* @param {object} record - the repository record.
|
|
512
|
+
* @param {object[]} defects - freshly parsed defects.
|
|
513
|
+
* @param {'replace' | 'append'} [mode] - import mode.
|
|
514
|
+
* @returns {{ imported: number, added: number, updated: number, removed: number }} import counts.
|
|
515
|
+
*/
|
|
516
|
+
importDefects(record, defects, mode = 'replace') {
|
|
517
|
+
const previous = new Map(record.bugs.map(bug => [bug.key, bug]))
|
|
518
|
+
const sorted = [...defects].sort(compareDefectOrder)
|
|
519
|
+
const incoming = []
|
|
520
|
+
const seenKeys = new Set()
|
|
521
|
+
let added = 0
|
|
522
|
+
let updated = 0
|
|
523
|
+
for (const defect of sorted) {
|
|
524
|
+
let key = defect.key
|
|
525
|
+
if (seenKeys.has(key)) key = `${key}-r${defect.row}`
|
|
526
|
+
seenKeys.add(key)
|
|
527
|
+
const normalized = key === defect.key ? defect : { ...defect, key }
|
|
528
|
+
const old = previous.get(normalized.key)
|
|
529
|
+
if (old === undefined) {
|
|
530
|
+
incoming.push(initialFix(normalized))
|
|
531
|
+
added += 1
|
|
532
|
+
} else {
|
|
533
|
+
incoming.push({ ...initialFix(normalized), fix: old.fix })
|
|
534
|
+
updated += 1
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (mode === 'append') {
|
|
538
|
+
const incomingByKey = new Map(incoming.map(bug => [bug.key, bug]))
|
|
539
|
+
const merged = record.bugs.map(bug => incomingByKey.get(bug.key) ?? bug)
|
|
540
|
+
for (const bug of incoming) {
|
|
541
|
+
if (!previous.has(bug.key)) merged.push(bug)
|
|
542
|
+
}
|
|
543
|
+
record.bugs = merged
|
|
544
|
+
return { imported: defects.length, added, updated, removed: 0 }
|
|
545
|
+
}
|
|
546
|
+
const keptKeys = new Set(incoming.map(bug => bug.key))
|
|
547
|
+
const removedBugs = record.bugs.filter(bug => !keptKeys.has(bug.key))
|
|
548
|
+
for (const oldBug of removedBugs) {
|
|
549
|
+
for (const att of oldBug.fix?.attachments ?? []) {
|
|
550
|
+
if (typeof att?.path === 'string' && att.path !== '') {
|
|
551
|
+
void rm(path.join(record.root, att.path), { force: true }).catch(() => {})
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
record.bugs = incoming
|
|
556
|
+
return { imported: defects.length, added, updated, removed: removedBugs.length }
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Add one ad-hoc defect created from pasted/typed text.
|
|
561
|
+
* @param {object} record - the repository record.
|
|
562
|
+
* @param {{ title?: string, content?: string }} input - user-provided text.
|
|
563
|
+
* @param {'append' | 'replace'} [mode] - import mode.
|
|
564
|
+
* @returns {object} the newly created defect record.
|
|
565
|
+
*/
|
|
566
|
+
appendTextDefect(record, { title = '', content = '' }, mode = 'append') {
|
|
567
|
+
const cleanTitle = String(title ?? '').trim()
|
|
568
|
+
const cleanContent = String(content ?? '').trim()
|
|
569
|
+
const firstLine = cleanContent.split(/\r?\n/).map(line => line.trim()).find(line => line !== '') ?? ''
|
|
570
|
+
const resolvedTitle = (cleanTitle !== '' ? cleanTitle : firstLine).slice(0, 200)
|
|
571
|
+
const analysis = cleanContent === resolvedTitle ? '' : cleanContent
|
|
572
|
+
let maxTextNumber = 0
|
|
573
|
+
let maxRow = 0
|
|
574
|
+
const existingKeys = new Set()
|
|
575
|
+
if (mode !== 'replace') {
|
|
576
|
+
for (const bug of record.bugs) {
|
|
577
|
+
existingKeys.add(bug.key)
|
|
578
|
+
if (Number(bug.row) > maxRow) maxRow = Number(bug.row)
|
|
579
|
+
const match = /^T(\d+)$/.exec(String(bug.id ?? '').trim())
|
|
580
|
+
if (match !== null) {
|
|
581
|
+
const number = Number(match[1])
|
|
582
|
+
if (number > maxTextNumber) maxTextNumber = number
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
const id = `T${maxTextNumber + 1}`
|
|
587
|
+
const stamp = Date.now()
|
|
588
|
+
let seq = 1
|
|
589
|
+
let key = `text-${stamp}-${seq}`
|
|
590
|
+
while (existingKeys.has(key)) {
|
|
591
|
+
seq += 1
|
|
592
|
+
key = `text-${stamp}-${seq}`
|
|
593
|
+
}
|
|
594
|
+
const now = new Date()
|
|
595
|
+
const pad = value => String(value).padStart(2, '0')
|
|
596
|
+
const registeredAt = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`
|
|
597
|
+
const bug = initialFix({
|
|
598
|
+
key,
|
|
599
|
+
row: maxRow + 1,
|
|
600
|
+
id,
|
|
601
|
+
title: resolvedTitle,
|
|
602
|
+
analysis,
|
|
603
|
+
severity: '',
|
|
604
|
+
state: '',
|
|
605
|
+
tags: '文字导入',
|
|
606
|
+
note: '',
|
|
607
|
+
url: '',
|
|
608
|
+
plan: '',
|
|
609
|
+
creator: '',
|
|
610
|
+
fixer: '',
|
|
611
|
+
registeredAt,
|
|
612
|
+
requirement: '',
|
|
613
|
+
reopenCount: '',
|
|
614
|
+
standardStatus: '',
|
|
615
|
+
standardOwner: '',
|
|
616
|
+
platform: '',
|
|
617
|
+
version: '',
|
|
618
|
+
})
|
|
619
|
+
record.bugs = mode === 'replace' ? [bug] : [...record.bugs, bug]
|
|
620
|
+
return bug
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Refresh the local branch list used by the settings surface.
|
|
625
|
+
* @param {object} record - the repository record.
|
|
626
|
+
* @param {AbortSignal} [signal] - caller cancellation.
|
|
627
|
+
* @returns {Promise<void>} after the branch cache update.
|
|
628
|
+
*/
|
|
629
|
+
async refreshBranches(record, signal) {
|
|
630
|
+
const [local, worktrees] = await Promise.all([
|
|
631
|
+
listLocalBranches(record.root, signal),
|
|
632
|
+
listWorktrees(record.root, signal),
|
|
633
|
+
])
|
|
634
|
+
const checkedOut = new Map()
|
|
635
|
+
for (const worktree of worktrees) {
|
|
636
|
+
if (worktree.branch === '') continue
|
|
637
|
+
checkedOut.set(worktree.branch, path.resolve(worktree.path) === path.resolve(record.root) ? 'current' : 'elsewhere')
|
|
638
|
+
}
|
|
639
|
+
record.allBranchNames = local.map(branch => branch.name)
|
|
640
|
+
record.branches = local
|
|
641
|
+
.filter(branch => !branch.name.startsWith('bugfix/'))
|
|
642
|
+
.map(branch => ({
|
|
643
|
+
name: branch.name,
|
|
644
|
+
headShort: branch.headShort,
|
|
645
|
+
committedAt: branch.committedAt,
|
|
646
|
+
current: branch.name === record.branch,
|
|
647
|
+
checkedOut: checkedOut.get(branch.name) ?? '',
|
|
648
|
+
}))
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Re-read repository facts and the skill catalog.
|
|
653
|
+
* @param {object} record - the repository record.
|
|
654
|
+
* @param {AbortSignal} [signal] - caller cancellation.
|
|
655
|
+
* @returns {Promise<void>} after the refresh.
|
|
656
|
+
*/
|
|
657
|
+
async refresh(record, signal) {
|
|
658
|
+
const repo = await resolveRepo(record.root, signal)
|
|
659
|
+
if (repo !== null) {
|
|
660
|
+
record.branch = repo.branch
|
|
661
|
+
record.detached = repo.detached
|
|
662
|
+
record.head = repo.head
|
|
663
|
+
record.headShort = repo.headShort
|
|
664
|
+
}
|
|
665
|
+
record.skills = await scanRepoSkills(record.root)
|
|
666
|
+
if (!record.skills.some(skill => skill.path === record.settings.skillPath)) {
|
|
667
|
+
const preferred = record.skills.find(skill => skill.score > 0) ?? record.skills[0]
|
|
668
|
+
record.settings.skillPath = preferred?.path ?? ''
|
|
669
|
+
}
|
|
670
|
+
await this.refreshBranches(record, signal)
|
|
671
|
+
await this.save(record)
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* Drop a record (used when the repository disappears).
|
|
676
|
+
* @param {string} root - repository root.
|
|
677
|
+
*/
|
|
678
|
+
forget(root) {
|
|
679
|
+
this.records.delete(root)
|
|
680
|
+
}
|
|
681
|
+
}
|