dsh-config-sync-plugin 0.3.66 → 0.3.68
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.en.md +50 -1
- package/README.md +50 -1
- package/client.js +81 -1
- package/index.js +215 -8
- package/package.json +1 -1
- package/runtime/apply.ps1 +33 -1
- package/runtime/capture.ps1 +68 -38
- package/runtime/dsh-sync-common.ps1 +131 -1
- package/runtime/tools/session-cache-guard.mjs +407 -0
- package/runtime/tools/session-log-guard.mjs +438 -0
- package/runtime/tools/session-log-lib.mjs +322 -0
- package/tools/check-session-log.mjs +156 -0
- package/tools/pack-plugin.ps1 +1 -1
- package/tools/selftest.mjs +69 -3
- package/tools/session-log-guard.mjs +438 -0
- package/tools/session-log-lib.mjs +322 -0
package/runtime/capture.ps1
CHANGED
|
@@ -54,6 +54,45 @@ $ErrorActionPreference = 'Stop'
|
|
|
54
54
|
if (-not $RepoRoot) { $RepoRoot = $PSScriptRoot }
|
|
55
55
|
. (Join-Path $PSScriptRoot 'dsh-sync-common.ps1')
|
|
56
56
|
|
|
57
|
+
function Get-NormalizedHash($path) {
|
|
58
|
+
# 文本文件按"去掉 CRLF/LF 差异后的内容"比较,避免换行转换制造假变更;归档文件按原始字节比较
|
|
59
|
+
$ext = [IO.Path]::GetExtension($path).ToLower()
|
|
60
|
+
if ($ext -in @('.tgz', '.zip')) {
|
|
61
|
+
return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash
|
|
62
|
+
}
|
|
63
|
+
$bytes = [IO.File]::ReadAllBytes($path)
|
|
64
|
+
$text = [Text.Encoding]::UTF8.GetString($bytes)
|
|
65
|
+
$norm = $text -replace "`r`n", "`n"
|
|
66
|
+
$sha = [Security.Cryptography.SHA256]::Create()
|
|
67
|
+
return [BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($norm)))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
# ---------- 大目录文件比较(性能关键路径) ----------
|
|
71
|
+
# 旧写法对每个文件算两次 Get-FileHash(源 + 仓库),5 万个文件实测约 120s。
|
|
72
|
+
# 现在:两个 tree 各枚举一次拿 FileInfo(Length/LastWriteTimeUtc 已在枚举时读好,不再 stat),
|
|
73
|
+
# 内存里比对;只有「大小不同」或「源比仓库新」才对该文件算哈希确认内容。
|
|
74
|
+
# 这与 git 自己的判定策略一致(size+mtime 变了才重算 blob)。
|
|
75
|
+
$script:CmpDeep = [bool]$DeepVerify
|
|
76
|
+
$script:CmpFileCount = 0
|
|
77
|
+
$script:CmpHashCount = 0
|
|
78
|
+
|
|
79
|
+
function Test-TreeFileChanged($srcInfo, $dstInfo) {
|
|
80
|
+
# $srcInfo / $dstInfo 都是 FileInfo($dstInfo 为 $null 表示仓库里没有这个文件)
|
|
81
|
+
$script:CmpFileCount++
|
|
82
|
+
if ($null -eq $dstInfo) { return $true }
|
|
83
|
+
if ($srcInfo.Length -ne $dstInfo.Length) { return $true }
|
|
84
|
+
if ($script:CmpDeep -or ($srcInfo.LastWriteTimeUtc -gt $dstInfo.LastWriteTimeUtc)) {
|
|
85
|
+
$script:CmpHashCount++
|
|
86
|
+
return ((Get-NormalizedHash $srcInfo.FullName) -ne (Get-NormalizedHash $dstInfo.FullName))
|
|
87
|
+
}
|
|
88
|
+
return $false
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function Get-TreeCmpSummary {
|
|
92
|
+
$deep = if ($script:CmpDeep) { '深校验开' } else { '快筛' }
|
|
93
|
+
return ('文件比较({0}):比对 {1} 个,深哈希 {2} 个' -f $deep, $script:CmpFileCount, $script:CmpHashCount)
|
|
94
|
+
}
|
|
95
|
+
|
|
57
96
|
if (-not $NoResetNotices) { Reset-SyncNotices $DshHome 'capture' }
|
|
58
97
|
|
|
59
98
|
# 客户端可能被卸载重装到别的盘:-AppRoot 先校验,对不上就自动定位(注册表 → 常见位置)。
|
|
@@ -421,6 +460,9 @@ function Sync-ConversationCapture {
|
|
|
421
460
|
if ($rel) { $dstRels[$rel] = $rf }
|
|
422
461
|
}
|
|
423
462
|
$madeDirs = @{}
|
|
463
|
+
# 会话日志不能整文件覆盖:两台机器可能各自 append 出不同 lineage,直接覆盖会让一方的事件
|
|
464
|
+
# 整段消失,DSH 启动时报 "seq gap"。这里先攒成批量任务,交给 seq 护栏对账后再写。
|
|
465
|
+
$guardJobs = [System.Collections.Generic.List[object]]::new()
|
|
424
466
|
foreach ($rel in @($srcRels.Keys)) {
|
|
425
467
|
$si = $srcRels[$rel]
|
|
426
468
|
if (-not (Test-TreeFileChanged $si $dstRels[$rel])) { continue }
|
|
@@ -430,11 +472,37 @@ function Sync-ConversationCapture {
|
|
|
430
472
|
if (-not (Test-Path -LiteralPath $dd)) { New-Item -ItemType Directory -Path $dd -Force | Out-Null }
|
|
431
473
|
$madeDirs[$dd] = $true
|
|
432
474
|
}
|
|
475
|
+
if (Test-SessionLogFile $rel) {
|
|
476
|
+
$guardJobs.Add([ordered]@{ Src = $si.FullName; Dst = $d; WriteTo = $d }) | Out-Null
|
|
477
|
+
$dstRels[$rel] = [IO.FileInfo]::new($d)
|
|
478
|
+
continue
|
|
479
|
+
}
|
|
433
480
|
Copy-Item -LiteralPath $si.FullName -Destination $d -Force
|
|
434
481
|
$changed.Add(('conversations/{0}/{1}' -f $b.Dst, $rel.Replace($BS,'/'))) | Out-Null
|
|
435
482
|
$nAdd++
|
|
436
483
|
$dstRels[$rel] = [IO.FileInfo]::new($d)
|
|
437
484
|
}
|
|
485
|
+
if ($guardJobs.Count -gt 0) {
|
|
486
|
+
$g = Invoke-SessionLogGuard -Jobs $guardJobs.ToArray() -AppRoot $AppRoot -ScriptRoot $PSScriptRoot -RepoRoot $RepoRoot -BackupDir (Join-Path $convDir '_session-log-guard-backup')
|
|
487
|
+
Write-SessionLogGuardReport $g $DshHome '抓取'
|
|
488
|
+
if ($g.Skipped) {
|
|
489
|
+
# 护栏用不了(没 Node/脚本缺失):退回整文件覆盖,至少保持原来的行为
|
|
490
|
+
foreach ($j in $guardJobs) {
|
|
491
|
+
Copy-Item -LiteralPath $j.Src -Destination $j.WriteTo -Force
|
|
492
|
+
$rr = Get-RelPath $dstRoot ([string]$j.WriteTo)
|
|
493
|
+
if ($rr) { $changed.Add(('conversations/{0}/{1}' -f $b.Dst, $rr.Replace($BS,'/'))) | Out-Null }
|
|
494
|
+
$nAdd++
|
|
495
|
+
}
|
|
496
|
+
} else {
|
|
497
|
+
foreach ($r in @($g.Results)) {
|
|
498
|
+
if ($r -and $r.wrote) {
|
|
499
|
+
$rr = Get-RelPath $dstRoot ([string]$r.wrote)
|
|
500
|
+
if ($rr) { $changed.Add(('conversations/{0}/{1}' -f $b.Dst, $rr.Replace($BS,'/'))) | Out-Null }
|
|
501
|
+
$nAdd++
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
438
506
|
# 镜像删除:本机已删的会话文件,仓库里也删
|
|
439
507
|
foreach ($rel in @($dstRels.Keys)) {
|
|
440
508
|
if (-not $srcRels.ContainsKey($rel)) {
|
|
@@ -515,44 +583,6 @@ if ($WorkspaceOnly) {
|
|
|
515
583
|
}
|
|
516
584
|
return
|
|
517
585
|
}
|
|
518
|
-
function Get-NormalizedHash($path) {
|
|
519
|
-
# 文本文件按"去掉 CRLF/LF 差异后的内容"比较,避免换行转换制造假变更;归档文件按原始字节比较
|
|
520
|
-
$ext = [IO.Path]::GetExtension($path).ToLower()
|
|
521
|
-
if ($ext -in @('.tgz', '.zip')) {
|
|
522
|
-
return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash
|
|
523
|
-
}
|
|
524
|
-
$bytes = [IO.File]::ReadAllBytes($path)
|
|
525
|
-
$text = [Text.Encoding]::UTF8.GetString($bytes)
|
|
526
|
-
$norm = $text -replace "`r`n", "`n"
|
|
527
|
-
$sha = [Security.Cryptography.SHA256]::Create()
|
|
528
|
-
return [BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($norm)))
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
# ---------- 大目录文件比较(性能关键路径) ----------
|
|
532
|
-
# 旧写法对每个文件算两次 Get-FileHash(源 + 仓库),5 万个文件实测约 120s。
|
|
533
|
-
# 现在:两个 tree 各枚举一次拿 FileInfo(Length/LastWriteTimeUtc 已在枚举时读好,不再 stat),
|
|
534
|
-
# 内存里比对;只有「大小不同」或「源比仓库新」才对该文件算哈希确认内容。
|
|
535
|
-
# 这与 git 自己的判定策略一致(size+mtime 变了才重算 blob)。
|
|
536
|
-
$script:CmpDeep = [bool]$DeepVerify
|
|
537
|
-
$script:CmpFileCount = 0
|
|
538
|
-
$script:CmpHashCount = 0
|
|
539
|
-
|
|
540
|
-
function Test-TreeFileChanged($srcInfo, $dstInfo) {
|
|
541
|
-
# $srcInfo / $dstInfo 都是 FileInfo($dstInfo 为 $null 表示仓库里没有这个文件)
|
|
542
|
-
$script:CmpFileCount++
|
|
543
|
-
if ($null -eq $dstInfo) { return $true }
|
|
544
|
-
if ($srcInfo.Length -ne $dstInfo.Length) { return $true }
|
|
545
|
-
if ($script:CmpDeep -or ($srcInfo.LastWriteTimeUtc -gt $dstInfo.LastWriteTimeUtc)) {
|
|
546
|
-
$script:CmpHashCount++
|
|
547
|
-
return ((Get-NormalizedHash $srcInfo.FullName) -ne (Get-NormalizedHash $dstInfo.FullName))
|
|
548
|
-
}
|
|
549
|
-
return $false
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
function Get-TreeCmpSummary {
|
|
553
|
-
$deep = if ($script:CmpDeep) { '深校验开' } else { '快筛' }
|
|
554
|
-
return ('文件比较({0}):比对 {1} 个,深哈希 {2} 个' -f $deep, $script:CmpFileCount, $script:CmpHashCount)
|
|
555
|
-
}
|
|
556
586
|
function CopyNormalized($src, $dst) {
|
|
557
587
|
# 二进制原样拷贝;文本统一写成 LF(与 .gitattributes 的 eol=lf 对齐),并保留原文件的 UTF-8 BOM
|
|
558
588
|
$ext = [IO.Path]::GetExtension($src).ToLower()
|
|
@@ -1010,4 +1010,134 @@ function Get-TokenHint([string]$token) {
|
|
|
1010
1010
|
return ('自选目录:' + $key + ' —— 这台机器上对应的路径由你来定')
|
|
1011
1011
|
}
|
|
1012
1012
|
}
|
|
1013
|
-
}
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
# ---------- 会话日志跨机护栏(按 seq 对账,防 corrupt / seq gap)----------
|
|
1016
|
+
# 为什么需要它:
|
|
1017
|
+
# 会话日志(session.v4.jsonl.zstd)是 append-only 的多帧 zstd,每个事件一行、带连续 seq。
|
|
1018
|
+
# 同步是「整文件覆盖」:capture 把本机整份拷进仓库,apply 把仓库整份铺回本机。
|
|
1019
|
+
# 两台机器同时在同一个会话里跑,各自 append 出不同 lineage;整文件覆盖必然让其中一方的
|
|
1020
|
+
# 事件整段消失。更糟的是「拼接」——本机文件被换成较短版本后 DSH 仍按自己的计数继续
|
|
1021
|
+
# append,于是「A 的前 N 条 + B 从 M 起」首尾相接,启动时报
|
|
1022
|
+
# corrupt session log: released v2 row N has seq gap (expected N, got M)
|
|
1023
|
+
# 写到这一步事件已经丢了,只能人工处理。所以写入之前先做一次 seq 对账。
|
|
1024
|
+
#
|
|
1025
|
+
# 判据(append-only 的硬性质):同源两份日志去掉首帧后,短的那份必然是长的那份的字节前缀。
|
|
1026
|
+
# take_src 源是目标的严格超集 → 覆盖(正常路径,零额外风险)
|
|
1027
|
+
# keep_dst 目标更全或两边相同 → 不写,绝不回退(保护「本机更新」的那一侧)
|
|
1028
|
+
# merge 两边各有对方没有的事件(真分叉),或目标自身已断档但能被源补齐
|
|
1029
|
+
# → 按 seq 求并集后写入,一个事件都不丢
|
|
1030
|
+
# 失败 并集仍有空洞(事件真的丢了)→ 拒绝写,Warn + 记 notices,等人工介入
|
|
1031
|
+
#
|
|
1032
|
+
# 退路:找不到 Node/Electron 执行器、或护栏自身报错时退回原来的整文件覆盖(并 Warn)。
|
|
1033
|
+
# 护栏是多加的一层保护,不能让没装 Node 的机器彻底同步不了。
|
|
1034
|
+
|
|
1035
|
+
# 会话日志文件名判定(与 DSH 的 ARTIFACT_NAMES 对齐:session.v4.jsonl.zstd / session.jsonl.zstd / session.jsonl ...)
|
|
1036
|
+
function Test-SessionLogFile([string]$relOrName) {
|
|
1037
|
+
if (-not $relOrName) { return $false }
|
|
1038
|
+
$leaf = @(($relOrName -replace '/', '\') -split '\\')[-1]
|
|
1039
|
+
return ($leaf -match '^session(\.[A-Za-z0-9]+)*\.jsonl(\.zstd)?$')
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
function Get-SessionLogGuardPath([string]$scriptRoot, [string]$repoRoot) {
|
|
1043
|
+
foreach ($base in @($scriptRoot, $repoRoot)) {
|
|
1044
|
+
if (-not $base) { continue }
|
|
1045
|
+
foreach ($rel in @('tools\session-log-guard.mjs', 'runtime\tools\session-log-guard.mjs')) {
|
|
1046
|
+
$p = Join-Path $base $rel
|
|
1047
|
+
if (Test-Path -LiteralPath $p) { return $p }
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
return $null
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
# $Jobs: @( @{ Src = '<要采用的候选>'; Dst = '<当前生效的那份>'; WriteTo = '<把赢家写到哪里>' }, ... )
|
|
1054
|
+
# 返回 [ordered]@{ Ok; Total; Take; Merge; Keep; Failed; Results; Skipped; Reason }
|
|
1055
|
+
# 一次调用把整批会话日志跑完:一台机器几十个会话,逐个起 node 光进程启动就要好几秒。
|
|
1056
|
+
function Invoke-SessionLogGuard {
|
|
1057
|
+
param(
|
|
1058
|
+
[object[]]$Jobs,
|
|
1059
|
+
[string]$AppRoot,
|
|
1060
|
+
[string]$ScriptRoot,
|
|
1061
|
+
[string]$RepoRoot,
|
|
1062
|
+
[string]$BackupDir
|
|
1063
|
+
)
|
|
1064
|
+
$res = [ordered]@{ Ok = $true; Total = 0; Take = 0; Merge = 0; Keep = 0; Failed = 0; Results = @(); Skipped = $true; Reason = '' }
|
|
1065
|
+
if (-not $Jobs -or @($Jobs).Count -eq 0) { $res.Reason = '没有需要带护栏写入的会话日志'; return $res }
|
|
1066
|
+
$jobs = @($Jobs)
|
|
1067
|
+
|
|
1068
|
+
$helper = Get-SessionLogGuardPath $ScriptRoot $RepoRoot
|
|
1069
|
+
if (-not $helper) {
|
|
1070
|
+
$res.Reason = '找不到 tools\session-log-guard.mjs'
|
|
1071
|
+
return $res
|
|
1072
|
+
}
|
|
1073
|
+
$runner = Get-HostNodeRunner $AppRoot
|
|
1074
|
+
if (-not $runner) {
|
|
1075
|
+
$res.Reason = '这台机器既没有 Node 也找不到客户端本体'
|
|
1076
|
+
return $res
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
$stamp = Get-Date -Format 'yyyyMMddHHmmssfff'
|
|
1080
|
+
$jobPath = Join-Path ([IO.Path]::GetTempPath()) ('dsh-sessionlog-job-{0}-{1}.json' -f $stamp, $PID)
|
|
1081
|
+
$outPath = Join-Path ([IO.Path]::GetTempPath()) ('dsh-sessionlog-out-{0}-{1}.json' -f $stamp, $PID)
|
|
1082
|
+
$spec = [ordered]@{
|
|
1083
|
+
backupDir = [string]$BackupDir
|
|
1084
|
+
jobs = @($jobs | ForEach-Object {
|
|
1085
|
+
[ordered]@{ src = [string]$_.Src; dst = [string]$_.Dst; writeTo = [string]$_.WriteTo }
|
|
1086
|
+
})
|
|
1087
|
+
}
|
|
1088
|
+
[IO.File]::WriteAllText($jobPath, ($spec | ConvertTo-Json -Depth 5 -Compress), (New-Object Text.UTF8Encoding($false)))
|
|
1089
|
+
|
|
1090
|
+
$oldRunAsNode = $env:ELECTRON_RUN_AS_NODE
|
|
1091
|
+
try {
|
|
1092
|
+
if ($runner.Electron) { $env:ELECTRON_RUN_AS_NODE = '1' }
|
|
1093
|
+
else { Remove-Item Env:\ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue }
|
|
1094
|
+
# 结果落文件而不是抓 stdout:执行器可能是客户端自带的 Electron(GUI 子系统,stdout 抓不到)
|
|
1095
|
+
& $runner.Exe $helper 'batch' $jobPath $outPath *> $null
|
|
1096
|
+
$code = $LASTEXITCODE
|
|
1097
|
+
if (-not (Test-Path -LiteralPath $outPath)) {
|
|
1098
|
+
$res.Reason = ('护栏没有产出结果文件(执行器退出码 {0})' -f $code)
|
|
1099
|
+
return $res
|
|
1100
|
+
}
|
|
1101
|
+
$r = ([IO.File]::ReadAllText($outPath)) | ConvertFrom-Json -ErrorAction Stop
|
|
1102
|
+
$res.Total = [int]$r.total
|
|
1103
|
+
$res.Take = [int]$r.take
|
|
1104
|
+
$res.Merge = [int]$r.merge
|
|
1105
|
+
$res.Keep = [int]$r.keep
|
|
1106
|
+
$res.Failed = [int]$r.failed
|
|
1107
|
+
$res.Ok = [bool]$r.ok
|
|
1108
|
+
$res.Results = @($r.results)
|
|
1109
|
+
$res.Skipped = $false
|
|
1110
|
+
return $res
|
|
1111
|
+
} catch {
|
|
1112
|
+
$res.Reason = ('护栏执行出错:{0}' -f $_.Exception.Message)
|
|
1113
|
+
return $res
|
|
1114
|
+
} finally {
|
|
1115
|
+
if ($null -eq $oldRunAsNode) { Remove-Item Env:\ELECTRON_RUN_AS_NODE -ErrorAction SilentlyContinue }
|
|
1116
|
+
else { $env:ELECTRON_RUN_AS_NODE = $oldRunAsNode }
|
|
1117
|
+
Remove-Item -LiteralPath $jobPath -Force -ErrorAction SilentlyContinue
|
|
1118
|
+
Remove-Item -LiteralPath $outPath -Force -ErrorAction SilentlyContinue
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
# 把护栏结果变成给用户看的提示。失败项一律记进 notices —— 面板/收尾汇总才看得到。
|
|
1123
|
+
function Write-SessionLogGuardReport($Guard, [string]$DshHome, [string]$Verb) {
|
|
1124
|
+
if (-not $Guard) { return }
|
|
1125
|
+
if ($Guard.Skipped) {
|
|
1126
|
+
Warn ('会话日志 seq 护栏本次未启用({0}):退回整文件覆盖' -f $Guard.Reason)
|
|
1127
|
+
return
|
|
1128
|
+
}
|
|
1129
|
+
Ok ('会话日志 seq 对账({0}):核对 {1} 个、覆盖 {2} 个、求并集 {3} 个、保留本机 {4} 个' -f $Verb, $Guard.Total, $Guard.Take, $Guard.Merge, $Guard.Keep)
|
|
1130
|
+
if ([int]$Guard.Merge -gt 0) {
|
|
1131
|
+
Ok (' 其中 {0} 个会话两边各有独占事件,已按 seq 求并集写入(两边的事件都保住了)' -f $Guard.Merge)
|
|
1132
|
+
}
|
|
1133
|
+
if ([int]$Guard.Failed -gt 0) {
|
|
1134
|
+
foreach ($item in @($Guard.Results)) {
|
|
1135
|
+
if ($item -and (-not $item.ok)) {
|
|
1136
|
+
Warn (' 会话日志无法自动修复:{0}({1})' -f [string]$item.dst, [string]$item.detail)
|
|
1137
|
+
if ($DshHome) { Add-SyncNotice -Kind 'failed' -Path ([string]$item.dst) -Reason ('会话日志 seq 断档:' + [string]$item.detail) }
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
Warn (' 有 {0} 个会话日志的断档补不回来(事件已丢),已保持原样不覆盖;DSH 里这些会话可能报 corrupt' -f $Guard.Failed)
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
// 会话投影缓存守卫(session_projcache 陈旧记录自动清理)
|
|
2
|
+
//
|
|
3
|
+
// 解决的问题
|
|
4
|
+
// DSH 的「新建会话」不是每次真建,UI 会先在工作区里找一条**空白会话**复用:
|
|
5
|
+
// client-ui-workspace/createInWorkspace() → sessions.ids.find(summary.blank && ...)
|
|
6
|
+
// → createNamed({ sessionId: blank })
|
|
7
|
+
// 而 summary.blank 来自投影缓存 session_projcache\sessions\<id>.json 里的
|
|
8
|
+
// record.rows.sessionListMetadata.val.blank。
|
|
9
|
+
//
|
|
10
|
+
// 缓存是「写一半就停」的产物:某次会话创建时缓存写出了 blank:true + seq:-1,
|
|
11
|
+
// 之后日志继续追加(有了 turn/start、user/message),缓存却没被推进。
|
|
12
|
+
// 于是列表仍把这条会话当"空白",UI 挑它复用 → 宿主抛
|
|
13
|
+
// session/agent-busy: session "<id>" is owned by subagent routing
|
|
14
|
+
// (子会话 origin=subagent 不允许被主会话直接复用),新建会话直接失败。
|
|
15
|
+
//
|
|
16
|
+
// 处理办法
|
|
17
|
+
// 删掉那条 cache json,DSH 下次读列表时会按完整日志重建缓存,blank 也就跟着变 false。
|
|
18
|
+
// 这是纯文件操作,不碰任何上游代码、不改日志、不改工作区登记。
|
|
19
|
+
//
|
|
20
|
+
// 判定条件(四重,全中才算陈旧,宁可漏判不可误删)
|
|
21
|
+
// 1) 缓存能解析,且 record.rows.sessionListMetadata.val.blank === true
|
|
22
|
+
// 2) 能找到对应日志 sessions\<workspace>\<id>\session.v*.jsonl.zstd
|
|
23
|
+
// 3) 日志里确实有 turn/start 或 user/message 事件(真空会话不会有)
|
|
24
|
+
// 4) 日志最后事件 seq > 缓存记录的最大 seq(缓存确实落后于日志)
|
|
25
|
+
//
|
|
26
|
+
// 导出:
|
|
27
|
+
// scanSessionCaches(dshHome, opts) 只读扫描,返回候选与判定依据
|
|
28
|
+
// clearSessionCaches(dshHome, ids) 删除指定缓存(先备份)
|
|
29
|
+
// runGuard(dshHome, opts) 扫描 + 按需清理,供定时器与路由共用
|
|
30
|
+
|
|
31
|
+
import {
|
|
32
|
+
existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync,
|
|
33
|
+
} from 'node:fs'
|
|
34
|
+
import { join } from 'node:path'
|
|
35
|
+
import { splitFrames } from './session-log-lib.mjs'
|
|
36
|
+
|
|
37
|
+
/** 缓存相对 .dsh 的固定位置 */
|
|
38
|
+
const CACHE_REL = ['storages', 'session_projcache', 'sessions']
|
|
39
|
+
/** 日志相对 .dsh 的固定位置 */
|
|
40
|
+
const LOG_ROOT_REL = ['sessions']
|
|
41
|
+
/** 判定日志正文时最多读这么多字节(够覆盖首个 turn/start,减少大日志的解析成本) */
|
|
42
|
+
const HEAD_BYTES = 256 * 1024
|
|
43
|
+
/** 真空会话日志一般只有 header 帧,超过这个大小才值得去解析 */
|
|
44
|
+
const MIN_LOG_BYTES = 64
|
|
45
|
+
|
|
46
|
+
function safeStat(path) {
|
|
47
|
+
try {
|
|
48
|
+
return statSync(path)
|
|
49
|
+
} catch {
|
|
50
|
+
return null
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isDir(path) {
|
|
55
|
+
const st = safeStat(path)
|
|
56
|
+
return st !== null && st.isDirectory()
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 缓存目录 */
|
|
60
|
+
export function cacheDirOf(dshHome) {
|
|
61
|
+
return join(dshHome, ...CACHE_REL)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 日志根目录 */
|
|
65
|
+
export function logRootOf(dshHome) {
|
|
66
|
+
return join(dshHome, ...LOG_ROOT_REL)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 建立 sessionId → 日志路径 的索引。
|
|
71
|
+
* 一次遍历 sessions\<workspace>\<sessionId>\session.v*.jsonl.zstd(两层,不做深递归)。
|
|
72
|
+
*/
|
|
73
|
+
export function indexSessionLogs(dshHome) {
|
|
74
|
+
const root = logRootOf(dshHome)
|
|
75
|
+
const map = new Map()
|
|
76
|
+
if (!isDir(root)) return map
|
|
77
|
+
let workspaces
|
|
78
|
+
try {
|
|
79
|
+
workspaces = readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory())
|
|
80
|
+
} catch {
|
|
81
|
+
return map
|
|
82
|
+
}
|
|
83
|
+
for (const ws of workspaces) {
|
|
84
|
+
const wsPath = join(root, ws.name)
|
|
85
|
+
let sessions
|
|
86
|
+
try {
|
|
87
|
+
sessions = readdirSync(wsPath, { withFileTypes: true }).filter((e) => e.isDirectory())
|
|
88
|
+
} catch {
|
|
89
|
+
continue
|
|
90
|
+
}
|
|
91
|
+
for (const s of sessions) {
|
|
92
|
+
const sPath = join(wsPath, s.name)
|
|
93
|
+
let files
|
|
94
|
+
try {
|
|
95
|
+
files = readdirSync(sPath).filter((f) => /^session\.v\d+\.jsonl\.zstd$/i.test(f))
|
|
96
|
+
} catch {
|
|
97
|
+
continue
|
|
98
|
+
}
|
|
99
|
+
if (files.length === 0) continue
|
|
100
|
+
// 同一会话只会有一份现役日志;万一有多份取 mtime 最新的
|
|
101
|
+
let best = null
|
|
102
|
+
for (const f of files) {
|
|
103
|
+
const p = join(sPath, f)
|
|
104
|
+
const st = safeStat(p)
|
|
105
|
+
if (st === null) continue
|
|
106
|
+
if (best === null || st.mtimeMs > best.mtimeMs) best = { path: p, mtimeMs: st.mtimeMs, bytes: st.size }
|
|
107
|
+
}
|
|
108
|
+
if (best !== null) map.set(s.name, best)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return map
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 一条缓存的概览(不解析日志) */
|
|
115
|
+
export function readCacheRecord(cachePath) {
|
|
116
|
+
const st = safeStat(cachePath)
|
|
117
|
+
if (st === null) return null
|
|
118
|
+
let json
|
|
119
|
+
try {
|
|
120
|
+
json = JSON.parse(readFileSync(cachePath, 'utf8'))
|
|
121
|
+
} catch (error) {
|
|
122
|
+
return { cachePath, bytes: st.size, mtimeMs: st.mtimeMs, broken: true, error: String(error && error.message) }
|
|
123
|
+
}
|
|
124
|
+
const record = json && json.record ? json.record : {}
|
|
125
|
+
const rows = record.rows && typeof record.rows === 'object' ? record.rows : {}
|
|
126
|
+
const meta = rows.sessionListMetadata && typeof rows.sessionListMetadata === 'object' ? rows.sessionListMetadata : null
|
|
127
|
+
// 缓存记录自身的最大 seq —— 用来判断它落后日志多少
|
|
128
|
+
let maxSeq = -1
|
|
129
|
+
for (const key of Object.keys(rows)) {
|
|
130
|
+
const row = rows[key]
|
|
131
|
+
if (row && typeof row.seq === 'number' && row.seq > maxSeq) maxSeq = row.seq
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
cachePath,
|
|
135
|
+
bytes: st.size,
|
|
136
|
+
mtimeMs: st.mtimeMs,
|
|
137
|
+
version: json && json.version,
|
|
138
|
+
identity: record.identity && typeof record.identity === 'object' ? record.identity : null,
|
|
139
|
+
blank: meta !== null && meta.val && typeof meta.val === 'object' ? meta.val.blank === true : null,
|
|
140
|
+
blankMetaSeq: meta !== null && typeof meta.seq === 'number' ? meta.seq : null,
|
|
141
|
+
lastPromptAt: meta !== null && meta.val && typeof meta.val === 'object' ? meta.val.lastPromptAt ?? null : null,
|
|
142
|
+
maxSeq,
|
|
143
|
+
rowKeys: Object.keys(rows),
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 只看日志头部若干帧,判断里面有没有真正发生过一轮对话。
|
|
149
|
+
* 返回 { hasTurn, turnSeq, hasUser, tailSeq, decodedFrames }
|
|
150
|
+
*/
|
|
151
|
+
export function inspectLogHead(logPath) {
|
|
152
|
+
const st = safeStat(logPath)
|
|
153
|
+
const out = { logPath, bytes: st ? st.size : 0, mtimeMs: st ? st.mtimeMs : 0, hasTurn: false, turnSeq: null, hasUser: false, tailSeq: null, decodedFrames: 0 }
|
|
154
|
+
if (st === null || st.size < MIN_LOG_BYTES) return out
|
|
155
|
+
let buf
|
|
156
|
+
try {
|
|
157
|
+
buf = readFileSync(logPath)
|
|
158
|
+
} catch (error) {
|
|
159
|
+
out.error = String(error && error.message)
|
|
160
|
+
return out
|
|
161
|
+
}
|
|
162
|
+
const slice = buf.length > HEAD_BYTES ? buf.subarray(0, HEAD_BYTES) : buf
|
|
163
|
+
let frames
|
|
164
|
+
try {
|
|
165
|
+
frames = splitFrames(slice)
|
|
166
|
+
} catch (error) {
|
|
167
|
+
out.error = String(error && error.message)
|
|
168
|
+
return out
|
|
169
|
+
}
|
|
170
|
+
let text = ''
|
|
171
|
+
for (const f of frames) {
|
|
172
|
+
if (!f.decoded) continue
|
|
173
|
+
out.decodedFrames += 1
|
|
174
|
+
text += f.decoded.toString('utf8')
|
|
175
|
+
if (text.length > HEAD_BYTES * 4) break
|
|
176
|
+
}
|
|
177
|
+
for (const line of text.split('\n')) {
|
|
178
|
+
if (!line.trim()) continue
|
|
179
|
+
let obj
|
|
180
|
+
try {
|
|
181
|
+
obj = JSON.parse(line)
|
|
182
|
+
} catch {
|
|
183
|
+
continue
|
|
184
|
+
}
|
|
185
|
+
if (typeof obj.seq === 'number') out.tailSeq = obj.seq
|
|
186
|
+
if (obj.type === 'turn/start') {
|
|
187
|
+
out.hasTurn = true
|
|
188
|
+
if (out.turnSeq === null && typeof obj.seq === 'number') out.turnSeq = obj.seq
|
|
189
|
+
}
|
|
190
|
+
if (obj.type === 'user/message') out.hasUser = true
|
|
191
|
+
}
|
|
192
|
+
return out
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 扫描全部投影缓存,标出陈旧记录。
|
|
197
|
+
*
|
|
198
|
+
* @param {string} dshHome
|
|
199
|
+
* @param {object} [opts]
|
|
200
|
+
* @param {boolean} [opts.deep=true] 是否去解析日志正文(false 只按缓存自身字段粗筛)
|
|
201
|
+
* @param {number} [opts.maxLogs=200] 最多解析多少份日志(防止极端情况下拖慢启动)
|
|
202
|
+
* @returns {{ ok:boolean, dshHome:string, cacheDir:string, scanned:number, stale:Array, blank:number, errors:Array }}
|
|
203
|
+
*/
|
|
204
|
+
export function scanSessionCaches(dshHome, opts = {}) {
|
|
205
|
+
const deep = opts.deep !== false
|
|
206
|
+
const maxLogs = Number.isFinite(opts.maxLogs) ? opts.maxLogs : 200
|
|
207
|
+
const cacheDir = cacheDirOf(dshHome)
|
|
208
|
+
const report = { ok: true, dshHome, cacheDir, scanned: 0, blank: 0, stale: [], errors: [], logsInspected: 0 }
|
|
209
|
+
if (!isDir(cacheDir)) {
|
|
210
|
+
report.ok = false
|
|
211
|
+
report.errors.push(`缓存目录不存在:${cacheDir}`)
|
|
212
|
+
return report
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
let names
|
|
216
|
+
try {
|
|
217
|
+
names = readdirSync(cacheDir).filter((f) => f.toLowerCase().endsWith('.json'))
|
|
218
|
+
} catch (error) {
|
|
219
|
+
report.ok = false
|
|
220
|
+
report.errors.push(`读缓存目录失败:${String(error && error.message)}`)
|
|
221
|
+
return report
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const logIndex = deep ? indexSessionLogs(dshHome) : new Map()
|
|
225
|
+
const judged = []
|
|
226
|
+
|
|
227
|
+
for (const name of names) {
|
|
228
|
+
const cachePath = join(cacheDir, name)
|
|
229
|
+
const rec = readCacheRecord(cachePath)
|
|
230
|
+
if (rec === null) continue
|
|
231
|
+
report.scanned += 1
|
|
232
|
+
if (rec.broken) {
|
|
233
|
+
// 缓存自己都解析不了,DSH 读它也会失败;但删除有风险(可能是别的格式版本),只报不改
|
|
234
|
+
report.errors.push(`缓存无法解析:${name}(${rec.error})`)
|
|
235
|
+
continue
|
|
236
|
+
}
|
|
237
|
+
if (rec.blank !== true) continue
|
|
238
|
+
report.blank += 1
|
|
239
|
+
|
|
240
|
+
const id = name.replace(/\.json$/i, '')
|
|
241
|
+
const item = {
|
|
242
|
+
id,
|
|
243
|
+
cachePath,
|
|
244
|
+
cacheBytes: rec.bytes,
|
|
245
|
+
cacheMtime: rec.mtimeMs,
|
|
246
|
+
cacheMaxSeq: rec.maxSeq,
|
|
247
|
+
blankMetaSeq: rec.blankMetaSeq,
|
|
248
|
+
cwd: rec.identity ? rec.identity.cwd ?? null : null,
|
|
249
|
+
createdAt: rec.identity ? rec.identity.createdAt ?? null : null,
|
|
250
|
+
logPath: null,
|
|
251
|
+
logBytes: null,
|
|
252
|
+
logTailSeq: null,
|
|
253
|
+
hasTurn: null,
|
|
254
|
+
hasUser: null,
|
|
255
|
+
stale: false,
|
|
256
|
+
reason: '',
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (!deep) {
|
|
260
|
+
// 粗筛:缓存 seq 还停在 -1 说明上一次写出后再没推进过,高度可疑
|
|
261
|
+
if (rec.maxSeq <= 0) {
|
|
262
|
+
item.stale = true
|
|
263
|
+
item.reason = `缓存从未推进(maxSeq=${rec.maxSeq})且仍标记 blank`
|
|
264
|
+
} else {
|
|
265
|
+
item.reason = '未检查日志(deep=false)'
|
|
266
|
+
}
|
|
267
|
+
judged.push(item)
|
|
268
|
+
continue
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const log = logIndex.get(id)
|
|
272
|
+
if (log === undefined) {
|
|
273
|
+
item.reason = '找不到对应会话日志,跳过(可能是别的机器同步来的空壳)'
|
|
274
|
+
judged.push(item)
|
|
275
|
+
continue
|
|
276
|
+
}
|
|
277
|
+
if (report.logsInspected >= maxLogs) {
|
|
278
|
+
item.reason = `本次已达日志解析上限 ${maxLogs} 份,跳过`
|
|
279
|
+
judged.push(item)
|
|
280
|
+
continue
|
|
281
|
+
}
|
|
282
|
+
report.logsInspected += 1
|
|
283
|
+
item.logPath = log.path
|
|
284
|
+
item.logBytes = log.bytes
|
|
285
|
+
const head = inspectLogHead(log.path)
|
|
286
|
+
item.hasTurn = head.hasTurn
|
|
287
|
+
item.hasUser = head.hasUser
|
|
288
|
+
item.logTailSeq = head.tailSeq
|
|
289
|
+
if (head.error) item.reason = `日志解析出错:${head.error}`
|
|
290
|
+
|
|
291
|
+
const progressed = head.hasTurn || head.hasUser
|
|
292
|
+
if (!progressed) {
|
|
293
|
+
item.reason = '日志里确实没有对话事件(真空会话),缓存是对的'
|
|
294
|
+
judged.push(item)
|
|
295
|
+
continue
|
|
296
|
+
}
|
|
297
|
+
if (typeof head.tailSeq === 'number' && head.tailSeq <= rec.maxSeq) {
|
|
298
|
+
item.reason = `缓存并不落后日志(缓存 maxSeq=${rec.maxSeq},日志 tail=${head.tailSeq}),不动`
|
|
299
|
+
judged.push(item)
|
|
300
|
+
continue
|
|
301
|
+
}
|
|
302
|
+
item.stale = true
|
|
303
|
+
item.reason = `日志已有对话(turn=${head.hasTurn} 首轮 seq=${head.turnSeq},user=${head.hasUser},tail=${head.tailSeq}),缓存仍标 blank 且停在 seq=${rec.maxSeq}`
|
|
304
|
+
judged.push(item)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
report.stale = judged.filter((x) => x.stale)
|
|
308
|
+
report.candidates = judged
|
|
309
|
+
return report
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* 删除指定会话的缓存(先挪到备份目录,不做物理删除)。
|
|
314
|
+
* 返回 { removed:[{id,from,to}], errors:[] }
|
|
315
|
+
*/
|
|
316
|
+
export function clearSessionCaches(dshHome, ids, opts = {}) {
|
|
317
|
+
const cacheDir = cacheDirOf(dshHome)
|
|
318
|
+
const backupDir = opts.backupDir || join(dshHome, 'logs', 'session-cache-guard-backup')
|
|
319
|
+
const out = { removed: [], errors: [] }
|
|
320
|
+
const list = Array.isArray(ids) ? ids : []
|
|
321
|
+
if (list.length === 0) return out
|
|
322
|
+
let backupReady = false
|
|
323
|
+
for (const raw of list) {
|
|
324
|
+
const id = String(raw || '').trim()
|
|
325
|
+
if (id === '' || /[\\/]/.test(id) || id.includes('..')) {
|
|
326
|
+
out.errors.push(`非法会话 id:${raw}`)
|
|
327
|
+
continue
|
|
328
|
+
}
|
|
329
|
+
const from = join(cacheDir, `${id}.json`)
|
|
330
|
+
if (!existsSync(from)) {
|
|
331
|
+
out.errors.push(`缓存已不存在:${id}`)
|
|
332
|
+
continue
|
|
333
|
+
}
|
|
334
|
+
try {
|
|
335
|
+
if (!backupReady) {
|
|
336
|
+
mkdirSync(backupDir, { recursive: true })
|
|
337
|
+
backupReady = true
|
|
338
|
+
}
|
|
339
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
340
|
+
const to = join(backupDir, `${stamp}-${id}.json`)
|
|
341
|
+
renameSync(from, to)
|
|
342
|
+
out.removed.push({ id, from, to })
|
|
343
|
+
} catch (error) {
|
|
344
|
+
out.errors.push(`删除失败 ${id}:${String(error && error.message)}`)
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
return out
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** 追加一行日志到 .dsh\logs\session-cache-guard.log(失败不影响主流程) */
|
|
351
|
+
export function appendGuardLog(dshHome, text) {
|
|
352
|
+
try {
|
|
353
|
+
const dir = join(dshHome, 'logs')
|
|
354
|
+
mkdirSync(dir, { recursive: true })
|
|
355
|
+
const line = `[${new Date().toISOString()}] ${text}\n`
|
|
356
|
+
const file = join(dir, 'session-cache-guard.log')
|
|
357
|
+
let prev = ''
|
|
358
|
+
try {
|
|
359
|
+
const st = safeStat(file)
|
|
360
|
+
if (st !== null && st.size > 512 * 1024) prev = ''
|
|
361
|
+
else prev = readFileSync(file, 'utf8')
|
|
362
|
+
} catch {
|
|
363
|
+
prev = ''
|
|
364
|
+
}
|
|
365
|
+
writeFileSync(file, prev + line, 'utf8')
|
|
366
|
+
} catch {
|
|
367
|
+
/* 日志写不出来就算了 */
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* 扫描 + 按需清理,路由与定时器共用。
|
|
373
|
+
*
|
|
374
|
+
* @param {string} dshHome
|
|
375
|
+
* @param {object} [opts]
|
|
376
|
+
* @param {boolean} [opts.apply=true] 是否真的删(false 只报告)
|
|
377
|
+
* @param {string[]} [opts.ids] 只处理这些 id(不传=全部陈旧项)
|
|
378
|
+
* @param {boolean} [opts.deep=true]
|
|
379
|
+
* @param {string} [opts.source='manual'] 触发来源,写日志用
|
|
380
|
+
*/
|
|
381
|
+
export function runGuard(dshHome, opts = {}) {
|
|
382
|
+
const apply = opts.apply !== false
|
|
383
|
+
const source = opts.source || 'manual'
|
|
384
|
+
const scan = scanSessionCaches(dshHome, { deep: opts.deep, maxLogs: opts.maxLogs })
|
|
385
|
+
const wanted = Array.isArray(opts.ids) && opts.ids.length > 0 ? opts.ids.map(String) : scan.stale.map((x) => x.id)
|
|
386
|
+
const result = {
|
|
387
|
+
ok: scan.ok,
|
|
388
|
+
dshHome,
|
|
389
|
+
source,
|
|
390
|
+
applied: apply,
|
|
391
|
+
scanned: scan.scanned,
|
|
392
|
+
blank: scan.blank,
|
|
393
|
+
staleCount: scan.stale.length,
|
|
394
|
+
stale: scan.stale.map((x) => ({ id: x.id, reason: x.reason, cwd: x.cwd, cacheMaxSeq: x.cacheMaxSeq, logTailSeq: x.logTailSeq, logPath: x.logPath })),
|
|
395
|
+
candidates: scan.candidates ? scan.candidates.map((x) => ({ id: x.id, stale: x.stale, reason: x.reason })) : [],
|
|
396
|
+
errors: scan.errors.slice(),
|
|
397
|
+
removed: [],
|
|
398
|
+
}
|
|
399
|
+
if (!apply || wanted.length === 0) return result
|
|
400
|
+
const cleared = clearSessionCaches(dshHome, wanted)
|
|
401
|
+
result.removed = cleared.removed
|
|
402
|
+
result.errors.push(...cleared.errors)
|
|
403
|
+
if (cleared.removed.length > 0) {
|
|
404
|
+
appendGuardLog(dshHome, `[${source}] 清理 ${cleared.removed.length} 条陈旧投影缓存:${cleared.removed.map((x) => x.id).join(', ')}`)
|
|
405
|
+
}
|
|
406
|
+
return result
|
|
407
|
+
}
|