@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,333 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { isPathWithinScope, validateWriteScopeInput } from './write-lease.js'
5
+ import { normalizeScope, SCOPE_KIND } from './write-scope.js'
6
+
7
+ const IGNORED_DIRS = new Set(['.git', '.hg', '.svn', 'node_modules', '.venv', '__pycache__'])
8
+ const MAX_ENTRIES = 30_000
9
+ const MAX_FILE_BYTES = 64 * 1024 * 1024
10
+ const MAX_SCAN_BYTES = 256 * 1024 * 1024
11
+ const CHUNK_BYTES = 64 * 1024
12
+ const MAX_REPORT_ROWS = 8
13
+ const WINDOWS = process.platform === 'win32'
14
+ const ISOLATION_NOTE = '当前宿主不提供逐子代理物理只读文件系统沙箱;这里只做工作区逻辑写后审计并告警。' +
15
+ '不会阻止写入,不覆盖工作区外或忽略目录,也不能区分并发写入者或检测两次采样间已还原的改动。'
16
+
17
+ const posixPath = (value) => value.split(path.sep).join('/')
18
+ const pathKey = (value) => WINDOWS ? value.toLowerCase() : value
19
+ const byPath = (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0
20
+
21
+ function insideWorkspace(cwd, filename) {
22
+ const relative = path.relative(cwd, filename)
23
+ if (relative === '' || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
24
+ return null
25
+ }
26
+ return posixPath(relative)
27
+ }
28
+
29
+ function expectedPath(cwd, value) {
30
+ if (typeof value !== 'string' || value.trim() === '' || value.includes('\0')) {
31
+ throw new TypeError('预期目标必须是非空文件路径。')
32
+ }
33
+ const relative = insideWorkspace(cwd, path.resolve(cwd, value))
34
+ if (relative === null) throw new TypeError(`预期目标必须位于工作区内:${JSON.stringify(value)}。`)
35
+ return relative
36
+ }
37
+
38
+ function fingerprintEntries(cwd, expectedFingerprints) {
39
+ if (expectedFingerprints == null) return []
40
+ if (typeof expectedFingerprints !== 'object' || Array.isArray(expectedFingerprints)) {
41
+ throw new TypeError('expectedFingerprints 必须是从文件路径到 SHA-256 的对象。')
42
+ }
43
+ const entries = new Map()
44
+ for (const [filename, sha256] of Object.entries(expectedFingerprints)) {
45
+ if (typeof sha256 !== 'string' || sha256 === '') {
46
+ throw new TypeError(`预期指纹必须是非空字符串:${JSON.stringify(filename)}。`)
47
+ }
48
+ const relative = expectedPath(cwd, filename)
49
+ const key = pathKey(relative)
50
+ const expected = sha256.toLowerCase()
51
+ if (entries.has(key) && entries.get(key).expected !== expected) {
52
+ throw new TypeError(`同一文件声明了不同的预期指纹:${JSON.stringify(filename)}。`)
53
+ }
54
+ entries.set(key, Object.freeze({ path: relative, expected }))
55
+ }
56
+ return [...entries.values()].sort(byPath)
57
+ }
58
+
59
+ function targetPaths(cwd, expectedTargets) {
60
+ if (expectedTargets == null) return []
61
+ if (!Array.isArray(expectedTargets)) throw new TypeError('expectedTargets 必须是文件路径数组。')
62
+ return expectedTargets.map((filename) => expectedPath(cwd, filename))
63
+ }
64
+
65
+ function scopeOf(writeScope, readOnly, cwd) {
66
+ const validated = validateWriteScopeInput({ writeScope, readOnly })
67
+ const normalized = validated.ok && !validated.readOnly
68
+ ? normalizeScope(validated.entries, cwd)
69
+ : validated
70
+ if (!normalized.ok) {
71
+ throw Object.assign(new TypeError(normalized.message), { code: normalized.code })
72
+ }
73
+ return normalized.entries
74
+ }
75
+
76
+ function sameObservation(left, right) {
77
+ return left.dev === right.dev && left.ino === right.ino && left.size === right.size &&
78
+ left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs
79
+ }
80
+
81
+ function fingerprint(filename, relative, stats, budget, chunk) {
82
+ const hash = createHash('sha256')
83
+ let bytes = 0
84
+ let lines = 0
85
+ let lastByte
86
+ const consume = (data) => {
87
+ bytes += data.length
88
+ budget.bytes -= data.length
89
+ hash.update(data)
90
+ for (let offset = data.indexOf(10); offset !== -1; offset = data.indexOf(10, offset + 1)) {
91
+ lines += 1
92
+ }
93
+ if (data.length > 0) lastByte = data[data.length - 1]
94
+ }
95
+
96
+ if (stats.isSymbolicLink()) {
97
+ // Fingerprint the link itself, never its target (which may lie outside the workspace).
98
+ const target = fs.readlinkSync(filename, { encoding: 'buffer' })
99
+ if (target.length > budget.bytes) return { limited: true }
100
+ consume(target)
101
+ if (!sameObservation(stats, fs.lstatSync(filename))) return { unstable: true }
102
+ } else {
103
+ if (stats.size > MAX_FILE_BYTES || stats.size > budget.bytes) return { limited: true }
104
+ const { O_RDONLY, O_NOFOLLOW = 0, O_NONBLOCK = 0 } = fs.constants
105
+ const fd = fs.openSync(filename, O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
106
+ try {
107
+ const opened = fs.fstatSync(fd)
108
+ if (!opened.isFile() || !sameObservation(stats, opened)) return { unstable: true }
109
+ while (bytes < stats.size) {
110
+ const count = fs.readSync(fd, chunk, 0, Math.min(chunk.length, stats.size - bytes), null)
111
+ if (count === 0) break
112
+ consume(chunk.subarray(0, count))
113
+ }
114
+ if (bytes !== stats.size || !sameObservation(stats, fs.lstatSync(filename))) {
115
+ return { unstable: true }
116
+ }
117
+ } finally {
118
+ fs.closeSync(fd)
119
+ }
120
+ }
121
+ return {
122
+ file: Object.freeze({
123
+ path: relative,
124
+ sha256: hash.digest('hex'),
125
+ bytes,
126
+ lines: lines + (lastByte === 10 ? 0 : 1),
127
+ mtimeMs: stats.mtimeMs,
128
+ size: stats.size,
129
+ }),
130
+ }
131
+ }
132
+
133
+ function snapshot(cwd) {
134
+ const files = []
135
+ const issues = []
136
+ const budget = { entries: MAX_ENTRIES, bytes: MAX_SCAN_BYTES }
137
+ const chunk = Buffer.allocUnsafe(CHUNK_BYTES)
138
+ const pending = ['.']
139
+ let truncated = false
140
+ const recordIssue = (filename, reason, limited = false) => {
141
+ issues.push(Object.freeze({ path: filename, reason }))
142
+ if (limited) truncated = true
143
+ }
144
+ while (pending.length > 0) {
145
+ const relativeDir = pending.pop()
146
+ let dir
147
+ try {
148
+ const directory = path.join(cwd, relativeDir)
149
+ if (relativeDir !== '.' && !fs.lstatSync(directory).isDirectory()) {
150
+ recordIssue(relativeDir, '采样时目录发生变化')
151
+ continue
152
+ }
153
+ dir = fs.opendirSync(directory)
154
+ let entry
155
+ while ((entry = dir.readSync()) !== null) {
156
+ if (budget.entries === 0 || budget.bytes === 0) {
157
+ recordIssue('.', '已达到扫描条目或总字节上限', true)
158
+ return { files: files.sort(byPath), issues: issues.sort(byPath), truncated }
159
+ }
160
+ budget.entries -= 1
161
+ if (pathKey(entry.name) === '.git' || (IGNORED_DIRS.has(pathKey(entry.name)) &&
162
+ (entry.isDirectory() || entry.isSymbolicLink()))) continue
163
+ const relative = relativeDir === '.' ? entry.name : `${relativeDir}/${entry.name}`
164
+ const filename = path.join(cwd, relative)
165
+ try {
166
+ const stats = fs.lstatSync(filename)
167
+ if (stats.isDirectory()) {
168
+ pending.push(relative)
169
+ } else if (stats.isFile() || stats.isSymbolicLink()) {
170
+ const result = fingerprint(filename, relative, stats, budget, chunk)
171
+ if (result.file) files.push(result.file)
172
+ else if (result.limited) recordIssue(relative, '超过单文件或剩余扫描字节上限', true)
173
+ else recordIssue(relative, '采样时文件发生变化')
174
+ }
175
+ } catch (error) {
176
+ recordIssue(relative, `无法采样:${error.code ?? error.name}`)
177
+ }
178
+ }
179
+ } catch (error) {
180
+ recordIssue(relativeDir, `无法读取目录:${error.code ?? error.name}`)
181
+ } finally {
182
+ dir?.closeSync()
183
+ }
184
+ }
185
+ return { files: files.sort(byPath), issues: issues.sort(byPath), truncated }
186
+ }
187
+
188
+ const fileMap = (files) => new Map(files.map((file) => [pathKey(file.path), file]))
189
+
190
+ function coverageOf(issues) {
191
+ const unknown = new Set(issues.map((issue) => pathKey(issue.path)))
192
+ return (filename) => {
193
+ if (unknown.has('.')) return false
194
+ const pieces = pathKey(filename).split('/')
195
+ let prefix = ''
196
+ for (const [index, piece] of pieces.entries()) {
197
+ if (piece === '.git' || (index < pieces.length - 1 && IGNORED_DIRS.has(piece))) return false
198
+ prefix = prefix === '' ? piece : `${prefix}/${piece}`
199
+ if (unknown.has(prefix)) return false
200
+ }
201
+ return true
202
+ }
203
+ }
204
+
205
+ /** Freeze the full in-workspace observation before activation, including out-of-scope files. */
206
+ export function captureBaseline({
207
+ cwd,
208
+ writeScope = [],
209
+ readOnly = false,
210
+ expectedFingerprints = null,
211
+ expectedTargets = null,
212
+ }) {
213
+ if (typeof cwd !== 'string' || cwd.trim() === '') throw new TypeError('审计需要有效的 cwd。')
214
+ const root = path.resolve(cwd)
215
+ const entries = scopeOf(writeScope, readOnly, root)
216
+ const expected = fingerprintEntries(root, expectedFingerprints)
217
+ const targets = targetPaths(root, expectedTargets)
218
+ const observed = snapshot(root)
219
+ const original = fileMap(observed.files)
220
+ for (const entry of entries) {
221
+ if (entry.kind !== SCOPE_KIND.file) continue
222
+ const relative = insideWorkspace(root, entry.path)
223
+ const file = relative === null ? undefined : original.get(pathKey(relative))
224
+ // A path named only in writeScope may be a planned creation, not a required deliverable.
225
+ if (file !== undefined) targets.push(file.path)
226
+ }
227
+ return Object.freeze({
228
+ baselineId: randomUUID(),
229
+ cwd: root,
230
+ writeScope: Object.freeze(typeof writeScope === 'string' ? [writeScope] : [...writeScope]),
231
+ readOnly: readOnly === true,
232
+ expectedFingerprints: Object.freeze(Object.fromEntries(expected.map((row) => [row.path, row.expected]))),
233
+ expectedTargets: Object.freeze([...new Set(targets)].sort()),
234
+ files: Object.freeze(observed.files),
235
+ truncated: observed.truncated,
236
+ scanIssues: Object.freeze(observed.issues),
237
+ })
238
+ }
239
+
240
+ function compareFingerprints(expected, observed, covered, phase, violations) {
241
+ for (const row of expected) {
242
+ const actual = observed.get(pathKey(row.path))?.sha256
243
+ if (actual === undefined && !covered(row.path)) {
244
+ violations.push({ code: 'audit-incomplete', path: row.path, phase, reason: '无法核对预期指纹' })
245
+ } else if (actual !== row.expected) {
246
+ violations.push({ code: 'fingerprint-mismatch', path: row.path, expected: row.expected, actual: actual ?? null, phase })
247
+ }
248
+ }
249
+ }
250
+
251
+ /** Recompute current bytes. Capture expectations refer to the old bytes; settlement expectations to the final bytes. */
252
+ export function auditBaseline(baseline, {
253
+ cwd,
254
+ writeScope,
255
+ readOnly,
256
+ expectedFingerprints,
257
+ expectedTargets,
258
+ } = {}) {
259
+ const root = baseline.cwd
260
+ if (cwd !== undefined && path.relative(root, path.resolve(cwd)) !== '') {
261
+ throw new TypeError('审计结算必须使用冻结基线时的 cwd。')
262
+ }
263
+ const effectiveReadOnly = baseline.readOnly || readOnly === true
264
+ const entries = scopeOf(baseline.writeScope, baseline.readOnly, root)
265
+ const narrowed = writeScope === undefined ? entries : scopeOf(writeScope, effectiveReadOnly, root)
266
+ const expected = fingerprintEntries(root, expectedFingerprints)
267
+ const targets = new Map([...targetPaths(root, expectedTargets), ...baseline.expectedTargets]
268
+ .map((filename) => [pathKey(filename), filename]))
269
+ const current = snapshot(root)
270
+ const before = fileMap(baseline.files)
271
+ const after = fileMap(current.files)
272
+ const coveredBefore = coverageOf(baseline.scanIssues)
273
+ const coveredAfter = coverageOf(current.issues)
274
+ const changedFiles = []
275
+ const violations = [...baseline.scanIssues.map((issue) => ({ code: 'audit-incomplete', ...issue, phase: 'baseline' })),
276
+ ...current.issues.map((issue) => ({ code: 'audit-incomplete', ...issue, phase: 'settlement' }))]
277
+
278
+ for (const key of new Set([...before.keys(), ...after.keys()])) {
279
+ const old = before.get(key)
280
+ const now = after.get(key)
281
+ if ((!old && !coveredBefore(now.path)) || (!now && !coveredAfter(old.path))) continue
282
+ if (old && now && old.sha256 === now.sha256 && old.mtimeMs === now.mtimeMs && old.path === now.path) continue
283
+ const filename = (now ?? old).path
284
+ const changeType = !old ? 'added' : !now ? 'deleted' : 'modified'
285
+ changedFiles.push({ path: filename, sha256: now?.sha256 ?? null, bytes: now?.bytes ?? 0, lines: now?.lines ?? 0, changeType })
286
+ const absolute = path.join(root, filename)
287
+ if (effectiveReadOnly || !isPathWithinScope(absolute, entries, { cwd: root }) ||
288
+ (narrowed !== entries && !isPathWithinScope(absolute, narrowed, { cwd: root }))) {
289
+ violations.push({ code: 'out-of-scope-write', path: filename, changeType })
290
+ }
291
+ }
292
+
293
+ compareFingerprints(fingerprintEntries(root, baseline.expectedFingerprints), before, coveredBefore, 'baseline', violations)
294
+ compareFingerprints(expected, after, coveredAfter, 'settlement', violations)
295
+ for (const [key, filename] of targets) {
296
+ if (after.has(key)) continue
297
+ if (coveredAfter(filename)) violations.push({ code: 'target-missing', path: filename })
298
+ else violations.push({ code: 'audit-incomplete', path: filename, phase: 'settlement', reason: '无法核对目标是否存在' })
299
+ }
300
+
301
+ const summary = {
302
+ added: 0,
303
+ modified: 0,
304
+ deleted: 0,
305
+ violations: violations.length,
306
+ truncated: baseline.truncated || current.truncated,
307
+ }
308
+ for (const file of changedFiles) summary[file.changeType] += 1
309
+ return {
310
+ baselineId: baseline.baselineId,
311
+ passed: violations.length === 0,
312
+ readOnly: effectiveReadOnly,
313
+ isolationLevel: 'logical-post-audit',
314
+ isolationNote: ISOLATION_NOTE,
315
+ changedFiles: changedFiles.sort(byPath),
316
+ violations: violations.sort(byPath),
317
+ summary,
318
+ }
319
+ }
320
+
321
+ /** Produce a bounded Chinese notice; structured evidence remains in the result. */
322
+ export function formatAuditReport(auditResult) {
323
+ if (auditResult.passed) return ''
324
+ const { baselineId, violations, summary } = auditResult
325
+ const details = violations.slice(0, MAX_REPORT_ROWS).map(({ code, path: filename }) =>
326
+ `- ${code}:${JSON.stringify(filename)}`)
327
+ if (violations.length > details.length) details.push(`另有 ${violations.length - details.length} 项未列出。`)
328
+ return [
329
+ `写作用域审计未通过(基线 ${baselineId},${violations.length} 项${summary.truncated ? ',采样已截断' : ''}):`,
330
+ ...details,
331
+ auditResult.isolationNote,
332
+ ].join('\n')
333
+ }
@@ -30,7 +30,17 @@
30
30
  * without the DSH runtime.
31
31
  */
32
32
 
33
- import { describeScope, isNormalizedScope, mergeScope, normalizeScope, overlaps } from './write-scope.js'
33
+ import { randomUUID } from 'node:crypto'
34
+ import {
35
+ WRITE_SCOPE_CODES,
36
+ coversPath,
37
+ describeScope,
38
+ isNormalizedScope,
39
+ mergeScope,
40
+ normalizeScope,
41
+ overlaps,
42
+ parseWriteScope,
43
+ } from './write-scope.js'
34
44
 
35
45
  /** Structured refusal codes; callers branch on these, never on the message text. */
36
46
  export const WRITE_LEASE_CODES = Object.freeze({
@@ -61,6 +71,65 @@ function isNonEmptyString(value) {
61
71
  return typeof value === 'string' && value !== ''
62
72
  }
63
73
 
74
+ function ownerKindOf(ownerId, parentId) {
75
+ if (ownerId.startsWith(`pending:${parentId}:`)) return 'provisional'
76
+ if (ownerId.startsWith(`batch-${parentId}-`)) return 'batch'
77
+ return 'delegate'
78
+ }
79
+
80
+ function normalizeOwnerKind(value, ownerId, parentId) {
81
+ if (value === 'child') return 'delegate'
82
+ return isNonEmptyString(value) ? value : ownerKindOf(ownerId, parentId)
83
+ }
84
+
85
+ function copyLeaseEntries(entries) {
86
+ return entries.map(({ path, key, kind }) => ({ path, key, kind }))
87
+ }
88
+
89
+ function restorePhysicalEntry({ path, key, kind }) {
90
+ // Preserve the historical global root conservatively; relative file claims are invalid.
91
+ if (path === '*' && key === '*' && kind === 'root') return { path, key, kind }
92
+ const cwd = path.startsWith('//') ? path.replaceAll('/', '\\') : path
93
+ const physical = normalizeScope('*', cwd).entries?.[0]
94
+ if (physical?.path !== path || (key !== path && key !== path.toLowerCase())) return null
95
+ const isRoot = /^(?:\/|[a-zA-Z]:\/|\/\/[^/]+\/[^/]+\/)$/.test(path)
96
+ if (isRoot && kind !== 'root') return null
97
+ const windowsPath = /^[a-zA-Z]:\/|^\/\//.test(path)
98
+ // A Windows snapshot must not bypass a normal claim by changing only the key's case.
99
+ return { path, key: windowsPath ? physical.key : key, kind }
100
+ }
101
+
102
+ /** Validate the declaration shape; actual path resolution still belongs to normalizeScope. */
103
+ export function validateWriteScopeInput({ writeScope, readOnly } = {}) {
104
+ if (readOnly === true) {
105
+ if (writeScope === undefined || (Array.isArray(writeScope) && writeScope.length === 0)) {
106
+ return { ok: true, readOnly: true, entries: [] }
107
+ }
108
+ return {
109
+ ok: false,
110
+ code: WRITE_SCOPE_CODES.invalid,
111
+ message: 'readOnly: true 与 writeScope 互斥:只读任务不得声明写路径,请省略 writeScope 或传空数组。',
112
+ }
113
+ }
114
+ const parsed = parseWriteScope(writeScope)
115
+ if (!parsed.ok) {
116
+ return {
117
+ ...parsed,
118
+ code: parsed.code === WRITE_SCOPE_CODES.empty ? WRITE_SCOPE_CODES.invalid : parsed.code,
119
+ message: parsed.message.replaceAll('write_scope', 'writeScope'),
120
+ }
121
+ }
122
+ return { ok: true, readOnly: false, entries: parsed.entries }
123
+ }
124
+
125
+ /** Test a single path against raw declarations or entries already normalized for a lease. */
126
+ export function isPathWithinScope(relPath, writeScopeSpecs, { cwd, caseInsensitive } = {}) {
127
+ const options = { cwd, caseInsensitive }
128
+ if (isNormalizedScope(writeScopeSpecs)) return coversPath(writeScopeSpecs, relPath, options)
129
+ const normalized = normalizeScope(writeScopeSpecs, cwd, options)
130
+ return normalized.ok && coversPath(normalized.entries, relPath, options)
131
+ }
132
+
64
133
  /** A positive finite millisecond count, or `undefined` for "not a TTL". */
65
134
  function ttlOf(value) {
66
135
  if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined
@@ -78,7 +147,9 @@ function invalid(message) {
78
147
  }
79
148
 
80
149
  /**
81
- * Every live lease that intersects `entries`.
150
+ * Every live lease that intersects `entries` by physical path, including `*` claims
151
+ * already resolved against the dispatch directory. No per-repository or branch identity
152
+ * participates: independent worktrees are separate, even at the same commit.
82
153
  *
83
154
  * Pure: the table passes its own snapshot in, and `orchestrate` can pass a simulated list
84
155
  * to pre-check a whole batch without registering anything. Rows are capped: past the cap
@@ -166,7 +237,6 @@ export function createWriteLeases(options = {}) {
166
237
  const byId = new Map()
167
238
  /** `childId -> leaseId`, the one-lease-per-child invariant. */
168
239
  const byChild = new Map()
169
- let sequence = 0
170
240
 
171
241
  const currentTime = () => {
172
242
  try {
@@ -187,8 +257,7 @@ export function createWriteLeases(options = {}) {
187
257
  // Fall through to the built-in generator.
188
258
  }
189
259
  }
190
- sequence += 1
191
- return `lease-${String(currentTime())}-${String(sequence)}`
260
+ return `lease-${randomUUID()}`
192
261
  }
193
262
 
194
263
  /** Frozen deep-enough copy, so a caller cannot rewrite the table by mutation. */
@@ -210,6 +279,65 @@ export function createWriteLeases(options = {}) {
210
279
  if (byChild.get(lease.childId) === lease.leaseId) byChild.delete(lease.childId)
211
280
  }
212
281
 
282
+ const remember = (lease) => {
283
+ byId.set(lease.leaseId, lease)
284
+ byChild.set(lease.childId, lease.leaseId)
285
+ }
286
+
287
+ function exportLeases({ now } = {}) {
288
+ const at = Number.isFinite(now) ? now : currentTime()
289
+ return [...byId.values()].filter((lease) => lease.expiresAt > at).map((lease) => ({
290
+ leaseId: lease.leaseId, ownerKind: lease.ownerKind, ownerId: lease.childId,
291
+ parentId: lease.parentId, entries: copyLeaseEntries(lease.entries), issuedAt: lease.issuedAt,
292
+ expiresAt: lease.expiresAt, baselineId: lease.baselineId,
293
+ }))
294
+ }
295
+
296
+ function hydrateLeases(rows, { now } = {}) {
297
+ const result = { restored: 0, skippedExpired: 0, skippedInvalid: 0, expiredLeaseIds: [] }
298
+ if (!Array.isArray(rows)) return result
299
+ const at = Number.isFinite(now) ? now : currentTime()
300
+ sweep(at)
301
+ const expired = new Set()
302
+ for (const row of rows) {
303
+ const childId = row?.ownerId ?? row?.childId
304
+ if (!isNonEmptyString(row?.leaseId) || !isNonEmptyString(childId) || !isNonEmptyString(row.parentId) ||
305
+ (row.ownerKind != null && !isNonEmptyString(row.ownerKind)) ||
306
+ (row.baselineId != null && !isNonEmptyString(row.baselineId)) ||
307
+ !Number.isFinite(row.issuedAt) || !Number.isFinite(row.expiresAt) || row.expiresAt < row.issuedAt ||
308
+ Math.abs(row.expiresAt) > 8.64e15 || !isNormalizedScope(row.entries)) {
309
+ result.skippedInvalid += 1
310
+ continue
311
+ }
312
+ const physicalEntries = row.entries.map(restorePhysicalEntry)
313
+ if (physicalEntries.includes(null) || physicalEntries.includes(undefined)) {
314
+ result.skippedInvalid += 1
315
+ continue
316
+ }
317
+ if (row.expiresAt <= at) {
318
+ result.skippedExpired += 1
319
+ expired.add(row.leaseId)
320
+ continue
321
+ }
322
+ const entries = mergeScope(physicalEntries)
323
+ if (byId.has(row.leaseId) || byChild.has(childId) || byId.size >= maxLeases ||
324
+ leaseConflicts(entries, [...byId.values()]).length > 0) {
325
+ result.skippedInvalid += 1
326
+ continue
327
+ }
328
+ remember({
329
+ leaseId: row.leaseId, childId, parentId: row.parentId,
330
+ ownerKind: normalizeOwnerKind(row.ownerKind, childId, row.parentId),
331
+ entries, scope: entries.map((entry) => entry.path), mode: LEASE_MODE,
332
+ issuedAt: row.issuedAt, expiresAt: row.expiresAt, baselineId: row.baselineId ?? null,
333
+ restored: true,
334
+ })
335
+ result.restored += 1
336
+ }
337
+ result.expiredLeaseIds = [...expired].filter((id) => !byId.has(id))
338
+ return result
339
+ }
340
+
213
341
  const conflictResult = (conflicts) => ({
214
342
  ok: false,
215
343
  code: WRITE_LEASE_CODES.conflict,
@@ -217,6 +345,13 @@ export function createWriteLeases(options = {}) {
217
345
  conflicts,
218
346
  })
219
347
 
348
+ // Read-only requests do not renew, create or release any lease, even for a known child.
349
+ const checkReadOnly = ({ scope, entries, writeScope }) => {
350
+ const declared = [scope, entries, writeScope].filter((value) => value !== undefined)
351
+ if (declared.length > 1) return invalid('scope、entries 与 writeScope 只能给一个。')
352
+ return validateWriteScopeInput({ writeScope: declared[0], readOnly: true })
353
+ }
354
+
220
355
  /** Raw declaration (`scope` + `cwd`) or a normalized one (`entries`), never both. */
221
356
  const resolveEntries = (input) => {
222
357
  if (input.scope !== undefined && input.entries !== undefined) {
@@ -252,11 +387,18 @@ export function createWriteLeases(options = {}) {
252
387
  * `childId` may be provisional. `delegate` must refuse a conflicting dispatch before
253
388
  * `startActivation` (AC1), but the host names the child only after it is created, so the
254
389
  * caller reserves the lease with its own id and calls `rebind` once the child exists.
390
+ * Retry uses this same method with the previously released lease's `entries` and
391
+ * owner IDs; it must not resume unless the new acquire succeeds. A read-only request
392
+ * returns `lease: null` and leaves the table unchanged.
255
393
  */
256
394
  const acquire = (input) => {
257
395
  if (input === null || typeof input !== 'object') {
258
396
  return invalid('acquire 需要一个对象参数:{ childId, parentId, scope, cwd }。')
259
397
  }
398
+ if (input.readOnly === true) {
399
+ const checked = checkReadOnly(input)
400
+ return checked.ok ? { ok: true, lease: null, reused: false, readOnly: true } : checked
401
+ }
260
402
  if (!isNonEmptyString(input.childId)) return invalid('childId 必须是非空字符串。')
261
403
  if (!isNonEmptyString(input.parentId)) return invalid('parentId 必须是非空字符串。')
262
404
  if (input.mode !== undefined && input.mode !== LEASE_MODE) {
@@ -278,6 +420,11 @@ export function createWriteLeases(options = {}) {
278
420
 
279
421
  const held = byId.get(byChild.get(input.childId))
280
422
  if (held !== undefined) {
423
+ if (held.parentId !== input.parentId || (held.restored && held.ownerKind !== 'delegate')) {
424
+ const conflicts = leaseConflicts(entries, [held])
425
+ return conflicts.length > 0 ? conflictResult(conflicts)
426
+ : invalid('租约持有人标识已占用,不能以新的派发复用。')
427
+ }
281
428
  const merged = mergeScope(held.entries, entries)
282
429
  const conflicts = leaseConflicts(merged, [...byId.values()], {
283
430
  ignoreChildId: held.childId,
@@ -312,6 +459,7 @@ export function createWriteLeases(options = {}) {
312
459
  leaseId,
313
460
  childId: input.childId,
314
461
  parentId: input.parentId,
462
+ ownerKind: normalizeOwnerKind(input.ownerKind, input.childId, input.parentId),
315
463
  scope: entries.map((entry) => entry.path),
316
464
  entries,
317
465
  mode: LEASE_MODE,
@@ -319,8 +467,7 @@ export function createWriteLeases(options = {}) {
319
467
  expiresAt: at + ttlMs,
320
468
  baselineId: isNonEmptyString(input.baselineId) ? input.baselineId : null,
321
469
  }
322
- byId.set(leaseId, lease)
323
- byChild.set(lease.childId, leaseId)
470
+ remember(lease)
324
471
  return { ok: true, lease: snapshot(lease), reused: false }
325
472
  }
326
473
 
@@ -333,6 +480,10 @@ export function createWriteLeases(options = {}) {
333
480
  if (input === null || typeof input !== 'object') {
334
481
  return invalid('check 需要一个对象参数:{ scope, cwd }。')
335
482
  }
483
+ if (input.readOnly === true) {
484
+ const checked = checkReadOnly(input)
485
+ return checked.ok ? { ...checked, conflicts: [] } : checked
486
+ }
336
487
  const normalized = resolveEntries(input)
337
488
  if (!normalized.ok) return normalized
338
489
  const at = currentTime()
@@ -403,6 +554,7 @@ export function createWriteLeases(options = {}) {
403
554
  return invalid(`子代理 ${nextChild} 已持有租约 ${occupied},不能再挂第二份。`)
404
555
  }
405
556
  if (byChild.get(lease.childId) === leaseId) byChild.delete(lease.childId)
557
+ if (lease.childId !== nextChild) lease.ownerKind = ownerKindOf(nextChild, nextParent)
406
558
  lease.childId = nextChild
407
559
  lease.parentId = nextParent
408
560
  byChild.set(nextChild, leaseId)
@@ -450,6 +602,8 @@ export function createWriteLeases(options = {}) {
450
602
  rebind,
451
603
  renew,
452
604
  sweep,
605
+ exportLeases,
606
+ hydrateLeases,
453
607
  get(leaseId) {
454
608
  const lease = isNonEmptyString(leaseId) ? byId.get(leaseId) : undefined
455
609
  return lease === undefined ? undefined : snapshot(lease)
@@ -25,6 +25,35 @@ export const WRITE_SCOPE_TOOL_CODES = Object.freeze({
25
25
  limit: 'write-scope-limit',
26
26
  })
27
27
 
28
+ export const ISOLATION_MODES = Object.freeze(['auto', 'worktree', 'shared'])
29
+
30
+ const WORKTREE_ERRORS = Object.freeze({
31
+ 'isolation-invalid': 'isolation 必须为 auto、worktree 或 shared。',
32
+ 'not-git-repo': '当前目录不在 Git 仓库中,无法使用独立工作树。',
33
+ 'unborn-head': 'Git 仓库尚无初始提交,无法创建独立工作树。',
34
+ 'worktree-outside-workspace': '工作树或执行目录超出会话工作区,无法使用独立工作树。',
35
+ 'worktree-create-failed': '无法创建独立 Git 工作树。',
36
+ 'worktree-child-locked': '此子代理的工作树已回收,不得继续运行;请重新派发。',
37
+ })
38
+
39
+ export function formatWorktreeError(code, detail) {
40
+ const message = Object.hasOwn(WORKTREE_ERRORS, code)
41
+ ? WORKTREE_ERRORS[code]
42
+ : `工作树操作失败${typeof code === 'string' && code !== '' ? `(${code})` : ''}。`
43
+ const reason = typeof detail === 'string' ? detail : detail?.message ?? detail?.reason
44
+ return typeof reason === 'string' && reason.trim() !== '' ? `${message} ${reason.trim()}` : message
45
+ }
46
+
47
+ export function parseIsolation(value) {
48
+ if (value == null || value === '') return { ok: true, mode: 'auto', explicit: false }
49
+ if (typeof value === 'string') {
50
+ const mode = value.trim().toLowerCase()
51
+ if (ISOLATION_MODES.includes(mode)) return { ok: true, mode, explicit: true }
52
+ }
53
+ const code = 'isolation-invalid'
54
+ return { ok: false, code, message: formatWorktreeError(code) }
55
+ }
56
+
28
57
  /** A tool error with a stable code; callers branch on `code`, never on the message. */
29
58
  export class WriteScopeError extends Error {
30
59
  constructor(code, message, details) {