@sshirkit/dsh-orchestrator 0.9.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,244 @@
1
+ import { dispatchCwd, formatWorktreeError } from './write-scope-tool.js'
2
+
3
+ const ACTIONS = ['list', 'inspect', 'merge', 'discard', 'prune']
4
+ const STRATEGIES = ['merge', 'squash', 'ff-only']
5
+ const CLOSED_STATES = new Set(['merged', 'discarded'])
6
+ const DIFF_LIMIT = { min: 1000, max: 64000, default: 12000 }
7
+ const COMMIT_LIMIT = { min: 1, max: 100, default: 20 }
8
+ const isId = (value) => typeof value === 'string' && value.trim() !== ''
9
+
10
+ function readOptions(args, action) {
11
+ const options = {}
12
+ for (const [key, fallback] of Object.entries({
13
+ list: { includeClosed: false },
14
+ merge: { autoStageDirty: false, deleteAfterMerge: true },
15
+ discard: { force: false },
16
+ prune: { dryRun: false },
17
+ }[action] ?? {})) {
18
+ options[key] = args[key] === undefined ? fallback : args[key]
19
+ if (typeof options[key] !== 'boolean') throw new Error(`${key} 必须是布尔值。`)
20
+ }
21
+ if (action === 'inspect') {
22
+ for (const [key, range] of Object.entries({ maxDiffChars: DIFF_LIMIT, maxCommits: COMMIT_LIMIT })) {
23
+ const value = args[key] === undefined ? range.default : args[key]
24
+ if (!Number.isInteger(value) || value < range.min || value > range.max) {
25
+ throw new Error(`${key} 必须是 ${range.min}..${range.max} 之间的整数。`)
26
+ }
27
+ options[key] = value
28
+ }
29
+ }
30
+ if (action === 'merge') {
31
+ const { strategy = 'merge', commitMessage } = args
32
+ if (!STRATEGIES.includes(strategy)) throw new Error('strategy 必须是 merge、squash 或 ff-only。')
33
+ if (commitMessage !== undefined && typeof commitMessage !== 'string') {
34
+ throw new Error('commitMessage 必须是字符串。')
35
+ }
36
+ options.strategy = strategy
37
+ if (commitMessage !== undefined) options.commitMessage = commitMessage
38
+ }
39
+ return options
40
+ }
41
+
42
+ function projectWorktreeRecord(record) {
43
+ if (record === null || typeof record !== 'object' || Array.isArray(record)) return record
44
+ // The manager stores these persistence fields as non-enumerable own properties.
45
+ // Preserve them on the tool receipt without changing the manager's record shape.
46
+ return {
47
+ ...record,
48
+ ...(Object.hasOwn(record, 'childIds') && { childIds: record.childIds }),
49
+ ...(Object.hasOwn(record, 'locked') && { locked: record.locked }),
50
+ }
51
+ }
52
+
53
+ function toLosslessJsonValue(value, ancestors = new Set()) {
54
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value
55
+ if (typeof value === 'number') return Number.isFinite(value) ? (value === 0 ? 0 : value) : null
56
+ if (typeof value !== 'object' || ancestors.has(value)) return undefined
57
+
58
+ ancestors.add(value)
59
+ try {
60
+ // Fill holes or unsupported elements with null; never shift array indices.
61
+ if (Array.isArray(value)) {
62
+ return Array.from({ length: value.length }, (_, index) =>
63
+ Object.hasOwn(value, index) ? toLosslessJsonValue(value[index], ancestors) ?? null : null)
64
+ }
65
+ const prototype = Object.getPrototypeOf(value)
66
+ if (prototype !== Object.prototype && prototype !== null) return undefined
67
+ // Copy only enumerable string keys, omitting unsupported values and back-edges.
68
+ const entries = []
69
+ for (const [key, entry] of Object.entries(value)) {
70
+ const json = toLosslessJsonValue(entry, ancestors)
71
+ if (json !== undefined) entries.push([key, json])
72
+ }
73
+ return Object.fromEntries(entries)
74
+ } finally {
75
+ ancestors.delete(value)
76
+ }
77
+ }
78
+
79
+ function toolResult(action, text, payload) {
80
+ const details = { ...payload, action, ok: payload.ok === true }
81
+ if (action === 'list') details.worktrees = details.worktrees.map(projectWorktreeRecord)
82
+ if (Object.hasOwn(details, 'worktree')) details.worktree = projectWorktreeRecord(details.worktree)
83
+ return toLosslessJsonValue({ content: [{ type: 'text', text: String(text) }], details })
84
+ }
85
+
86
+ function auditReviewText({ auditSummary } = {}) {
87
+ if (typeof auditSummary?.auditPassed !== 'boolean') return ''
88
+ const { commits, dirty, auditPassed } = auditSummary
89
+ return ` 最近审计${auditPassed ? '通过' : '未通过'}(${commits} 个提交${dirty ? ',有未提交改动' : ''})。`
90
+ }
91
+
92
+ function nextWorktreeState(record, action, result) {
93
+ if (result.worktree?.state) return result.worktree.state
94
+ if (result.state) return result.state
95
+ if (result.code === 'merge-conflict') return 'merge_conflict'
96
+ if (result.code === 'worktree-cleanup-failed') return 'cleanup_failed'
97
+ if (result.ok && !result.noop) {
98
+ if (action === 'merge' && result.merged !== false) return 'merged'
99
+ if (action === 'discard' && result.discarded !== false) return 'discarded'
100
+ }
101
+ return record.state
102
+ }
103
+
104
+ function syncDelivery(timeline, record, action, result) {
105
+ if (!record.childId || typeof timeline?.recordWorktreeState !== 'function') return
106
+ const state = nextWorktreeState(record, action, result)
107
+ const mergeCommit = result.mergeCommit ?? result.worktree?.mergeCommit ?? record.mergeCommit ?? null
108
+ timeline.recordWorktreeState(record.childId, {
109
+ id: record.id,
110
+ state,
111
+ mergeCommit,
112
+ conflictFiles: result.conflictFiles ?? result.worktree?.conflictFiles ?? record.conflictFiles ?? [],
113
+ locked: CLOSED_STATES.has(state) || (mergeCommit !== null && result.worktree?.cleaned === false),
114
+ })
115
+ }
116
+
117
+ function deliverySummary(action, record, result) {
118
+ const label = `工作树 ${record.id}`
119
+ const state = nextWorktreeState(record, action, result)
120
+ if (!result.ok) {
121
+ if (state === 'merge_conflict' && result.code === 'merge-conflict') {
122
+ const files = result.conflictFiles ?? result.worktree?.conflictFiles ?? []
123
+ const rollback = result.rollbackError ? '源仓自动回退失败,请立即核查源仓状态。' : ''
124
+ return `${label} 合回发生冲突(${files.length} 个文件),未合回,保留现场供评审。${rollback}`
125
+ }
126
+ if (action === 'merge' && result.merged === true) {
127
+ return `${label} 已合回,但清理失败:${result.message ?? '请检查工作树状态。'}\n` +
128
+ '不要重复合并;请调用 worktree_manage(action: "discard", force: true) 清理残留目录或分支。'
129
+ }
130
+ if (action === 'merge' && result.code === 'worktree-already-closed' && result.message) return result.message
131
+ return `${label} ${action === 'merge' ? '合回' : '丢弃'}未完成:${result.message ?? formatWorktreeError(result.code)}`
132
+ }
133
+ if (action === 'discard') return record.mergeCommit ? `${label} 已清理,交付物此前已合回。` : `${label} 已丢弃。`
134
+ if (result.noop || result.merged === false) return `${label} 没有待合回的提交,工作树未关闭。`
135
+ const commit = result.mergeCommit ?? result.worktree?.mergeCommit
136
+ return `${label} 已合回${commit ? `(提交 ${commit})` : ''}。` + (result.cleaned === false
137
+ ? '工作树仍保留;可调用 worktree_manage(action: "discard", force: true) 清理。' : '')
138
+ }
139
+
140
+ /** The root session reviews and disposes of managed worktrees; the manager owns Git I/O. */
141
+ export function createWorktreeManageTool({
142
+ worktrees,
143
+ timeline = null,
144
+ toolName = 'worktree_manage',
145
+ isRootAgent,
146
+ onClosed,
147
+ defineTool = (definition) => definition,
148
+ } = {}) {
149
+ return defineTool({
150
+ name: toolName,
151
+ description: '仅根代理可用:列出、检查、合回或丢弃当前会话的 Git 工作树交付,或清理当前仓库的孤立工作树。审计通过不表示交付物已合回。',
152
+ parameters: {
153
+ action: { type: 'string', enum: ACTIONS, required: true, description: '要执行的工作树操作。' },
154
+ worktreeId: { type: 'string', description: '工作树 ID;inspect、merge、discard 需要此项或 childId。' },
155
+ childId: { type: 'string', description: '子代理 ID;未提供 worktreeId 时用于定位工作树。' },
156
+ includeClosed: { type: 'boolean', default: false, description: 'list 是否包含已合回或已丢弃的工作树。' },
157
+ // The host's author schema does not support minimum/maximum; enforce ranges in execute.
158
+ maxDiffChars: { type: 'integer', default: DIFF_LIMIT.default, description: 'inspect 返回的 diff 字符上限(1000..64000)。' },
159
+ maxCommits: { type: 'integer', default: COMMIT_LIMIT.default, description: 'inspect 返回的提交条数上限(1..100)。' },
160
+ strategy: { type: 'string', enum: STRATEGIES, default: 'merge', description: '合回策略。' },
161
+ commitMessage: { type: 'string', description: '可选:用于合回或自动提交的消息。' },
162
+ autoStageDirty: { type: 'boolean', default: false, description: 'merge 是否自动暂存并提交隔离目录中的未提交改动。' },
163
+ deleteAfterMerge: { type: 'boolean', default: true, description: '成功合回后是否删除隔离目录及分支。' },
164
+ force: { type: 'boolean', default: false, description: 'discard 是否强制丢弃未提交或未合回的工作。' },
165
+ dryRun: { type: 'boolean', default: false, description: 'prune 是否仅预览孤立项,不执行删除。' },
166
+ },
167
+ output: {
168
+ schema: {
169
+ type: 'object',
170
+ additionalProperties: false,
171
+ properties: {
172
+ content: {
173
+ type: 'array',
174
+ items: {
175
+ type: 'object',
176
+ additionalProperties: false,
177
+ properties: { type: { type: 'string', const: 'text' }, text: { type: 'string' } },
178
+ },
179
+ },
180
+ details: {
181
+ type: 'object',
182
+ additionalProperties: true,
183
+ properties: {
184
+ action: { type: 'string', enum: ACTIONS },
185
+ ok: { type: 'boolean' },
186
+ },
187
+ },
188
+ },
189
+ },
190
+ render: (_args, value) => value.content,
191
+ },
192
+ isConcurrencySafe: () => false,
193
+ async execute(args, exec) {
194
+ if (typeof isRootAgent !== 'function' || isRootAgent(exec) !== true) {
195
+ throw new Error(`仅根代理可调用 ${toolName}。`)
196
+ }
197
+ const parentId = exec?.agent?.id
198
+ if (!isId(parentId)) throw new Error(`${toolName} 无法识别调用代理的会话 ID,拒绝操作。`)
199
+
200
+ const { action, worktreeId, childId } = args ?? {}
201
+ if (!ACTIONS.includes(action)) throw new Error('action 必须是 list、inspect、merge、discard 或 prune。')
202
+ for (const [key, value] of Object.entries({ worktreeId, childId })) {
203
+ if (value !== undefined && !isId(value)) throw new Error(`${key} 必须是非空字符串。`)
204
+ }
205
+ const options = readOptions(args, action)
206
+ if (action === 'list') {
207
+ const rows = await worktrees.list({ parentId, ...options })
208
+ const owned = rows.filter((row) => row?.parentId === parentId &&
209
+ (options.includeClosed || !CLOSED_STATES.has(row.state)))
210
+ const text = [`当前会话有 ${owned.length} 棵工作树。`,
211
+ ...owned.map((row) => `- ${row.id}:${row.state}(分支 ${row.branch ?? '未知'})${auditReviewText(row)}`)].join('\n')
212
+ return toolResult(action, text, { ok: true, worktrees: owned, total: owned.length })
213
+ }
214
+ if (action === 'prune') {
215
+ const repoRoot = dispatchCwd({}, exec)
216
+ if (!repoRoot) throw new Error(`${toolName} 无法识别当前会话工作目录,拒绝清理。`)
217
+ const result = await worktrees.prune({ repoRoot, ...options })
218
+ const text = !result.ok ? `清理失败:${result.message ?? formatWorktreeError(result.code)}`
219
+ : options.dryRun ? `清理预览:发现 ${result.orphans?.length ?? 0} 个孤立项,未执行删除。`
220
+ : `清理完成:工作树 ${result.prunedWorktrees?.length ?? 0} 棵,分支 ${result.prunedBranches?.length ?? 0} 个,错误 ${result.errors?.length ?? 0} 项。`
221
+ return toolResult(action, text, result)
222
+ }
223
+
224
+ const id = worktreeId || childId
225
+ if (!id) throw new Error(`${action} 需要提供 worktreeId 或 childId。`)
226
+ const record = await worktrees.getByWorktreeOrChild(id)
227
+ if (!record) return toolResult(action, '未找到工作树记录。', { ok: false, code: 'worktree-not-found' })
228
+ if (record.parentId && record.parentId !== parentId) throw new Error('拒绝访问不属于当前根代理的工作树。')
229
+
230
+ const result = await worktrees[action](record.id, options)
231
+ if (action === 'inspect') {
232
+ const text = result.ok
233
+ ? `工作树 ${record.id}(分支 ${record.branch ?? '未知'}):${result.exists === false ? '目录已不存在。'
234
+ : `新增提交 ${result.aheadCount ?? result.commits?.length ?? 0} 个${result.dirty ? ',有未提交改动' : ''}${result.diffTruncated ? ',差异已截断' : ''}。`}` +
235
+ auditReviewText(result.worktree ?? record)
236
+ : `检查工作树 ${record.id} 失败:${result.message ?? formatWorktreeError(result.code)}`
237
+ return toolResult(action, text, result)
238
+ }
239
+ syncDelivery(timeline, record, action, result)
240
+ if (result.merged === true || nextWorktreeState(record, action, result) === 'discarded') onClosed?.(record)
241
+ return toolResult(action, deliverySummary(action, record, result), result)
242
+ },
243
+ })
244
+ }
@@ -0,0 +1,38 @@
1
+ import { createWorktreeManageTool } from './worktree-manage.js'
2
+
3
+ const MUTATIONS = ['merge', 'discard', 'prune']
4
+ const durableFields = (row) => JSON.stringify(row)
5
+
6
+ /** Queue registry changes in the same turn as the Git mutation, before a reload can close the store. */
7
+ export function createPersistentWorktreeTool({
8
+ worktrees, stateStore, timeline, assertActive, persist, isWakePending, ...options
9
+ }) {
10
+ const manager = { ...worktrees }
11
+ for (const action of MUTATIONS) {
12
+ manager[action] = async (...args) => {
13
+ if (action === 'prune' && args[0]?.dryRun === true) return worktrees.prune(...args)
14
+ assertActive()
15
+ const target = action !== 'prune' && worktrees.getByWorktreeOrChild(args[0])
16
+ if (target?.childIds.some((childId) => isWakePending?.(childId))) {
17
+ return { ok: false, code: 'worktree-active', message: '子代理正在恢复,待本轮结算后再操作工作树。' }
18
+ }
19
+ const before = new Map(worktrees.exportRecords().map((row) => [row.id, durableFields(row)]))
20
+ try {
21
+ return worktrees[action](...args)
22
+ } finally {
23
+ const changed = worktrees.exportRecords().filter((row) => before.get(row.id) !== durableFields(row))
24
+ await Promise.all(changed.map((row) => persist(stateStore.putWorktree(row))))
25
+ await stateStore.flush()
26
+ for (const row of changed) {
27
+ for (const childId of row.childIds) {
28
+ timeline.recordWorktreeState(childId, {
29
+ id: row.id, parentId: row.parentId, state: row.state,
30
+ mergeCommit: row.mergeCommit, locked: row.locked,
31
+ })
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }
37
+ return createWorktreeManageTool({ ...options, worktrees: manager, timeline })
38
+ }