@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.
- package/README.md +142 -93
- package/README.zh.md +144 -95
- package/docs/images/dispatch-panel.png +0 -0
- package/docs/images/hero-banner.png +0 -0
- package/lib/api.js +1 -0
- package/lib/catalog.js +2 -1
- package/lib/client.js +131 -44
- package/lib/delegate-status.js +125 -0
- package/lib/delegate.js +299 -59
- package/lib/gate.js +57 -15
- package/lib/git-audit.js +383 -0
- package/lib/index.js +1185 -173
- package/lib/orchestrate.js +313 -89
- package/lib/reconcile.js +590 -0
- package/lib/retry.js +68 -5
- package/lib/rules.js +15 -2
- package/lib/state-store.js +455 -0
- package/lib/supervise.js +593 -87
- package/lib/timeline.js +464 -0
- package/lib/tool-surface.js +69 -21
- package/lib/worktree-manage.js +244 -0
- package/lib/worktree-tool.js +38 -0
- package/lib/worktree.js +687 -0
- package/lib/write-audit.js +333 -0
- package/lib/write-lease.js +161 -7
- package/lib/write-scope-tool.js +29 -0
- package/lib/write-scope.js +14 -18
- package/package.json +3 -3
package/lib/timeline.js
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
export const INLINE_AUDIT_SOURCE_KIND = 'orchestrator-write-audit-inline'
|
|
2
|
+
|
|
3
|
+
const DEFAULT_ISOLATION = 'logical-post-audit'
|
|
4
|
+
const WORKTREE_ISOLATION = 'git-worktree'
|
|
5
|
+
const WORKTREE_STATES = new Set([
|
|
6
|
+
'active', 'ready_for_review', 'merged', 'discarded', 'merge_conflict', 'cleanup_failed',
|
|
7
|
+
])
|
|
8
|
+
const TERMINAL_DISPATCH_STATES = new Set(['ended', 'completed', 'interrupted', 'aborted', 'failed', 'lost'])
|
|
9
|
+
const OPEN_WORKTREE_STATES = new Set(['active', 'ready_for_review', 'merge_conflict', 'cleanup_failed'])
|
|
10
|
+
const isId = (value) => typeof value === 'string' && value.length > 0
|
|
11
|
+
const idOrNull = (value) => isId(value) ? value : null
|
|
12
|
+
const textOrNull = (value) => typeof value === 'string' ? value : null
|
|
13
|
+
const snapshot = (entry) => structuredClone(entry)
|
|
14
|
+
|
|
15
|
+
function copyMetadata(value) {
|
|
16
|
+
if (typeof value === 'string') return value
|
|
17
|
+
if (value == null || typeof value !== 'object') return null
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(JSON.stringify(value))
|
|
20
|
+
} catch {
|
|
21
|
+
return null
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function copyViolation(value) {
|
|
26
|
+
const result = {}
|
|
27
|
+
for (const key of ['kind', 'code', 'path', 'reason', 'phase', 'changeType', 'expected', 'actual']) {
|
|
28
|
+
if (typeof value?.[key] === 'string' || value?.[key] === null) result[key] = value[key]
|
|
29
|
+
}
|
|
30
|
+
if (value?.detail !== undefined) result.detail = copyMetadata(value.detail)
|
|
31
|
+
return result
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const isCompleted = (entry) => entry.dispatchState === 'ended' && entry.auditState !== 'pending'
|
|
35
|
+
const isEvictable = (entry) => isCompleted(entry) &&
|
|
36
|
+
(entry.auditState !== 'failed' || Boolean(entry.auditDeliveredVia)) &&
|
|
37
|
+
!OPEN_WORKTREE_STATES.has(entry.worktree?.state)
|
|
38
|
+
const needsAttention = (entry) => entry.dispatchState === 'ended' &&
|
|
39
|
+
(entry.auditState === 'pending' || (entry.auditState === 'failed' && !entry.auditDeliveredVia))
|
|
40
|
+
const queryPriority = (entry) => isCompleted(entry) && entry.auditState !== 'failed' ? 1 : 0
|
|
41
|
+
const newestFirst = (left, right) => right.updatedAt - left.updatedAt
|
|
42
|
+
|
|
43
|
+
function initialWorktree(worktree) {
|
|
44
|
+
if (worktree == null || typeof worktree !== 'object') return null
|
|
45
|
+
const { id, path, execCwd, branch, baseCommit } = worktree
|
|
46
|
+
return {
|
|
47
|
+
id: idOrNull(id), path: textOrNull(path ?? worktree.worktreePath), execCwd: textOrNull(execCwd),
|
|
48
|
+
branch: textOrNull(branch), baseCommit: idOrNull(baseCommit),
|
|
49
|
+
state: 'active', commits: 0, dirty: false, mergeCommit: null, conflictFiles: [], locked: false,
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function normalizeWorktreeState(state) {
|
|
54
|
+
if (state === 'ready') return 'ready_for_review'
|
|
55
|
+
const normalized = typeof state === 'string' ? state.replaceAll('-', '_') : null
|
|
56
|
+
return WORKTREE_STATES.has(normalized) ? normalized : null
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function persistedWorktree(row) {
|
|
60
|
+
const tree = row.worktree
|
|
61
|
+
if (tree == null && !isId(row.worktreeId) && !isId(row.worktreeState)) return null
|
|
62
|
+
const restored = initialWorktree({ ...tree, id: tree?.id ?? row.worktreeId })
|
|
63
|
+
restored.state = normalizeWorktreeState(tree?.state ?? row.worktreeState) ?? restored.state
|
|
64
|
+
restored.commits = countOr(tree?.commits, 0)
|
|
65
|
+
restored.dirty = tree?.dirty === true
|
|
66
|
+
restored.mergeCommit = idOrNull(tree?.mergeCommit)
|
|
67
|
+
restored.conflictFiles = textList(tree?.conflictFiles)
|
|
68
|
+
restored.locked = tree?.locked === true
|
|
69
|
+
return restored
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const countOr = (value, fallback) => Number.isSafeInteger(value) && value >= 0 ? value : fallback
|
|
73
|
+
const timeOrNull = (value) => Number.isFinite(value) ? value : null
|
|
74
|
+
const textList = (value) => Array.isArray(value) ? value.filter((item) => typeof item === 'string') : []
|
|
75
|
+
|
|
76
|
+
function initialAttempt({ readOnly, baselineId, leaseId, startedAt, worktree }) {
|
|
77
|
+
return {
|
|
78
|
+
readOnly: readOnly === true,
|
|
79
|
+
runId: null,
|
|
80
|
+
baselineId: idOrNull(baselineId),
|
|
81
|
+
dispatchState: 'running',
|
|
82
|
+
auditState: isId(baselineId) ? 'pending' : 'unmanaged',
|
|
83
|
+
leaseState: readOnly !== true && isId(leaseId) ? 'held' : 'none',
|
|
84
|
+
leaseId: idOrNull(leaseId),
|
|
85
|
+
startedAt,
|
|
86
|
+
endedAt: null,
|
|
87
|
+
disposedAt: null,
|
|
88
|
+
auditedAt: null,
|
|
89
|
+
releasedAt: null,
|
|
90
|
+
updatedAt: startedAt,
|
|
91
|
+
stopReason: null,
|
|
92
|
+
violations: [],
|
|
93
|
+
truncatedViolations: 0,
|
|
94
|
+
incomplete: false,
|
|
95
|
+
isolation: worktree ? WORKTREE_ISOLATION : isId(baselineId) ? DEFAULT_ISOLATION : null,
|
|
96
|
+
auditSummary: null,
|
|
97
|
+
auditDeliveredVia: null,
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Bounded, in-memory acceptance evidence. It does not own a lease or enforce isolation. */
|
|
102
|
+
export function createDispatchTimeline({
|
|
103
|
+
maxPerParent = 64,
|
|
104
|
+
maxParents = 64,
|
|
105
|
+
maxViolations = 32,
|
|
106
|
+
now = () => Date.now(),
|
|
107
|
+
} = {}) {
|
|
108
|
+
for (const [name, value, minimum] of [
|
|
109
|
+
['maxPerParent', maxPerParent, 1],
|
|
110
|
+
['maxParents', maxParents, 1],
|
|
111
|
+
['maxViolations', maxViolations, 0],
|
|
112
|
+
]) {
|
|
113
|
+
if (!Number.isSafeInteger(value) || value < minimum) {
|
|
114
|
+
throw new RangeError(`${name} 必须是大于或等于 ${minimum} 的安全整数。`)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const parents = new Map()
|
|
118
|
+
const timestamp = (at) => Number.isFinite(at) ? at : now()
|
|
119
|
+
|
|
120
|
+
function lookup({ parentId, childId }) {
|
|
121
|
+
if (parentId !== undefined) return parents.get(parentId)?.get(childId)
|
|
122
|
+
// Some host callbacks have only a child id. Do not guess if it is ambiguous.
|
|
123
|
+
let match
|
|
124
|
+
for (const records of parents.values()) {
|
|
125
|
+
const candidate = records.get(childId)
|
|
126
|
+
if (candidate === undefined) continue
|
|
127
|
+
if (match !== undefined) return undefined
|
|
128
|
+
match = candidate
|
|
129
|
+
}
|
|
130
|
+
return match
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function touch(entry, at) {
|
|
134
|
+
entry.updatedAt = Math.max(entry.updatedAt, at)
|
|
135
|
+
const records = parents.get(entry.parentId)
|
|
136
|
+
records.delete(entry.childId)
|
|
137
|
+
records.set(entry.childId, entry)
|
|
138
|
+
parents.delete(entry.parentId)
|
|
139
|
+
parents.set(entry.parentId, records)
|
|
140
|
+
return true
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function evictOldest(records) {
|
|
144
|
+
let oldest
|
|
145
|
+
let oldestEvictable
|
|
146
|
+
for (const entry of records.values()) {
|
|
147
|
+
if (!oldest || entry.updatedAt < oldest.updatedAt) oldest = entry
|
|
148
|
+
if (isEvictable(entry) && (!oldestEvictable || entry.updatedAt < oldestEvictable.updatedAt)) {
|
|
149
|
+
oldestEvictable = entry
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
records.delete((oldestEvictable ?? oldest).childId)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function evictParent() {
|
|
156
|
+
let oldestOrdinary
|
|
157
|
+
let oldestAt = Infinity
|
|
158
|
+
for (const [parentId, records] of parents) {
|
|
159
|
+
let latest = -Infinity
|
|
160
|
+
let ordinary = true
|
|
161
|
+
for (const entry of records.values()) {
|
|
162
|
+
if (!isEvictable(entry)) { ordinary = false; break }
|
|
163
|
+
latest = Math.max(latest, entry.updatedAt)
|
|
164
|
+
}
|
|
165
|
+
if (ordinary && latest < oldestAt) {
|
|
166
|
+
oldestOrdinary = parentId
|
|
167
|
+
oldestAt = latest
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
// Preserve the old LRU fallback if there are only protected parents.
|
|
171
|
+
parents.delete(oldestOrdinary ?? parents.keys().next().value)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function exportEntries() {
|
|
175
|
+
return JSON.parse(JSON.stringify([...parents.values()].flatMap((rows) => [...rows.values()])))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function hydrateEntries(rows, { replace = false } = {}) {
|
|
179
|
+
const result = { restored: 0, skipped: 0 }
|
|
180
|
+
if (!Array.isArray(rows)) return result
|
|
181
|
+
if (replace) parents.clear()
|
|
182
|
+
for (const row of rows) {
|
|
183
|
+
if (!isId(row?.parentId) || !isId(row?.childId)) {
|
|
184
|
+
result.skipped += 1
|
|
185
|
+
continue
|
|
186
|
+
}
|
|
187
|
+
const { parentId, childId } = row
|
|
188
|
+
const startedAt = timestamp(row.startedAt ?? row.updatedAt ?? row.endedAt)
|
|
189
|
+
const updatedAt = timeOrNull(row.updatedAt) ?? Math.max(startedAt, timeOrNull(row.endedAt) ?? startedAt)
|
|
190
|
+
const previous = lookup({ parentId, childId })
|
|
191
|
+
if (previous && previous.updatedAt > updatedAt) {
|
|
192
|
+
result.skipped += 1
|
|
193
|
+
continue
|
|
194
|
+
}
|
|
195
|
+
const worktree = persistedWorktree(row)
|
|
196
|
+
const entry = { childId, parentId, worktree, ...initialAttempt({ ...row, startedAt, worktree }) }
|
|
197
|
+
const dispatchState = row.dispatchState
|
|
198
|
+
entry.dispatchState = TERMINAL_DISPATCH_STATES.has(dispatchState) ? 'ended'
|
|
199
|
+
: idOrNull(dispatchState) ?? (Number.isFinite(row.endedAt) ? 'ended' : entry.dispatchState)
|
|
200
|
+
entry.attemptSeq = countOr(row.attemptSeq, 1)
|
|
201
|
+
for (const key of ['runId', 'auditState', 'leaseState']) {
|
|
202
|
+
if (isId(row[key])) entry[key] = row[key]
|
|
203
|
+
}
|
|
204
|
+
for (const key of ['label', 'cwd', 'stopReason', 'auditDeliveredVia']) entry[key] = textOrNull(row[key])
|
|
205
|
+
for (const key of ['endedAt', 'disposedAt', 'auditedAt', 'releasedAt']) entry[key] = timeOrNull(row[key])
|
|
206
|
+
entry.writeScope = textList(row.writeScope)
|
|
207
|
+
entry.incomplete = row.incomplete === true
|
|
208
|
+
if (Object.hasOwn(row, 'isolation')) entry.isolation = copyMetadata(row.isolation)
|
|
209
|
+
entry.auditSummary = copyMetadata(row.auditSummary)
|
|
210
|
+
const violations = Array.isArray(row.violations) ? row.violations : []
|
|
211
|
+
entry.violations = violations.slice(0, maxViolations).map(copyViolation)
|
|
212
|
+
entry.truncatedViolations = countOr(row.truncatedViolations, 0) + Math.max(0, violations.length - maxViolations)
|
|
213
|
+
for (const key of ['agentName', 'rootSessionId', 'batchId']) if (isId(row[key])) entry[key] = row[key]
|
|
214
|
+
for (const key of ['itemIndex', 'stageIndex']) {
|
|
215
|
+
const index = countOr(row[key], null)
|
|
216
|
+
if (index !== null) entry[key] = index
|
|
217
|
+
}
|
|
218
|
+
if (Array.isArray(row.expectedTargets)) entry.expectedTargets = textList(row.expectedTargets)
|
|
219
|
+
if (!parents.has(parentId)) parents.set(parentId, new Map())
|
|
220
|
+
entry.updatedAt = updatedAt
|
|
221
|
+
touch(entry, updatedAt)
|
|
222
|
+
result.restored += 1
|
|
223
|
+
}
|
|
224
|
+
for (const records of parents.values()) {
|
|
225
|
+
while (records.size > maxPerParent) evictOldest(records)
|
|
226
|
+
}
|
|
227
|
+
while (parents.size > maxParents) evictParent()
|
|
228
|
+
return result
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function recordDispatched({ parentId, childId, agentName, label, readOnly, writeScope, cwd, baselineId, leaseId,
|
|
232
|
+
startedAt, worktree }) {
|
|
233
|
+
if (!isId(parentId) || !isId(childId)) return false
|
|
234
|
+
if (!parents.has(parentId)) parents.set(parentId, new Map())
|
|
235
|
+
const records = parents.get(parentId)
|
|
236
|
+
const isolatedTree = initialWorktree(worktree)
|
|
237
|
+
const entry = {
|
|
238
|
+
childId,
|
|
239
|
+
parentId,
|
|
240
|
+
...(isId(agentName) && { agentName }),
|
|
241
|
+
label: textOrNull(label),
|
|
242
|
+
writeScope: Array.isArray(writeScope) ? writeScope.filter((item) => typeof item === 'string') : [],
|
|
243
|
+
cwd: textOrNull(cwd),
|
|
244
|
+
attemptSeq: records.get(childId)?.attemptSeq ?? 1,
|
|
245
|
+
worktree: isolatedTree,
|
|
246
|
+
...initialAttempt({ readOnly, baselineId, leaseId, startedAt: timestamp(startedAt), worktree: isolatedTree }),
|
|
247
|
+
}
|
|
248
|
+
touch(entry, entry.startedAt)
|
|
249
|
+
if (records.size > maxPerParent) evictOldest(records)
|
|
250
|
+
if (parents.size > maxParents) evictParent()
|
|
251
|
+
return true
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function recordRunStarted({ childId, runId, parentId }) {
|
|
255
|
+
const entry = lookup({ childId, parentId })
|
|
256
|
+
if (!entry || !isId(runId) || (entry.runId && entry.runId !== runId)) return false
|
|
257
|
+
entry.runId = runId
|
|
258
|
+
return touch(entry, timestamp())
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function recordRetry({ childId, baselineId, leaseId, readOnly, startedAt, parentId }) {
|
|
262
|
+
const entry = lookup({ childId, parentId })
|
|
263
|
+
if (!entry) return false
|
|
264
|
+
const at = timestamp(startedAt)
|
|
265
|
+
Object.assign(entry, initialAttempt({
|
|
266
|
+
readOnly: readOnly ?? entry.readOnly,
|
|
267
|
+
baselineId,
|
|
268
|
+
leaseId,
|
|
269
|
+
startedAt: at,
|
|
270
|
+
worktree: entry.worktree,
|
|
271
|
+
}), { attemptSeq: entry.attemptSeq + 1 })
|
|
272
|
+
return touch(entry, at)
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function recordDisposed({ childId, at, parentId }) {
|
|
276
|
+
const entry = lookup({ childId, parentId })
|
|
277
|
+
if (!entry) return false
|
|
278
|
+
entry.disposedAt = timestamp(at)
|
|
279
|
+
return touch(entry, entry.disposedAt)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function recordEnded({ childId, runId, stopReason, at, parentId }) {
|
|
283
|
+
const entry = lookup({ childId, parentId })
|
|
284
|
+
if (!entry || (isId(runId) && entry.runId && entry.runId !== runId)) return false
|
|
285
|
+
entry.runId ??= idOrNull(runId)
|
|
286
|
+
entry.dispatchState = 'ended'
|
|
287
|
+
entry.endedAt = timestamp(at)
|
|
288
|
+
entry.stopReason = textOrNull(stopReason)
|
|
289
|
+
return touch(entry, entry.endedAt)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function recordWorktreeState(childId, patch) {
|
|
293
|
+
if (patch == null || typeof patch !== 'object') return false
|
|
294
|
+
const entry = lookup({ childId, parentId: patch.parentId })
|
|
295
|
+
const worktree = entry?.worktree
|
|
296
|
+
if (!worktree || (patch.id !== undefined && patch.id !== worktree.id)) return false
|
|
297
|
+
worktree.state = normalizeWorktreeState(patch.state) ?? worktree.state
|
|
298
|
+
if (Number.isSafeInteger(patch.commits) && patch.commits >= 0) worktree.commits = patch.commits
|
|
299
|
+
if (typeof patch.dirty === 'boolean') worktree.dirty = patch.dirty
|
|
300
|
+
if (patch.mergeCommit === null || isId(patch.mergeCommit)) worktree.mergeCommit = patch.mergeCommit
|
|
301
|
+
if (Array.isArray(patch.conflictFiles)) {
|
|
302
|
+
worktree.conflictFiles = patch.conflictFiles.filter((file) => typeof file === 'string')
|
|
303
|
+
}
|
|
304
|
+
if (typeof patch.locked === 'boolean') worktree.locked = patch.locked
|
|
305
|
+
return touch(entry, timestamp(patch.at))
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function recordAudit(event, report, metadata) {
|
|
309
|
+
// Legacy callers supply flat evidence; Git settlement may also supply the raw audit.
|
|
310
|
+
const evidence = typeof event === 'string' ? { ...metadata, childId: event } : event
|
|
311
|
+
const audit = report ?? evidence.audit
|
|
312
|
+
const { childId, runId, baselineId, passed, incomplete, unmanaged, violations, summary,
|
|
313
|
+
isolation, git, at, parentId } = { ...audit, ...evidence }
|
|
314
|
+
const entry = lookup({ childId, parentId })
|
|
315
|
+
if (!entry || (isId(runId) && entry.runId && entry.runId !== runId) ||
|
|
316
|
+
(isId(baselineId) && entry.baselineId && entry.baselineId !== baselineId)) return false
|
|
317
|
+
const rows = Array.isArray(violations) ? violations : []
|
|
318
|
+
entry.baselineId ??= idOrNull(baselineId)
|
|
319
|
+
entry.incomplete = incomplete === true || (incomplete === undefined && git != null &&
|
|
320
|
+
(summary?.truncated === true || rows.some((row) => row?.code === 'audit-incomplete')))
|
|
321
|
+
if (unmanaged === true) {
|
|
322
|
+
entry.auditState = 'unmanaged'
|
|
323
|
+
} else {
|
|
324
|
+
entry.auditState = !entry.incomplete && isId(baselineId) && passed === true ? 'passed' : 'failed'
|
|
325
|
+
}
|
|
326
|
+
entry.violations = rows.slice(0, maxViolations).map(copyViolation)
|
|
327
|
+
entry.truncatedViolations = Math.max(0, rows.length - maxViolations)
|
|
328
|
+
entry.auditedAt = timestamp(at)
|
|
329
|
+
entry.auditSummary = textOrNull(summary)
|
|
330
|
+
if (git != null && entry.worktree) {
|
|
331
|
+
entry.worktree.commits = git.commits?.length ?? 0
|
|
332
|
+
entry.worktree.dirty = (git.dirtyFiles?.length ?? 0) > 0
|
|
333
|
+
}
|
|
334
|
+
const explicitIsolation = copyMetadata(audit?.isolationLevel || evidence.isolationLevel || isolation)
|
|
335
|
+
entry.isolation = explicitIsolation ?? (git != null || entry.worktree
|
|
336
|
+
? entry.isolation
|
|
337
|
+
: entry.auditState === 'unmanaged' ? null : DEFAULT_ISOLATION)
|
|
338
|
+
return touch(entry, entry.auditedAt)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function recordLeaseReleased({ childId, leaseId, at, parentId }) {
|
|
342
|
+
const entry = lookup({ childId, parentId })
|
|
343
|
+
if (!entry || (leaseId != null && leaseId !== entry.leaseId)) return false
|
|
344
|
+
entry.leaseState = 'released'
|
|
345
|
+
entry.releasedAt = timestamp(at)
|
|
346
|
+
return touch(entry, entry.releasedAt)
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function markAuditDelivered({ childId, via, parentId }) {
|
|
350
|
+
const entry = lookup({ childId, parentId })
|
|
351
|
+
if (!entry || via !== 'inline-pre-step') return false
|
|
352
|
+
entry.auditDeliveredVia = via
|
|
353
|
+
return touch(entry, timestamp())
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function get(parentId, childId) {
|
|
357
|
+
const entry = parents.get(parentId)?.get(childId)
|
|
358
|
+
return entry ? snapshot(entry) : null
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function queryParent(parentId, { childId, includeCompleted = true, limit = 20 } = {}) {
|
|
362
|
+
const records = parents.get(parentId)
|
|
363
|
+
const entry = records?.get(childId)
|
|
364
|
+
const entries = childId === undefined ? [...(records?.values() ?? [])] : entry ? [entry] : []
|
|
365
|
+
const filtered = includeCompleted ? entries : entries.filter((item) => item.dispatchState !== 'ended')
|
|
366
|
+
const counts = {
|
|
367
|
+
running: 0, endedPendingAudit: 0, auditPassed: 0, auditFailed: 0, auditUnmanaged: 0, worktreePendingReview: 0,
|
|
368
|
+
}
|
|
369
|
+
for (const item of filtered) {
|
|
370
|
+
const state = item.worktree?.state
|
|
371
|
+
if (state === 'ready_for_review' || state === 'merge_conflict') counts.worktreePendingReview += 1
|
|
372
|
+
if (item.dispatchState !== 'ended') counts.running += 1
|
|
373
|
+
else if (item.auditState === 'pending') counts.endedPendingAudit += 1
|
|
374
|
+
else if (item.auditState === 'passed') counts.auditPassed += 1
|
|
375
|
+
else if (item.auditState === 'failed') counts.auditFailed += 1
|
|
376
|
+
else counts.auditUnmanaged += 1
|
|
377
|
+
}
|
|
378
|
+
const items = filtered.reverse()
|
|
379
|
+
.sort((left, right) => queryPriority(left) - queryPriority(right) || newestFirst(left, right))
|
|
380
|
+
.slice(0, limit)
|
|
381
|
+
.map(snapshot)
|
|
382
|
+
return { parentId, total: filtered.length, counts, items }
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function listAttentionItems(parentId) {
|
|
386
|
+
return [...(parents.get(parentId)?.values() ?? [])].reverse()
|
|
387
|
+
.filter(needsAttention)
|
|
388
|
+
.sort(newestFirst)
|
|
389
|
+
.map(snapshot)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
return {
|
|
393
|
+
recordDispatched, recordRunStarted, recordRetry, recordDisposed, recordEnded, recordAudit,
|
|
394
|
+
recordLeaseReleased, markAuditDelivered, recordWorktreeState,
|
|
395
|
+
get, queryParent, listAttentionItems, exportEntries, hydrateEntries,
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function worktreeDeliveryNotice(worktree, passed) {
|
|
400
|
+
const id = worktree?.id ?? '未知'
|
|
401
|
+
if (worktree?.state === 'discarded') {
|
|
402
|
+
return worktree.mergeCommit ? `工作树 ${id} 已清理,其交付物此前已合回。`
|
|
403
|
+
: `工作树 ${id} 的交付物已丢弃,未合回主仓。`
|
|
404
|
+
}
|
|
405
|
+
if (worktree?.state === 'merged' || (worktree?.state === 'cleanup_failed' && worktree.mergeCommit)) {
|
|
406
|
+
return `工作树 ${id} 的交付物已合回。`
|
|
407
|
+
}
|
|
408
|
+
return passed
|
|
409
|
+
? `交付物保留在工作树 ${id},尚未合回主仓,请调用 worktree_manage 执行 inspect / merge / discard。`
|
|
410
|
+
: `违规现场保留在工作树 ${id},尚未合回主仓;请先调用 worktree_manage 执行 inspect 核查。`
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Render same-frame evidence without implying that a logical audit is a sandbox. */
|
|
414
|
+
export function formatInlineAuditNotice(records) {
|
|
415
|
+
const entries = Array.isArray(records) ? records
|
|
416
|
+
: records == null ? [] : [{ childId: records.childId, entry: records.entry ?? records }]
|
|
417
|
+
const lines = []
|
|
418
|
+
for (const { childId, entry } of entries) {
|
|
419
|
+
const prefix = `【${childId}】` + (entry?.agentName ? `(${entry.agentName})` : '')
|
|
420
|
+
const baseline = entry?.baselineId ?? '无'
|
|
421
|
+
const worktree = entry?.worktree
|
|
422
|
+
const isolated = entry?.isolation === WORKTREE_ISOLATION || worktree != null
|
|
423
|
+
const branch = worktree?.branch ?? '未知'
|
|
424
|
+
switch (entry?.auditState) {
|
|
425
|
+
case 'passed':
|
|
426
|
+
if (isolated) {
|
|
427
|
+
const changes = `新增提交 ${worktree?.commits ?? 0} 个${worktree?.dirty ? ',含未提交改动' : ''}`
|
|
428
|
+
lines.push(`${prefix}写作用域审计已通过(基线 ${baseline};git-worktree 独立检出,分支 ${branch},${changes})。` +
|
|
429
|
+
worktreeDeliveryNotice(worktree, true))
|
|
430
|
+
} else {
|
|
431
|
+
lines.push(`${prefix}写作用域审计已通过(基线 ${baseline};${entry.readOnly ? '只读逻辑审计' : '作用域内变更'})。`)
|
|
432
|
+
}
|
|
433
|
+
break
|
|
434
|
+
case 'failed': {
|
|
435
|
+
const violations = entry.violations ?? []
|
|
436
|
+
const omitted = entry.truncatedViolations
|
|
437
|
+
const count = `${violations.length + (Number.isInteger(omitted) ? omitted : 0)}${omitted === true ? '+' : ''}`
|
|
438
|
+
const isolation = isolated ? `;git-worktree 工作树 ${worktree?.id ?? '未知'},分支 ${branch}` : ''
|
|
439
|
+
lines.push(`${prefix}不得验收为通过。写作用域审计未通过(基线 ${baseline},${count} 项${isolation}):`)
|
|
440
|
+
for (const row of violations) {
|
|
441
|
+
const kind = row.kind ?? row.code ?? '违规'
|
|
442
|
+
const detail = row.detail ?? row.reason
|
|
443
|
+
const path = row.path ? `:${JSON.stringify(row.path)}` : ''
|
|
444
|
+
lines.push(`- ${kind}${path}${detail ? `(${JSON.stringify(detail)})` : ''}`)
|
|
445
|
+
}
|
|
446
|
+
if (omitted) lines.push(Number.isInteger(omitted) ? `另有 ${omitted} 项未列出。` : '其余违规未列出。')
|
|
447
|
+
if (entry.incomplete) lines.push('审计采样不完整或超限。')
|
|
448
|
+
lines.push(isolated ? worktreeDeliveryNotice(worktree)
|
|
449
|
+
: 'logical-post-audit:只做工作区逻辑写后审计,不是物理隔离;不能阻止写入、覆盖工作区外或区分并发写入者。')
|
|
450
|
+
break
|
|
451
|
+
}
|
|
452
|
+
case 'pending':
|
|
453
|
+
lines.push(isolated
|
|
454
|
+
? `${prefix}执行已结束,但 git-worktree 工作树 ${worktree?.id ?? '未知'}(分支 ${branch})的写作用域审计仍为 pending(尚未结算),不得直接验收通过;验收前请调用 delegate_status 核验终态。`
|
|
455
|
+
: `${prefix}执行已结束,但写作用域审计仍为 pending(尚未结算),不得直接验收通过;验收前请调用 delegate_status 核验终态。`)
|
|
456
|
+
break
|
|
457
|
+
default:
|
|
458
|
+
lines.push(isolated
|
|
459
|
+
? `${prefix}git-worktree 工作树 ${worktree?.id ?? '未知'}(分支 ${branch})未纳入本插件写作用域审计基线(unmanaged),请调用 worktree_manage 执行 inspect 核查。`
|
|
460
|
+
: `${prefix}未纳入本插件写作用域审计基线(unmanaged),请按需核验工作区变更。`)
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return lines.join('\n')
|
|
464
|
+
}
|
package/lib/tool-surface.js
CHANGED
|
@@ -23,11 +23,31 @@
|
|
|
23
23
|
* — so the transient leak never reaches a request.
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
|
-
import { DELEGATE_TOOL, ORCHESTRATE_TOOL } from './api.js'
|
|
26
|
+
import { DELEGATE_STATUS_TOOL_NAME, DELEGATE_TOOL, ORCHESTRATE_TOOL } from './api.js'
|
|
27
27
|
import { viewNames } from './catalog.js'
|
|
28
|
-
import {
|
|
28
|
+
import { isDelegatedChild, resolveEffectiveAllowedTools } from './gate.js'
|
|
29
29
|
import { RUN_CODE_TOOL } from './run-code-guard.js'
|
|
30
30
|
|
|
31
|
+
export { DEFAULT_BLOCKED_NATIVE_TOOLS, NATIVE_TEAM_TOOLS, resolveEffectiveAllowedTools } from './gate.js'
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The shipped main-agent whitelist while dispatch mode is on. The Web client mirrors
|
|
35
|
+
* this order. Delegation remains event-driven: use the completion notice, not `wait_agent`.
|
|
36
|
+
*/
|
|
37
|
+
export const DEFAULT_ALLOWED_TOOLS = [
|
|
38
|
+
// Delegation, audit and worker control
|
|
39
|
+
'delegate',
|
|
40
|
+
'orchestrate',
|
|
41
|
+
'delegate_status',
|
|
42
|
+
'worktree_manage',
|
|
43
|
+
'send_message',
|
|
44
|
+
'interrupt_agent',
|
|
45
|
+
// Planning, user clarification & context compression
|
|
46
|
+
'todo_write',
|
|
47
|
+
'ask_user_question',
|
|
48
|
+
'compress',
|
|
49
|
+
]
|
|
50
|
+
|
|
31
51
|
/**
|
|
32
52
|
* The official tool a `dsh-ops` replacement stands in for, used only when both are
|
|
33
53
|
* registered. `bash`/`pwsh` are deliberately absent: whether `pwsh` is hidden is a user
|
|
@@ -41,6 +61,9 @@ export const OFFICIAL_SHADOW = Object.freeze([
|
|
|
41
61
|
|
|
42
62
|
/** One wrapper per tool service, so a second install is a no-op with the same disposer. */
|
|
43
63
|
const SURFACE = Symbol.for('dsh-orchestrator.toolSurface')
|
|
64
|
+
// Cordis exports this as symbols.original. Use its global key without adding a dependency.
|
|
65
|
+
const CORDIS_ORIGINAL = Symbol.for('cordis.original')
|
|
66
|
+
const ROOT_ONLY_TOOLS = new Set([DELEGATE_STATUS_TOOL_NAME, 'worktree_manage'])
|
|
44
67
|
|
|
45
68
|
/** A name a definition carries, or `''` for a shape this wrapper does not understand. */
|
|
46
69
|
function nameOf(definition) {
|
|
@@ -52,25 +75,35 @@ function nameOf(definition) {
|
|
|
52
75
|
* Install the filtering wrapper on `tools.definitions`.
|
|
53
76
|
*
|
|
54
77
|
* `allowed` is the live Allowed Tools whitelist (a plain array is accepted too), `enabled`
|
|
55
|
-
* is the dispatch switch and `workerDeny` the names a delegated child must not see.
|
|
56
|
-
*
|
|
57
|
-
*
|
|
78
|
+
* is the dispatch switch and `workerDeny` the names a delegated child must not see.
|
|
79
|
+
* `delegate_status` and `worktree_manage` are root-only in either mode, including with a
|
|
80
|
+
* custom deny list.
|
|
81
|
+
* `allowAgentTeam` is a boolean or live getter for the optional root task board. The call
|
|
82
|
+
* returns a disposer that restores the original `definitions`; a second install on the same
|
|
83
|
+
* service hands back the first disposer instead of stacking wrappers.
|
|
58
84
|
*/
|
|
59
85
|
export function installToolSurface({
|
|
60
86
|
tools,
|
|
61
87
|
allowed,
|
|
88
|
+
allowAgentTeam = true,
|
|
62
89
|
enabled = () => true,
|
|
63
90
|
workerDeny = [DELEGATE_TOOL, ORCHESTRATE_TOOL],
|
|
64
91
|
disabledDeny = [DELEGATE_TOOL, ORCHESTRATE_TOOL],
|
|
65
92
|
shadow = OFFICIAL_SHADOW,
|
|
66
93
|
} = {}) {
|
|
67
|
-
|
|
68
|
-
|
|
94
|
+
// Cordis returns a new method proxy on every ordinary get. Patch the actual service so
|
|
95
|
+
// neither the saved method nor the ownership check depends on the caller's context proxy.
|
|
96
|
+
const target = tools?.[CORDIS_ORIGINAL] ?? tools
|
|
97
|
+
if (target === undefined || target === null) return () => {}
|
|
98
|
+
const installed = target[SURFACE]
|
|
69
99
|
if (installed !== undefined) return installed.dispose
|
|
70
100
|
|
|
71
|
-
const
|
|
72
|
-
const
|
|
73
|
-
|
|
101
|
+
const originalDescriptor = Object.getOwnPropertyDescriptor(target, 'definitions')
|
|
102
|
+
const original = target.definitions
|
|
103
|
+
if (typeof original !== 'function') return () => {}
|
|
104
|
+
const liveAllowed = typeof allowed === 'function' ? allowed : () => allowed
|
|
105
|
+
const liveAllowAgentTeam = typeof allowAgentTeam === 'function' ? allowAgentTeam : () => allowAgentTeam
|
|
106
|
+
const deny = new Set([...ROOT_ONLY_TOOLS, ...(workerDeny ?? [])])
|
|
74
107
|
const offDeny = new Set(disabledDeny ?? [])
|
|
75
108
|
const pairs = (shadow ?? []).filter((entry) => Array.isArray(entry) && entry.length === 2)
|
|
76
109
|
|
|
@@ -104,7 +137,8 @@ export function installToolSurface({
|
|
|
104
137
|
}
|
|
105
138
|
|
|
106
139
|
const mainSurface = (list, present) => {
|
|
107
|
-
|
|
140
|
+
// The plugin entry supplies the shipped defaults via `allowed`; omitted values share the gate's empty base.
|
|
141
|
+
const allow = new Set(resolveEffectiveAllowedTools(liveAllowed(), { allowAgentTeam: liveAllowAgentTeam() }))
|
|
108
142
|
const shadowed = shadowedOf(present)
|
|
109
143
|
return list.filter((definition) => {
|
|
110
144
|
const name = nameOf(definition)
|
|
@@ -126,32 +160,46 @@ export function installToolSurface({
|
|
|
126
160
|
})
|
|
127
161
|
}
|
|
128
162
|
|
|
163
|
+
let disposed = false
|
|
129
164
|
const definitions = function definitions(scope, toolSet) {
|
|
130
|
-
|
|
131
|
-
|
|
165
|
+
if (disposed) return original.call(this, scope, toolSet)
|
|
166
|
+
// Keep the host's calling context; a detached call falls back to the raw service.
|
|
167
|
+
const service = this ?? target
|
|
132
168
|
const list = original.call(service, scope, toolSet)
|
|
133
169
|
if (!Array.isArray(list)) return list
|
|
134
170
|
// The context-global view feeds the Allowed Tools panel: it must stay complete.
|
|
135
171
|
if (scope === undefined || scope === null) return list
|
|
172
|
+
const delegated = isDelegatedChild(scope)
|
|
136
173
|
if (!enabled()) {
|
|
137
|
-
if (offDeny.size === 0) return list
|
|
174
|
+
if (!delegated && offDeny.size === 0) return list
|
|
138
175
|
return list.filter((definition) => {
|
|
139
176
|
const name = nameOf(definition)
|
|
140
|
-
return name === '' || !offDeny.has(name)
|
|
177
|
+
return name === '' || (!offDeny.has(name) && !(delegated && ROOT_ONLY_TOOLS.has(name)))
|
|
141
178
|
})
|
|
142
179
|
}
|
|
143
180
|
const present = presentNames(service, scope, list)
|
|
144
|
-
return
|
|
181
|
+
return delegated ? workerSurface(list, present) : mainSurface(list, present)
|
|
145
182
|
}
|
|
146
183
|
|
|
147
|
-
tools.definitions = definitions
|
|
148
|
-
let disposed = false
|
|
149
184
|
const dispose = () => {
|
|
150
185
|
if (disposed) return
|
|
151
186
|
disposed = true
|
|
152
|
-
|
|
153
|
-
|
|
187
|
+
try {
|
|
188
|
+
// A third party may still call this wrapper. Leave its outer method intact.
|
|
189
|
+
if (Object.getOwnPropertyDescriptor(target, 'definitions')?.value === definitions) {
|
|
190
|
+
if (originalDescriptor === undefined) delete target.definitions
|
|
191
|
+
else Object.defineProperty(target, 'definitions', originalDescriptor)
|
|
192
|
+
}
|
|
193
|
+
} finally {
|
|
194
|
+
if (target[SURFACE]?.dispose === dispose) delete target[SURFACE]
|
|
195
|
+
}
|
|
154
196
|
}
|
|
155
|
-
|
|
197
|
+
Object.defineProperty(target, 'definitions', {
|
|
198
|
+
value: definitions,
|
|
199
|
+
configurable: originalDescriptor?.configurable ?? true,
|
|
200
|
+
enumerable: originalDescriptor?.enumerable ?? true,
|
|
201
|
+
writable: originalDescriptor?.writable ?? true,
|
|
202
|
+
})
|
|
203
|
+
target[SURFACE] = { dispose }
|
|
156
204
|
return dispose
|
|
157
205
|
}
|