@sshirkit/dsh-orchestrator 1.0.1 → 1.0.3
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 +65 -30
- package/README.zh.md +62 -29
- package/lib/client.js +809 -311
- package/lib/delegate-status.js +42 -67
- package/lib/delegate.js +98 -140
- package/lib/gate.js +11 -5
- package/lib/index.js +533 -442
- package/lib/orchestrate.js +143 -129
- package/lib/read-index.js +186 -0
- package/lib/reconcile.js +2 -3
- package/lib/rules.js +22 -10
- package/lib/session-tools.js +516 -0
- package/lib/state-store.js +14 -9
- package/lib/supervise.js +69 -85
- package/lib/switch-notice.js +2 -2
- package/lib/timeline.js +23 -181
- package/lib/tool-surface.js +57 -9
- package/lib/worker.js +18 -7
- package/lib/worktree-manage.js +3 -10
- package/lib/worktree.js +3 -12
- package/lib/write-lease.js +57 -12
- package/package.json +1 -1
- package/lib/git-audit.js +0 -383
- package/lib/write-audit.js +0 -333
package/lib/write-lease.js
CHANGED
|
@@ -237,6 +237,9 @@ export function createWriteLeases(options = {}) {
|
|
|
237
237
|
const byId = new Map()
|
|
238
238
|
/** `childId -> leaseId`, the one-lease-per-child invariant. */
|
|
239
239
|
const byChild = new Map()
|
|
240
|
+
// Keep the removed part reserved until a definitive delivery outcome permits commit or rollback.
|
|
241
|
+
const replacements = new Map()
|
|
242
|
+
const conflictHolders = () => [...byId.values(), ...[...replacements.values()].filter(Boolean)]
|
|
240
243
|
|
|
241
244
|
const currentTime = () => {
|
|
242
245
|
try {
|
|
@@ -271,7 +274,6 @@ export function createWriteLeases(options = {}) {
|
|
|
271
274
|
mode: lease.mode,
|
|
272
275
|
issuedAt: lease.issuedAt,
|
|
273
276
|
expiresAt: lease.expiresAt,
|
|
274
|
-
baselineId: lease.baselineId,
|
|
275
277
|
})
|
|
276
278
|
|
|
277
279
|
const drop = (lease) => {
|
|
@@ -289,7 +291,7 @@ export function createWriteLeases(options = {}) {
|
|
|
289
291
|
return [...byId.values()].filter((lease) => lease.expiresAt > at).map((lease) => ({
|
|
290
292
|
leaseId: lease.leaseId, ownerKind: lease.ownerKind, ownerId: lease.childId,
|
|
291
293
|
parentId: lease.parentId, entries: copyLeaseEntries(lease.entries), issuedAt: lease.issuedAt,
|
|
292
|
-
expiresAt: lease.expiresAt,
|
|
294
|
+
expiresAt: lease.expiresAt,
|
|
293
295
|
}))
|
|
294
296
|
}
|
|
295
297
|
|
|
@@ -303,7 +305,6 @@ export function createWriteLeases(options = {}) {
|
|
|
303
305
|
const childId = row?.ownerId ?? row?.childId
|
|
304
306
|
if (!isNonEmptyString(row?.leaseId) || !isNonEmptyString(childId) || !isNonEmptyString(row.parentId) ||
|
|
305
307
|
(row.ownerKind != null && !isNonEmptyString(row.ownerKind)) ||
|
|
306
|
-
(row.baselineId != null && !isNonEmptyString(row.baselineId)) ||
|
|
307
308
|
!Number.isFinite(row.issuedAt) || !Number.isFinite(row.expiresAt) || row.expiresAt < row.issuedAt ||
|
|
308
309
|
Math.abs(row.expiresAt) > 8.64e15 || !isNormalizedScope(row.entries)) {
|
|
309
310
|
result.skippedInvalid += 1
|
|
@@ -329,7 +330,7 @@ export function createWriteLeases(options = {}) {
|
|
|
329
330
|
leaseId: row.leaseId, childId, parentId: row.parentId,
|
|
330
331
|
ownerKind: normalizeOwnerKind(row.ownerKind, childId, row.parentId),
|
|
331
332
|
entries, scope: entries.map((entry) => entry.path), mode: LEASE_MODE,
|
|
332
|
-
issuedAt: row.issuedAt, expiresAt: row.expiresAt,
|
|
333
|
+
issuedAt: row.issuedAt, expiresAt: row.expiresAt,
|
|
333
334
|
restored: true,
|
|
334
335
|
})
|
|
335
336
|
result.restored += 1
|
|
@@ -391,10 +392,11 @@ export function createWriteLeases(options = {}) {
|
|
|
391
392
|
* owner IDs; it must not resume unless the new acquire succeeds. A read-only request
|
|
392
393
|
* returns `lease: null` and leaves the table unchanged.
|
|
393
394
|
*/
|
|
394
|
-
const acquire = (input) => {
|
|
395
|
+
const acquire = (input, replace = false) => {
|
|
395
396
|
if (input === null || typeof input !== 'object') {
|
|
396
397
|
return invalid('acquire 需要一个对象参数:{ childId, parentId, scope, cwd }。')
|
|
397
398
|
}
|
|
399
|
+
if (replacements.has(input.childId)) return invalid("该子代理已有待确认的租约替换。")
|
|
398
400
|
if (input.readOnly === true) {
|
|
399
401
|
const checked = checkReadOnly(input)
|
|
400
402
|
return checked.ok ? { ok: true, lease: null, reused: false, readOnly: true } : checked
|
|
@@ -425,22 +427,21 @@ export function createWriteLeases(options = {}) {
|
|
|
425
427
|
return conflicts.length > 0 ? conflictResult(conflicts)
|
|
426
428
|
: invalid('租约持有人标识已占用,不能以新的派发复用。')
|
|
427
429
|
}
|
|
428
|
-
const merged = mergeScope(held.entries, entries)
|
|
429
|
-
const conflicts = leaseConflicts(merged,
|
|
430
|
+
const merged = replace ? mergeScope(entries) : mergeScope(held.entries, entries)
|
|
431
|
+
const conflicts = leaseConflicts(merged, conflictHolders(), {
|
|
430
432
|
ignoreChildId: held.childId,
|
|
431
433
|
})
|
|
432
434
|
if (conflicts.length > 0) return conflictResult(conflicts)
|
|
433
435
|
held.entries = merged
|
|
434
436
|
held.scope = merged.map((entry) => entry.path)
|
|
435
437
|
held.expiresAt = at + ttlMs
|
|
436
|
-
if (isNonEmptyString(input.baselineId)) held.baselineId = input.baselineId
|
|
437
438
|
return { ok: true, lease: snapshot(held), reused: true }
|
|
438
439
|
}
|
|
439
440
|
|
|
440
|
-
const conflicts = leaseConflicts(entries,
|
|
441
|
+
const conflicts = leaseConflicts(entries, conflictHolders())
|
|
441
442
|
if (conflicts.length > 0) return conflictResult(conflicts)
|
|
442
443
|
|
|
443
|
-
if (
|
|
444
|
+
if (new Set(conflictHolders().map((lease) => lease.childId)).size >= maxLeases) {
|
|
444
445
|
return {
|
|
445
446
|
ok: false,
|
|
446
447
|
code: WRITE_LEASE_CODES.capacity,
|
|
@@ -465,12 +466,53 @@ export function createWriteLeases(options = {}) {
|
|
|
465
466
|
mode: LEASE_MODE,
|
|
466
467
|
issuedAt: at,
|
|
467
468
|
expiresAt: at + ttlMs,
|
|
468
|
-
baselineId: isNonEmptyString(input.baselineId) ? input.baselineId : null,
|
|
469
469
|
}
|
|
470
470
|
remember(lease)
|
|
471
471
|
return { ok: true, lease: snapshot(lease), reused: false }
|
|
472
472
|
}
|
|
473
473
|
|
|
474
|
+
/** Replace one owner's scope without unioning it with historical paths. */
|
|
475
|
+
function replaceOwnerLease(input, { reversible = false } = {}) {
|
|
476
|
+
if (!isNonEmptyString(input?.childId) || !isNonEmptyString(input?.parentId)) {
|
|
477
|
+
return invalid('childId 与 parentId 必须是非空字符串。')
|
|
478
|
+
}
|
|
479
|
+
const { childId, parentId, readOnly } = input
|
|
480
|
+
if (replacements.has(childId)) return invalid('该子代理已有待确认的租约替换。')
|
|
481
|
+
sweep()
|
|
482
|
+
const held = byId.get(byChild.get(childId))
|
|
483
|
+
if (held && (held.parentId !== parentId || held.ownerKind !== 'delegate')) {
|
|
484
|
+
return invalid('只能替换当前父会话下的委派租约。')
|
|
485
|
+
}
|
|
486
|
+
const previous = held && { ...held }
|
|
487
|
+
let result
|
|
488
|
+
if (readOnly === true) {
|
|
489
|
+
const checked = checkReadOnly(input)
|
|
490
|
+
if (!checked.ok) return checked
|
|
491
|
+
if (held) drop(held)
|
|
492
|
+
result = { ok: true, lease: null, reused: false, readOnly: true }
|
|
493
|
+
} else {
|
|
494
|
+
result = acquire(input, true)
|
|
495
|
+
if (!result.ok) return result
|
|
496
|
+
}
|
|
497
|
+
if (!reversible) return result
|
|
498
|
+
|
|
499
|
+
replacements.set(childId, previous)
|
|
500
|
+
let finished = false
|
|
501
|
+
const finalize = (rollback) => {
|
|
502
|
+
if (finished || !replacements.has(childId)) return false
|
|
503
|
+
finished = true
|
|
504
|
+
replacements.delete(childId)
|
|
505
|
+
if (rollback) {
|
|
506
|
+
const current = byId.get(byChild.get(childId))
|
|
507
|
+
if (current) drop(current)
|
|
508
|
+
if (previous && previous.expiresAt > currentTime()) remember(previous)
|
|
509
|
+
}
|
|
510
|
+
return true
|
|
511
|
+
}
|
|
512
|
+
return { ...result, previousLease: previous && snapshot(previous),
|
|
513
|
+
commit: () => finalize(false), rollback: () => finalize(true) }
|
|
514
|
+
}
|
|
515
|
+
|
|
474
516
|
/**
|
|
475
517
|
* Pre-flight check without registering anything: the answer a caller needs to decide
|
|
476
518
|
* between refusing one dispatch and serializing a batch. Expired leases are ignored, so
|
|
@@ -480,6 +522,7 @@ export function createWriteLeases(options = {}) {
|
|
|
480
522
|
if (input === null || typeof input !== 'object') {
|
|
481
523
|
return invalid('check 需要一个对象参数:{ scope, cwd }。')
|
|
482
524
|
}
|
|
525
|
+
if (replacements.has(input.childId)) return invalid("该子代理已有待确认的租约替换。")
|
|
483
526
|
if (input.readOnly === true) {
|
|
484
527
|
const checked = checkReadOnly(input)
|
|
485
528
|
return checked.ok ? { ...checked, conflicts: [] } : checked
|
|
@@ -488,7 +531,7 @@ export function createWriteLeases(options = {}) {
|
|
|
488
531
|
if (!normalized.ok) return normalized
|
|
489
532
|
const at = currentTime()
|
|
490
533
|
const live = []
|
|
491
|
-
for (const lease of
|
|
534
|
+
for (const lease of conflictHolders()) {
|
|
492
535
|
if (lease.expiresAt > at) live.push(lease)
|
|
493
536
|
}
|
|
494
537
|
const conflicts = leaseConflicts(normalized.entries, live, {
|
|
@@ -593,6 +636,7 @@ export function createWriteLeases(options = {}) {
|
|
|
593
636
|
|
|
594
637
|
return {
|
|
595
638
|
acquire,
|
|
639
|
+
replaceOwnerLease,
|
|
596
640
|
check,
|
|
597
641
|
release,
|
|
598
642
|
releaseChild,
|
|
@@ -619,6 +663,7 @@ export function createWriteLeases(options = {}) {
|
|
|
619
663
|
const removed = byId.size
|
|
620
664
|
byId.clear()
|
|
621
665
|
byChild.clear()
|
|
666
|
+
replacements.clear()
|
|
622
667
|
return removed
|
|
623
668
|
},
|
|
624
669
|
get size() {
|
package/package.json
CHANGED
package/lib/git-audit.js
DELETED
|
@@ -1,383 +0,0 @@
|
|
|
1
|
-
import { execFileSync } from 'node:child_process'
|
|
2
|
-
import { createHash, randomUUID } from 'node:crypto'
|
|
3
|
-
import fs from 'node:fs'
|
|
4
|
-
import path from 'node:path'
|
|
5
|
-
import { isPathWithinScope, validateWriteScopeInput } from './write-lease.js'
|
|
6
|
-
import { normalizeScope, SCOPE_KIND } from './write-scope.js'
|
|
7
|
-
import { WORKTREE_POOL_DIRNAME } from './worktree.js'
|
|
8
|
-
|
|
9
|
-
const WINDOWS = process.platform === 'win32'
|
|
10
|
-
const MAX_FILE_BYTES = 64 * 1024 * 1024
|
|
11
|
-
const CHUNK_BYTES = 64 * 1024
|
|
12
|
-
const MAX_REPORT_ROWS = 8
|
|
13
|
-
const ISOLATION_NOTE = '子代理在独立 Git 工作树中执行;审计覆盖 Git 可见净变更,不是操作系统写权限沙箱。' +
|
|
14
|
-
'不会识别普通忽略文件、已还原的未提交改动,也不会将主仓污点归因给该子代理。'
|
|
15
|
-
const posix = (value) => value.split(path.sep).join('/')
|
|
16
|
-
const pathKey = (value) => WINDOWS ? value.toLowerCase() : value
|
|
17
|
-
const byPath = (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0
|
|
18
|
-
const missing = (error) => error.code === 'ENOENT' || error.code === 'ENOTDIR'
|
|
19
|
-
const gitError = (error) => String(error.stderr || error.message).trim()
|
|
20
|
-
|
|
21
|
-
function git(cwd, ...args) {
|
|
22
|
-
const bytes = execFileSync('git', ['--no-optional-locks', '--literal-pathspecs', ...args], {
|
|
23
|
-
cwd,
|
|
24
|
-
windowsHide: true,
|
|
25
|
-
env: { ...process.env, GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
|
|
26
|
-
maxBuffer: 16 * 1024 * 1024,
|
|
27
|
-
timeout: 30000,
|
|
28
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
29
|
-
})
|
|
30
|
-
// A lossy decode could conflate two filenames; fail closed instead.
|
|
31
|
-
return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
function relativeInside(root, filename) {
|
|
35
|
-
const relative = path.relative(root, filename)
|
|
36
|
-
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return null
|
|
37
|
-
return posix(relative)
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function expectedPath(cwd, value) {
|
|
41
|
-
if (typeof value !== 'string' || !value.trim() || value.includes('\0')) {
|
|
42
|
-
throw new TypeError('预期目标必须是非空文件路径。')
|
|
43
|
-
}
|
|
44
|
-
const relative = relativeInside(cwd, path.resolve(cwd, value))
|
|
45
|
-
if (!relative) throw new TypeError(`预期目标必须位于工作区内:${JSON.stringify(value)}。`)
|
|
46
|
-
return relative
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function fingerprintEntries(cwd, expectedFingerprints) {
|
|
50
|
-
if (expectedFingerprints == null) return []
|
|
51
|
-
if (typeof expectedFingerprints !== 'object' || Array.isArray(expectedFingerprints)) {
|
|
52
|
-
throw new TypeError('expectedFingerprints 必须是从文件路径到 SHA-256 的对象。')
|
|
53
|
-
}
|
|
54
|
-
const entries = new Map()
|
|
55
|
-
for (const [filename, sha256] of Object.entries(expectedFingerprints)) {
|
|
56
|
-
if (typeof sha256 !== 'string' || sha256 === '') {
|
|
57
|
-
throw new TypeError(`预期指纹必须是非空字符串:${JSON.stringify(filename)}。`)
|
|
58
|
-
}
|
|
59
|
-
const relative = expectedPath(cwd, filename)
|
|
60
|
-
const key = pathKey(relative)
|
|
61
|
-
const expected = sha256.toLowerCase()
|
|
62
|
-
if (entries.has(key) && entries.get(key).expected !== expected) {
|
|
63
|
-
throw new TypeError(`同一文件声明了不同的预期指纹:${JSON.stringify(filename)}。`)
|
|
64
|
-
}
|
|
65
|
-
entries.set(key, { path: relative, expected })
|
|
66
|
-
}
|
|
67
|
-
return [...entries.values()].sort(byPath)
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function targetPaths(cwd, expectedTargets) {
|
|
71
|
-
if (expectedTargets == null) return []
|
|
72
|
-
if (!Array.isArray(expectedTargets)) throw new TypeError('expectedTargets 必须是文件路径数组。')
|
|
73
|
-
return expectedTargets.map((filename) => expectedPath(cwd, filename))
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function scopeOf(cwd, writeScope, readOnly) {
|
|
77
|
-
const validated = validateWriteScopeInput({ writeScope, readOnly })
|
|
78
|
-
const normalized = validated.ok && !validated.readOnly ? normalizeScope(validated.entries, cwd) : validated
|
|
79
|
-
if (!normalized.ok) throw Object.assign(new TypeError(normalized.message), { code: normalized.code })
|
|
80
|
-
return normalized.entries
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function observationMatches(left, right) {
|
|
84
|
-
return left.dev === right.dev && left.ino === right.ino && left.size === right.size &&
|
|
85
|
-
left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function fileObservation(root, realRoot, relative, fingerprint = true) {
|
|
89
|
-
try {
|
|
90
|
-
const filename = path.resolve(root, relative)
|
|
91
|
-
if (!relativeInside(root, filename) || relative.split('/').some((part) => pathKey(part) === '.git')) {
|
|
92
|
-
return { exists: null, reason: '目标超出文件审计边界' }
|
|
93
|
-
}
|
|
94
|
-
// Never follow a symlink/junction in the parent chain out of the checkout.
|
|
95
|
-
const realParent = fs.realpathSync.native(path.dirname(filename))
|
|
96
|
-
if (relativeInside(realRoot, realParent) === null) return { exists: null, reason: '目标父目录指向工作树外部' }
|
|
97
|
-
const stats = fs.lstatSync(filename)
|
|
98
|
-
if (!stats.isFile() && !stats.isSymbolicLink()) {
|
|
99
|
-
return fingerprint ? { exists: false, reason: '目标不是普通文件或符号链接' } : { exists: false }
|
|
100
|
-
}
|
|
101
|
-
if (!fingerprint) return { exists: true }
|
|
102
|
-
if (stats.isFile() && stats.size > MAX_FILE_BYTES) return { exists: true, reason: '超过单文件采样上限' }
|
|
103
|
-
|
|
104
|
-
const hash = createHash('sha256')
|
|
105
|
-
let bytes = 0
|
|
106
|
-
let lines = 0
|
|
107
|
-
let lastByte
|
|
108
|
-
const consume = (data) => {
|
|
109
|
-
hash.update(data)
|
|
110
|
-
bytes += data.length
|
|
111
|
-
for (let offset = data.indexOf(10); offset !== -1; offset = data.indexOf(10, offset + 1)) lines += 1
|
|
112
|
-
if (data.length > 0) lastByte = data[data.length - 1]
|
|
113
|
-
}
|
|
114
|
-
if (stats.isSymbolicLink()) {
|
|
115
|
-
consume(fs.readlinkSync(filename, { encoding: 'buffer' }))
|
|
116
|
-
} else {
|
|
117
|
-
const { O_RDONLY, O_NOFOLLOW = 0, O_NONBLOCK = 0 } = fs.constants
|
|
118
|
-
const fd = fs.openSync(filename, O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
|
|
119
|
-
try {
|
|
120
|
-
const opened = fs.fstatSync(fd)
|
|
121
|
-
if (!opened.isFile() || !observationMatches(stats, opened)) return { exists: true, reason: '采样时文件发生变化' }
|
|
122
|
-
const chunk = Buffer.allocUnsafe(Math.min(CHUNK_BYTES, stats.size))
|
|
123
|
-
while (bytes < stats.size) {
|
|
124
|
-
const count = fs.readSync(fd, chunk, 0, Math.min(chunk.length, stats.size - bytes), null)
|
|
125
|
-
if (count === 0) break
|
|
126
|
-
consume(chunk.subarray(0, count))
|
|
127
|
-
}
|
|
128
|
-
if (bytes !== stats.size) return { exists: true, reason: '采样时文件发生变化' }
|
|
129
|
-
} finally {
|
|
130
|
-
fs.closeSync(fd)
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
if (!observationMatches(stats, fs.lstatSync(filename))) return { exists: true, reason: '采样时文件发生变化' }
|
|
134
|
-
return { exists: true, sha256: hash.digest('hex'), bytes, lines: lines + (lastByte === 10 ? 0 : 1) }
|
|
135
|
-
} catch (error) {
|
|
136
|
-
return missing(error) ? { exists: false } : { exists: null, reason: `无法采样:${error.code ?? error.name}` }
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function readStatus(root) {
|
|
141
|
-
const dirty = []
|
|
142
|
-
const untracked = []
|
|
143
|
-
const args = ['status', '--porcelain=v1', '-z', '--no-renames', '--ignore-submodules=none', '--untracked-files=all']
|
|
144
|
-
for (const row of git(root, ...args).split('\0').filter(Boolean)) {
|
|
145
|
-
const filename = row.slice(3)
|
|
146
|
-
dirty.push(filename)
|
|
147
|
-
if (row.startsWith('??')) untracked.push(filename)
|
|
148
|
-
}
|
|
149
|
-
return { dirty, untracked }
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function diffRows(root, ...revisions) {
|
|
153
|
-
const tokens = git(root, 'diff', '--no-ext-diff', '--no-textconv', '--ignore-submodules=none',
|
|
154
|
-
'--no-renames', '--name-status', '-z', ...revisions, '--').split('\0')
|
|
155
|
-
const files = new Map()
|
|
156
|
-
for (let index = 0; index < tokens.length - 1; index += 2) {
|
|
157
|
-
const type = tokens[index]
|
|
158
|
-
const filename = tokens[index + 1]
|
|
159
|
-
if (!filename) throw new Error('Git name-status 没有返回有效路径。')
|
|
160
|
-
files.set(filename, type === 'A' ? 'added' : type === 'D' ? 'deleted' : 'modified')
|
|
161
|
-
}
|
|
162
|
-
return files
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
function checkoutRoot(cwd) {
|
|
166
|
-
return fs.realpathSync.native(git(cwd, 'rev-parse', '--show-toplevel').replace(/\r?\n$/, ''))
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
function assertCheckout(worktreePath) {
|
|
170
|
-
if (!fs.lstatSync(worktreePath).isDirectory() ||
|
|
171
|
-
path.relative(checkoutRoot(worktreePath), fs.realpathSync.native(worktreePath)) !== '') {
|
|
172
|
-
throw new TypeError('目录不是冻结的 Git 工作树根目录。')
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export function captureGitBaseline({ worktree, cwd = null, repoRoot = null, writeScope = [], readOnly = false,
|
|
177
|
-
expectedFingerprints = null, expectedTargets = null }) {
|
|
178
|
-
if (!worktree || typeof worktree.worktreePath !== 'string' || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i.test(worktree.baseCommit)) {
|
|
179
|
-
throw new TypeError('Git 审计需要工作树路径和有效的冻结基线提交。')
|
|
180
|
-
}
|
|
181
|
-
const worktreePath = path.resolve(worktree.worktreePath)
|
|
182
|
-
const execCwd = path.resolve(cwd ?? worktree.execCwd ?? worktreePath)
|
|
183
|
-
const sourceRoot = path.resolve(repoRoot ?? worktree.repoRoot)
|
|
184
|
-
assertCheckout(worktreePath)
|
|
185
|
-
const realRoot = fs.realpathSync.native(worktreePath)
|
|
186
|
-
if (relativeInside(worktreePath, execCwd) === null || relativeInside(realRoot, fs.realpathSync.native(execCwd)) === null) {
|
|
187
|
-
throw new TypeError('Git 审计的执行目录必须位于冻结的工作树内。')
|
|
188
|
-
}
|
|
189
|
-
const entries = scopeOf(execCwd, writeScope, readOnly)
|
|
190
|
-
const fingerprints = fingerprintEntries(execCwd, expectedFingerprints)
|
|
191
|
-
const fingerprintKeys = new Set(fingerprints.map((row) => pathKey(row.path)))
|
|
192
|
-
const explicitTargets = targetPaths(execCwd, expectedTargets)
|
|
193
|
-
const targets = new Map(explicitTargets.map((filename) => [pathKey(filename), filename]))
|
|
194
|
-
const selected = new Map([...explicitTargets, ...fingerprints.map((row) => row.path)]
|
|
195
|
-
.map((filename) => [pathKey(filename), filename]))
|
|
196
|
-
const declaredFiles = new Map()
|
|
197
|
-
for (const entry of entries) {
|
|
198
|
-
if (entry.kind !== SCOPE_KIND.file) continue
|
|
199
|
-
const filename = relativeInside(execCwd, entry.path)
|
|
200
|
-
if (!filename) continue
|
|
201
|
-
const key = pathKey(filename)
|
|
202
|
-
declaredFiles.set(key, filename)
|
|
203
|
-
if (!selected.has(key)) selected.set(key, filename)
|
|
204
|
-
}
|
|
205
|
-
const targetSnapshots = []
|
|
206
|
-
const baselineIssues = []
|
|
207
|
-
for (const [key, filename] of selected) {
|
|
208
|
-
const entry = fileObservation(worktreePath, realRoot, posix(path.relative(worktreePath, path.resolve(execCwd, filename))))
|
|
209
|
-
targetSnapshots.push(Object.freeze({ path: filename, ...entry }))
|
|
210
|
-
if (declaredFiles.has(key) && entry.exists) targets.set(key, filename)
|
|
211
|
-
if (entry.exists === null && declaredFiles.has(key) && !fingerprintKeys.has(key)) {
|
|
212
|
-
baselineIssues.push(Object.freeze({ code: 'audit-incomplete', path: filename, phase: 'baseline', reason: entry.reason }))
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
return Object.freeze({
|
|
216
|
-
baselineId: randomUUID(), kind: 'git-worktree', worktreeId: worktree.id, worktreePath, execCwd, cwd: execCwd,
|
|
217
|
-
repoRoot: sourceRoot, branch: worktree.branch, baseCommit: worktree.baseCommit,
|
|
218
|
-
writeScope: Object.freeze(typeof writeScope === 'string' ? [writeScope] : [...writeScope]), readOnly: readOnly === true,
|
|
219
|
-
expectedFingerprints: Object.freeze(Object.fromEntries(fingerprints.map((row) => [row.path, row.expected]))),
|
|
220
|
-
expectedTargets: Object.freeze([...targets.values()].sort()), capturedAt: Date.now(),
|
|
221
|
-
targetSnapshots: Object.freeze(targetSnapshots.sort(byPath)), baselineIssues: Object.freeze(baselineIssues),
|
|
222
|
-
mainBeforeDirty: Object.freeze(readStatus(sourceRoot).dirty),
|
|
223
|
-
})
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
function listCommits(root, baseCommit) {
|
|
227
|
-
return git(root, 'log', '--format=%H%x1f%h%x1f%s', `${baseCommit}..HEAD`, '--')
|
|
228
|
-
.split('\n').filter(Boolean).map((row) => {
|
|
229
|
-
const [hash, shortHash, ...subject] = row.split('\x1f')
|
|
230
|
-
return { hash, shortHash, subject: subject.join('\x1f') }
|
|
231
|
-
})
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
function compareFingerprint(row, observation, phase, violations) {
|
|
235
|
-
const actual = observation?.sha256
|
|
236
|
-
if (actual == null && (phase === 'baseline' || observation?.exists !== false)) {
|
|
237
|
-
violations.push({ code: 'audit-incomplete', path: row.path, phase, reason: observation?.reason ?? '无法核对预期指纹' })
|
|
238
|
-
} else if (actual !== row.expected) {
|
|
239
|
-
violations.push({ code: 'fingerprint-mismatch', path: row.path, phase, expected: row.expected, actual: actual ?? null })
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// An index deletion can make a recreated file appear both deleted and untracked.
|
|
244
|
-
// Compare the recreated object (after Git's normal clean conversion) with the base tree.
|
|
245
|
-
function replacesBaseFile(root, baseCommit, filename, observation) {
|
|
246
|
-
const entry = git(root, 'ls-tree', '-z', baseCommit, '--', filename)
|
|
247
|
-
const match = /^(100(?:644|755)|120000) blob ([a-f0-9]+)\t/.exec(entry)
|
|
248
|
-
if (!match || !observation.exists) return true
|
|
249
|
-
const absolute = path.resolve(root, filename)
|
|
250
|
-
const stats = fs.lstatSync(absolute)
|
|
251
|
-
const symlink = stats.isSymbolicLink()
|
|
252
|
-
if ((match[1] === '120000') !== symlink) return true
|
|
253
|
-
if (!symlink && !WINDOWS && (match[1] === '100755') !== Boolean(stats.mode & 0o100)) return true
|
|
254
|
-
if (symlink) {
|
|
255
|
-
const data = fs.readlinkSync(absolute, { encoding: 'buffer' })
|
|
256
|
-
const algo = match[2].length === 64 ? 'sha256' : 'sha1'
|
|
257
|
-
return createHash(algo).update(`blob ${data.length}\0`).update(data).digest('hex') !== match[2]
|
|
258
|
-
}
|
|
259
|
-
return git(root, 'hash-object', `--path=${filename}`, '--', absolute).trim() !== match[2]
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
export function auditGitBaseline(baseline, overrides = {}) {
|
|
263
|
-
const { execCwd, worktreePath, repoRoot, baseCommit } = baseline
|
|
264
|
-
const { cwd, writeScope, readOnly, expectedFingerprints, expectedTargets } = overrides
|
|
265
|
-
if (cwd !== undefined && path.relative(execCwd, path.resolve(cwd)) !== '') {
|
|
266
|
-
throw new TypeError('审计结算必须使用冻结基线时的 cwd。')
|
|
267
|
-
}
|
|
268
|
-
const effectiveReadOnly = baseline.readOnly || readOnly === true
|
|
269
|
-
const entries = scopeOf(execCwd, baseline.writeScope, baseline.readOnly)
|
|
270
|
-
const narrowed = writeScope === undefined ? entries : scopeOf(execCwd, writeScope, effectiveReadOnly)
|
|
271
|
-
const expected = fingerprintEntries(execCwd, expectedFingerprints)
|
|
272
|
-
const targets = new Map([...targetPaths(execCwd, expectedTargets), ...baseline.expectedTargets]
|
|
273
|
-
.map((filename) => [pathKey(filename), filename]))
|
|
274
|
-
const before = new Map(baseline.targetSnapshots.map((row) => [pathKey(row.path), row]))
|
|
275
|
-
const violations = [...baseline.baselineIssues]
|
|
276
|
-
const changedFiles = []
|
|
277
|
-
let commits = []
|
|
278
|
-
let headCommit = null
|
|
279
|
-
let dirtyFiles = []
|
|
280
|
-
let mainWorkspaceTaint = []
|
|
281
|
-
let isolationNote = ISOLATION_NOTE
|
|
282
|
-
const incomplete = (filename, reason) => violations.push({ code: 'audit-incomplete', path: filename, phase: 'settlement', reason })
|
|
283
|
-
|
|
284
|
-
for (const row of fingerprintEntries(execCwd, baseline.expectedFingerprints)) {
|
|
285
|
-
compareFingerprint(row, before.get(pathKey(row.path)), 'baseline', violations)
|
|
286
|
-
}
|
|
287
|
-
try {
|
|
288
|
-
assertCheckout(worktreePath)
|
|
289
|
-
const realRoot = fs.realpathSync.native(worktreePath)
|
|
290
|
-
headCommit = git(worktreePath, 'rev-parse', 'HEAD').trim()
|
|
291
|
-
commits = listCommits(worktreePath, baseCommit)
|
|
292
|
-
const committed = diffRows(worktreePath, `${baseCommit}..HEAD`)
|
|
293
|
-
const staged = diffRows(worktreePath, '--cached')
|
|
294
|
-
const unstaged = diffRows(worktreePath)
|
|
295
|
-
const current = readStatus(worktreePath)
|
|
296
|
-
dirtyFiles = [...new Set([...staged.keys(), ...unstaged.keys(), ...current.dirty])]
|
|
297
|
-
const net = diffRows(worktreePath, baseCommit)
|
|
298
|
-
const untracked = new Set(current.untracked)
|
|
299
|
-
const post = new Map()
|
|
300
|
-
const observe = (repoRelative, fingerprint = true) => {
|
|
301
|
-
const key = `${fingerprint}:${repoRelative}`
|
|
302
|
-
if (!post.has(key)) post.set(key, fileObservation(worktreePath, realRoot, repoRelative, fingerprint))
|
|
303
|
-
return post.get(key)
|
|
304
|
-
}
|
|
305
|
-
// Restrict byte observations to the effective change set, not every historical path.
|
|
306
|
-
for (const filename of new Set([...committed.keys(), ...staged.keys(), ...unstaged.keys(), ...net.keys(), ...untracked])) {
|
|
307
|
-
let changeType = net.get(filename)
|
|
308
|
-
let observation
|
|
309
|
-
if (untracked.has(filename)) {
|
|
310
|
-
observation = observe(filename)
|
|
311
|
-
if (changeType === 'deleted') {
|
|
312
|
-
if (observation.sha256 && !replacesBaseFile(worktreePath, baseCommit, filename, observation)) continue
|
|
313
|
-
changeType = 'modified'
|
|
314
|
-
} else changeType ??= 'added'
|
|
315
|
-
}
|
|
316
|
-
if (!changeType) continue
|
|
317
|
-
const absolute = path.resolve(worktreePath, filename)
|
|
318
|
-
const relative = posix(path.relative(execCwd, absolute))
|
|
319
|
-
const inExecCwd = Boolean(relativeInside(execCwd, absolute))
|
|
320
|
-
if (changeType !== 'deleted') {
|
|
321
|
-
observation ??= observe(filename)
|
|
322
|
-
if (observation.exists === false && !observation.reason) {
|
|
323
|
-
if (changeType === 'added') continue
|
|
324
|
-
changeType = 'deleted'
|
|
325
|
-
} else if (!observation.sha256) incomplete(relative, observation.reason ?? '无法计算变更文件指纹')
|
|
326
|
-
}
|
|
327
|
-
changedFiles.push({ path: relative, changeType,
|
|
328
|
-
sha256: changeType === 'deleted' ? null : observation.sha256 ?? null,
|
|
329
|
-
bytes: changeType === 'deleted' ? 0 : observation.bytes ?? 0,
|
|
330
|
-
lines: changeType === 'deleted' ? 0 : observation.lines ?? 0,
|
|
331
|
-
})
|
|
332
|
-
if (effectiveReadOnly) violations.push({ code: 'readonly-write', path: relative, changeType })
|
|
333
|
-
else if (!inExecCwd || !isPathWithinScope(absolute, entries, { cwd: execCwd }) ||
|
|
334
|
-
(narrowed !== entries && !isPathWithinScope(absolute, narrowed, { cwd: execCwd }))) {
|
|
335
|
-
violations.push({ code: 'out-of-scope-write', path: relative, changeType })
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
const toRepoPath = (filename) => posix(path.relative(worktreePath, path.resolve(execCwd, filename)))
|
|
340
|
-
for (const row of expected) compareFingerprint(row, observe(toRepoPath(row.path)), 'settlement', violations)
|
|
341
|
-
for (const filename of targets.values()) {
|
|
342
|
-
const observation = observe(toRepoPath(filename), false)
|
|
343
|
-
if (observation.exists === false) violations.push({ code: 'target-missing', path: filename })
|
|
344
|
-
else if (observation.exists === null) incomplete(filename, observation.reason ?? '无法核对目标是否存在')
|
|
345
|
-
}
|
|
346
|
-
} catch (error) {
|
|
347
|
-
incomplete('.', `无法完成 Git 工作树采样:${gitError(error)}`)
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
try {
|
|
351
|
-
const previous = new Set(baseline.mainBeforeDirty.map(pathKey))
|
|
352
|
-
const pool = pathKey(WORKTREE_POOL_DIRNAME)
|
|
353
|
-
mainWorkspaceTaint = readStatus(repoRoot).dirty
|
|
354
|
-
.filter((filename) => !previous.has(pathKey(filename)) && pathKey(filename) !== pool &&
|
|
355
|
-
!pathKey(filename).startsWith(`${pool}/`)).sort()
|
|
356
|
-
} catch (error) {
|
|
357
|
-
isolationNote += `无法观测主仓污点:${gitError(error)}`
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
const summary = { added: 0, modified: 0, deleted: 0, violations: violations.length, truncated: false,
|
|
361
|
-
commits: commits.length, dirty: dirtyFiles.length > 0 }
|
|
362
|
-
for (const file of changedFiles) summary[file.changeType] += 1
|
|
363
|
-
return {
|
|
364
|
-
baselineId: baseline.baselineId, passed: violations.length === 0, readOnly: effectiveReadOnly,
|
|
365
|
-
isolationLevel: 'git-worktree', isolationNote,
|
|
366
|
-
changedFiles: changedFiles.sort(byPath), violations: violations.sort(byPath), summary,
|
|
367
|
-
git: { worktreeId: baseline.worktreeId, worktreePath, branch: baseline.branch, baseCommit, headCommit,
|
|
368
|
-
commits, dirtyFiles: dirtyFiles.sort(), mainWorkspaceTaint },
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
export function formatGitAuditReport(auditResult) {
|
|
373
|
-
const { baselineId, passed, violations, summary, git: evidence } = auditResult
|
|
374
|
-
const details = violations.slice(0, MAX_REPORT_ROWS).map(({ code, path: filename }) =>
|
|
375
|
-
`- ${code}:${JSON.stringify(filename)}`)
|
|
376
|
-
if (violations.length > details.length) details.push(`另有 ${violations.length - details.length} 项未列出。`)
|
|
377
|
-
return [
|
|
378
|
-
`写作用域审计${passed ? '通过' : '未通过'}(git-worktree;基线 ${baselineId};分支 ${evidence.branch};${summary.commits} 个提交)。`,
|
|
379
|
-
...(summary.dirty ? [`工作树有 ${evidence.dirtyFiles.length} 项未提交改动。`] : []),
|
|
380
|
-
...(evidence.mainWorkspaceTaint.length ? [`主仓出现 ${evidence.mainWorkspaceTaint.length} 项新增污点(仅观测)。`] : []),
|
|
381
|
-
...details,
|
|
382
|
-
].join('\n')
|
|
383
|
-
}
|