@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/rules.js
CHANGED
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* native `subagent` and `workflow`), so the rule can assume a main-agent reader.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
+
import { DELEGATE_STATUS_TOOL_NAME } from './api.js'
|
|
14
|
+
|
|
13
15
|
/**
|
|
14
16
|
* Build the rule text. `allowedTools` is the live whitelist the gate enforces,
|
|
15
17
|
* so the closing sentence names exactly what stays available.
|
|
@@ -19,8 +21,19 @@ export function mainAgentRule(allowedTools) {
|
|
|
19
21
|
const allowedNames = allowed.join(', ')
|
|
20
22
|
return (
|
|
21
23
|
'主代理规则:主代理只负责规划,读/写/编辑/搜索/命令/抓取均通过 delegate 或 orchestrate 交子代理执行,勿试探调用被禁工具。' +
|
|
22
|
-
'
|
|
23
|
-
'
|
|
24
|
+
'同任务报错重试、参数纠偏、小幅返工或追问,优先用 send_message 复用原代理;仅在 writeScope 需变更、Worktree 已锁定、原上下文严重跑偏或无法继续时才新开 delegate。' +
|
|
25
|
+
'已结束的写任务续跑前重抢原写租约并拍新基线,租约冲突或工作树已锁定时拒绝投递;本轮结束后写审计并再次释放租约。' +
|
|
26
|
+
'新会话或压缩后直接推进,无需重新确认。' +
|
|
27
|
+
'独立任务在同一消息内并发派发,delegate 完成后直接结束回合等待子代理完成,勿空转轮询状态。' +
|
|
28
|
+
'子代理完成通知只代表执行结束,不等于写作用域审计通过。' +
|
|
29
|
+
(allowed.includes(DELEGATE_STATUS_TOOL_NAME)
|
|
30
|
+
? `若未见同帧审计通过确认,验收前按需调用一次 ${DELEGATE_STATUS_TOOL_NAME} 核验审计状态(pending / passed / failed);只有 passed 才确认通过,勿盲等或循环轮询。`
|
|
31
|
+
: '') +
|
|
32
|
+
'Git 仓库的写任务默认在独立 Git Worktree 中执行,用 git diff / git log 审计;非 Git 目录自动降级为逻辑写后审计。可用 isolation: "auto" | "worktree" | "shared" 覆盖。' +
|
|
33
|
+
'Worktree 不自动合回;执行结束、写审计通过、主代理合回是三步。' +
|
|
34
|
+
(allowed.includes('worktree_manage')
|
|
35
|
+
? '用 worktree_manage(list / inspect / merge / discard / prune)显式评审、合回或清理。'
|
|
36
|
+
: '') +
|
|
24
37
|
'子代理无收尾中断时插件会自动重试,期间勿重派;提示停止重试时按通知询问用户。' +
|
|
25
38
|
'provider/model/reasoning_effort 仅在用户当前消息或 AGENTS.md 等工作区指令中显式指定时才传,否则全部省略;当前消息点名仅限本次派发,工作区指令指定的按其持续生效,两者冲突以当前消息为准;严禁复用历史轮次或摘要中的模型。' +
|
|
26
39
|
(allowedNames === ''
|
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer'
|
|
2
|
+
|
|
3
|
+
const DOMAIN_NAME = /^[a-z][a-z0-9_]*$/
|
|
4
|
+
const RECORD_KEY = /^(?:k|u)_[a-zA-Z0-9_-]*$/
|
|
5
|
+
const INITIAL_GLOBAL = Object.freeze({ schemaVersion: 1, generation: 0, updatedAt: 0 })
|
|
6
|
+
const DEFAULT_LIMITS = Object.freeze({
|
|
7
|
+
maxTerminalDelegates: 256,
|
|
8
|
+
maxDoneActions: 512,
|
|
9
|
+
maxClosedWorktrees: 256,
|
|
10
|
+
terminalTtlMs: 7 * 24 * 3600 * 1000,
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
const isId = (value) => typeof value === 'string' && value.length > 0
|
|
14
|
+
const isText = (value) => typeof value === 'string'
|
|
15
|
+
const isBoolean = (value) => typeof value === 'boolean'
|
|
16
|
+
const isCount = (value) => Number.isSafeInteger(value) && value >= 0
|
|
17
|
+
const isTime = (value) => Number.isFinite(value) && value >= 0
|
|
18
|
+
const isListOf = (check) => (value) => Array.isArray(value) && Array.from(value).every(check)
|
|
19
|
+
const isTextList = isListOf(isText)
|
|
20
|
+
const isIdList = isListOf(isId)
|
|
21
|
+
|
|
22
|
+
function isObject(value) {
|
|
23
|
+
if (value === null || typeof value !== 'object') return false
|
|
24
|
+
const prototype = Object.getPrototypeOf(value)
|
|
25
|
+
return prototype === Object.prototype || prototype === null
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const isLeaseEntries = isListOf((entry) => isObject(entry) && isId(entry.path) &&
|
|
29
|
+
isId(entry.key) && ['file', 'dir', 'root'].includes(entry.kind))
|
|
30
|
+
|
|
31
|
+
const TABLES = {
|
|
32
|
+
worktrees: {
|
|
33
|
+
key: 'id',
|
|
34
|
+
fields: {
|
|
35
|
+
parentId: isText, childId: isText, childIds: isIdList, batchId: isText, itemIndex: isCount,
|
|
36
|
+
repoRoot: isText, sourceCwd: isText, subPath: isText, worktreePath: isText, execCwd: isText,
|
|
37
|
+
branch: isText, baseBranch: isText, baseCommit: isText, label: isText, state: isId,
|
|
38
|
+
mergeCommit: isText, cleaned: isBoolean, locked: isBoolean, createdAt: isTime,
|
|
39
|
+
updatedAt: isTime, auditSummary: (value) => isText(value) || isObject(value),
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
delegates: {
|
|
43
|
+
key: 'childId',
|
|
44
|
+
fields: {
|
|
45
|
+
parentId: isText, rootSessionId: isText, agentName: isId, label: isText, cwd: isText, readOnly: isBoolean,
|
|
46
|
+
writeScope: isTextList, expectedTargets: isTextList, batchId: isText, itemIndex: isCount,
|
|
47
|
+
stageIndex: isCount, worktreeId: isText, leaseId: isText, attemptSeq: isCount, runId: isText,
|
|
48
|
+
dispatchState: isId, stopReason: isText, baselineId: isText, auditState: isId,
|
|
49
|
+
incomplete: isBoolean, auditDeliveredVia: isText, startedAt: isTime, endedAt: isTime,
|
|
50
|
+
updatedAt: isTime, retry: isObject, watchCursor: isObject,
|
|
51
|
+
gitBaseline: isObject, auditSummary: isText, violations: isListOf(isObject), wakeActionKey: isText,
|
|
52
|
+
truncatedViolations: isCount, disposedAt: isTime, auditedAt: isTime, releasedAt: isTime,
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
leases: {
|
|
56
|
+
key: 'leaseId',
|
|
57
|
+
fields: {
|
|
58
|
+
ownerKind: isText, ownerId: isText, parentId: isText, entries: isLeaseEntries,
|
|
59
|
+
issuedAt: isTime, expiresAt: isTime, baselineId: isText,
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
actions: {
|
|
63
|
+
key: 'key',
|
|
64
|
+
fields: {
|
|
65
|
+
kind: isId, phase: (value) => ['prepared', 'accepted', 'unknown', 'done'].includes(value),
|
|
66
|
+
rootSessionId: isText, parentId: isText, childId: isText, runId: isText, attemptSeq: isCount,
|
|
67
|
+
requestId: isText, messageId: isText, detail: () => true, createdAt: isTime, updatedAt: isTime,
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
}
|
|
71
|
+
const TABLE_NAMES = Object.keys(TABLES)
|
|
72
|
+
|
|
73
|
+
/** Distinguish malformed UTF-16 from valid Unicode, without losing any JS code units. */
|
|
74
|
+
export function encodeRecordKey(rawKey) {
|
|
75
|
+
if (!isText(rawKey)) throw new TypeError('record key must be a string')
|
|
76
|
+
return rawKey.isWellFormed()
|
|
77
|
+
? `k_${Buffer.from(rawKey, 'utf8').toString('base64url')}`
|
|
78
|
+
: `u_${Buffer.from(rawKey, 'utf16le').toString('base64url')}`
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function decodeRecordKey(encodedKey) {
|
|
82
|
+
if (!isText(encodedKey) || !RECORD_KEY.test(encodedKey)) {
|
|
83
|
+
throw new TypeError('invalid encoded record key')
|
|
84
|
+
}
|
|
85
|
+
const rawKey = Buffer.from(encodedKey.slice(2), 'base64url')
|
|
86
|
+
.toString(encodedKey.startsWith('k_') ? 'utf8' : 'utf16le')
|
|
87
|
+
// Buffer accepts non-canonical Base64 and replaces malformed UTF-8.
|
|
88
|
+
if (encodeRecordKey(rawKey) !== encodedKey) throw new TypeError('invalid encoded record key')
|
|
89
|
+
return rawKey
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function copyJson(value, ancestors = new Set()) {
|
|
93
|
+
if (value === null || isText(value) || isBoolean(value) || Number.isFinite(value)) return value
|
|
94
|
+
if ((!Array.isArray(value) && !isObject(value)) || ancestors.has(value)) {
|
|
95
|
+
throw new TypeError('expected plain JSON data')
|
|
96
|
+
}
|
|
97
|
+
ancestors.add(value)
|
|
98
|
+
const copy = Array.isArray(value)
|
|
99
|
+
? Array.from(value, (item) => copyJson(item, ancestors))
|
|
100
|
+
: Object.fromEntries(Object.entries(value)
|
|
101
|
+
.filter(([, item]) => item !== undefined)
|
|
102
|
+
.map(([key, item]) => [key, copyJson(item, ancestors)]))
|
|
103
|
+
ancestors.delete(value)
|
|
104
|
+
return copy
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function normalizeRecord(table, value) {
|
|
108
|
+
const { key, fields } = TABLES[table]
|
|
109
|
+
if (!isObject(value) || value.__corrupt === true || !Object.hasOwn(value, key) || !isId(value[key])) {
|
|
110
|
+
throw new TypeError(`${table}.${key} must be a non-empty string in a plain record`)
|
|
111
|
+
}
|
|
112
|
+
const record = { [key]: value[key] }
|
|
113
|
+
for (const [field, check] of Object.entries(fields)) {
|
|
114
|
+
if (!Object.hasOwn(value, field)) continue
|
|
115
|
+
const item = value[field]
|
|
116
|
+
if (item === undefined) continue
|
|
117
|
+
if (item !== null && !check(item)) throw new TypeError(`invalid ${table}.${field}`)
|
|
118
|
+
record[field] = copyJson(item)
|
|
119
|
+
}
|
|
120
|
+
return record
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function tableSpec(table) {
|
|
124
|
+
return {
|
|
125
|
+
valueSchema: {
|
|
126
|
+
parse(raw) {
|
|
127
|
+
try {
|
|
128
|
+
return normalizeRecord(table, raw)
|
|
129
|
+
} catch {
|
|
130
|
+
// Single JSON units cannot back up individual rows. Skip the value, not the domain.
|
|
131
|
+
return { __corrupt: true, rawType: typeof raw }
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function isGlobal(raw) {
|
|
139
|
+
return isObject(raw) && raw.schemaVersion === INITIAL_GLOBAL.schemaVersion &&
|
|
140
|
+
isCount(raw.generation) && isTime(raw.updatedAt)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function domainSpec(name, onInvalidGlobal) {
|
|
144
|
+
const schema = {
|
|
145
|
+
parse(raw) {
|
|
146
|
+
if (raw === null) throw new Error('global cannot be null')
|
|
147
|
+
if (isGlobal(raw)) {
|
|
148
|
+
return { schemaVersion: raw.schemaVersion, generation: raw.generation, updatedAt: raw.updatedAt }
|
|
149
|
+
}
|
|
150
|
+
onInvalidGlobal()
|
|
151
|
+
return { ...INITIAL_GLOBAL }
|
|
152
|
+
},
|
|
153
|
+
safeParse(raw) {
|
|
154
|
+
try {
|
|
155
|
+
return { success: true, data: schema.parse(raw) }
|
|
156
|
+
} catch (error) {
|
|
157
|
+
return { success: false, error }
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
name,
|
|
163
|
+
version: INITIAL_GLOBAL.schemaVersion,
|
|
164
|
+
layout: 'single',
|
|
165
|
+
tables: Object.fromEntries(TABLE_NAMES.map((table) => [table, tableSpec(table)])),
|
|
166
|
+
global: { schema, initial: { ...INITIAL_GLOBAL } },
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const isTombstone = (record) => record.locked === true || record.cleaned === true ||
|
|
171
|
+
Boolean(record.mergeCommit) || record.state === 'merged' || record.state === 'discarded'
|
|
172
|
+
const OPEN_WORKTREE_STATES = new Set([
|
|
173
|
+
'active', 'ready', 'cleanup-failed', 'ready_for_review', 'cleanup_failed', 'merge_conflict',
|
|
174
|
+
])
|
|
175
|
+
const CLOSED_WORKTREE_STATES = new Set(['closed', 'merged', 'discarded'])
|
|
176
|
+
const needsWorktreeReview = (record) => record.state === 'discarded'
|
|
177
|
+
? record.cleaned === false
|
|
178
|
+
: !CLOSED_WORKTREE_STATES.has(record.state) || record.cleaned !== true ||
|
|
179
|
+
!(record.state === 'merged' || record.mergeCommit)
|
|
180
|
+
const TERMINAL_DISPATCH_STATES = new Set([
|
|
181
|
+
'ended', 'completed', 'interrupted', 'aborted', 'failed', 'lost',
|
|
182
|
+
])
|
|
183
|
+
|
|
184
|
+
function lastTouched(record) {
|
|
185
|
+
return record.updatedAt ?? record.endedAt ?? record.createdAt ?? record.startedAt
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function historyKeys(records, max, cutoff) {
|
|
189
|
+
const retained = []
|
|
190
|
+
const expired = []
|
|
191
|
+
for (const [id, record] of records) {
|
|
192
|
+
const timestamp = lastTouched(record)
|
|
193
|
+
if (timestamp !== undefined && timestamp <= cutoff) expired.push(id)
|
|
194
|
+
else retained.push([id, timestamp ?? Number.NEGATIVE_INFINITY])
|
|
195
|
+
}
|
|
196
|
+
retained.sort(([, left], [, right]) => right - left)
|
|
197
|
+
return [...expired, ...retained.slice(max).map(([id]) => id)]
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** One store per plugin instance. Reads return detached data; writes settle after durability. */
|
|
201
|
+
export function createStateStore({
|
|
202
|
+
ctx, facility, domainName = 'dsh_orchestrator_state', logger, limits, now = Date.now,
|
|
203
|
+
} = {}) {
|
|
204
|
+
if (!isText(domainName) || !DOMAIN_NAME.test(domainName) || /\s/.test(domainName)) {
|
|
205
|
+
throw new TypeError('invalid storage domain name')
|
|
206
|
+
}
|
|
207
|
+
const records = Object.fromEntries(TABLE_NAMES.map((table) => [table, new Map()]))
|
|
208
|
+
const handles = Object.create(null)
|
|
209
|
+
let domain
|
|
210
|
+
let generation = 0
|
|
211
|
+
let corruptCount = 0
|
|
212
|
+
let unsafeState = false
|
|
213
|
+
let opened = false
|
|
214
|
+
let closing = false
|
|
215
|
+
let openPromise
|
|
216
|
+
let closePromise
|
|
217
|
+
let writeChain = Promise.resolve()
|
|
218
|
+
|
|
219
|
+
function warn(message) {
|
|
220
|
+
try {
|
|
221
|
+
logger?.warn?.(`orchestrator: state store: ${message}`)
|
|
222
|
+
} catch {
|
|
223
|
+
// Logging must not prevent fallback or teardown.
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function currentTime() {
|
|
228
|
+
const value = now()
|
|
229
|
+
if (!isTime(value)) throw new TypeError('invalid state store clock')
|
|
230
|
+
return value
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function hydrate(candidate, spec) {
|
|
234
|
+
const loaded = Object.fromEntries(TABLE_NAMES.map((table) => [table, new Map()]))
|
|
235
|
+
const candidateHandles = Object.create(null)
|
|
236
|
+
let skipped = 0
|
|
237
|
+
for (const table of TABLE_NAMES) {
|
|
238
|
+
const handle = candidate.table(table)
|
|
239
|
+
candidateHandles[table] = handle
|
|
240
|
+
for (const [encoded, value] of handle.entries()) {
|
|
241
|
+
const record = spec.tables[table].valueSchema.parse(value)
|
|
242
|
+
const id = record[TABLES[table].key]
|
|
243
|
+
if (record.__corrupt || encodeRecordKey(id) !== encoded) {
|
|
244
|
+
skipped += 1
|
|
245
|
+
continue
|
|
246
|
+
}
|
|
247
|
+
loaded[table].set(id, record)
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return { loaded, candidateHandles, skipped }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async function start() {
|
|
254
|
+
let candidate
|
|
255
|
+
try {
|
|
256
|
+
const storage = facility ?? ctx?.get?.('storageDomain')
|
|
257
|
+
if (typeof storage?.open === 'function') {
|
|
258
|
+
const spec = domainSpec(domainName, () => {
|
|
259
|
+
unsafeState = true
|
|
260
|
+
warn('invalid global data; using defaults')
|
|
261
|
+
})
|
|
262
|
+
candidate = await storage.open(spec)
|
|
263
|
+
const { loaded, candidateHandles, skipped } = hydrate(candidate, spec)
|
|
264
|
+
corruptCount = skipped
|
|
265
|
+
if (skipped > 0) {
|
|
266
|
+
unsafeState = true
|
|
267
|
+
warn(`skipped ${skipped} corrupt record(s) while opening ${domainName}`)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const current = spec.global.schema.parse(candidate.global.get())
|
|
271
|
+
const next = {
|
|
272
|
+
schemaVersion: INITIAL_GLOBAL.schemaVersion,
|
|
273
|
+
generation: current.generation + 1,
|
|
274
|
+
updatedAt: currentTime(),
|
|
275
|
+
}
|
|
276
|
+
if (!isGlobal(next)) throw new RangeError('invalid next storage generation')
|
|
277
|
+
// Do not rewrite a single-layout document before a damaged ledger is reviewed.
|
|
278
|
+
if (!unsafeState) await candidate.global.set(next)
|
|
279
|
+
Object.assign(records, loaded)
|
|
280
|
+
Object.assign(handles, candidateHandles)
|
|
281
|
+
generation = next.generation
|
|
282
|
+
domain = candidate
|
|
283
|
+
}
|
|
284
|
+
} catch (error) {
|
|
285
|
+
unsafeState = true
|
|
286
|
+
warn(`cannot open ${domainName}; using memory: ${error instanceof Error ? error.message : String(error)}`)
|
|
287
|
+
if (candidate) {
|
|
288
|
+
try {
|
|
289
|
+
await candidate.close()
|
|
290
|
+
} catch (closeError) {
|
|
291
|
+
warn(`cannot release partially opened ${domainName}: ${String(closeError)}`)
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
if (!domain) generation = 1
|
|
296
|
+
opened = true
|
|
297
|
+
return store
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function open() {
|
|
301
|
+
if (closing) return Promise.resolve(false)
|
|
302
|
+
openPromise ??= Promise.resolve().then(start)
|
|
303
|
+
return openPromise
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function flush() {
|
|
307
|
+
return writeChain
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function close() {
|
|
311
|
+
closing = true
|
|
312
|
+
closePromise ??= Promise.resolve().then(async () => {
|
|
313
|
+
// Opening may already have claimed a host domain; let it finish before releasing it.
|
|
314
|
+
await openPromise
|
|
315
|
+
await flush()
|
|
316
|
+
await domain?.close()
|
|
317
|
+
})
|
|
318
|
+
return closePromise
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function enqueue(write) {
|
|
322
|
+
if (closing || !openPromise) return Promise.resolve(false)
|
|
323
|
+
const pending = writeChain.then(async () => {
|
|
324
|
+
if (!opened) await openPromise
|
|
325
|
+
return write()
|
|
326
|
+
})
|
|
327
|
+
// Observe failures on the tail without turning the caller's failed write into success.
|
|
328
|
+
writeChain = pending.then(() => {}, () => {})
|
|
329
|
+
return pending
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function put(table, value) {
|
|
333
|
+
if (closing || !openPromise) return Promise.resolve(false)
|
|
334
|
+
let record
|
|
335
|
+
try {
|
|
336
|
+
// Capture the input before yielding to the queue; callers may reuse the original object.
|
|
337
|
+
record = normalizeRecord(table, value)
|
|
338
|
+
} catch (error) {
|
|
339
|
+
return enqueue(() => { throw error })
|
|
340
|
+
}
|
|
341
|
+
const id = record[TABLES[table].key]
|
|
342
|
+
return enqueue(async () => {
|
|
343
|
+
await handles[table]?.put(encodeRecordKey(id), copyJson(record))
|
|
344
|
+
records[table].set(id, record)
|
|
345
|
+
return true
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async function remove(table, id) {
|
|
350
|
+
if (!records[table].has(id)) return false
|
|
351
|
+
await handles[table]?.delete(encodeRecordKey(id))
|
|
352
|
+
return records[table].delete(id)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function removeMany(table, ids) {
|
|
356
|
+
const present = [...new Set(ids)].filter((id) => records[table].has(id))
|
|
357
|
+
if (present.length === 0) return 0
|
|
358
|
+
const handle = handles[table]
|
|
359
|
+
if (typeof handle?.deleteMany === 'function') {
|
|
360
|
+
await handle.deleteMany(present.map(encodeRecordKey))
|
|
361
|
+
for (const id of present) records[table].delete(id)
|
|
362
|
+
} else {
|
|
363
|
+
for (const id of present) await remove(table, id)
|
|
364
|
+
}
|
|
365
|
+
return present.length
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function deleteLeases(ids) {
|
|
369
|
+
if (closing || !openPromise) return Promise.resolve(false)
|
|
370
|
+
if (!isIdList(ids)) return enqueue(() => { throw new TypeError('lease IDs must be an array of strings') })
|
|
371
|
+
const keys = [...ids]
|
|
372
|
+
return enqueue(() => removeMany('leases', keys))
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function get(table, id) {
|
|
376
|
+
const record = records[table].get(id)
|
|
377
|
+
return record === undefined ? undefined : copyJson(record)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function list(table) {
|
|
381
|
+
return [...records[table].values()].map((record) => copyJson(record))
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function pruneHistory(options = {}) {
|
|
385
|
+
if (closing || !openPromise) return Promise.resolve(false)
|
|
386
|
+
const settings = { ...limits, ...options }
|
|
387
|
+
const forcePruneTombstones = options?.forcePruneTombstones === true &&
|
|
388
|
+
process.env.NODE_TEST_CONTEXT !== undefined
|
|
389
|
+
return enqueue(async () => {
|
|
390
|
+
const at = settings.now ?? currentTime()
|
|
391
|
+
if (!isTime(at)) throw new TypeError('invalid history pruning time')
|
|
392
|
+
const resolved = Object.fromEntries(Object.entries(DEFAULT_LIMITS).map(([key, initial]) => [
|
|
393
|
+
key, isCount(settings[key]) ? settings[key] : initial,
|
|
394
|
+
]))
|
|
395
|
+
const cutoff = at - resolved.terminalTtlMs
|
|
396
|
+
const protectedChildren = new Set()
|
|
397
|
+
for (const record of records.worktrees.values()) {
|
|
398
|
+
if (!needsWorktreeReview(record)) continue
|
|
399
|
+
if (record.childId) protectedChildren.add(record.childId)
|
|
400
|
+
for (const childId of record.childIds ?? []) protectedChildren.add(childId)
|
|
401
|
+
}
|
|
402
|
+
const delegates = [...records.delegates].filter(([id, record]) => {
|
|
403
|
+
if (!TERMINAL_DISPATCH_STATES.has(record.dispatchState) || record.auditState === 'pending' ||
|
|
404
|
+
(record.auditState === 'failed' && !record.auditDeliveredVia) || protectedChildren.has(id)) return false
|
|
405
|
+
if (!record.worktreeId) return true
|
|
406
|
+
const worktree = records.worktrees.get(record.worktreeId)
|
|
407
|
+
return Boolean(worktree) && !needsWorktreeReview(worktree)
|
|
408
|
+
})
|
|
409
|
+
const worktrees = [...records.worktrees].filter(([, record]) => {
|
|
410
|
+
if (OPEN_WORKTREE_STATES.has(record.state)) return false
|
|
411
|
+
// Explicit escape hatch for unit tests only; never sourced from production limits.
|
|
412
|
+
if (isTombstone(record)) return forcePruneTombstones
|
|
413
|
+
return CLOSED_WORKTREE_STATES.has(record.state)
|
|
414
|
+
})
|
|
415
|
+
const leases = [...records.leases].filter(([, record]) => isTime(record.expiresAt) && record.expiresAt <= at)
|
|
416
|
+
const actions = [...records.actions].filter(([, record]) => record.phase === 'done')
|
|
417
|
+
|
|
418
|
+
return {
|
|
419
|
+
worktrees: await removeMany('worktrees', historyKeys(worktrees, resolved.maxClosedWorktrees, cutoff)),
|
|
420
|
+
delegates: await removeMany('delegates', historyKeys(delegates, resolved.maxTerminalDelegates, cutoff)),
|
|
421
|
+
leases: await removeMany('leases', leases.map(([id]) => id)),
|
|
422
|
+
actions: await removeMany('actions', historyKeys(actions, resolved.maxDoneActions, cutoff)),
|
|
423
|
+
}
|
|
424
|
+
})
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const isPersistent = () => domain !== undefined
|
|
428
|
+
const store = {
|
|
429
|
+
open, close, flush, isPersistent, pruneHistory,
|
|
430
|
+
hasUnsafeState: () => unsafeState,
|
|
431
|
+
getSnapshot: () => ({
|
|
432
|
+
generation, persistent: isPersistent(), corruptCount,
|
|
433
|
+
worktrees: list('worktrees'), delegates: list('delegates'),
|
|
434
|
+
leases: list('leases'), actions: list('actions'),
|
|
435
|
+
}),
|
|
436
|
+
putWorktree: (record) => put('worktrees', record),
|
|
437
|
+
deleteWorktree: (id) => enqueue(() => remove('worktrees', id)),
|
|
438
|
+
getWorktree: (id) => get('worktrees', id),
|
|
439
|
+
listWorktrees: () => list('worktrees'),
|
|
440
|
+
putDelegate: (record) => put('delegates', record),
|
|
441
|
+
deleteDelegate: (id) => enqueue(() => remove('delegates', id)),
|
|
442
|
+
getDelegate: (id) => get('delegates', id),
|
|
443
|
+
listDelegates: () => list('delegates'),
|
|
444
|
+
putLease: (record) => put('leases', record),
|
|
445
|
+
deleteLease: (id) => enqueue(() => remove('leases', id)),
|
|
446
|
+
deleteLeases,
|
|
447
|
+
getLease: (id) => get('leases', id),
|
|
448
|
+
listLeases: () => list('leases'),
|
|
449
|
+
putAction: (record) => put('actions', record),
|
|
450
|
+
deleteAction: (id) => enqueue(() => remove('actions', id)),
|
|
451
|
+
getAction: (id) => get('actions', id),
|
|
452
|
+
listActions: () => list('actions'),
|
|
453
|
+
}
|
|
454
|
+
return store
|
|
455
|
+
}
|