dsh-workplan 2.1.3 → 2.2.6
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 +380 -1
- package/README.en.md +5 -2
- package/README.md +5 -2
- package/README.zh.md +5 -2
- package/client.js +143 -3
- package/docs/dsh-workplan_T4_runtime.patch +508 -0
- package/docs/release-records/_release_notes_2.1.2_20261106.md +44 -0
- package/docs/release-records/_t2_version_determination_20261106.md +39 -0
- package/docs/release-records/_t5_external_reverify_20261106.md +18 -0
- package/docs/release-records/release-dryrun-report-20261106.md +74 -0
- package/docs/release-records/release-notes-2.2.6-T3.md +128 -0
- package/docs/release-records/release-record-2.1.3-20261106.md +82 -0
- package/docs/release-records/release-steps-20261106.md +129 -0
- package/docs/release-records/version-freeze-20261109-T2.md +37 -0
- package/lib/client.js +143 -3
- package/lib/comm-format.js +17 -0
- package/lib/departments.js +19 -0
- package/lib/host.js +95 -17
- package/lib/notice-channel.js +290 -0
- package/lib/plan.js +541 -32
- package/lib/replan.js +4 -0
- package/lib/runtime.js +1481 -85
- package/lib/supersede.js +2 -2
- package/lib/understanding.js +8 -2
- package/lib/watchdog.js +52 -1
- package/package.json +3 -2
- package/scripts/repair-malformed-user-messages.mjs +312 -0
- package/src/client.ts +150 -2
- package/src/comm-format.ts +17 -0
- package/src/departments.ts +22 -0
- package/src/host.ts +90 -12
- package/src/notice-channel.ts +328 -0
- package/src/plan.ts +575 -24
- package/src/replan.ts +4 -0
- package/src/runtime.ts +1500 -86
- package/src/supersede.ts +2 -1
- package/src/understanding.ts +10 -2
- package/src/watchdog.ts +80 -1
package/lib/supersede.js
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
* 由用户消息确认(V8)承载。这不是实现缺陷,而是 RC-2(自证闭环)的结构性
|
|
27
27
|
* 防线。
|
|
28
28
|
*/
|
|
29
|
-
import { buildCancelMessage, derivePlanSnapshot, flattenSubtasks, isRecord, isTerminalPhase, messageText, parseWorkplanMessage, truncate, } from './plan.js';
|
|
29
|
+
import { appendUserMessage, buildCancelMessage, derivePlanSnapshot, flattenSubtasks, isRecord, isTerminalPhase, messageText, parseWorkplanMessage, truncate, } from './plan.js';
|
|
30
30
|
import { withMappingDigest } from './supersede-digest.js';
|
|
31
31
|
/** V1–V8 的失败码。对外契约:工具结果、测试与审计日志按字面值断言。 */
|
|
32
32
|
export const SUPERSEDE_CODES = {
|
|
@@ -333,7 +333,7 @@ export function supersedePlanRecord(session, record, args, deps) {
|
|
|
333
333
|
return deny(SUPERSEDE_CODES.WRITE_FAILED, `构造取代记录失败:${error?.message ?? String(error)}`);
|
|
334
334
|
}
|
|
335
335
|
try {
|
|
336
|
-
session
|
|
336
|
+
appendUserMessage(session, message);
|
|
337
337
|
}
|
|
338
338
|
catch (error) {
|
|
339
339
|
record.errors = [...(Array.isArray(record?.errors) ? record.errors : []),
|
package/lib/understanding.js
CHANGED
|
@@ -1080,10 +1080,16 @@ export function auditTaskUnderstanding(plan, context = {}) {
|
|
|
1080
1080
|
if (!found)
|
|
1081
1081
|
return reference;
|
|
1082
1082
|
// Option letters are resolved only when the conversation lists that option
|
|
1083
|
-
// as a listed choice
|
|
1083
|
+
// as a listed choice, not a bare letter in a word. Listed-choice markers:
|
|
1084
|
+
// "C 方案" / "C 选项" and the enumeration forms "C=…" / "C=…" / "C:…" /
|
|
1085
|
+
// "C、…" / "C)…" / "C)…" / "C.…" / "C.…" (marker must be followed by
|
|
1086
|
+
// content). Q10-style reports enumerate options as "A=… / B=… / C=…";
|
|
1087
|
+
// [2.2.6] the old regex only accepted 方案/选项, so a plain "选C" was
|
|
1088
|
+
// falsely judged unresolvable, burned two full planner attempts (~12 min
|
|
1089
|
+
// of silent planning in session-a404d49d) and degraded a legitimate task.
|
|
1084
1090
|
// Task-text entities never satisfy this rule on their own: the option must
|
|
1085
1091
|
// be defined where the user chose it, i.e. in the conversation.
|
|
1086
|
-
const listedOption = new RegExp('(?:^|[^A-Za-z])' + reference.token + '\\s*(
|
|
1092
|
+
const listedOption = new RegExp('(?:^|[^A-Za-z])' + reference.token + '\\s*(?:方案|选项|=|=|:|:|、|\\)|)|\\.|.)\\s*\\S');
|
|
1087
1093
|
if (/^[A-D]$/.test(reference.token) && !listedOption.test(conversation))
|
|
1088
1094
|
return reference;
|
|
1089
1095
|
/*
|
package/lib/watchdog.js
CHANGED
|
@@ -89,6 +89,11 @@ export function describeError(value) {
|
|
|
89
89
|
}
|
|
90
90
|
return String(value);
|
|
91
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* Warning window floor: two minutes. The approaching-deadline window is
|
|
94
|
+
* `max(timeoutMs × 0.2, WARN_FLOOR_MS)` (O-4b, design doc §2.3/§2.6 #9).
|
|
95
|
+
*/
|
|
96
|
+
const WARN_FLOOR_MS = 120_000;
|
|
92
97
|
/**
|
|
93
98
|
* Watch one child's session-log growth and reject when it stalls or runs out.
|
|
94
99
|
*
|
|
@@ -98,6 +103,9 @@ export function describeError(value) {
|
|
|
98
103
|
* @param input.pollMs - observation period.
|
|
99
104
|
* @param input.makeError - builds the rejection for the decided reason.
|
|
100
105
|
* @param input.onProgress - called after each observed log growth.
|
|
106
|
+
* @param input.onApproachingDeadline - called once per armed cycle when the
|
|
107
|
+
* remaining time enters `max(timeoutMs × 0.2, WARN_FLOOR_MS)` before the ceiling (O-4b).
|
|
108
|
+
* @param input.subtaskId - reported back inside `onApproachingDeadline` info (optional).
|
|
101
109
|
* @param input.now - clock, injectable for tests.
|
|
102
110
|
* @returns a watchdog handle.
|
|
103
111
|
*/
|
|
@@ -109,6 +117,12 @@ export function createProgressWatchdog(input) {
|
|
|
109
117
|
let lastSeq = null;
|
|
110
118
|
let growth = 0;
|
|
111
119
|
let settled = false;
|
|
120
|
+
// [2.2.0][O-4b/O-4d] Absolute ceiling (ms from `startedAt`) currently in
|
|
121
|
+
// force. Only `rearm` below moves it — the warning itself never extends
|
|
122
|
+
// anything, so an un-extended ceiling still settles as `exhausted`.
|
|
123
|
+
let hardMs = Math.max(1, Math.floor(input.hardMs));
|
|
124
|
+
// [2.2.0][O-4b] One-shot warning latch per armed cycle; cleared by `rearm`.
|
|
125
|
+
let warned = false;
|
|
112
126
|
let timer = null;
|
|
113
127
|
let rejectOnce = () => { };
|
|
114
128
|
const fired = new Promise((_resolve, reject) => {
|
|
@@ -127,6 +141,36 @@ export function createProgressWatchdog(input) {
|
|
|
127
141
|
}
|
|
128
142
|
rejectOnce(input.makeError(reason));
|
|
129
143
|
};
|
|
144
|
+
// [2.2.0][O-4d] 推移绝对上限(自尝试起点计)并重新武装一次性预警。
|
|
145
|
+
// 看门狗自身没有延期能力:只有调用方显式调用才会动上限
|
|
146
|
+
// (design doc §5.3「预警是提示,不是拦截」)。
|
|
147
|
+
const rearm = (newTimeoutMs) => {
|
|
148
|
+
if (settled || !Number.isFinite(newTimeoutMs))
|
|
149
|
+
return;
|
|
150
|
+
hardMs = Math.max(1, Math.floor(newTimeoutMs));
|
|
151
|
+
warned = false;
|
|
152
|
+
};
|
|
153
|
+
// [2.2.0][O-4b] 即将超时预警:剩余 ≤ max(timeoutMs × 0.2, WARN_FLOOR_MS)
|
|
154
|
+
// (取大者)且到点之前(remainingMs > 0,D1「到点之前到达」)时触发一次;
|
|
155
|
+
// 同一武装周期内幂等(warned 闩锁),rearm 后按新时限重新武装。
|
|
156
|
+
const warnApproachingDeadline = (now) => {
|
|
157
|
+
if (warned || !input.onApproachingDeadline)
|
|
158
|
+
return;
|
|
159
|
+
const remainingMs = hardMs - (now - startedAt);
|
|
160
|
+
if (remainingMs <= 0 || remainingMs > Math.max(hardMs * 0.2, WARN_FLOOR_MS))
|
|
161
|
+
return;
|
|
162
|
+
warned = true;
|
|
163
|
+
try {
|
|
164
|
+
input.onApproachingDeadline({
|
|
165
|
+
subtaskId: input.subtaskId ?? '',
|
|
166
|
+
remainingMs,
|
|
167
|
+
timeoutMs: hardMs,
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
// An observer must never break the watchdog.
|
|
172
|
+
}
|
|
173
|
+
};
|
|
130
174
|
const poll = () => {
|
|
131
175
|
if (settled)
|
|
132
176
|
return;
|
|
@@ -154,12 +198,13 @@ export function createProgressWatchdog(input) {
|
|
|
154
198
|
}
|
|
155
199
|
}
|
|
156
200
|
}
|
|
201
|
+
warnApproachingDeadline(now);
|
|
157
202
|
const reason = pickTimeoutReason({
|
|
158
203
|
now,
|
|
159
204
|
startedAt,
|
|
160
205
|
lastProgressAt: lastProgress,
|
|
161
206
|
idleMs: Math.max(1, Math.floor(input.idleMs)),
|
|
162
|
-
hardMs
|
|
207
|
+
hardMs,
|
|
163
208
|
progressObservable: lastSeq !== null,
|
|
164
209
|
});
|
|
165
210
|
if (reason)
|
|
@@ -180,5 +225,11 @@ export function createProgressWatchdog(input) {
|
|
|
180
225
|
},
|
|
181
226
|
lastProgressAt: () => lastProgress,
|
|
182
227
|
progressEvents: () => growth,
|
|
228
|
+
extend: (newHardMs) => {
|
|
229
|
+
rearm(newHardMs);
|
|
230
|
+
},
|
|
231
|
+
rearmApproachingDeadline: (newTimeoutMs) => {
|
|
232
|
+
rearm(newTimeoutMs);
|
|
233
|
+
},
|
|
183
234
|
};
|
|
184
235
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-workplan",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.6",
|
|
4
4
|
"description": "Automatic task decomposition, real department subagents, and a responsive workplan dashboard for DeepSeek Harness.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -49,7 +49,8 @@
|
|
|
49
49
|
"README.en.md",
|
|
50
50
|
"LICENSE",
|
|
51
51
|
"SECURITY.md",
|
|
52
|
-
"docs"
|
|
52
|
+
"docs",
|
|
53
|
+
"scripts/repair-malformed-user-messages.mjs"
|
|
53
54
|
],
|
|
54
55
|
"engines": {
|
|
55
56
|
"node": ">=22"
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/*
|
|
3
|
+
* [2.2.1] One-time repair for sessions corrupted by dsh-workplan <= 2.2.0.
|
|
4
|
+
*
|
|
5
|
+
* What went wrong: the plugin appended plain strings as `user/message` data.
|
|
6
|
+
* DSH stores non-record payloads without complaint, but projections assume the
|
|
7
|
+
* canonical message shape and crash on `event.data.source.kind`:
|
|
8
|
+
* "Cannot read properties of undefined (reading 'kind')"
|
|
9
|
+
* The GUI reports that as "历史加载失败 / failed to project session".
|
|
10
|
+
*
|
|
11
|
+
* What this script does:
|
|
12
|
+
* - decompresses session.v4.jsonl.zstd (concatenated zstd frames);
|
|
13
|
+
* - converts every malformed `user/message` payload that is a plain string
|
|
14
|
+
* into a complete DSH UserMessage. The original text is preserved verbatim;
|
|
15
|
+
* source.kind becomes 'workplan' for known dsh-workplan notice text and
|
|
16
|
+
* 'recovered' for any other producer, so attribution is never invented:
|
|
17
|
+
* { id, role:'user', content:[{type:'text', text}],
|
|
18
|
+
* source:{ kind:'workplan'|'recovered', form:'notice', summary } }
|
|
19
|
+
* - preserves seq/time/surfaceOp/sourceEventSeqs/ignorable and the event count;
|
|
20
|
+
* - validates every `user/message` after conversion and seq continuity;
|
|
21
|
+
* - dry-runs by default; `--write` backs up the original, writes atomically,
|
|
22
|
+
* verifies the result by decompressing again, and invalidates a projection
|
|
23
|
+
* cache only when its watermark reaches the repaired range.
|
|
24
|
+
*
|
|
25
|
+
* Refuses to write while any process holds the log open (for example a live
|
|
26
|
+
* DSH server). Stop DSH first, run with --write, then start DSH again.
|
|
27
|
+
*
|
|
28
|
+
* Usage:
|
|
29
|
+
* node scripts/repair-malformed-user-messages.mjs <session-id|session-dir|.zstd> [...] [--write] [--force]
|
|
30
|
+
* node scripts/repair-malformed-user-messages.mjs --scan-recent [--hours 24] [--write]
|
|
31
|
+
*
|
|
32
|
+
* `--scan-recent` repairs every session log modified within the last N hours
|
|
33
|
+
* (default 24), which is the safe post-incident blast-radius check.
|
|
34
|
+
*/
|
|
35
|
+
import { execFileSync, spawnSync } from 'node:child_process'
|
|
36
|
+
import { randomUUID } from 'node:crypto'
|
|
37
|
+
import { constants as zlibConstants, zstdCompressSync } from 'node:zlib'
|
|
38
|
+
import {
|
|
39
|
+
copyFileSync,
|
|
40
|
+
existsSync,
|
|
41
|
+
readdirSync,
|
|
42
|
+
readFileSync,
|
|
43
|
+
renameSync,
|
|
44
|
+
rmSync,
|
|
45
|
+
statSync,
|
|
46
|
+
writeFileSync,
|
|
47
|
+
} from 'node:fs'
|
|
48
|
+
import { homedir, tmpdir } from 'node:os'
|
|
49
|
+
import { basename, dirname, join, resolve } from 'node:path'
|
|
50
|
+
|
|
51
|
+
const CHECKSUM_LEVEL_19 = {
|
|
52
|
+
params: {
|
|
53
|
+
[zlibConstants.ZSTD_c_compressionLevel]: 19,
|
|
54
|
+
[zlibConstants.ZSTD_c_checksumFlag]: 1,
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
const MAX_BUFFER = 1024 * 1024 * 1024
|
|
58
|
+
|
|
59
|
+
const rawArgs = process.argv.slice(2)
|
|
60
|
+
const write = rawArgs.includes('--write')
|
|
61
|
+
const force = rawArgs.includes('--force')
|
|
62
|
+
const scanRecent = rawArgs.includes('--scan-recent')
|
|
63
|
+
const hoursIndex = rawArgs.indexOf('--hours')
|
|
64
|
+
const scanHours = hoursIndex === -1 ? 24 : Number(rawArgs[hoursIndex + 1])
|
|
65
|
+
const targets = []
|
|
66
|
+
for (let index = 0; index < rawArgs.length; index += 1) {
|
|
67
|
+
const arg = rawArgs[index]
|
|
68
|
+
if (arg === '--hours') {
|
|
69
|
+
index += 1
|
|
70
|
+
continue
|
|
71
|
+
}
|
|
72
|
+
if (arg.startsWith('--')) continue
|
|
73
|
+
targets.push(arg)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (targets.length === 0 && !scanRecent) {
|
|
77
|
+
console.error('usage: node scripts/repair-malformed-user-messages.mjs <session-id|session-dir|.zstd> [...] [--write] [--force]')
|
|
78
|
+
console.error(' node scripts/repair-malformed-user-messages.mjs --scan-recent [--hours 24] [--write]')
|
|
79
|
+
process.exit(2)
|
|
80
|
+
}
|
|
81
|
+
if (scanRecent && (!Number.isFinite(scanHours) || scanHours <= 0 || scanHours > 24 * 365)) {
|
|
82
|
+
console.error(`--hours must be a positive number, got ${String(rawArgs[hoursIndex + 1])}`)
|
|
83
|
+
process.exit(2)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function log(message) {
|
|
87
|
+
console.log(message)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function oneLine(value) {
|
|
91
|
+
const text = String(value ?? '').replace(/\s+/g, ' ').trim() || '(无摘要)'
|
|
92
|
+
return text.length <= 120 ? text : `${text.slice(0, 119)}…`
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function shapeProblem(data) {
|
|
96
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) return 'payload is not a plain object'
|
|
97
|
+
if (typeof data.id !== 'string' || data.id.length === 0) return 'missing message id'
|
|
98
|
+
if (data.role !== 'user') return 'role must be "user"'
|
|
99
|
+
if (!Array.isArray(data.content) || data.content.length === 0) return 'content must be a non-empty array'
|
|
100
|
+
if (typeof data.source !== 'object' || data.source === null) return 'missing source'
|
|
101
|
+
if (typeof data.source.kind !== 'string' || data.source.kind.length === 0) return 'missing source.kind'
|
|
102
|
+
return null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function resolveSessionFile(target) {
|
|
106
|
+
const direct = resolve(target)
|
|
107
|
+
if (existsSync(direct)) {
|
|
108
|
+
const stat = statSync(direct)
|
|
109
|
+
if (stat.isFile() && direct.endsWith('.zstd')) return direct
|
|
110
|
+
if (stat.isDirectory()) {
|
|
111
|
+
const candidate = join(direct, 'session.v4.jsonl.zstd')
|
|
112
|
+
if (existsSync(candidate)) return candidate
|
|
113
|
+
throw new Error(`no session.v4.jsonl.zstd in ${direct}`)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (/^session-[0-9a-f-]+$/i.test(basename(target))) {
|
|
117
|
+
const sessionsRoot = join(homedir(), '.dsh', 'sessions')
|
|
118
|
+
const matches = []
|
|
119
|
+
if (existsSync(sessionsRoot)) {
|
|
120
|
+
for (const workspace of readdirSync(sessionsRoot)) {
|
|
121
|
+
const candidate = join(sessionsRoot, workspace, basename(target), 'session.v4.jsonl.zstd')
|
|
122
|
+
if (existsSync(candidate)) matches.push(candidate)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (matches.length === 1) return matches[0]
|
|
126
|
+
if (matches.length > 1) throw new Error(`session id ${target} matched ${matches.length} workspaces; pass an explicit path`)
|
|
127
|
+
throw new Error(`session id ${target} not found under ~/.dsh/sessions`)
|
|
128
|
+
}
|
|
129
|
+
throw new Error(`cannot resolve session target: ${target}`)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function assertNotOpen(file) {
|
|
133
|
+
const probe = spawnSync('lsof', [file], { encoding: 'utf8' })
|
|
134
|
+
if (probe.error || typeof probe.stdout !== 'string') return
|
|
135
|
+
if (probe.stdout.trim().length > 0) {
|
|
136
|
+
throw new Error(`refusing to write: the session log is still open by another process\n${probe.stdout.trim()}\nStop DSH first, then rerun with --write.`)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function decompress(file) {
|
|
141
|
+
return execFileSync('zstd', ['-dc', file], { maxBuffer: MAX_BUFFER })
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function encodeContainer(lines) {
|
|
145
|
+
const headerFrame = zstdCompressSync(Buffer.from(`${lines[0]}\n`), CHECKSUM_LEVEL_19)
|
|
146
|
+
if (lines.length === 1) return headerFrame
|
|
147
|
+
const eventsFrame = zstdCompressSync(Buffer.from(`${lines.slice(1).join('\n')}\n`), CHECKSUM_LEVEL_19)
|
|
148
|
+
return Buffer.concat([headerFrame, eventsFrame])
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function invalidateProjectionCache(sessionId, firstRepairedSeq) {
|
|
152
|
+
const cachePath = join(homedir(), '.dsh', 'storages', 'session_projcache', 'sessions', `${sessionId}.json`)
|
|
153
|
+
if (!existsSync(cachePath)) return null
|
|
154
|
+
let maxSeq = -1
|
|
155
|
+
try {
|
|
156
|
+
const cache = JSON.parse(readFileSync(cachePath, 'utf8'))
|
|
157
|
+
for (const row of Object.values(cache?.record?.rows ?? {})) {
|
|
158
|
+
if (Number.isSafeInteger(row?.seq) && row.seq > maxSeq) maxSeq = row.seq
|
|
159
|
+
}
|
|
160
|
+
} catch {
|
|
161
|
+
maxSeq = firstRepairedSeq
|
|
162
|
+
}
|
|
163
|
+
if (maxSeq < firstRepairedSeq) return null
|
|
164
|
+
const backup = `${cachePath}.bak-${new Date().toISOString().replace(/[:.]/g, '-')}`
|
|
165
|
+
renameSync(cachePath, backup)
|
|
166
|
+
return backup
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function repairOne(target) {
|
|
170
|
+
const file = resolveSessionFile(target)
|
|
171
|
+
log(`\n=== ${file} ===`)
|
|
172
|
+
const text = decompress(file).toString('utf8')
|
|
173
|
+
const lines = text.split('\n').filter(Boolean)
|
|
174
|
+
if (lines.length === 0) throw new Error('session log is empty')
|
|
175
|
+
|
|
176
|
+
const parsed = lines.map((line, index) => {
|
|
177
|
+
try {
|
|
178
|
+
return JSON.parse(line)
|
|
179
|
+
} catch (error) {
|
|
180
|
+
throw new Error(`line ${index + 1} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`)
|
|
181
|
+
}
|
|
182
|
+
})
|
|
183
|
+
const header = parsed[0]
|
|
184
|
+
if (header?.type !== 'session') throw new Error('first line is not a session header')
|
|
185
|
+
const sessionId = String(header.id ?? basename(dirname(file)))
|
|
186
|
+
const beforeCounts = new Map()
|
|
187
|
+
const repairedSeqs = []
|
|
188
|
+
let firstRepairedSeq = Number.POSITIVE_INFINITY
|
|
189
|
+
|
|
190
|
+
for (let index = 1; index < parsed.length; index += 1) {
|
|
191
|
+
const event = parsed[index]
|
|
192
|
+
const expectedSeq = index - 1
|
|
193
|
+
if (event?.seq !== expectedSeq) throw new Error(`event at line ${index + 1} has seq ${String(event?.seq)}, expected ${expectedSeq}`)
|
|
194
|
+
if (event.type !== 'user/message') continue
|
|
195
|
+
const problem = shapeProblem(event.data)
|
|
196
|
+
if (problem === null) continue
|
|
197
|
+
beforeCounts.set(problem, (beforeCounts.get(problem) ?? 0) + 1)
|
|
198
|
+
if (typeof event.data !== 'string') {
|
|
199
|
+
throw new Error(`seq ${event.seq}: unsupported malformed user/message (${problem}); refusing to guess a repair`)
|
|
200
|
+
}
|
|
201
|
+
const text = event.data
|
|
202
|
+
const workplanNotice = /^\[dsh-workplan\] 子任务 /.test(text) || /^子任务 .+ 即将到点:/.test(text)
|
|
203
|
+
event.data = {
|
|
204
|
+
id: randomUUID(),
|
|
205
|
+
role: 'user',
|
|
206
|
+
content: [{ type: 'text', text }],
|
|
207
|
+
source: {
|
|
208
|
+
kind: workplanNotice ? 'workplan' : 'recovered',
|
|
209
|
+
form: 'notice',
|
|
210
|
+
summary: oneLine(text),
|
|
211
|
+
},
|
|
212
|
+
}
|
|
213
|
+
repairedSeqs.push(event.seq)
|
|
214
|
+
firstRepairedSeq = Math.min(firstRepairedSeq, event.seq)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
log(`session: ${sessionId}`)
|
|
218
|
+
log(`events: ${parsed.length - 1}; malformed user/message: ${repairedSeqs.length}`)
|
|
219
|
+
if (repairedSeqs.length === 0) {
|
|
220
|
+
log('result: clean, nothing to repair')
|
|
221
|
+
return { file, sessionId, repaired: 0 }
|
|
222
|
+
}
|
|
223
|
+
log(`repaired seqs: ${repairedSeqs.slice(0, 20).join(', ')}${repairedSeqs.length > 20 ? ' …' : ''}`)
|
|
224
|
+
log(`payload kinds: ${[...beforeCounts.entries()].map(([key, value]) => `${key}=${value}`).join(', ')}`)
|
|
225
|
+
|
|
226
|
+
const repairedLines = parsed.map((event, index) => {
|
|
227
|
+
const line = JSON.stringify(event)
|
|
228
|
+
if (index === 0) return line
|
|
229
|
+
if (event.type === 'user/message') {
|
|
230
|
+
const problem = shapeProblem(event.data)
|
|
231
|
+
if (problem !== null) throw new Error(`seq ${event.seq}: repaired payload still invalid (${problem})`)
|
|
232
|
+
}
|
|
233
|
+
return line
|
|
234
|
+
})
|
|
235
|
+
const encoded = encodeContainer(repairedLines)
|
|
236
|
+
// A dry-run must not touch the (possibly read-only) session directory.
|
|
237
|
+
const staged = write
|
|
238
|
+
? join(dirname(file), `.session.v4.jsonl.zstd.repair-${process.pid}.tmp`)
|
|
239
|
+
: join(tmpdir(), `dsh-session-repair-${process.pid}.zst`)
|
|
240
|
+
writeFileSync(staged, encoded, { mode: 0o600 })
|
|
241
|
+
|
|
242
|
+
const verifyText = execFileSync('zstd', ['-dc', staged], { maxBuffer: MAX_BUFFER }).toString('utf8')
|
|
243
|
+
const verifyLines = verifyText.split('\n').filter(Boolean)
|
|
244
|
+
if (verifyLines.length !== lines.length) throw new Error(`verification failed: event line count ${verifyLines.length} != ${lines.length}`)
|
|
245
|
+
const verifyEvents = verifyLines.map((line) => JSON.parse(line))
|
|
246
|
+
const verifyHeader = verifyEvents[0]
|
|
247
|
+
if (verifyHeader?.id !== sessionId) throw new Error('verification failed: session id changed')
|
|
248
|
+
for (let index = 1; index < verifyEvents.length; index += 1) {
|
|
249
|
+
if (verifyEvents[index].seq !== index - 1) throw new Error(`verification failed: seq discontinuity at ${index}`)
|
|
250
|
+
if (verifyEvents[index].type === 'user/message') {
|
|
251
|
+
const problem = shapeProblem(verifyEvents[index].data)
|
|
252
|
+
if (problem !== null) throw new Error(`verification failed: seq ${verifyEvents[index].seq} (${problem})`)
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (!write) {
|
|
257
|
+
rmSync(staged, { force: true })
|
|
258
|
+
log('dry-run: OK; pass --write to apply')
|
|
259
|
+
return { file, sessionId, repaired: repairedSeqs.length, wrote: false }
|
|
260
|
+
}
|
|
261
|
+
if (!force) assertNotOpen(file)
|
|
262
|
+
|
|
263
|
+
const backup = `${file}.bak-${new Date().toISOString().replace(/[:.]/g, '-')}`
|
|
264
|
+
copyFileSync(file, backup)
|
|
265
|
+
renameSync(staged, file)
|
|
266
|
+
const cacheBackup = invalidateProjectionCache(sessionId, firstRepairedSeq)
|
|
267
|
+
log(`wrote: ${repairedSeqs.length} event(s) repaired`)
|
|
268
|
+
log(`backup: ${backup}`)
|
|
269
|
+
if (cacheBackup) log(`projection cache moved aside: ${cacheBackup}`)
|
|
270
|
+
log(`verify: ${execFileSync('zstd', ['-dc', file], { maxBuffer: MAX_BUFFER }).toString('utf8').split('\n').filter(Boolean).length} lines readable`)
|
|
271
|
+
return { file, sessionId, repaired: repairedSeqs.length, wrote: true, backup }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function recentSessionFiles(hours) {
|
|
275
|
+
const sessionsRoot = join(homedir(), '.dsh', 'sessions')
|
|
276
|
+
const cutoff = Date.now() - hours * 3600 * 1000
|
|
277
|
+
const files = []
|
|
278
|
+
if (!existsSync(sessionsRoot)) return files
|
|
279
|
+
for (const workspace of readdirSync(sessionsRoot)) {
|
|
280
|
+
const workspacePath = join(sessionsRoot, workspace)
|
|
281
|
+
let sessionDirs = []
|
|
282
|
+
try {
|
|
283
|
+
sessionDirs = readdirSync(workspacePath, { withFileTypes: true })
|
|
284
|
+
} catch {
|
|
285
|
+
continue
|
|
286
|
+
}
|
|
287
|
+
for (const entry of sessionDirs) {
|
|
288
|
+
if (!entry.isDirectory()) continue
|
|
289
|
+
const file = join(workspacePath, entry.name, 'session.v4.jsonl.zstd')
|
|
290
|
+
try {
|
|
291
|
+
if (statSync(file).mtimeMs >= cutoff) files.push(file)
|
|
292
|
+
} catch {
|
|
293
|
+
// A session without a v4 log is not a repair candidate.
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return files.sort()
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const workTargets = scanRecent ? [...new Set([...recentSessionFiles(scanHours), ...targets])] : targets
|
|
301
|
+
if (scanRecent) log(`scan-recent: ${workTargets.length} session log(s) modified in the last ${scanHours}h`)
|
|
302
|
+
|
|
303
|
+
let failed = false
|
|
304
|
+
for (const target of workTargets) {
|
|
305
|
+
try {
|
|
306
|
+
repairOne(target)
|
|
307
|
+
} catch (error) {
|
|
308
|
+
failed = true
|
|
309
|
+
console.error(`\n[ERROR] ${target}: ${error instanceof Error ? error.message : String(error)}`)
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
process.exit(failed ? 1 : 0)
|