dsh-session-detox 0.0.0-stage → 0.3.2
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/CHANGELOG.md +59 -0
- package/LICENSE +21 -0
- package/README.md +148 -2
- package/cordis.patch.yml +4 -0
- package/lib/blocks.js +77 -0
- package/lib/config.js +46 -0
- package/lib/detect.js +192 -0
- package/lib/find.js +187 -0
- package/lib/index.js +418 -0
- package/lib/paths.js +74 -0
- package/lib/session.js +121 -0
- package/lib/stream.js +151 -0
- package/lib/workspace.js +122 -0
- package/lib/zstd.js +121 -0
- package/package.json +47 -3
- package/skills/session-detox/SKILL.md +270 -0
package/lib/session.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// 会话文件的扫描与手术:解包 → 逐条判 → 备份 → 清洗 → 轻校验 → 覆盖 → 删投影缓存。
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { unpack, pack, verifyPack } from './zstd.js';
|
|
6
|
+
import { walkEvent, eventNeedsChange } from './detect.js';
|
|
7
|
+
import { BACKUP_ROOT, ensureDir, projcacheFile, stamp } from './paths.js';
|
|
8
|
+
|
|
9
|
+
/** 会话文件 mtime 距今不足这么久,就认为它还在写,拒绝动刀。 */
|
|
10
|
+
export const IDLE_SECONDS = 180;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 读会话文件并统计。
|
|
14
|
+
* @param {string} file
|
|
15
|
+
* @returns {{ events: number, touched: number, stubs: number, loops: number, chars: number, frames: number, mtimeAgeSec: number }}
|
|
16
|
+
*/
|
|
17
|
+
export function scanSessionFile(file) {
|
|
18
|
+
const age = (Date.now() - fs.statSync(file).mtimeMs) / 1000;
|
|
19
|
+
const { text, frames } = unpack(fs.readFileSync(file));
|
|
20
|
+
const stat = { events: 0, touched: 0, stubs: 0, loops: 0, chars: 0 };
|
|
21
|
+
for (const line of text.split('\n')) {
|
|
22
|
+
if (!line.trim()) continue;
|
|
23
|
+
let ev;
|
|
24
|
+
try {
|
|
25
|
+
ev = JSON.parse(line);
|
|
26
|
+
} catch {
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
stat.events++;
|
|
30
|
+
const r = walkEvent(ev, false);
|
|
31
|
+
stat.touched += r.touched;
|
|
32
|
+
stat.stubs += r.stubs;
|
|
33
|
+
stat.loops += r.loops;
|
|
34
|
+
stat.chars += r.chars;
|
|
35
|
+
}
|
|
36
|
+
return { ...stat, frames, mtimeAgeSec: Math.round(age) };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 只在需要改的行上重新序列化,其余行逐字节保留(seq / arguments / user 全文都不动)。 */
|
|
40
|
+
function cleanJsonl(text) {
|
|
41
|
+
const out = [];
|
|
42
|
+
const stat = { events: 0, touched: 0, stubs: 0, loops: 0, chars: 0 };
|
|
43
|
+
for (const line of text.split('\n')) {
|
|
44
|
+
if (!line.trim()) {
|
|
45
|
+
out.push(line);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
let ev;
|
|
49
|
+
try {
|
|
50
|
+
ev = JSON.parse(line);
|
|
51
|
+
} catch {
|
|
52
|
+
out.push(line); // 解析不了的原样留着,不因为一行坏掉把整份搞乱
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
stat.events++;
|
|
56
|
+
if (!eventNeedsChange(ev)) {
|
|
57
|
+
out.push(line);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const r = walkEvent(ev, true);
|
|
61
|
+
stat.touched += r.touched;
|
|
62
|
+
stat.stubs += r.stubs;
|
|
63
|
+
stat.loops += r.loops;
|
|
64
|
+
stat.chars += r.chars;
|
|
65
|
+
out.push(JSON.stringify(ev));
|
|
66
|
+
}
|
|
67
|
+
return { text: out.join('\n'), stat };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 给一个会话文件动手术。
|
|
72
|
+
* @param {string} file
|
|
73
|
+
* @param {string} id
|
|
74
|
+
* @param {{ force?: boolean }} [opts]
|
|
75
|
+
* @returns {object} 结果摘要
|
|
76
|
+
*/
|
|
77
|
+
export function cutSessionFile(file, id, opts = {}) {
|
|
78
|
+
const age = (Date.now() - fs.statSync(file).mtimeMs) / 1000;
|
|
79
|
+
if (!opts.force && age < IDLE_SECONDS) {
|
|
80
|
+
throw new Error(
|
|
81
|
+
`会话 id=${id} 还在写(mtime ${Math.round(age)} 秒前,判据 ${IDLE_SECONDS} 秒)。停掉它再来,否则会把 seq 写断。\n`
|
|
82
|
+
+ '如果切的就是你自己这条会话:你自己说话/调工具都会写事件,mtime 永远归零,你会永远切不了自己——'
|
|
83
|
+
+ '改派一个子智能体,让它在等待期间什么都不写,等过 180 秒再切(见 skill 的《给自己清理》一节)。',
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
ensureDir(BACKUP_ROOT);
|
|
88
|
+
const stampStr = stamp();
|
|
89
|
+
const backup = path.join(BACKUP_ROOT, `orig-${id.slice(0, 8)}-${stampStr}.v4.jsonl.zstd`);
|
|
90
|
+
fs.copyFileSync(file, backup);
|
|
91
|
+
|
|
92
|
+
const { text } = unpack(fs.readFileSync(file));
|
|
93
|
+
const { text: cleaned, stat } = cleanJsonl(text);
|
|
94
|
+
const packed = pack(cleaned);
|
|
95
|
+
const check = verifyPack(packed, cleaned);
|
|
96
|
+
if (!check.ok) {
|
|
97
|
+
const dump = path.join(BACKUP_ROOT, `failed-${id.slice(0, 8)}-${stampStr}.jsonl`);
|
|
98
|
+
fs.writeFileSync(dump, cleaned, 'utf8');
|
|
99
|
+
throw new Error(`校验没过,没有覆盖原文件:${check.problems.join(';')}。清洗结果留在 ${dump}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
fs.writeFileSync(file, packed);
|
|
103
|
+
const cache = projcacheFile(id);
|
|
104
|
+
let removedCache = false;
|
|
105
|
+
if (fs.existsSync(cache)) {
|
|
106
|
+
fs.rmSync(cache, { force: true });
|
|
107
|
+
removedCache = true;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
session: id,
|
|
112
|
+
backup,
|
|
113
|
+
removedCache,
|
|
114
|
+
...stat,
|
|
115
|
+
events: check.events,
|
|
116
|
+
framesIn: check.frames,
|
|
117
|
+
seqMin: check.seqMin,
|
|
118
|
+
seqMax: check.seqMax,
|
|
119
|
+
sizeAfter: fs.statSync(file).size,
|
|
120
|
+
};
|
|
121
|
+
}
|
package/lib/stream.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// 流中截断:挂在 llm/stream 上,边收 reasoning-delta 边判,命中就停止转发这一段思考。
|
|
2
|
+
// 关键不是界面不刷屏 —— 而是把 block-end 也换成截断版:**只有落盘的那份决定下一轮会不会被回灌**。
|
|
3
|
+
import { STUB_LINE, cleanText } from './detect.js';
|
|
4
|
+
|
|
5
|
+
/** 尾部窗口:只看最后这么多字。循环通常紧邻结尾。 */
|
|
6
|
+
const TAIL_CHARS = 2000;
|
|
7
|
+
/** 攒够这么多字才开始判,省得每来一个 delta 都跑一遍。 */
|
|
8
|
+
const MIN_PROBE = 80;
|
|
9
|
+
/** 之后每多攒这么多字判一次。 */
|
|
10
|
+
const PROBE_STEP = 40;
|
|
11
|
+
/** 连续这么多行是极短碎句就熔断。 */
|
|
12
|
+
const RUN_LIMIT = 5;
|
|
13
|
+
/** 或者:尾部极短行占到一半、且至少这么多行。 */
|
|
14
|
+
const RATIO_MIN = 0.5;
|
|
15
|
+
const STUB_MIN = 10;
|
|
16
|
+
/** 尾部至少这么多行才判,太少不判(开头几句正常短句不该被误伤)。 */
|
|
17
|
+
const MIN_LINES = 10;
|
|
18
|
+
/** 保留的尾部行数上限。 */
|
|
19
|
+
const TAIL_LINES = 40;
|
|
20
|
+
/** 截断时保留开头这么多字。 */
|
|
21
|
+
const KEEP_HEAD = 240;
|
|
22
|
+
/** 思考文本的内存上限;超了只留尾巴,判定只看尾部,砍中段不影响。 */
|
|
23
|
+
const MAX_KEEP_CHARS = 200000;
|
|
24
|
+
/** 截断后接的一句。 */
|
|
25
|
+
const YIELD_TEXT = '\n…(这里绕进去了,换个说法继续)';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 判一段文本(通常只喂尾部)在不在绕。
|
|
29
|
+
* @param {string} text
|
|
30
|
+
* @returns {{ reasons: string[], ratio: number, maxRun: number, stubs: number, lines: number } | null}
|
|
31
|
+
*/
|
|
32
|
+
export function loopScore(text) {
|
|
33
|
+
const lines = String(text)
|
|
34
|
+
.split('\n')
|
|
35
|
+
.map((l) => l.trim())
|
|
36
|
+
.filter(Boolean);
|
|
37
|
+
if (lines.length < MIN_LINES) return null;
|
|
38
|
+
|
|
39
|
+
const tail = lines.slice(-TAIL_LINES);
|
|
40
|
+
let stubs = 0;
|
|
41
|
+
let run = 0;
|
|
42
|
+
let maxRun = 0;
|
|
43
|
+
for (const line of tail) {
|
|
44
|
+
if (STUB_LINE.test(line)) {
|
|
45
|
+
stubs++;
|
|
46
|
+
run++;
|
|
47
|
+
if (run > maxRun) maxRun = run;
|
|
48
|
+
} else {
|
|
49
|
+
run = 0;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const ratio = stubs / tail.length;
|
|
54
|
+
const reasons = [];
|
|
55
|
+
if (maxRun >= RUN_LIMIT) reasons.push(`run:${maxRun}`);
|
|
56
|
+
if (ratio >= RATIO_MIN && stubs >= STUB_MIN) reasons.push(`ratio:${ratio.toFixed(2)}`);
|
|
57
|
+
if (!reasons.length) return null;
|
|
58
|
+
return { reasons, ratio, maxRun, stubs, lines: tail.length };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 截断:保留开头(顺手把里面的碎句行删掉)+ 一句收尾。
|
|
63
|
+
* 保留原文是给下一轮留上下文,删碎句是别把退化形态再写回历史。
|
|
64
|
+
* @param {string} text
|
|
65
|
+
* @param {number} [keepHead]
|
|
66
|
+
*/
|
|
67
|
+
export function truncate(text, keepHead = KEEP_HEAD) {
|
|
68
|
+
const src = String(text ?? '');
|
|
69
|
+
const head = src.length > keepHead ? src.slice(0, keepHead) : src;
|
|
70
|
+
return cleanText(head).text.trimEnd() + YIELD_TEXT;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 包一层 stream:拦住 reasoning 里的极短碎句。
|
|
75
|
+
* 任何异常都退回原样透传 —— 绝不能让这个插件把模型调用搞挂。
|
|
76
|
+
*
|
|
77
|
+
* chunk 类型(DSH 的 llm/stream):
|
|
78
|
+
* block-start | text-delta | reasoning-delta | tool-call-delta | block-end | usage | finish
|
|
79
|
+
*
|
|
80
|
+
* @param {AsyncIterable<any>} upstream
|
|
81
|
+
* @param {{ onHit?: (info: object) => void }} [opts]
|
|
82
|
+
*/
|
|
83
|
+
export async function* guardStream(upstream, opts = {}) {
|
|
84
|
+
const slots = new Map(); // index -> { text, halted, lastProbe }
|
|
85
|
+
const onHit = typeof opts.onHit === 'function' ? opts.onHit : null;
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
for await (const chunk of upstream) {
|
|
89
|
+
if (!chunk || typeof chunk !== 'object') {
|
|
90
|
+
yield chunk;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (chunk.type === 'reasoning-delta') {
|
|
95
|
+
const idx = chunk.index ?? 0;
|
|
96
|
+
let slot = slots.get(idx);
|
|
97
|
+
if (!slot) {
|
|
98
|
+
slot = { text: '', halted: false, lastProbe: 0 };
|
|
99
|
+
slots.set(idx, slot);
|
|
100
|
+
}
|
|
101
|
+
if (slot.halted) continue; // 这一段已经熔断,后面全部丢掉
|
|
102
|
+
|
|
103
|
+
slot.text += String(chunk.text ?? '');
|
|
104
|
+
if (slot.text.length > MAX_KEEP_CHARS) slot.text = slot.text.slice(-TAIL_CHARS * 4);
|
|
105
|
+
|
|
106
|
+
if (slot.text.length >= MIN_PROBE && slot.text.length - slot.lastProbe >= PROBE_STEP) {
|
|
107
|
+
slot.lastProbe = slot.text.length;
|
|
108
|
+
try {
|
|
109
|
+
const probe = slot.text.length > TAIL_CHARS ? slot.text.slice(-TAIL_CHARS) : slot.text;
|
|
110
|
+
const hit = loopScore(probe);
|
|
111
|
+
if (hit) {
|
|
112
|
+
slot.halted = true;
|
|
113
|
+
if (onHit) {
|
|
114
|
+
try {
|
|
115
|
+
onHit({ index: idx, chars: slot.text.length, ...hit });
|
|
116
|
+
} catch {
|
|
117
|
+
/* 记日志失败不影响熔断 */
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
continue; // 这个 delta 也不转发
|
|
121
|
+
}
|
|
122
|
+
} catch {
|
|
123
|
+
// 判据出错就放行:宁可漏抓,不能把整轮搞挂
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
yield chunk;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (chunk.type === 'block-end') {
|
|
132
|
+
const idx = chunk.index ?? 0;
|
|
133
|
+
const slot = slots.get(idx);
|
|
134
|
+
if (slot?.halted) {
|
|
135
|
+
// 关键:落盘的那份也要换掉,否则碎句进历史、下一轮自我强化
|
|
136
|
+
const kept = truncate(slot.text);
|
|
137
|
+
slots.delete(idx);
|
|
138
|
+
yield { ...chunk, block: { type: 'reasoning', text: kept } };
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
slots.delete(idx);
|
|
142
|
+
yield chunk;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
yield chunk;
|
|
147
|
+
}
|
|
148
|
+
} finally {
|
|
149
|
+
slots.clear();
|
|
150
|
+
}
|
|
151
|
+
}
|
package/lib/workspace.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// 工作区扫描:找出「会被注入上下文」的文件里残留的可疑内容。
|
|
2
|
+
// 只报告、不改文件——文档里的极短行可能是正常内容,删不删得人来看。
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { LOOP, BAD_SECT, BAD_LINE } from './detect.js';
|
|
7
|
+
|
|
8
|
+
/** 这些目录里的东西不进上下文,扫了只是噪声。 */
|
|
9
|
+
const SKIP_DIRS = new Set([
|
|
10
|
+
'node_modules',
|
|
11
|
+
'.git',
|
|
12
|
+
'temp',
|
|
13
|
+
'_gen',
|
|
14
|
+
'comfy-out',
|
|
15
|
+
'comfy-models',
|
|
16
|
+
'ollama-models',
|
|
17
|
+
'ollama-dist',
|
|
18
|
+
'存档',
|
|
19
|
+
'截图',
|
|
20
|
+
'B站视频',
|
|
21
|
+
'备份',
|
|
22
|
+
'skills-disabled',
|
|
23
|
+
]);
|
|
24
|
+
|
|
25
|
+
/** 只有这些位置的内容会被注入或被读进上下文。
|
|
26
|
+
* 记忆库这类目录是某些工作区自建的,不是 DSH 通用结构,所以不放进默认扫描——
|
|
27
|
+
* 要扫就显式传 root 指过去。 */
|
|
28
|
+
const TARGETS = [
|
|
29
|
+
{ rel: 'AGENTS.md', kind: '系统提示' },
|
|
30
|
+
{ rel: '.dsh/skills', kind: 'skill(描述进目录、正文按需加载)', mode: 'dir' },
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
// LOOP 在 detect.js 里带 /g,用 .test() 会因 lastIndex 残留而交替返回真假(实测 true/false/true)。
|
|
34
|
+
// 这里用一份去掉 g 的副本,逐行判定才不会漏报。
|
|
35
|
+
const LOOP_TEST = new RegExp(LOOP.source);
|
|
36
|
+
|
|
37
|
+
const RULES = [
|
|
38
|
+
{ id: 'germ-word', re: /单字祈使句/, label: '点名这类的措辞' },
|
|
39
|
+
{ id: 'bad-sect', re: /^#{2,3}[^\n]*(?:主人点出本鱼|本鱼.{0,4}的病)/, label: '相关小节标题' },
|
|
40
|
+
{ id: 'loop', re: LOOP_TEST, label: '连写循环段' },
|
|
41
|
+
];
|
|
42
|
+
// 注意:文档里**不报**「独立极短行」这一条。存档与记忆里大量正常内容就是一两行短句
|
|
43
|
+
// (主人原话、操作小结),按会话文件的判据扫过去全是误报——2026-11-22 实测 7 处命中全是误报。
|
|
44
|
+
|
|
45
|
+
function walkMd(dir, out) {
|
|
46
|
+
let entries;
|
|
47
|
+
try {
|
|
48
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
49
|
+
} catch {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
for (const e of entries) {
|
|
53
|
+
const full = path.join(dir, e.name);
|
|
54
|
+
if (e.isDirectory()) {
|
|
55
|
+
if (SKIP_DIRS.has(e.name)) continue;
|
|
56
|
+
if (e.name.endsWith('的存档')) continue; // 历史存档不常被 read,扫了只是噪声
|
|
57
|
+
walkMd(full, out);
|
|
58
|
+
} else if (e.isFile() && e.name.toLowerCase().endsWith('.md')) {
|
|
59
|
+
out.push(full);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 扫工作区里会被注入上下文的文件。
|
|
66
|
+
* @param {string} root 工作区根
|
|
67
|
+
* @returns {{ scanned: number, files: Array<{ path: string, kind: string, hits: Array<{ line: number, rule: string, label: string, snippet: string }> }> }}
|
|
68
|
+
*/
|
|
69
|
+
export function scanWorkspace(root) {
|
|
70
|
+
const files = [];
|
|
71
|
+
for (const t of TARGETS) {
|
|
72
|
+
const full = path.join(root, t.rel);
|
|
73
|
+
if (!fs.existsSync(full)) continue;
|
|
74
|
+
if (t.mode === 'dir') {
|
|
75
|
+
const list = [];
|
|
76
|
+
walkMd(full, list);
|
|
77
|
+
for (const f of list) files.push({ path: f, kind: t.kind });
|
|
78
|
+
} else {
|
|
79
|
+
files.push({ path: full, kind: t.kind });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const report = [];
|
|
84
|
+
let scanned = 0;
|
|
85
|
+
for (const f of files) {
|
|
86
|
+
let text;
|
|
87
|
+
try {
|
|
88
|
+
text = fs.readFileSync(f.path, 'utf8');
|
|
89
|
+
} catch {
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
scanned++;
|
|
93
|
+
const lines = text.split('\n');
|
|
94
|
+
const hits = [];
|
|
95
|
+
for (let i = 0; i < lines.length; i++) {
|
|
96
|
+
const line = lines[i];
|
|
97
|
+
for (const rule of RULES) {
|
|
98
|
+
if (!rule.re.test(line)) continue;
|
|
99
|
+
const trimmed = line.trim();
|
|
100
|
+
// 行内循环段单独报,不跟极短行规则重复计数
|
|
101
|
+
if (rule.id === 'loop' && !(trimmed.match(LOOP) || []).length) continue;
|
|
102
|
+
hits.push({
|
|
103
|
+
line: i + 1,
|
|
104
|
+
rule: rule.id,
|
|
105
|
+
label: rule.label,
|
|
106
|
+
snippet: trimmed.length > 60 ? `${trimmed.slice(0, 60)}…` : trimmed,
|
|
107
|
+
});
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (hits.length) report.push({ path: f.path, kind: f.kind, hits });
|
|
112
|
+
}
|
|
113
|
+
return { scanned, files: report };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 扫出来的总数(给一句话结论用)。 */
|
|
117
|
+
export function countHits(report) {
|
|
118
|
+
return report.files.reduce((n, f) => n + f.hits.length, 0);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** BAD_SECT / BAD_LINE 这两个正则只在这里用,导出去让调用方能复用。 */
|
|
122
|
+
export { BAD_SECT, BAD_LINE };
|
package/lib/zstd.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// 多帧 zstd:按 magic 切帧逐帧解 / 首帧只放 header,其余每 N 条事件一帧。
|
|
2
|
+
// DSH 会话文件是多帧 zstd,zstdDecompressSync 只解第一帧,所以必须自己切帧。
|
|
3
|
+
import zlib from 'node:zlib';
|
|
4
|
+
|
|
5
|
+
const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
|
|
6
|
+
|
|
7
|
+
/** 每帧装多少条事件(打包时)。 */
|
|
8
|
+
export const EVENTS_PER_FRAME = 400;
|
|
9
|
+
|
|
10
|
+
/** 在一段 buffer 里找出所有 zstd 帧的起始偏移。 */
|
|
11
|
+
export function frameOffsets(buf) {
|
|
12
|
+
const offs = [];
|
|
13
|
+
let i = 0;
|
|
14
|
+
for (;;) {
|
|
15
|
+
const j = buf.indexOf(MAGIC, i);
|
|
16
|
+
if (j < 0) break;
|
|
17
|
+
offs.push(j);
|
|
18
|
+
i = j + 4;
|
|
19
|
+
}
|
|
20
|
+
return offs;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 解包多帧 zstd → 文本(jsonl)。
|
|
25
|
+
* @param {Buffer} buf 文件字节
|
|
26
|
+
* @returns {{ text: string, frames: number }}
|
|
27
|
+
*/
|
|
28
|
+
export function unpack(buf) {
|
|
29
|
+
const offs = frameOffsets(buf);
|
|
30
|
+
if (!offs.length) throw new Error('没找到 zstd 帧;这不是多帧会话文件?');
|
|
31
|
+
const parts = [];
|
|
32
|
+
for (let k = 0; k < offs.length; k++) {
|
|
33
|
+
const end = k + 1 < offs.length ? offs[k + 1] : buf.length;
|
|
34
|
+
parts.push(zlib.zstdDecompressSync(buf.subarray(offs[k], end)));
|
|
35
|
+
}
|
|
36
|
+
const whole = Buffer.concat(parts);
|
|
37
|
+
return { text: whole.toString('utf8'), frames: offs.length };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 打包:首帧恰好 header 一行,之后每 EVENTS_PER_FRAME 条事件一帧。
|
|
42
|
+
* @param {string} text jsonl 全文
|
|
43
|
+
* @returns {Buffer}
|
|
44
|
+
*/
|
|
45
|
+
export function pack(text) {
|
|
46
|
+
const lines = text.split('\n').filter((l) => l.length > 0);
|
|
47
|
+
if (lines.length < 2) throw new Error('jsonl 里没有事件(只有 header?)');
|
|
48
|
+
const frames = [];
|
|
49
|
+
// 首帧必须恰好一行 header,多一行宿主会报 first frame is not exactly one header line
|
|
50
|
+
frames.push(zlib.zstdCompressSync(Buffer.from(lines[0] + '\n', 'utf8')));
|
|
51
|
+
for (let i = 1; i < lines.length; i += EVENTS_PER_FRAME) {
|
|
52
|
+
const chunk = lines.slice(i, i + EVENTS_PER_FRAME).map((l) => l + '\n').join('');
|
|
53
|
+
frames.push(zlib.zstdCompressSync(Buffer.from(chunk, 'utf8')));
|
|
54
|
+
}
|
|
55
|
+
return Buffer.concat(frames);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 轻校验:解回暖结果与源 jsonl 逐字节一致、首帧正好一行、seq 无空洞、user/message 都有 role。
|
|
60
|
+
* @param {Buffer} packed 打包结果
|
|
61
|
+
* @param {string} srcText 源 jsonl
|
|
62
|
+
* @returns {{ ok: boolean, frames: number, identical: boolean, gaps: number, missingRole: number, events: number, seqMin: number|null, seqMax: number|null, problems: string[] }}
|
|
63
|
+
*/
|
|
64
|
+
export function verifyPack(packed, srcText) {
|
|
65
|
+
const problems = [];
|
|
66
|
+
const offs = frameOffsets(packed);
|
|
67
|
+
const firstEnd = offs.length > 1 ? offs[1] : packed.length;
|
|
68
|
+
const firstText = zlib.zstdDecompressSync(packed.subarray(0, firstEnd)).toString('utf8');
|
|
69
|
+
const firstLines = firstText.split('\n').filter((l) => l.length > 0);
|
|
70
|
+
if (firstLines.length !== 1) problems.push(`首帧有 ${firstLines.length} 行,应恰好 1 行`);
|
|
71
|
+
|
|
72
|
+
const parts = [];
|
|
73
|
+
for (let k = 0; k < offs.length; k++) {
|
|
74
|
+
const end = k + 1 < offs.length ? offs[k + 1] : packed.length;
|
|
75
|
+
parts.push(zlib.zstdDecompressSync(packed.subarray(offs[k], end)));
|
|
76
|
+
}
|
|
77
|
+
const whole = Buffer.concat(parts);
|
|
78
|
+
const src = Buffer.from(srcText, 'utf8');
|
|
79
|
+
const identical = whole.equals(src);
|
|
80
|
+
if (!identical) problems.push(`回读与源 jsonl 不一致(${whole.length} vs ${src.length} 字节)`);
|
|
81
|
+
|
|
82
|
+
const seqs = [];
|
|
83
|
+
let missingRole = 0;
|
|
84
|
+
let events = 0;
|
|
85
|
+
for (const line of whole.toString('utf8').split('\n')) {
|
|
86
|
+
if (!line.trim()) continue;
|
|
87
|
+
events++;
|
|
88
|
+
let o;
|
|
89
|
+
try {
|
|
90
|
+
o = JSON.parse(line);
|
|
91
|
+
} catch (e) {
|
|
92
|
+
problems.push(`第 ${events} 行不是合法 JSON:${e.message}`);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (typeof o.seq === 'number') seqs.push(o.seq);
|
|
96
|
+
if (o.type === 'user/message') {
|
|
97
|
+
const d = o.data || {};
|
|
98
|
+
if (d.role !== 'user') missingRole++;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (missingRole > 0) problems.push(`${missingRole} 条 user/message 缺 role`);
|
|
102
|
+
|
|
103
|
+
seqs.sort((a, b) => a - b);
|
|
104
|
+
let gaps = 0;
|
|
105
|
+
for (let i = 0; i + 1 < seqs.length; i++) {
|
|
106
|
+
if (seqs[i + 1] !== seqs[i] + 1) gaps++;
|
|
107
|
+
}
|
|
108
|
+
if (gaps > 0) problems.push(`seq 有 ${gaps} 处空洞`);
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
ok: problems.length === 0,
|
|
112
|
+
frames: offs.length,
|
|
113
|
+
identical,
|
|
114
|
+
gaps,
|
|
115
|
+
missingRole,
|
|
116
|
+
events,
|
|
117
|
+
seqMin: seqs.length ? seqs[0] : null,
|
|
118
|
+
seqMax: seqs.length ? seqs[seqs.length - 1] : null,
|
|
119
|
+
problems,
|
|
120
|
+
};
|
|
121
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-session-detox",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.2",
|
|
4
|
+
"description": "Session-level cleanup for DSH: scan a session log for the short-line loop pattern, cut it out of the reasoning blocks, and clean the same pattern out of compressed-block summaries. Zero dependencies, pure node.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "lib/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./lib/index.js",
|
|
9
|
+
"./package.json": "./package.json"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"lib",
|
|
13
|
+
"skills",
|
|
14
|
+
"cordis.patch.yml",
|
|
15
|
+
"README.md",
|
|
16
|
+
"CHANGELOG.md",
|
|
17
|
+
"LICENSE"
|
|
18
|
+
],
|
|
19
|
+
"dsh": {
|
|
20
|
+
"bundle": {
|
|
21
|
+
"patch": "./cordis.patch.yml"
|
|
22
|
+
},
|
|
23
|
+
"minVersion": "0.2.0"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"dsh",
|
|
27
|
+
"dsh-plugin",
|
|
28
|
+
"deepseek-harness",
|
|
29
|
+
"session",
|
|
30
|
+
"repair",
|
|
31
|
+
"cleanup",
|
|
32
|
+
"reasoning-loop"
|
|
33
|
+
],
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=24"
|
|
36
|
+
},
|
|
37
|
+
"author": "backpang <backpang@users.noreply.github.com>",
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/backpang/dsh-session-detox.git"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://github.com/backpang/dsh-session-detox#readme",
|
|
43
|
+
"bugs": {
|
|
44
|
+
"url": "https://github.com/backpang/dsh-session-detox/issues"
|
|
45
|
+
},
|
|
46
|
+
"license": "MIT",
|
|
47
|
+
"scripts": {
|
|
48
|
+
"test": "node test/smoke.mjs"
|
|
49
|
+
}
|
|
6
50
|
}
|