diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c6cd1cb..a23b72b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,19 +5,28 @@ on: branches: [main] pull_request: +permissions: + contents: read + jobs: test: runs-on: ubuntu-latest + timeout-minutes: 10 strategy: fail-fast: false matrix: node: [20, 22] steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false - uses: actions/setup-node@v4 with: node-version: ${{ matrix.node }} cache: npm + - name: Install Zstandard CLI for Node 20 compression and codec checks + run: sudo apt-get update && sudo apt-get install -y zstd - name: Install deps (cordis/react/react-dom for the host+client suites) run: npm ci - name: Test suite (reader + host smoke + client render; hermetic, no dsh install needed) @@ -32,6 +41,9 @@ jobs: timeout-minutes: 15 steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false - uses: actions/setup-node@v4 with: node-version: 22 @@ -40,10 +52,19 @@ jobs: - name: pack plugin and add to a scratch web profile run: | export DSH_HOME="$RUNNER_TEMP/dsh-home" - npm pack --silent - pnpm dlx @deepseek-ai/dsh plugin --profile web add "$PWD"/dsh-codex-sync-*.tgz + npm pack --json > pack.json + TGZ="$(node -p 'JSON.parse(require("fs").readFileSync("pack.json"))[0].filename')" + mkdir "$RUNNER_TEMP/packed-plugin" + tar -xzf "$TGZ" -C "$RUNNER_TEMP/packed-plugin" + cmp lib/codex-reader.mjs "$RUNNER_TEMP/packed-plugin/package/lib/codex-reader.mjs" + cmp package.json "$RUNNER_TEMP/packed-plugin/package/package.json" + cmp lib/zstd-frame.mjs "$RUNNER_TEMP/packed-plugin/package/lib/zstd-frame.mjs" + cmp docs/COMPATIBILITY.md "$RUNNER_TEMP/packed-plugin/package/docs/COMPATIBILITY.md" + git rev-parse HEAD + sha256sum "$TGZ" + pnpm dlx @deepseek-ai/dsh@0.2.0-rc.2 plugin --profile web add "$PWD/$TGZ" echo "DSH_HOME=$DSH_HOME" >> "$GITHUB_ENV" - name: composed config mentions this plugin run: | - pnpm dlx @deepseek-ai/dsh --profile web --dump-config > composed.txt + pnpm dlx @deepseek-ai/dsh@0.2.0-rc.2 --profile web --dump-config > composed.txt grep -E "dsh-codex-sync|codex-sync" composed.txt diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md new file mode 100644 index 0000000..652fd00 --- /dev/null +++ b/docs/COMPATIBILITY.md @@ -0,0 +1,19 @@ +# Verified DSH runtime compatibility + +The PR #3 local follow-up was tested with the official npm/CLI +`@deepseek-ai/dsh@0.2.0-rc.2`, its `@deepseek-ai/dsh-session@0.2.0-rc.2` +and session-format catalog v4. Desktop version numbers are independent and +are not substitutes for npm package versions. + +The optional MCP client peer admits `0.2.0-rc.2` explicitly, alongside the +existing `^0.0.1-rc.1` range. This does not claim compatibility with every +future 0.2 release or prove full MCP mirroring acceptance. Session import +requires the host's production migration/catalog packages; development-only +migration packages must not be installed into a production profile as a fix. + +Use a profile dependency plus the bundle patch insert, as in +`examples/web-profile.cordis.patch.yml`. Do not also add the same bundle to +`dsh.profile.bundles`. Verify installation and actual activation without +`plugin allow-version`; a composed configuration alone is insufficient. + +Node 20 requires the `zstd` executable for checksummed compression; newer Node runtimes with native Zstandard use the native API. The repair CLI already requires `zstd` for decompression. CI checks both compression paths. diff --git a/docs/compat.md b/docs/compat.md index 7f8decb..40619dd 100644 --- a/docs/compat.md +++ b/docs/compat.md @@ -35,3 +35,8 @@ DSH sessions can be exported back to Codex as rollout JSONL files and indexed in - **Selectable rules**: Only DSH-updated Codex-origin chats (`dshUpdated=true`, tagged "Updated in DSH" / "DSH 已续聊") are selectable. Unchanged or source-missing Codex chats remain grayed out and locked. Native DSH sessions are selectable. - **Independent copy**: Every export creates a brand-new Codex rollout (new uuid) and thread entry. It never overwrites the original Codex thread. - **Sub-agents**: Hidden by default (`hideSub`, default on) and nested under their parent sessions for organization. Selecting a child sub-agent exports it as a separate standalone Codex thread (no merge with parent). + + +Runtime package versions and default activation checks are described in [COMPATIBILITY.md](COMPATIBILITY.md). + +Reverse export preserves user and assistant text; it does not reconstruct tool traces or the original thread id. Use the native DSH archive export to retain the stored event log. diff --git a/lib/attach-workspaces.mjs b/lib/attach-workspaces.mjs index a91708d..faefc2f 100644 --- a/lib/attach-workspaces.mjs +++ b/lib/attach-workspaces.mjs @@ -8,6 +8,8 @@ * 服务不存在(headless 等未加载 workspace 插件的组合)时静默跳过。 */ +import { normalizePersistence } from './persistence-facade.mjs' + /** 路径显示:home 用 `~` 前缀;超过 3 级只保留最后 3 级(保证同名可区分又简洁)。 */ export function displayPath(cwd) { const home = process.env.HOME ?? '' @@ -117,6 +119,7 @@ export async function unifyWorkspaceTitles(ctx) { * @returns [{id, cwd}],按持久化 header 读取。 */ export async function listImportedSessions(persistence) { + persistence = normalizePersistence(persistence) const headers = await persistence.list() const imported = [] for (const header of headers) { diff --git a/lib/codex-reader.mjs b/lib/codex-reader.mjs index eee6702..2a0d85d 100644 --- a/lib/codex-reader.mjs +++ b/lib/codex-reader.mjs @@ -184,7 +184,7 @@ export function parseCodexSession(file) { if (type === 'custom_tool_call' || type === 'function_call') { if (pending.length === 0) pendingTime = at const id = typeof payload.call_id === 'string' ? payload.call_id : `codex-call-${crypto.randomUUID()}` - const input = payload.input + const input = type === 'function_call' ? (payload.arguments ?? payload.input) : payload.input const args = typeof input === 'string' ? input : input === undefined ? '' : JSON.stringify(input) pending.push({ type: 'tool-call', id, name: String(payload.name ?? 'tool'), arguments: args }) continue diff --git a/lib/convert.mjs b/lib/convert.mjs index 33b81da..b00dead 100644 --- a/lib/convert.mjs +++ b/lib/convert.mjs @@ -32,6 +32,7 @@ export function buildDshEvents(messages, options = {}) { const events = [] let turn = 0 let step = 0 + let stepHasAssistant = false let openTurn = false let lastTime = 0 let firstUserSeq @@ -77,9 +78,18 @@ export function buildDshEvents(messages, options = {}) { openTurn = false } turn += 1 - step = 0 + step = 1 + stepHasAssistant = false openTurn = true push('turn/start', message.time, { turn }) + // 每个 turn 必须先开一个 step 区,才能承接后面的 surface 事件 + // (user/message / assistant/message / tool/result)。dsl 持久化读入时的 + // format v2→v3 迁移要求:任何 surface 事件出现在第一个 step/start 之前, + // 会因“无法在不改变时间顺序的情况下获取 system head”而拒绝导入。 + // 原生 agent-loop 是先 step/start 再写 surface;导入器必须复用同样的 + // “step/start 前置于首条 surface 事件”的序列,否则 DSH 0.9.0 已导入会话 + // 无法打开(issue #2)。 + openStepFor(turn, step, message.time) if (message.blocks.length > 0) { push('user/message', message.time, { role: 'user', @@ -92,9 +102,13 @@ export function buildDshEvents(messages, options = {}) { } else { if (!openTurn) { turn += 1 - step = 0 + step = 1 + stepHasAssistant = false openTurn = true push('turn/start', message.time, { turn }) + // 首个消息是 assistant(无前置用户消息)时也要先开 step 区, + // 才能承接其后的 surface 事件。 + openStepFor(turn, step, message.time) } // Paired tool-result blocks (from codex custom_tool_call_output) are // consumed by the tool/result surface event, never written into the @@ -118,8 +132,16 @@ export function buildDshEvents(messages, options = {}) { } } if (contentBlocks.length === 0) continue - step += 1 - openStepFor(turn, step, message.time) + // 若当前 turn 已有 open step 区且尚未被任何 assistant 占用(即刚由用户 + // 消息开启的 step 1),则首个 assistant 复用该 step——与原生 agent-loop + // 行为一致(首条 user/message 与 assistant/message 共享 step 1)。否则 + // 递增开启新 step,保证同一 turn 内多条 assistant 各自成步。 + const regionMatches = openStep !== null && openStep.turn === turn && openStep.step === step + if (!regionMatches || stepHasAssistant) { + step += 1 + openStepFor(turn, step, message.time) + } + stepHasAssistant = true push('assistant/message', message.time, { turn, step, @@ -171,12 +193,14 @@ export function buildDshEvents(messages, options = {}) { // 继承源会话标题:latest-wins 的 session/title 事件。默认 fallback 源 // (继续对话后 LLM 标题生成器接管更新);`titlePinned` 时用 user 源 // 固定标题(自动生成停止调度,来源标识与标题持久保留)。 + // V4 relationship rule:user 源标题是独立文本,messageSeqs 必须为空; + // fallback 源标题必须引用一条更早的 user/message 事件。 if (options.title !== undefined && options.title.length > 0) { - push('session/title', lastTime, { - title: options.title, - messageSeqs: firstUserSeq !== undefined ? [firstUserSeq] : [], - source: options.titlePinned === true ? { kind: 'user' } : { kind: 'fallback' }, - }) + const source = options.titlePinned === true ? { kind: 'user' } : { kind: 'fallback' } + const messageSeqs = options.titlePinned === true ? [] : (firstUserSeq !== undefined ? [firstUserSeq] : []) + if (messageSeqs.length > 0 || options.titlePinned === true) { + push('session/title', lastTime, { title: options.title, messageSeqs, source }) + } } return events } diff --git a/lib/dsh-writer.mjs b/lib/dsh-writer.mjs index 8a99e13..55a7390 100644 --- a/lib/dsh-writer.mjs +++ b/lib/dsh-writer.mjs @@ -16,7 +16,7 @@ * verify the decompressed SHA-256 is unchanged. */ -import { constants, zstdCompressSync } from 'node:zlib' +import { compressChecksummedFrame } from './zstd-frame.mjs' import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs' import { join } from 'node:path' @@ -63,9 +63,7 @@ export function projectKey(cwd) { /** One zstd-compressed frame with the backend's checksum flag. */ function zstdFrame(text) { - return zstdCompressSync(Buffer.from(text, 'utf8'), { - params: { [constants.ZSTD_c_checksumFlag]: 1 }, - }) + return compressChecksummedFrame(Buffer.from(text, 'utf8')) } /** diff --git a/lib/export-codex.js b/lib/export-codex.js index e565409..b2fb288 100644 --- a/lib/export-codex.js +++ b/lib/export-codex.js @@ -12,6 +12,7 @@ import { execFileSync } from 'node:child_process' import { dirname, join } from 'node:path' import { randomFillSync } from 'node:crypto' import { listCodexSessions, parseCodexSession } from './codex-reader.mjs' +import { normalizePersistence } from './persistence-facade.mjs' function uuidv7() { const b = Buffer.alloc(16) @@ -405,6 +406,7 @@ export function indexCodexThread(codexHome, { uuid, path, cwd, createdAt, title, * List DSH sessions as an export catalog (grouped by cwd). */ export async function listExportCatalog(persistence, options = {}, codexHome = join(process.env.HOME ?? '', '.codex')) { + persistence = normalizePersistence(persistence) const includeCodex = options.includeCodex === true const includeSubagents = options.includeSubagents === true @@ -538,6 +540,7 @@ export async function listExportCatalog(persistence, options = {}, codexHome = j * Export selected DSH sessions to new Codex rollouts + thread index. */ export async function exportToCodex(persistence, options = {}, codexHome = join(process.env.HOME ?? '', '.codex')) { + persistence = normalizePersistence(persistence) const dryRun = options.dryRun === true const want = Array.isArray(options.ids) && options.ids.length > 0 ? new Set(options.ids) : null const metas = (await persistence.list()) || [] diff --git a/lib/import-service.js b/lib/import-service.js index 7261d26..994082f 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -24,6 +24,8 @@ import { join } from 'node:path' import { listCodexSessions, parseCodexSession, isSubagentThread } from './codex-reader.mjs' import { buildDshEvents, deriveImportTitle } from './convert.mjs' +import { migrateToCurrent } from './session-migrate.mjs' +import { normalizePersistence } from './persistence-facade.mjs' import { attachSessionsToWorkspaces, listImportedSessions } from './attach-workspaces.mjs' const DEFAULT_MAX_SESSION_BYTES = 256 * 1024 * 1024 @@ -59,6 +61,50 @@ function lastTurnNumber(events) { return turn } +/** + * Repack continuation events into ONE fresh, self-contained turn (turn = + * `turn`): structure markers from the slice are dropped and rebuilt (step + * boundaries re-derived from assistant boundaries), content events re-attach + * to the new turn/step. The append-only store can not rewrite the old tail + * (its closing step/end and turn/end), so a same-turn continuation must land + * in a new turn whose markers are internally consistent no matter which + * structural boundaries the slice starts at. + */ +function wrapAsFreshTurn(leftover, turn) { + const out = [] + let step = 0 + let open = false + let stepHasAssistant = false + let lastTime = leftover[0]?.time ?? 0 + out.push({ type: 'turn/start', time: lastTime, data: { turn } }) + const openStep = (time) => { + step += 1 + out.push({ type: 'step/start', time, data: { turn, step } }) + open = true + } + const closeStep = (time) => { + if (open) { + out.push({ type: 'step/end', time, data: { turn, step } }) + open = false + } + } + for (const event of leftover) { + lastTime = event.time ?? lastTime + if (event.type === 'turn/start' || event.type === 'turn/end' || event.type === 'step/start' || event.type === 'step/end') continue + if (event.type === 'assistant/message' && open && stepHasAssistant) closeStep(event.time) + if (!open) openStep(event.time) + if (event.type === 'assistant/message') stepHasAssistant = true + const data = event.data && typeof event.data === 'object' ? { ...event.data } : event.data + if (data && typeof data.turn === 'number') data.turn = turn + if (data && typeof data.step === 'number') data.step = step + out.push({ ...event, data }) + } + closeStep(lastTime) + out.push({ type: 'turn/end', time: lastTime, data: { turn, reason: { kind: 'completed' } } }) + out.forEach((e, i) => { e.seq = i }) + return out +} + /** * Events in `next` that are not already in `old` (matched by leading user-message * text). Used to refresh an imported session after Codex continued the thread. @@ -71,65 +117,83 @@ export function diffImportEvents(oldEvents, nextEvents) { if (match < oldUsers.length) return [] const last = oldEvents[oldEvents.length - 1] - const nextSeq = (typeof last?.seq === 'number' ? last.seq : oldEvents.length - 1) + 1 + const baseSeq = (typeof last?.seq === 'number' ? last.seq : oldEvents.length - 1) + 1 const oldTurn = lastTurnNumber(oldEvents) - const remap = (slice, turnOffset) => slice + const remap = (slice, turnOffset, seqBase) => slice .filter((e) => e.type !== 'session/title') .map((event, i) => { const data = event.data && typeof event.data === 'object' ? { ...event.data } : event.data if (data && typeof data.turn === 'number') data.turn = data.turn + turnOffset - const copy = { ...event, data, seq: nextSeq + i } + const copy = { ...event, data, seq: seqBase + i } return copy }) - if (nextUsers.length > oldUsers.length) { - let seen = -1 - let start = -1 - for (let i = 0; i < nextEvents.length; i++) { - if (nextEvents[i].type !== 'user/message') continue - seen += 1 - if (seen === match) { - start = i - while (start > 0 && nextEvents[start].type !== 'turn/start') start -= 1 - break + // Locate the first event of `next` that the previous import did not store. + // Rollouts are append-only, so `old`'s users and assistants are PREFIXES of + // `next`'s: the (oldAssistants)-th assistant (0-based) and the (match)-th + // user are the first NEW ones. The zero cases matter — `oldAssistants === 0` + // is the reply to a question that was still pending at the previous import + // (counting the current event BEFORE comparing; the old code incremented + // first and never matched, silently dropping the answer), and a new user + // may arrive while old's last turn also gained its (first) assistant. + const oldAssistants = oldEvents.filter((e) => e.type === 'assistant/message').length + let firstNewAssistant = -1 + let firstNewUser = -1 + let assistants = 0 + let seenUsers = -1 + for (let i = 0; i < nextEvents.length; i += 1) { + const type = nextEvents[i].type + if (type === 'assistant/message') { + if (firstNewAssistant === -1) { + if (assistants === oldAssistants) firstNewAssistant = i + else assistants += 1 } + } else if (type === 'user/message') { + seenUsers += 1 + if (seenUsers === match) firstNewUser = i } - if (start < 0) return [] - const slice = nextEvents.slice(start) - const firstTurn = slice.find((e) => e.type === 'turn/start')?.data?.turn ?? (oldTurn + 1) - return remap(slice, (oldTurn + 1) - firstTurn) } + if (firstNewAssistant === -1 && firstNewUser === -1) return [] - const oldLast = oldEvents.at(-1)?.time ?? 0 - const nextLast = nextEvents.at(-1)?.time ?? 0 - if (nextLast <= oldLast) return [] + const cut = firstNewAssistant === -1 ? firstNewUser + : firstNewUser === -1 ? firstNewAssistant + : Math.min(firstNewAssistant, firstNewUser) - let seen = -1 - let assistants = 0 - const oldAssistants = oldEvents.filter((e) => e.type === 'assistant/message').length - let cut = nextEvents.length - for (let i = 0; i < nextEvents.length; i++) { - const event = nextEvents[i] - if (event.type === 'user/message') seen += 1 - if (event.type === 'assistant/message') { - assistants += 1 - if (seen === match - 1 && assistants === oldAssistants) { - cut = i + 1 - while (cut < nextEvents.length && (nextEvents[cut].type === 'tool/call' || nextEvents[cut].type === 'tool/result')) cut += 1 - if (nextEvents[cut]?.type === 'turn/end') cut += 1 - break - } - } + // Split the new content at the first turn/start at or after its beginning: + // - a slice that continues old's LAST turn (the reply arrived after the + // import) must be repacked into ONE fresh turn — the stored tail's + // closing step/end + turn/end are already on disk and the append-only + // store cannot rewrite them; + // - complete new turns keep their converted structure, renumbered to + // continue after the fresh turn. + let boundary + if (cut === firstNewAssistant) { + boundary = cut + 1 + while (boundary < nextEvents.length && nextEvents[boundary].type !== 'turn/start') boundary += 1 + } else { + boundary = cut + while (boundary > 0 && nextEvents[boundary].type !== 'turn/start') boundary -= 1 + if (nextEvents[boundary].type !== 'turn/start') return [] } - const leftover = nextEvents.slice(cut).filter((e) => e.type !== 'session/title' && e.type !== 'turn/end') - if (leftover.length === 0) return [] - const turn = oldTurn + 1 - const wrapped = leftover[0].type === 'turn/start' - ? leftover - : [{ type: 'turn/start', time: leftover[0].time, data: { turn } }, ...leftover] - const firstTurn = wrapped.find((e) => e.type === 'turn/start')?.data?.turn ?? turn - return remap(wrapped, turn - firstTurn) + const suffix = [] + let nextTurn = oldTurn + 1 + if (cut === firstNewAssistant) { + const fresh = wrapAsFreshTurn( + nextEvents.slice(cut, boundary).filter((e) => e.type !== 'session/title'), + nextTurn, + ) + fresh.forEach((e, i) => { e.seq = baseSeq + i }) + suffix.push(...fresh) + nextTurn += 1 + } + if (boundary < nextEvents.length) { + const rest = nextEvents.slice(boundary) + const firstRestTurn = rest.find((e) => e.type === 'turn/start')?.data?.turn + if (typeof firstRestTurn !== 'number') return [] + suffix.push(...remap(rest, nextTurn - firstRestTurn, baseSeq + suffix.length)) + } + return suffix } /** @@ -141,6 +205,7 @@ export function diffImportEvents(oldEvents, nextEvents) { * @returns {Promise} human-readable summary lines. */ export async function importCodex(ctx, persistence, options = {}, codexHome = join(process.env.HOME ?? '', '.codex')) { + persistence = normalizePersistence(persistence) const maxBytes = options.maxSessionBytes ?? DEFAULT_MAX_SESSION_BYTES const dryRun = options.dryRun === true const existing = new Set((await persistence.list()).map((meta) => meta.id)) @@ -188,7 +253,22 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo }) } - let selected = candidates + // Codex writes paginated continuation rollouts for one thread: the base + // `rollout--.jsonl` plus later `rollout--_.jsonl` + // segments (verified delta-only — no message overlap between segments). + // Processing each file as its own candidate would create the session twice + // and abort the whole batch with "session … already exists" on the second + // segment. Merge segments per id, oldest file first (listCodexSessions + // sorts paths, and the embedded rollout timestamps sort chronologically). + const mergedById = new Map() + for (const candidate of candidates) { + const prev = mergedById.get(candidate.id) + if (prev === undefined) mergedById.set(candidate.id, candidate) + else prev.parsed.messages.push(...candidate.parsed.messages) + } + const deduped = [...mergedById.values()] + + let selected = deduped if (Array.isArray(options.ids) && options.ids.length > 0) { const want = new Set(options.ids) selected = selected.filter((c) => want.has(c.id) || want.has(c.parsed.header.id)) @@ -219,6 +299,30 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo title: deriveImportTitle(candidate.parsed.header.title, messages, 'codex'), titlePinned: true, }).map((event, seq) => ({ ...event, seq })) + // DSH 0.9.0 session-persistence now *writes* only the current (v3) format: + // encodeCurrentHeader throws "encodeCurrent requires Session format v3" for a + // v0 header, so the importer must migrate the imported v0 header + events + // through the real v0->v1->v2->v3 chain before create/append (issue #2). + const importHeader = { + version: 0, + id: candidate.id, + createdAt: candidate.createdAt ?? messages[0].time, + ...(candidate.cwd !== undefined ? { cwd: candidate.cwd } : {}), + agentPreset: typeof options.agentPreset === 'string' && options.agentPreset.length > 0 + ? options.agentPreset + : 'cordis', + } + // Fail LOUDLY instead of falling back to a v0 write: real DSH persistence + // rejects v0 anyway ("encodeCurrent requires Session format v3"/"v4"), so + // a silent fallback would break the import while hiding the root cause + // (missing migration packages / data-dependent migration failure). + const { header: currentHeader, events: currentEvents } = (() => { + try { + return migrateToCurrent(importHeader, events) + } catch (error) { + throw new Error(`import-codex: session ${candidate.id} could not be migrated to the current session format: ${error.message}`) + } + })() if (existing.has(candidate.id)) { let oldEvents = [] try { @@ -227,7 +331,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo skipped += 1 continue } - const suffix = diffImportEvents(oldEvents, events) + const suffix = diffImportEvents(oldEvents, currentEvents) if (suffix.length === 0) { skipped += 1 continue @@ -244,21 +348,12 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo } if (dryRun) { imported += 1 - lines.push(` [would-import] ${candidate.id} ${candidate.cwd ?? '(no cwd)'} ${messages.length} messages -> ${events.length} events`) + lines.push(` [would-import] ${candidate.id} ${candidate.cwd ?? '(no cwd)'} ${messages.length} messages -> ${currentEvents.length} events`) continue } - await persistence.create({ - version: 0, - id: candidate.id, - createdAt: candidate.createdAt ?? messages[0].time, - ...(candidate.cwd !== undefined ? { cwd: candidate.cwd } : {}), - agentPreset: typeof options.agentPreset === 'string' && options.agentPreset.length > 0 - ? options.agentPreset - : 'cordis', - }) - await persistence.append(candidate.id, events) + await persistence.createAndAppend(currentHeader, currentEvents) imported += 1 - lines.push(` [imported] ${candidate.id} ${candidate.cwd ?? '(no cwd)'} ${messages.length} messages -> ${events.length} events`) + lines.push(` [imported] ${candidate.id} ${candidate.cwd ?? '(no cwd)'} ${messages.length} messages -> ${currentEvents.length} events`) } const verb = dryRun ? 'would-import' : 'imported' lines.push(`[codex] result: ${verb} ${imported}, updated ${updated}, skipped ${skipped}, empty ${empty}, subagent-skipped ${skippedSubagent}, oversized-skipped ${skippedBig}, unreadable ${unreadable}`) @@ -283,6 +378,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo * Does not write persistence. */ export async function listImportCatalog(persistence, options = {}, codexHome = join(process.env.HOME ?? '', '.codex')) { + persistence = normalizePersistence(persistence) const maxBytes = options.maxSessionBytes ?? DEFAULT_MAX_SESSION_BYTES const includeSubagents = options.importSubagents === true const existing = new Set((await persistence.list()).map((meta) => meta.id)) diff --git a/lib/persistence-facade.mjs b/lib/persistence-facade.mjs new file mode 100644 index 0000000..5977aee --- /dev/null +++ b/lib/persistence-facade.mjs @@ -0,0 +1,131 @@ +/** + * Persistence-interface adapter for DSH session-persistence. + * + * DSH 0.9.0 refactored `ctx.sessionPersistence` to a **handle-based** API: + * - `create(header, { inheritedEventCount })` returns a WRITE handle, + * - `open(id, 'read'|'write')` returns a handle, + * - `list()` returns `[{ header, revision, sizeBytes }]` (id lives under `.header`), + * - there is NO `append(id, …)` and NO `inspect(id)` on the service object. + * + * Older DSH exposed convenience methods directly on the service object + * (`append(id, events)`, `inspect(id)`), which is what this plugin's call + * sites were written against. `normalizePersistence` detects which shape it + * received and returns either the original (old shape) or a facade that maps + * the plugin's familiar calls onto the handle-based API, so the rest of the + * plugin code can stay unchanged. + */ + +/** + * Detect whether `persistence` already exposes the plugin's familiar + * `inspect(id)` read semantics (older DSH). The real DSH 0.9.0 object exposes + * `open(id,'read')` instead, so we only build the handle-based facade when + * `inspect` is absent. + * @param {object} persistence - the service object from `ctx.get('sessionPersistence')`. + * @returns {boolean} true when the service already provides `inspect(id)`. + */ +function hasLegacyRead(persistence) { + return persistence !== null && typeof persistence === 'object' && typeof persistence.inspect === 'function' +} + +/** + * Flatten one DSH `list()` snapshot into the flat metadata shape this plugin + * expects (`{ id, cwd, origin, delegationDepth, ...header }`). + * @param {object} snapshot - `{ header, revision, sizeBytes }` (or legacy flat meta). + * @returns {object} a flat meta object carrying the header fields at top level. + */ +function flattenSnapshot(snapshot) { + const header = snapshot && typeof snapshot.header === 'object' ? snapshot.header : snapshot + return { ...(header ?? {}), header } +} + +/** + * Build the handle-based facade for the plugin's familiar calls. + * @param {object} persistence - the real DSH 0.9.0 service object. + */ +function buildFacade(persistence) { + return { + // list() -> flat metas [{ id, cwd, origin, delegationDepth, ...header }] + async list() { + const snapshots = (await persistence.list()) || [] + return snapshots.map(flattenSnapshot) + }, + + // inspect(id) -> { meta, events } (0.9.0+ uses open(id,'read') + handle.read()) + // A FAILED read must propagate: treating it as empty history would make the + // importer append the whole source onto an existing session. + async inspect(id) { + const handle = await persistence.open(id, 'read') + try { + const read = await handle.read(0) + const events = read && Array.isArray(read.events) ? read.events : [] + return { meta: { ...(handle.header ?? {}), id }, events } + } finally { + try { await handle.close() } catch { /* cleanup is best-effort */ } + } + }, + + // append(id, events) -> open 'write', append, close (for existing sessions). + async append(id, events) { + if (!Array.isArray(events) || events.length === 0) return + const handle = await persistence.open(id, 'write') + let closeError + try { + await handle.append(events) + } finally { + try { await handle.close() } catch (error) { closeError = error } + } + if (closeError !== undefined) throw closeError + }, + + // create(header, events) -> create handle, append, close (for new sessions). + // The plugin's old call sites did create(header) then append(id, events); with + // the handle-based API the freshly-created session is not yet durable, so we + // combine create+append through the same handle. Durability failures + // (flush/close) surface AFTER cleanup is attempted — the importer must not + // report a successful import when the durable write failed. + async createAndAppend(header, events) { + const handle = await persistence.create(header, { inheritedEventCount: 0 }) + let cleanupError + try { + if (Array.isArray(events) && events.length > 0) await handle.append(events) + } finally { + try { await handle.flush() } catch (error) { cleanupError = error } + try { await handle.close() } catch (error) { if (cleanupError === undefined) cleanupError = error } + } + if (cleanupError !== undefined) throw cleanupError + }, + } +} + +/** + * Wrap a legacy-shape persistence object (which already exposes + * `append(id,…)` / `inspect(id)` / `create(header)`) so it also exposes the + * combined `createAndAppend` the plugin now uses; every other method delegates + * straight to the original. + */ +function wrapLegacy(persistence) { + if (typeof persistence.createAndAppend === 'function') return persistence + return new Proxy(persistence, { + get(target, prop, receiver) { + if (prop === 'createAndAppend') { + return async (header, events) => { + await target.create(header) + if (Array.isArray(events) && events.length > 0) await target.append(header.id, events) + } + } + const value = Reflect.get(target, prop, receiver) + return typeof value === 'function' ? value.bind(target) : value + }, + }) +} + +/** + * Return the plugin's familiar persistence API for a DSH service object. + * @param {object|null|undefined} persistence - the service from `ctx.get('sessionPersistence')`. + * @returns {object} a proxy giving the plugin the calls it expects. + */ +export function normalizePersistence(persistence) { + if (persistence === null || persistence === undefined) return persistence + if (hasLegacyRead(persistence)) return wrapLegacy(persistence) + return buildFacade(persistence) +} diff --git a/lib/session-migrate.mjs b/lib/session-migrate.mjs new file mode 100644 index 0000000..3218624 --- /dev/null +++ b/lib/session-migrate.mjs @@ -0,0 +1,138 @@ +/** + * Session-format migration helper for imported (v0) sessions. + * + * DSH's session-persistence backend *writes* only the CURRENT format: + * `encodeCurrentHeader` throws + * "encodeCurrent requires Session format v4" + * (DSH 0.10.x; v3 on 0.9.x) for anything older, so the importer can no longer + * hand `persistence.create` a v0 header + v0 events. This module runs the + * imported artifact through the real `@deepseek-ai/dsh-session-format` + * v0→v1→…→current chain the harness uses on read, producing a header and + * events in the installed current format (with the promoted system/message + * head and the embedded assistant/message stream that current-format restore + * requires). + * + * The chain is discovered DYNAMICALLY: the stages + * `@deepseek-ai/dsh-session-format-vN-to-v{N+1}` are resolved consecutively + * from one resolution base until the next stage is missing, and the longest + * consecutive chain wins. The importer therefore follows the installed DSH + * build (v3 on 0.9.x, v4 on 0.10.x, v5 on later builds, …) without a plugin + * change for every format bump. All stages always come from the SAME base so + * versions cannot be mixed. + * + * Resolution bases, in order: the running DSH app bundle, the standard macOS + * install (asar and asar.unpacked layouts), DSH_CHECKOUT, the profile + * node_modules, and — last, for dev and tests — the plugin's own + * node_modules (the real migration packages are devDependencies). + */ + +import { createRequire } from 'node:module' +import { homedir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** + * Pull the `sessionFormatVNToV{N+1}` migration object out of a stage package. + * Stages whose body migration needs explicit child evidence (V3→V4 onward) + * ship a `createSessionFormatVNToV{N+1}(children)` factory; an empty array is + * the documented declaration for a parent without children — imported Codex + * sessions are imported as roots and never reference DSH children. Stages + * must expose the `migrateHeader` + `createStage` pair used below. + */ +function stageApi(mod, from) { + const plain = mod?.[`sessionFormatV${from}ToV${from + 1}`] + if (plain === undefined) return undefined + const factory = mod?.[`createSessionFormatV${from}ToV${from + 1}`] + const api = typeof factory === 'function' ? factory([]) : plain + return api && typeof api.migrateHeader === 'function' && typeof api.createStage === 'function' ? api : undefined +} + +/** + * Resolve the longest CONSECUTIVE migration chain (v0→v1, v1→v2, …) reachable + * from one require anchor. Stops at the first missing/unusable stage. + * @returns {Array<{ mig: object, from: number }>} + */ +function chainFrom(r) { + const stages = [] + for (let from = 0; ; from += 1) { + let mod + try { mod = r(`@deepseek-ai/dsh-session-format-v${from}-to-v${from + 1}`) } catch { break } + const api = stageApi(mod, from) + if (api === undefined) break + stages.push({ mig: api, from }) + } + return stages +} + +/** + * Resolve the full migration chain. Ties keep the EARLIER base, so the + * running DSH app always wins over dev fallbacks and versions never mix + * (every accepted chain comes from a single base). + * @returns {Array<{ mig: object, from: number }>} at least one stage. + */ +function loadChain() { + const candidates = [] + // 1. Derive from the running electron binary (…/DSH Desktop.app/Contents/MacOS/…) + const execDir = process.execPath ? join(dirname(process.execPath), '..') : '' + if (execDir) { + candidates.push(join(execDir, 'Resources', 'app', 'node_modules')) + } + // 2. Standard macOS install, asar + unpacked layouts, and env/profile fallbacks. + candidates.push('/Applications/DSH Desktop.app/Contents/Resources/app/node_modules') + candidates.push('/Applications/DSH Desktop.app/Contents/Resources/app.asar.unpacked/node_modules') + candidates.push(process.env.DSH_CHECKOUT || '') + candidates.push(join(homedir(), '.dsh', 'profiles', 'node_modules')) + let best = [] + for (const base of candidates.filter(Boolean)) { + let r + try { r = createRequire(join(base, '@deepseek-ai', 'dsh', 'lib', 'index.js')) } catch { continue } + const stages = chainFrom(r) + if (stages.length > best.length) best = stages + } + // 3. The plugin's own node_modules: devDependencies ship the real packages, + // so tests exercise the true migration path without a DSH install. + const local = chainFrom(createRequire(import.meta.url)) + if (local.length > best.length) best = local + if (best.length === 0) { + throw new Error('cannot resolve @deepseek-ai/dsh-session-format-* migration packages') + } + return best +} + +/** + * Migrate a released session header + event list to the installed CURRENT + * format. The chain starts at the header's ACTUAL stored version (v0 from the + * importer, v3 from stored-artifact repair). The source input is not mutated; + * a fresh header/event list is returned. + * @param {object} header - stored header ({version, id, createdAt, cwd, …}). + * @param {Array} events - canonical event rows (each with `seq`). + * @returns {{ header: object, events: Array }} the current-format header and events. + */ +export function migrateToCurrent(header, events) { + const stages = loadChain() + // Start the chain at the header's ACTUAL stored version (v0 from the + // importer, v3 from stored-artifact repair) — re-running earlier stages on a + // later-version artifact would validate its events against the wrong + // vocabulary ("format v0 contains unknown historical event type …"). + const fromVersion = header?.version ?? 0 + const applicable = stages.filter((s) => s.from >= fromVersion) + const normalized = { + ...header, + version: fromVersion, + isSeeded: header.isSeeded ?? false, + delegationDepth: header.delegationDepth ?? 0, + } + let h = { ...normalized } + for (const { mig } of applicable) h = mig.migrateHeader(h) + // Migrate the events stage by stage; each stage expects the SOURCE header of + // its own `fromVersion`. + let cur = events.map((e, i) => ({ ...e, seq: i })) + for (const { mig, from } of applicable) { + const sourceHeader = { ...normalized, version: from } + const stage = mig.createStage({ sourceHeader, sourceInheritedEventCount: 0 }) + const out = [] + for (const ev of cur) stage.transformEvent(ev, { emitEvent: (e) => out.push(e) }) + cur = out + } + return { header: h, events: cur } +} diff --git a/lib/session-repair.mjs b/lib/session-repair.mjs index d30d3e0..239c248 100644 --- a/lib/session-repair.mjs +++ b/lib/session-repair.mjs @@ -23,12 +23,14 @@ * measures clean AND the on-disk form does not. */ import { execFileSync } from 'node:child_process' -import { copyFileSync, existsSync, readdirSync, statSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' +import { copyFileSync, existsSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' import { homedir } from 'node:os' -import { zstdCompressSync, constants as zstdConstants } from 'node:zlib' +import { compressChecksummedFrame } from './zstd-frame.mjs' import { createRequire } from 'node:module' +import { migrateToCurrent } from './session-migrate.mjs' + const require = createRequire(import.meta.url) /** @@ -44,7 +46,10 @@ function dshPackage(name) { } attempts.push(`@deepseek-ai/${name}`) const home = process.env.DSH_HOME ?? join(homedir(), '.dsh') - for (const base of [process.env.DSH_CHECKOUT, join(home, 'profiles', 'web', 'node_modules')]) { + // The macOS desktop app bundles the packages under its app.asar.unpacked + // node_modules — resolvable from a plain-node CLI without DSH_CHECKOUT. + const appBase = '/Applications/DSH Desktop.app/Contents/Resources/app.asar.unpacked/node_modules' + for (const base of [process.env.DSH_CHECKOUT, appBase, join(home, 'profiles', 'web', 'node_modules')]) { if (!base) continue const r = createRequire(join(base, '@deepseek-ai', name, 'noop.js')) try { @@ -65,14 +70,29 @@ function loadEvents(file) { const raw = execFileSync('zstd', ['-dc', file], { maxBuffer: 1 << 28 }).toString('utf8') const lines = raw.split('\n') if (!lines[0].startsWith('{"type":"session"')) throw new Error('not a dsh session log') - const { decodeStorageRecord } = dshPackage('dsh-session') + // dsh-session 在不同版本暴露的物理行解码 API 名称不定(`decodeStorageRecord` + // 在 DSH 0.9.1 已不再导出)。这里先试 decodeStorageRecord,不可用时直接按 + // 逻辑行 JSON.parse——本插件自行写入的 v0/v3 artifact 就是逻辑行形状 + // ({type, seq, time, data, surfaceOp}),直接解析即可,也保证 + // repairEvents / migrateToCurrent 拿到数据。 + const dshSession = dshPackage('dsh-session') + const decodeStorageRecord = typeof dshSession?.decodeStorageRecord === 'function' ? dshSession.decodeStorageRecord : null const evs = [] for (let i = 1; i < lines.length; i++) { const line = lines[i].trim() if (!line) continue - try { evs.push(...decodeStorageRecord(JSON.parse(line))) } catch { /* skip torn tail row */ } + let row + try { row = JSON.parse(line) } catch { continue /* torn tail row */ } + try { + if (decodeStorageRecord) evs.push(...decodeStorageRecord(row)) + else evs.push(row) + } catch { /* skip a single unreadable row */ } } - return { headerLine: `${lines[0]}\n`, evs } + // 逻辑 header(去掉 storage 的 `type: "session"` 包装)供 v0→v3 迁移使用。 + const headerLine = `${lines[0]}\n` + const rawHeader = JSON.parse(lines[0]) + const { type: _type, ...logicalHeader } = rawHeader + return { headerLine, header: logicalHeader, evs } } /** Fold events through dsh's real TokenMeter; throws on any replay damage. */ @@ -80,8 +100,13 @@ function measure(evs) { const { Session } = dshPackage('dsh-session') const meterMod = dshPackage('dsh-token-meter') const TokenMeter = meterMod.default ?? meterMod + // DSH 0.9.1 的 `Session.create` 只接受当前(v3)header;用 dsh-session 导出的 + // SESSION_FORMAT_VERSION 而不是写死 version: 0,否则创建 meter 校验会话即抛 + // "session header version must be 3, got 0"。 + const dshSession = dshPackage('dsh-session') + const version = typeof dshSession?.SESSION_FORMAT_VERSION === 'number' ? dshSession.SESSION_FORMAT_VERSION : 0 const session = Session.create('repair-check', JSON.parse(JSON.stringify(evs)), { - id: 'repair-check', version: 0, createdAt: Date.now(), cwd: '/tmp', + id: 'repair-check', version, isSeeded: false, delegationDepth: 0, createdAt: Date.now(), cwd: '/tmp', }) const meter = Object.create(TokenMeter.prototype) meter.states = new WeakMap() // bypass cordis Service wiring; fold logic only @@ -130,21 +155,86 @@ export function repairEvents(input) { } // ── step pairing: open a step before unmarked message/tool events, close at turn bounds ── - const STEP_TYPES = new Set(['assistant/message', 'tool/call', 'tool/result', 'assistant/chunk']) + // STEP_TYPES 覆盖所有「surface」类型(含 user/message)。DSH 的 format v0→v1→v2→v3 + // 迁移在首个 step/start 处才取得 system head,任何 surface 事件出现在它之前都会抛 + // "format v2 surface before first step cannot acquire a system head ..."。旧版导入器 + // 生成的 user/message(无 data.turn/step)正属于此类,导致 DSH 0.9.1 无法把已导入的 + // v0 会话迁移到 v3。这里统一为无 open step 的 surface 事件前置一对 step/start。 + const STEP_TYPES = new Set(['user/message', 'assistant/message', 'tool/call', 'tool/result', 'assistant/chunk']) const fixed = [] + let currentTurn = 0 + let lastTurn = 0 + let inTurn = false + // v4 lifecycle: turns open in strict 1,2,3… order and steps restart at 1 + // within each turn, incrementing strictly. Old importer logs carry duplicate + // step/start markers, surface events AFTER the last turn/end (bare-appended + // paginated segments), and surface events whose stored turn/step no longer + // matches — the REGION STRUCTURE of the log is kept but every marker is + // RENORMALIZED while pairing: each step/start gets the next number of its + // turn, each step/end mirrors its open region, surface events re-attach to + // the open region, and orphan surfaces open a fresh turn. + const nextStep = new Map() // turn -> next step number to assign + const open = { turn: null, step: null } + const emitStepEnd = (time) => { + if (open.turn === null) return + fixed.push({ type: 'step/end', time, data: { turn: open.turn, step: open.step } }) + open.turn = null + open.step = null + } + const emitStepStart = (time, turn) => { + const s = nextStep.get(turn) ?? 1 + nextStep.set(turn, s + 1) + fixed.push({ type: 'step/start', time, data: { turn, step: s } }) + open.turn = turn + open.step = s + } + const openFreshTurn = (time) => { + const t = lastTurn + 1 + lastTurn = t + currentTurn = t + inTurn = true + nextStep.set(t, 1) + fixed.push({ type: 'turn/start', time, data: { turn: t } }) + } for (const e of evs) { - if (STEP_TYPES.has(e.type) && e.data && typeof e.data.turn === 'number' && typeof e.data.step === 'number') { - const open = openStepOf(fixed) - if (!open || open.data.turn !== e.data.turn || open.data.step !== e.data.step) { - // meter only enforces pairing order: close the old step first, even across turns - if (open) fixed.push({ type: 'step/end', time: e.time, data: { turn: open.data.turn, step: open.data.step } }) - fixed.push({ type: 'step/start', time: e.time, data: { turn: e.data.turn, step: e.data.step } }) + if (e.type === 'turn/start' && e.data && typeof e.data.turn === 'number') { + // v4: turn/end (and therefore the new turn/start) requires NO open step — + // close the region FIRST, then close the previous turn. + emitStepEnd(e.time) + if (inTurn) fixed.push({ type: 'turn/end', time: e.time, data: { turn: currentTurn, reason: { kind: 'completed' } } }) + currentTurn = e.data.turn + lastTurn = Math.max(lastTurn, e.data.turn) + inTurn = true + nextStep.set(currentTurn, 1) + } + if (e.type === 'turn/end') { + inTurn = false + emitStepEnd(e.time) // turn/end requires no open step + } + if (e.type === 'step/start' || e.type === 'step/end') { + // The stored marker defines region structure only; re-emit it with a + // normalized number (a duplicate open becomes start…end…start). + if (e.type === 'step/start') { + if (open.turn !== null) emitStepEnd(e.time) + emitStepStart(e.time, currentTurn) + } else { + emitStepEnd(e.time) } + continue } - if (e.type === 'turn/start' || e.type === 'turn/end') { - const open = openStepOf(fixed) - if (open) fixed.push({ type: 'step/end', time: e.time, data: { turn: open.data.turn, step: open.data.step } }) + if (STEP_TYPES.has(e.type)) { + // Surface events after the last turn/end (bare-appended paginated + // segments) open a fresh turn instead of leaking outside turn bounds. + if (!inTurn) openFreshTurn(e.time) + if (open.turn === null || open.turn !== currentTurn) { + emitStepEnd(e.time) + emitStepStart(e.time, currentTurn) + } + if (e.data && typeof e.data === 'object' && (e.data.turn !== undefined || e.data.step !== undefined)) { + e.data = { ...e.data, turn: open.turn, step: open.step } + } } + if (e.type === 'turn/end') emitStepEnd(e.time) // turn/end requires no open step fixed.push(e) } @@ -198,15 +288,15 @@ export function repairEvents(input) { /** Encode header + events as the standard two-frame artifact body. */ function encodeLog(headerLine, evs) { - const frameOpts = { params: { [zstdConstants.ZSTD_c_checksumFlag]: 1 } } const body = evs.map((e) => JSON.stringify(e)).join('\n') + '\n' return Buffer.concat([ - zstdCompressSync(Buffer.from(headerLine), frameOpts), - zstdCompressSync(Buffer.from(body), frameOpts), + compressChecksummedFrame(Buffer.from(headerLine)), + compressChecksummedFrame(Buffer.from(body)), ]) } -function listSessionFiles(root) { +/** Scan a session store root for one log per session dir; exported for tests. */ +export function listSessionFiles(root) { const out = [] if (!existsSync(root)) return out for (const ws of readdirSync(root)) { @@ -214,36 +304,176 @@ function listSessionFiles(root) { let st; try { st = statSync(wp) } catch { continue } if (!st.isDirectory()) continue for (const d of readdirSync(wp)) { - const f = join(wp, d, 'session.jsonl.zstd') + const dp = join(wp, d) + let dst; try { dst = statSync(dp) } catch { continue } + if (!dst.isDirectory()) continue + // DSH 0.10.x names current-format logs `session.v4.jsonl.zstd`; older + // builds wrote `session.jsonl.zstd`. When both exist the highest + // current-format log wins (the old file was superseded by a previous + // repair and only remains as the pre-repair state beside its .bak). + const versioned = readdirSync(dp).filter((n) => /^session\.v\d+\.jsonl\.zstd$/.test(n)).sort() + if (versioned.length > 0) { out.push(join(dp, versioned.at(-1))); continue } + const f = join(dp, 'session.jsonl.zstd') if (existsSync(f)) out.push(f) } } return out } +/** Resolve the released session-format catalog used by DSH's own persistence + * (exposes currentVersion + encodeCurrentHeader/encodeCurrentEvent). */ +function sessionFormatCatalog() { + const mod = dshPackage('dsh-session-format-catalog') + return mod?.sessionFormatCatalog ?? mod +} + +/** + * Pre-migration normalization: the pre-0.10.0 importer wrote user-kind + * session/title events citing messageSeqs — legal under v3 (no rule) but + * rejected by the v4 relationship rule ("session/title messageSeqs must be + * empty exactly for a user title"). A user-kind title is standalone text and + * must carry EMPTY messageSeqs; clear them so the migrated v4 artifact + * restores cleanly. Exported for tests. + * @param {Array} evs - stored event rows. + * @returns {Array} event rows with user-kind title citations cleared. + */ +export function normalizeTitleMessageSeqs(evs) { + return (evs ?? []).map((ev) => { + if (ev?.type !== 'session/title') return ev + if (ev?.data?.source?.kind !== 'user') return ev + if (!Array.isArray(ev.data.messageSeqs) || ev.data.messageSeqs.length === 0) return ev + return { ...ev, data: { ...ev.data, messageSeqs: [] } } + }) +} + +/** + * Rewrite one stored artifact to the installed CURRENT format in place. + * + * DSH 0.9.0+ `session-persistence` writes only v3 and migrates pre-v3 artifacts + * on read via the v0→v1→v2→v3 chain. That chain acquires its "system head" at + * the FIRST step/start, so any surface event (user/message / assistant/message / + * tool/result) appearing before the first step/start makes the whole migration + * throw "format v2 surface before first step cannot acquire a system head ...", + * leaving the session unreadable (symptom: `encodeCurrent requires Session + * format v3` / "session ... already exists" on re-import). Old imported v0 logs + * emitted turn/start → user/message with no leading step region, exactly this + * case. This repair runs repairEvents (which now opens a step before orphan + * surfaces), then migrates v0→v3 and validates that the resulting v3 artifact + * encodes cleanly end-to-end before writing. + * + * @param {string} file - path to a stored `session.jsonl.zstd`. + * @param {object} [options] - { write?: boolean } controls whether the repaired + * v3 artifact is written to disk (default false → dry-run, validates only). + * @returns {{ ok: boolean, reason?: string, from?: number, to?: number }} outcome. + */ +export function migrateArtifactToCurrent(file, options = {}) { + const writeOut = options.write === true + let header, evs + try { ({ header, evs } = loadEvents(file)) } catch (e) { return { ok: false, reason: `load: ${e?.message}` } } + // Logs with compaction events need compaction-aware restructuring: the + // stored compaction/shadowedRange citations name exact surface spans that + // marker normalization would invalidate, and an open compaction forbids new + // turns. Skip them honestly instead of writing an invalid artifact. + if (evs.some((e) => typeof e?.type === 'string' && e.type.startsWith('compaction/'))) { + return { ok: false, reason: 'compaction events present; skipped (needs compaction-aware restructure)', from: header.version } + } + const cat = sessionFormatCatalog() + // Already matches current format: nothing to migrate. + if (header.version === cat.currentVersion) return { ok: false, reason: 'already-current', from: header.version, to: cat.currentVersion } + + const repaired = repairEvents(normalizeTitleMessageSeqs(evs)) + let migrated + try { + migrated = migrateToCurrent(header, repaired) + } catch (e) { return { ok: false, reason: `migrate: ${e?.message}`, from: header.version } } + + // Encode the migrated artifact into the exact physical frames the JSONL + // backend persists (one header frame, one events frame). + let headerLine, bodyLines + try { + headerLine = JSON.stringify(cat.encodeCurrentHeader({ ...migrated.header, delegationDepth: migrated.header.delegationDepth ?? 0 }, 0)) + bodyLines = migrated.events.map((e) => JSON.stringify(cat.encodeCurrentEvent(e))) + } catch (e) { return { ok: false, reason: `encode: ${e?.message}`, from: header.version } } + + // FULL current-format restoration + relationship validation before touching + // disk: encoding alone misses lifecycle relationships (open steps across + // turn bounds, stale region membership, …) and would persist an artifact + // the real restorer rejects. This replays the exact stored frames through + // the catalog's own reader, the same code path DSH uses to open sessions. + try { + const restore = cat.createRestore(JSON.parse(headerLine), { validation: 'current' }) + for (const row of bodyLines) restore.decodeRow(JSON.parse(row)) + restore.finish() + } catch (e) { return { ok: false, reason: `restore: ${e?.message}`, from: header.version } } + + const headerLineText = headerLine + '\n' + const bodyText = bodyLines.join('\n') + '\n' + if (!writeOut) return { ok: true, from: header.version, to: cat.currentVersion, dry: true } + + const bytes = Buffer.concat([ + compressChecksummedFrame(Buffer.from(headerLineText)), + compressChecksummedFrame(Buffer.from(bodyText)), + ]) + copyFileSync(file, `${file}.bak`) // always keep a backup of the original artifact + // DSH 0.10.x names current-format logs `session.v.jsonl.zstd`; + // writing the migrated artifact back under the OLD name would leave it + // invisible to the new persistence (the "already exists" on re-import). + const targetFile = join(dirname(file), `session.v${cat.currentVersion}.jsonl.zstd`) + writeFileSync(targetFile, bytes) + if (targetFile !== file) rmSync(file) // the old-named log is superseded + return { ok: true, from: header.version, to: cat.currentVersion } +} + /** * Scan (and optionally repair) every stored session log. * @param {object} options - { fix?: boolean, root?: string }. * @returns {{ total: number, ok: number, bad: string[], fixed: string[] }} summary. */ export function repairSessionStore(options = {}) { - const root = options.root ?? join(homedir(), '.dsh', 'sessions') + // 默认 session store 根:DSH Desktop 的会话存于 $DSH_HOME/sessions + // (如 ~/Library/Application Support/dsh-desktop/harness/sessions),而非 + // ~/.dsh/sessions。旧默认会扫空目录,导致 /repair-sessions 永远扫不到。 + const root = options.root ?? (process.env.DSH_HOME ? join(process.env.DSH_HOME, 'sessions') : join(homedir(), '.dsh', 'sessions')) const files = listSessionFiles(root) - const bad = []; const fixed = []; let ok = 0 + const bad = []; const fixed = []; const stale = []; let ok = 0; let skipped = 0 for (const f of files) { - let evs - try { ({ evs } = loadEvents(f)) } catch { continue } // non-dsh file: ignore - if (isClean(evs)) { ok += 1; continue } - bad.push(f) - if (!options.fix) continue - const { headerLine } = loadEvents(f) - const repaired = repairEvents(evs) - measure(repaired) // never write an unverified repair - copyFileSync(f, `${f}.bak`) - writeFileSync(f, encodeLog(headerLine, repaired)) - fixed.push(f) + let evs, header + try { ({ evs, header } = loadEvents(f)) } catch { skipped += 1; continue } // non-dsh file: ignore + // Pre-current-version artifact (v0 from early imports, v3 from the 0.9.x + // era): rewrite to the current format so the installed DSH can list and + // open it. On DSH 0.10.x a stored v3 log is INVISIBLE to persistence + // list() — the importer then tries create() on re-import and aborts the + // batch with "session … already exists", so healing here is required. + const cat = sessionFormatCatalog() + if (header.version !== cat.currentVersion) { + const res = migrateArtifactToCurrent(f, { write: options.fix === true }) + if (res.ok) { + if (options.fix === true) fixed.push(f) + else stale.push(f) + } else bad.push(f) + continue + } + // 已是最新(v3)格式:不再用 token meter 重写。导入/迁移出来的会话往往缺乏 + // DSH 的 token-usage 记录,TokenMeter 对其冷重放会误报("Cannot read + // properties of undefined (reading 'get')" / settle 字段缺失),这是已知局限 + // 而非格式损坏;用 meter 重写会破坏本来能正常打开的 v3 会话。故 v3 一律视为 + // 正常,仅当明确要求 meter 级修复(options.meterRepair)才处理。 + if (options.meterRepair === true) { + if (isClean(evs)) { ok += 1; continue } + bad.push(f) + if (!options.fix) continue + const { headerLine } = loadEvents(f) + const repaired = repairEvents(evs) + measure(repaired) // never write an unverified repair + copyFileSync(f, `${f}.bak`) + writeFileSync(f, encodeLog(headerLine, repaired)) + fixed.push(f) + continue + } + ok += 1 + continue } - return { total: files.length, ok, bad, fixed } + return { total: files.length, ok, bad, fixed, stale, skipped } } /** CLI entry: `dsh-codex-sync repair-sessions [--fix] [--root ]`. */ @@ -251,8 +481,9 @@ export function runRepairCli(args) { const fix = args.fix === true const root = typeof args.root === 'string' ? args.root : undefined const summary = repairSessionStore({ fix, root }) - console.log(`scan: ${summary.total} logs, ${summary.ok} clean, ${summary.bad.length} damaged`) + console.log(`scan: ${summary.total} logs, ${summary.ok} clean, ${summary.stale.length} stale, ${summary.bad.length} damaged, ${summary.skipped} skipped`) + for (const f of summary.stale) console.log(` STALE ${f}`) for (const f of summary.bad) console.log(` BAD ${f}`) - for (const f of summary.fixed) console.log(` FIXED → ${f} (.bak kept)`) - if (!fix && summary.bad.length > 0) console.log('\ndry run — rerun with --fix to repair') + for (const f of summary.fixed) console.log(` FIXED → ${f} (superseded log removed, .bak kept)`) + if (!fix && (summary.stale.length > 0 || summary.bad.length > 0)) console.log('\ndry run — rerun with --fix to repair') } diff --git a/lib/zstd-frame.mjs b/lib/zstd-frame.mjs new file mode 100644 index 0000000..786f3a6 --- /dev/null +++ b/lib/zstd-frame.mjs @@ -0,0 +1,15 @@ +/** Native Zstandard on Node 22.15+, or the existing zstd CLI on Node 20. */ +import * as zlib from 'node:zlib' +import { execFileSync } from 'node:child_process' + +export function compressChecksummedFrame(input) { + if (typeof zlib.zstdCompressSync === 'function') { + return zlib.zstdCompressSync(input, { + params: { [zlib.constants.ZSTD_c_checksumFlag]: 1 }, + }) + } + return execFileSync('zstd', ['--quiet', '--compress', '--stdout', '--check'], { + input, + maxBuffer: Math.max(1 << 20, input.length * 2), + }) +} diff --git a/package-lock.json b/package-lock.json index b74f7c0..297a7ed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,27 +1,32 @@ { "name": "dsh-codex-sync", - "version": "0.6.1", + "version": "1.6.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "dsh-codex-sync", - "version": "0.6.1", + "version": "1.6.1", "license": "MIT", "bin": { "dsh-codex-sync": "bin/dsh-codex-sync.js" }, "devDependencies": { "@deepseek-ai/cordis": "^4.0.1", + "@deepseek-ai/dsh-session-format-catalog": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v0-to-v1": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v1-to-v2": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v2-to-v3": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v3-to-v4": "0.1.7-rc.2", "react": "^18.3.1", "react-dom": "^18.3.1" }, "engines": { - "node": ">=22.19.0" + "node": ">=20" }, "peerDependencies": { "@deepseek-ai/cordis": "^4.0.1", - "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1" + "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1 || 0.2.0-rc.2" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-mcp-client": { @@ -30,21 +35,21 @@ } }, "node_modules/@deepseek-ai/cordis": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@deepseek-ai/cordis/-/cordis-4.0.1.tgz", - "integrity": "sha512-YBdskTU2Po1kru3GgcUWUbkTsPMA9LkSQDAY8rBkFJeajdgcQad3QPJZE26JyK99Xb6HaASvoXg2DSUTeN/0Nw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cordis/-/cordis-4.0.4.tgz", + "integrity": "sha512-obgyxqWAmFn3Re8kvsuUnyW+ihrz6eJCnJO4fh1cQzDtmPYz/zzVeUkH9R94I0OwSVOocK67Kgakm04j/oQXzg==", "dev": true, "license": "MIT", "dependencies": { - "@deepseek-ai/cosmokit": "^1.8.2", + "@deepseek-ai/cosmokit": "~1.8.5", "@standard-schema/spec": "^1.1.0" }, "bin": { "cordis": "bin.js" }, "peerDependencies": { - "@deepseek-ai/cordis-plugin-include": "^1.0.6", - "@deepseek-ai/cordis-plugin-loader": "^1.0.2" + "@deepseek-ai/cordis-plugin-include": "~1.0.9", + "@deepseek-ai/cordis-plugin-loader": "~1.0.5" }, "peerDependenciesMeta": { "@deepseek-ai/cordis-plugin-include": { @@ -56,12 +61,354 @@ } }, "node_modules/@deepseek-ai/cosmokit": { - "version": "1.8.2", - "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.2.tgz", - "integrity": "sha512-muBOKtSrUKU5m/xpq8ZXWL6hQ/jgd4PhU2PqH97bcxIiLEJfNwZOGQEx4t/aS/GgxRAR+ra9pMHPMtTHU4sqqA==", + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.5.tgz", + "integrity": "sha512-LXsrlem9z8dq4sLflj2yuCuYX7KqhdzF5hZly3eZyuTo8d6oDSOXuEgC5DbQWKW+lksm6zmOutQLsP/ma6wR6A==", "dev": true, "license": "MIT" }, + "node_modules/@deepseek-ai/dsh-agent": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-agent/-/dsh-agent-0.1.7-rc.2.tgz", + "integrity": "sha512-9U/zHZvZqRR5S2FD9fjjAuoMh+WfDan+bE/cLBLSLpqftjZ0FhIlEBK99yonUkNkGemyHiH/lL3jCKYw35ahJA==", + "dev": true, + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-invariants": "0.1.7-rc.2", + "@deepseek-ai/dsh-llm": "0.1.7-rc.2", + "@deepseek-ai/dsh-scope": "0.1.7-rc.2", + "@deepseek-ai/dsh-session": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-projection": "0.1.7-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.1.7-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.1.7-rc.2", + "@deepseek-ai/dsh-util-values": "0.1.7-rc.2", + "@deepseek-ai/dsh-workspace": "0.1.7-rc.2" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-workspace": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/dsh-attachment": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-attachment/-/dsh-attachment-0.1.7-rc.2.tgz", + "integrity": "sha512-g2SQ12Ki1l28T/H+fZKtSWDFF5Y1gavcKVBb2X4eOVX5uT5Jwumx+9Svelp1pHaknuAE1N2Yt9tMwj2quMkhDg==", + "dev": true, + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-brand": "0.1.7-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-brand": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-brand/-/dsh-brand-0.1.7-rc.2.tgz", + "integrity": "sha512-cvcvlNRuiFqZNNqyxdu7wcpiBjd9xa/0MpuhRvee43zBp9uED2p5JolZr5/2EKJf57gYx9k9bedb+Zbyiqnpkw==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-commands": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-commands/-/dsh-commands-0.1.7-rc.2.tgz", + "integrity": "sha512-wVAHwHNDLDNBKXJZU2rHnwc+e3mhi6EuazAfJmqtbzU/ldQVEoJ9f5eXqesBcdQbRIrWQlpjfjdlw3nCJfK2HQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-util-crypto": "0.1.7-rc.2", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-agent": "0.1.7-rc.2", + "@deepseek-ai/dsh-attachment": "0.1.7-rc.2", + "@deepseek-ai/dsh-brand": "0.1.7-rc.2", + "@deepseek-ai/dsh-invariants": "0.1.7-rc.2", + "@deepseek-ai/dsh-llm": "0.1.7-rc.2", + "@deepseek-ai/dsh-scope": "0.1.7-rc.2", + "@deepseek-ai/dsh-session": "0.1.7-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.1.7-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-compaction": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-compaction/-/dsh-compaction-0.1.7-rc.2.tgz", + "integrity": "sha512-NOrFYDM6EdvO+UBioNcpiZ+Klv5v2xvOxLXDWKtA0rjKKW8IvW7Rui2hBnOpchsWe5So5vwBvu4lNjTdl5/2CA==", + "dev": true, + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-brand": "0.1.7-rc.2", + "@deepseek-ai/dsh-commands": "0.1.7-rc.2", + "@deepseek-ai/dsh-invariants": "0.1.7-rc.2", + "@deepseek-ai/dsh-llm": "0.1.7-rc.2", + "@deepseek-ai/dsh-session": "0.1.7-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-compaction-image-offload": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-compaction-image-offload/-/dsh-compaction-image-offload-0.1.7-rc.2.tgz", + "integrity": "sha512-IraXZq6uR88RbJcxkK7vfDViIB4WCxm8Kf9s43VWoias9Tr//w0s8oHZWTfNuy8kVgpw4cBze6DeExZooMALrw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.1.7-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-agent": "0.1.7-rc.2", + "@deepseek-ai/dsh-compaction": "0.1.7-rc.2", + "@deepseek-ai/dsh-llm": "0.1.7-rc.2", + "@deepseek-ai/dsh-session": "0.1.7-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-invariants": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-invariants/-/dsh-invariants-0.1.7-rc.2.tgz", + "integrity": "sha512-GY2lY2TUUH2Qk1ZnrB3Q5+lXSh4webn1kbt5nQfhojVmNbist/f3dJC8JJa7XXOUNvqAgqRN9IZ4egbDZ9LLxQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.4" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-llm": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-llm/-/dsh-llm-0.1.7-rc.2.tgz", + "integrity": "sha512-hNT3ovFnbNDQ8g544bh2Q9ORX40aI6Y+jhjer1lETeHS4g0jTjqUUVfARCTA7uAFvHucSBg2rFgbisIktmJCxw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-brand": "0.1.7-rc.2", + "@deepseek-ai/dsh-timeout": "0.1.7-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.1.7-rc.2", + "@deepseek-ai/dsh-util-crypto": "0.1.7-rc.2", + "@deepseek-ai/dsh-util-values": "0.1.7-rc.2", + "@deepseek-ai/schemastery": "~3.18.4", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-scope": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-scope/-/dsh-scope-0.1.7-rc.2.tgz", + "integrity": "sha512-rk/OM5ej6/V8pCNczEqQ3BkKx3DuPeFGzNUsEZo8hF+tnkF/EhsxMWSXC/yP/uLKeNkSsVHzjFpaQR0qr0J3gQ==", + "dev": true, + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-invariants": "0.1.7-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-session": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session/-/dsh-session-0.1.7-rc.2.tgz", + "integrity": "sha512-0dXv1t4Zox/yHkZ4PfPNSBWJfIc72PDqOvjz43EMoHpbmoKTVpit2UpUI+yTtX01e4MVBbDMxBZ95oJW/Oydnw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.1.7-rc.2", + "@deepseek-ai/dsh-llm": "0.1.7-rc.2", + "@deepseek-ai/dsh-util-values": "0.1.7-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-scope": "0.1.7-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-session-format": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-format/-/dsh-session-format-0.1.7-rc.2.tgz", + "integrity": "sha512-ayk2VoX3r7m8U9rVc+F70qx76Eq3Mi3ToLySi29hDZPFLy8ujjSOO5LVCC1xmon8uukfcnScvElNPoP/mKTkBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.1.7-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-session-format-catalog": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-format-catalog/-/dsh-session-format-catalog-0.1.7-rc.2.tgz", + "integrity": "sha512-PMwm6M713ZWMqV0NVRFGeP0eYoBBCe0n4l5k8g1sRI+e2wD5xVoTEn8ZduG0vxnrVrGneJRDPQjZ4TiMi/fgDw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-compaction-image-offload": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v0-to-v1": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v1-to-v2": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v2-to-v3": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v3-to-v4": "0.1.7-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-session": "0.1.7-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-session-format-v0-to-v1": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-format-v0-to-v1/-/dsh-session-format-v0-to-v1-0.1.7-rc.2.tgz", + "integrity": "sha512-2JjUnl5+00N8/eda1s47VXP8wEl0HFqLRKk3MgEcRb6PEH3NH3Mvxb6jmkF6EeH0mMLLvzYHbpfDazOhECkXRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-session-format": "0.1.7-rc.2", + "@deepseek-ai/dsh-util-values": "0.1.7-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-session-format-v1-to-v2": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-format-v1-to-v2/-/dsh-session-format-v1-to-v2-0.1.7-rc.2.tgz", + "integrity": "sha512-a7Rsv7z2zeIyWpwRWkdtbi1T8r9zBGvbcoQVQEPpmpMFH9qu5hZmzYUGNFS1qRW5KW2cZoOU+qRxHwRoKI0dcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-llm": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v0-to-v1": "0.1.7-rc.2", + "@deepseek-ai/dsh-util-values": "0.1.7-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-session-format-v2-to-v3": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-format-v2-to-v3/-/dsh-session-format-v2-to-v3-0.1.7-rc.2.tgz", + "integrity": "sha512-che+x4X57f4MPWYWjj3UkcDs4qU0sQspUvy0Ie8w+iMFPkH0C7f/629l6ubZXRFrGF/k6djbyLR/NYH7nArZaA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-session-format": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v0-to-v1": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v1-to-v2": "0.1.7-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-session-format-v3-to-v4": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-format-v3-to-v4/-/dsh-session-format-v3-to-v4-0.1.7-rc.2.tgz", + "integrity": "sha512-PpGsFntVbc6HEnIlTRMluk55YPAFGmbz7SSyYMXDaz7N+jzWTa54AuMg9gUthHxPwZyj7KF2QtJAJnSQ2+GPGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-session-format": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v2-to-v3": "0.1.7-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-session-projection": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-projection/-/dsh-session-projection-0.1.7-rc.2.tgz", + "integrity": "sha512-s5T8oHBEh+GeOTJ+wehD4CGZkTiWgczZZA+NDbfbqUO0k5L+dk0kk3fN+/srAg77rhR7UeeDSR8ZNcpYx/VUdw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-session": "0.1.7-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-system-prompt": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-system-prompt/-/dsh-system-prompt-0.1.7-rc.2.tgz", + "integrity": "sha512-vxKcADh7XOuWJOfa0WeEOhvFiUbMOdoK4w6M7KVCI0S99c9ktxrgY4wKdmAxap+nQjwTEPme3QuOlY3Na+cz9w==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.4" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-invariants": "0.1.7-rc.2", + "@deepseek-ai/dsh-llm": "0.1.7-rc.2", + "@deepseek-ai/dsh-scope": "0.1.7-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-timeout": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-timeout/-/dsh-timeout-0.1.7-rc.2.tgz", + "integrity": "sha512-YunLoLZSF8Ld9eYwyvKoBnxgy3GZrIQpw98HfFS15ZfZlqcFiZcchFhYmStLtUbtX+gjhoeXc8Xz913YbVifNA==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-typert-protocol": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-typert-protocol/-/dsh-typert-protocol-0.1.7-rc.2.tgz", + "integrity": "sha512-oJm03zqMQlvt16Ejw7VWy3/gqlJGrBCZj3Z4KL8ydLJeeTToKIR49WVCxMbJTlH0F9QFljruLtHguA5B99AeUQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-brand": "0.1.7-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-util-crypto": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-crypto/-/dsh-util-crypto-0.1.7-rc.2.tgz", + "integrity": "sha512-BGc55/bSj/1LcDTQ5fpok4U24X9SFyN+TB23/hBlbe2TBUKVuwO8+X5FFKKje2MLO8PWYEDkXv/LrV6jRVKZEg==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-util-values": { + "version": "0.1.7-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-values/-/dsh-util-values-0.1.7-rc.2.tgz", + "integrity": "sha512-UX8nh5SbtZcPVVEvjd+9PCPcbybA6OpVzJGgFxYn59ao/7QQGyYbByS8KXr+THU5JtqmDDVb9xGUSJaF2IYmeQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/schemastery": { + "version": "3.18.4", + "resolved": "https://registry.npmjs.org/@deepseek-ai/schemastery/-/schemastery-3.18.4.tgz", + "integrity": "sha512-SSXO6tYuyrIqKVbmOnIq0s+riUywYzouFMcnBluHF9n4KMo2G8HvEzhCYj6pj2617/glOjbJuVInJ9hfONsjkg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.5", + "@standard-schema/spec": "^1.1.0" + } + }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", @@ -125,6 +472,16 @@ "dependencies": { "loose-envify": "^1.1.0" } + }, + "node_modules/zod": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } } } } diff --git a/package.json b/package.json index 0eccef4..1e77c1a 100644 --- a/package.json +++ b/package.json @@ -71,7 +71,7 @@ }, "peerDependencies": { "@deepseek-ai/cordis": "^4.0.1", - "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1" + "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1 || 0.2.0-rc.2" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-mcp-client": { @@ -80,6 +80,11 @@ }, "devDependencies": { "@deepseek-ai/cordis": "^4.0.1", + "@deepseek-ai/dsh-session-format-catalog": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v0-to-v1": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v1-to-v2": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v2-to-v3": "0.1.7-rc.2", + "@deepseek-ai/dsh-session-format-v3-to-v4": "0.1.7-rc.2", "react": "^18.3.1", "react-dom": "^18.3.1" } diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs index 0ef042f..9bac80a 100644 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -14,7 +14,9 @@ const suites = [ 'test/plugin-skill.test.mjs', 'test/export-codex.test.mjs', 'test/item-sync.test.mjs', + 'test/convert-order.test.mjs', 'test/session-repair.test.mjs', + 'test/zstd-frame.test.mjs', ] function findDshCheckout() { diff --git a/test/codex-reader.test.mjs b/test/codex-reader.test.mjs index c760fe3..dae3d38 100644 --- a/test/codex-reader.test.mjs +++ b/test/codex-reader.test.mjs @@ -59,7 +59,10 @@ test('convert: control-only user message opens no turn and never seeds the title // no turn/start before the first real user message const firstUser = events.find((e) => e.type === 'user/message') assert.ok(firstUser, 'a user/message exists') - assert.equal(events.indexOf(firstUser), 1, 'first event is turn/start of the REAL first user message') + // event order is turn/start → step/start → user/message (issue #2: the first + // surface event must follow a step/start so the format v2→v3 migration can + // acquire its system head). + assert.equal(events.indexOf(firstUser), 2, 'user/message follows turn/start and step/start') const text = firstUser.data.content.map((b) => b.text).join('') assert.equal(text, '帮我安装 deepseek harness 到本机\n') @@ -277,3 +280,35 @@ test('convert: consecutive assistant messages get one step each, closed at turn } } }) + + +test('function_call: preserves arguments and prefers them over legacy input', () => { + const args = '{"text":"standard function argument"}' + const file = nextFile('function-arguments') + write(file, rolloutOf([ + { type: 'response_item', timestamp: '2026-08-17T10:00:01Z', payload: { + type: 'function_call', call_id: 'function-1', name: 'fixture_echo', arguments: args, input: 'wrong legacy input', + } }, + { type: 'response_item', timestamp: '2026-08-17T10:00:02Z', payload: { + type: 'function_call_output', call_id: 'function-1', output: 'function result', + } }, + ])) + const { messages } = parseCodexSession(file) + const blocks = messages.flatMap(m => m.blocks) + assert.equal(blocks.find(b => b.type === 'tool-call').arguments, args) + assert.deepEqual(blocks.find(b => b.type === 'tool-result').content, [{ type: 'text', text: 'function result' }]) +}) + +test('tool inputs: function arguments objects and empty strings; custom calls keep input', () => { + const file = nextFile('tool-input-variants') + write(file, rolloutOf([ + ...[ + { type: 'function_call', call_id: 'object', name: 'echo', arguments: { text: 'object' } }, + { type: 'function_call', call_id: 'empty', name: 'echo', arguments: '', input: 'must not replace empty' }, + { type: 'function_call', call_id: 'legacy', name: 'echo', input: 'legacy input' }, + { type: 'custom_tool_call', call_id: 'custom', name: 'patch', input: 'custom input', arguments: 'wrong' }, + ].map(payload => ({ type: 'response_item', timestamp: '2026-08-17T10:00:01Z', payload })), + ])) + const calls = parseCodexSession(file).messages.flatMap(m => m.blocks).filter(b => b.type === 'tool-call') + assert.deepEqual(calls.map(b => b.arguments), ['{"text":"object"}', '', 'legacy input', 'custom input']) +}) diff --git a/test/convert-order.test.mjs b/test/convert-order.test.mjs new file mode 100644 index 0000000..36a591b --- /dev/null +++ b/test/convert-order.test.mjs @@ -0,0 +1,104 @@ +/** + * convert.mjs event-ordering regression tests (issue #2). + * + * Regresses the "format v2 surface before first step cannot acquire a system + * head without changing chronology" failure: DSH's persistence restore runs + * the imported log through the format v0→v1→v2→v3 migration chain, and that + * chain only acquires its "system head" at the first `step/start`. In v2→v3, + * any surface event (user/message / assistant/message / tool/result / + * system/message) appearing BEFORE the first step/start is rejected, so + * sessions imported with the old converter (turn/start → user/message with no + * step region) fail to open on DSH 0.9.0+. + * + * Our converter must therefore emit `step/start` before the first surface + * event of each turn (matching the native agent-loop), so every imported log + * survives the migration chain and becomes a resumable v3 session. + */ + +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { buildDshEvents } from '../lib/convert.mjs' + +const SURFACE = new Set(['user/message', 'assistant/message', 'tool/result', 'system/message']) + +/** Assert: every surface event is inside an open step region. */ +function assertSurfaceInsideSteps(events) { + let open = null + const violations = [] + for (const e of events) { + if (e.type === 'step/start') { + open = e.data + } else if (e.type === 'step/end') { + if (open === null) violations.push(`stray step/end ${e.data?.step}`) + open = null + } else if (SURFACE.has(e.type)) { + if (open === null) violations.push(`${e.type} at ${e.seq} outside a step region`) + } + } + assert.deepEqual(violations, [], `step ordering broken: ${violations.join('; ')}`) +} + +/** Assert helper: surface events never precede the first step/start. */ +function assertFirstStepBeforeFirstSurface(events) { + const firstStep = events.findIndex((e) => e.type === 'step/start') + const firstSurface = events.findIndex((e) => SURFACE.has(e.type)) + assert.ok(firstStep >= 0, 'a step/start must exist') + assert.ok( + firstSurface === -1 || firstStep < firstSurface, + `first surface (${firstSurface}) must not precede first step/start (${firstStep})`, + ) +} + +const mkUser = (time, text) => ({ role: 'user', time, provider: 'codex', model: 'unknown', blocks: [{ type: 'text', text }] }) +const mkAsst = (time, blocks) => ({ role: 'assistant', time, provider: 'codex', model: 'unknown', blocks }) + +test('user-only turn opens a step region before its user/message', () => { + const events = buildDshEvents([mkUser(1000, 'q')], { toolEvents: true }) + assertFirstStepBeforeFirstSurface(events) + assertSurfaceInsideSteps(events) + // turn/start → step/start → user/message + const kinds = events.map((e) => e.type) + const iStep = kinds.indexOf('step/start') + const iUser = kinds.indexOf('user/message') + assert.ok(iStep === 1, `step/start is the second event (got index ${iStep})`) + assert.ok(iUser === 2, `user/message follows step/start (got index ${iUser})`) +}) + +test('user + assistant + tool turn keeps surface inside one step then opens new step', () => { + const events = buildDshEvents([ + mkUser(1000, 'q'), + mkAsst(2000, [{ type: 'tool-call', id: 'c1', name: 'exec', arguments: '{}' }]), + mkAsst(2000, [{ type: 'text', text: 'answer' }]), + ], { toolEvents: true }) + assertFirstStepBeforeFirstSurface(events) + assertSurfaceInsideSteps(events) + // user & first assistant share step 1; second assistant gets its own step + const asstSteps = events + .filter((e) => e.type === 'assistant/message') + .map((e) => e.data.step) + assert.deepEqual(asstSteps, [1, 2], 'first assistant reuses step 1, next advances') +}) + +test('assistant-first turn still opens a step before its first surface', () => { + const events = buildDshEvents([mkAsst(1000, [{ type: 'text', text: 'direct answer' }])], { toolEvents: true }) + assertFirstStepBeforeFirstSurface(events) + assertSurfaceInsideSteps(events) +}) + +test('multiple consecutive user turns each open their own leading step', () => { + const events = buildDshEvents([ + mkUser(1000, 'first'), + mkUser(2000, 'second'), + mkUser(3000, 'third'), + ], { toolEvents: true }) + assertFirstStepBeforeFirstSurface(events) + assertSurfaceInsideSteps(events) + // each user/message preceded by a step/start for that turn + const kinds = events.map((e) => e.type) + const starts = kinds + .map((t, i) => (t === 'user/message' ? i : -1)) + .filter((i) => i >= 0) + for (const i of starts) { + assert.equal(kinds[i - 1], 'step/start', `user/message at ${i} preceded by step/start`) + } +}) diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index dafd690..1ac66c8 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -1,7 +1,9 @@ /** * import-service: codex sub-agent threads are filtered by default and * re-included with importSubagents: true. Hermetic — stub persistence + ctx, - * throwaway codex home. No dsh install needed. + * throwaway codex home. The real @deepseek-ai/dsh-session-format-* migration + * packages are devDependencies, so the migration path is exercised without a + * DSH install. */ import { test } from 'node:test' import assert from 'node:assert/strict' @@ -32,6 +34,47 @@ function makeSession(root, name, metaExtra = {}) { return `codex-sess-${name}` } +/** Write a rollout with an arbitrary message sequence: [{ role, text, time }]. */ +function writeRollout(root, name, entries) { + const dir = join(root, 'sessions', '2026', '08', '17') + mkdirSync(dir, { recursive: true }) + const meta = { + type: 'session_meta', + payload: { id: `sess-${name}`, cwd: '/tmp/proj', timestamp: '2026-08-17T10:00:00.000Z', source: 'cli' }, + } + const lines = [meta, ...entries.map((e) => rawEvent({ + type: 'message', + id: `m-${name}-${e.role}-${e.text}`, + role: e.role, + content: [{ type: e.role === 'user' ? 'input_text' : 'output_text', text: e.text }], + }))] + writeFileSync(join(dir, `rollout-${name}.jsonl`), lines.map((e) => JSON.stringify(e)).join('\n') + '\n') + return `codex-sess-${name}` +} + +/** Append raw response_item lines to an existing rollout file. */ +function appendMessages(root, name, entries) { + const file = join(root, 'sessions', '2026', '08', '17', `rollout-${name}.jsonl`) + appendFileSync(file, entries.map((e) => JSON.stringify(rawEvent({ + type: 'message', + id: `m-${name}-${e.role}-${e.text}`, + role: e.role, + content: [{ type: e.role === 'user' ? 'input_text' : 'output_text', text: e.text }], + }))).join('\n') + '\n') +} + +/** + * Mirror real DSH session-persistence: `create` runs `encodeCurrentHeader`, + * which rejects anything below the current format ("encodeCurrent requires + * Session format v3" on 0.9.x, "…v4" on 0.10.x). A silent v0 fallback in the + * importer therefore becomes a hard test failure here instead of passing. + */ +function assertCurrentFormatHeader(header) { + if ((header?.version ?? 0) < 3) { + throw new Error(`encodeCurrent requires Session format v3 (got v${header?.version ?? 'undefined'})`) + } +} + function stubPersistence() { const store = new Map() const metas = new Map() @@ -40,7 +83,7 @@ function stubPersistence() { metas, persistence: { async list() { return [...store.keys()].map((id) => ({ id })) }, - async create(meta) { metas.set(meta.id, meta); store.set(meta.id, []) }, + async create(meta) { assertCurrentFormatHeader(meta); metas.set(meta.id, meta); store.set(meta.id, []) }, async append(id, events) { store.set(id, [...(store.get(id) ?? []), ...events]) }, async inspect(id) { return { meta: metas.get(id) ?? { id }, events: store.get(id) ?? [] } }, }, @@ -144,3 +187,319 @@ test('import-codex: re-import appends new Codex turns onto an existing session', const users = store.get(main).filter((e) => e.type === 'user/message').map((e) => e.data.content.map((b) => b.text).join('')) assert.ok(users.some((t) => t.includes('user-main-2'))) }) + +test('import-codex: paginated rollout segments of one thread merge into a single session', async () => { + // Codex continues a thread in NEW rollout files named + // `rollout--_.jsonl` carrying the same session id and only + // the delta turns. Each file used to be its own candidate → the second + // segment called create() again and aborted the batch with + // "session codex-… already exists". + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = makeSession(root, 'main') + const dir = join(root, 'sessions', '2026', '08', '17') + const segment = [ + { type: 'session_meta', payload: { id: 'sess-main', cwd: '/tmp/proj', timestamp: '2026-08-17T12:00:00.000Z', source: 'cli' } }, + rawEvent({ type: 'message', id: 'm-main-seg', role: 'user', content: [{ type: 'input_text', text: 'user-main-seg' }] }), + ] + writeFileSync(join(dir, 'rollout-main_fork1.jsonl'), segment.map((e) => JSON.stringify(e)).join('\n') + '\n') + + const { persistence, ctx, store } = stubPersistence() + const lines = await importCodex(ctx, persistence, { ids: [main] }, root) + assert.match(lines.join('\n'), /imported 1/, 'both segments must produce exactly ONE create') + const users = store.get(main).filter((e) => e.type === 'user/message').map((e) => e.data.content.map((b) => b.text).join('')) + assert.ok(users.some((t) => t.includes('user-main-1')), 'base segment messages imported') + assert.ok(users.some((t) => t.includes('user-main-seg')), 'continuation segment messages imported in the same session') +}) + +test('import-codex: writes the session in the installed current format, not v0 (issue #2)', async () => { + // DSH persistence rejects older formats on write ("encodeCurrent requires + // Session format v4" on DSH 0.10.x), so the importer must migrate the + // imported v0 artifact to the installed current format via session-migrate. + // The REAL migration packages are devDependencies, so this path is REQUIRED + // (no early return): if the chain cannot resolve, migrateToCurrent throws + // and importCodex now fails loudly instead of writing v0. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = makeSession(root, 'main') + const { persistence, ctx, store, metas } = stubPersistence() + const { migrateToCurrent } = await import('../lib/session-migrate.mjs') + const probe = migrateToCurrent({ version: 0, id: 'probe', createdAt: 1, cwd: '/tmp' }, []) + assert.ok( + probe.header.version >= 3, + `migration chain must resolve to the current format (got v${probe.header.version}); run npm install so the @deepseek-ai/dsh-session-format-* devDependencies are present`, + ) + await importCodex(ctx, persistence, {}, root) + const meta = metas.get(main) + assert.ok(meta, 'session created') + assert.equal(meta.version, probe.header.version, 'imported session header must be the migrated current format (not v0)') + assert.equal(meta.isSeeded, false, 'migrated header carries isSeeded=false') + const events = store.get(main) ?? [] + const asst = events.find((e) => e.type === 'assistant/message') + assert.ok(asst !== undefined && Array.isArray(asst.data.stream), 'current-format assistant/message carries a stream') + assert.ok(events.some((e) => e.type === 'system/message'), 'session carries a promoted system/message head') +}) + +test('import-codex: written session passes the real DSH current-format write gate', async () => { + // The exact gate that rejected v3 writes on DSH 0.10.0 with + // "encodeCurrent requires Session format v4": the written header and every + // written event must encode as the installed current format, and the + // artifact must restore through the real current-format restorer (i.e. the + // persisted session can be reopened by DSH). + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = makeSession(root, 'main') + const { persistence, ctx, store, metas } = stubPersistence() + await importCodex(ctx, persistence, {}, root) + const meta = metas.get(main) + const events = store.get(main) ?? [] + const { sessionFormatCatalog } = await import('@deepseek-ai/dsh-session-format-catalog') + assert.equal(meta.version, sessionFormatCatalog.currentVersion, 'written header version must equal the installed current format') + sessionFormatCatalog.encodeCurrentHeader(meta, 0) // must not throw + for (const event of events) sessionFormatCatalog.encodeCurrentEvent(event) // must not throw + // Restore through the real restorer (pinned to v4 while the devDeps track + // the 0.1.7-rc.2 packages of DSH 0.10.0). + const { restoreReleasedV4Artifact } = await import('@deepseek-ai/dsh-session-format-v3-to-v4') + const { KNOWN_SESSION_EVENT_TYPES } = await import('@deepseek-ai/dsh-session') + restoreReleasedV4Artifact({ header: meta, events, inheritedEventCount: 0 }, KNOWN_SESSION_EVENT_TYPES) +}) + +test('import-codex: writes through the DSH 0.9.0 handle-based persistence API (no persistence.append)', async () => { + // DSH 0.9.0's sessionPersistence exposes list/create/open/delete and returns + // per-session HANDLES — it has NO append(id,…) and NO inspect(id). The + // plugin's facade must map its familiar calls onto open(id,'read'/'write') + + // handle.append/read/flush/close. Regression: importer used to call + // `persistence.append(id, events)` directly, which 0.9.0 rejects as + // "persistence.append is not a function" (issue #2 follow-up). + const store = new Map() // id -> { header, events } + const ops = [] + const persistence = { + async list() { return [...store.keys()].map((id) => ({ header: store.get(id).header, revision: 'r', sizeBytes: 0 })) }, + async create(header) { + if ((header?.version ?? 0) < 3) throw new Error(`encodeCurrent requires Session format v3 (got v${header?.version ?? 'undefined'})`) + store.set(header.id, { header, events: [] }) + return { + async append(events) { ops.push('handle.append'); store.get(header.id).events.push(...events) }, + async flush() { ops.push('handle.flush') }, + async read() { return { eventState: 'current', events: store.get(header.id).events } }, + async close() { ops.push('handle.close') }, + header, + } + }, + async open(id, access) { + ops.push(`open(${access})`) + const s = store.get(id) + if (s === undefined) throw new Error(`not found: ${id}`) + return { + async append(events) { ops.push('handle.append'); s.events.push(...events) }, + async flush() { ops.push('handle.flush') }, + async read() { return { eventState: 'current', events: s.events } }, + async close() { ops.push('handle.close') }, + header: s.header, + } + }, + async delete(id) { return store.delete(id) }, + } + + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = makeSession(root, 'main') + await importCodex({ get: () => undefined }, persistence, {}, root) + + assert.ok(store.has(main), 'session imported via create+handle.append') + assert.ok(!ops.some((o) => String(o).startsWith('persistence.')), 'must not call a persistence.* legacy method') + assert.ok(ops.includes('handle.append'), 'write goes through handle.append') + // Re-import with no new turns → update path inspects via open('read') and skips. + ops.length = 0 + await importCodex({ get: () => undefined }, persistence, {}, root) + assert.ok(ops.includes('open(read)'), 'existing session is read via open(id,"read") not inspect()') +}) + +test('import-codex: same-turn assistant continuation lands in a self-consistent turn (combined restore)', async () => { + // Old importer damage (review issue 1): re-importing [q,a,b] over a stored + // [q,a] produced a suffix starting with turn/start(2) followed by step/end(1) + // — old.events + suffix failed the real v4 restorer. The continuation is now + // repacked into ONE fresh turn and the COMBINED artifact must restore. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = makeSession(root, 'main') + const { persistence, ctx, store, metas } = stubPersistence() + await importCodex(ctx, persistence, { ids: [main] }, root) + const { restoreReleasedV4Artifact } = await import('@deepseek-ai/dsh-session-format-v3-to-v4') + const { KNOWN_SESSION_EVENT_TYPES } = await import('@deepseek-ai/dsh-session') + const validate = () => restoreReleasedV4Artifact( + { header: metas.get(main), events: store.get(main), inheritedEventCount: 0 }, + KNOWN_SESSION_EVENT_TYPES, + ) + validate() // first import restores cleanly + const file = join(root, 'sessions', '2026', '08', '17', 'rollout-main.jsonl') + appendFileSync(file, [ + { type: 'response_item', timestamp: '2026-08-17T11:00:00.000Z', payload: { type: 'message', id: 'm-main-b', role: 'assistant', content: [{ type: 'output_text', text: 'assistant-main-cont' }] } }, + ].map((e) => JSON.stringify(e)).join('\n') + '\n') + + const lines = await importCodex(ctx, persistence, { ids: [main] }, root) + assert.match(lines.join('\n'), /updated 1/) + validate() // combined old + appended suffix must STILL restore cleanly + const users = store.get(main).filter((e) => e.type === 'user/message') + assert.equal(users.length, 1, 'no duplicated user message') +}) + +test('import-codex: a reply arriving after a user-only import is stored (pending-question continuation)', async () => { + // Review round 4: the first import while the reply was still pending stored + // [user q] only. Re-importing after the assistant answered reported + // "updated 0, skipped 1" and the answer was silently LOST: the equal-user + // branch of diffImportEvents incremented its assistant counter before + // comparing, so the oldAssistants === 0 match could never fire. The stored + // answer, the combined-artifact restore AND idempotence are all asserted. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = writeRollout(root, 'pend', [ + { role: 'user', text: 'user-pend-q', time: '2026-08-17T10:00:01.000Z' }, + ]) + const { persistence, ctx, store, metas } = stubPersistence() + await importCodex(ctx, persistence, { ids: [main] }, root) + assert.equal((store.get(main) ?? []).filter((e) => e.type === 'assistant/message').length, 0, 'precondition: imported while the reply was pending') + + const { restoreReleasedV4Artifact } = await import('@deepseek-ai/dsh-session-format-v3-to-v4') + const { KNOWN_SESSION_EVENT_TYPES } = await import('@deepseek-ai/dsh-session') + const validate = () => restoreReleasedV4Artifact( + { header: metas.get(main), events: store.get(main), inheritedEventCount: 0 }, + KNOWN_SESSION_EVENT_TYPES, + ) + validate() + + appendMessages(root, 'pend', [ + { role: 'assistant', text: 'assistant-pend-answer', time: '2026-08-17T11:00:00.000Z' }, + ]) + const lines = await importCodex(ctx, persistence, { ids: [main] }, root) + assert.match(lines.join('\n'), /updated 1/, 'the pending reply must be stored, not skipped') + const events = store.get(main) + const answers = events.filter((e) => e.type === 'assistant/message') + assert.equal(answers.length, 1, 'exactly the one new assistant message is stored') + assert.ok(JSON.stringify(answers[0].data.message.content).includes('assistant-pend-answer'), 'the stored answer carries the new text') + assert.equal(events.filter((e) => e.type === 'user/message').length, 1, 'no duplicated user message') + validate() // combined old + appended answer must restore through the real restorer + + const again = await importCodex(ctx, persistence, { ids: [main] }, root) + assert.match(again.join('\n'), /updated 0, skipped 1/, 'an unchanged re-import stays idempotent') + assert.equal(store.get(main).length, events.length, 'idempotent re-import writes nothing') +}) + +test('import-codex: a pending reply AND a following new turn are both stored', async () => { + // The new content may START inside old's last turn (the reply to a still + // pending question) and CONTINUE with complete new turns. Both parts must + // land: the pending-turn slice repacked as one fresh turn, the new turns + // renumbered after it — the combined artifact must restore. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = writeRollout(root, 'mix', [ + { role: 'user', text: 'user-mix-q1', time: '2026-08-17T10:00:01.000Z' }, + ]) + const { persistence, ctx, store, metas } = stubPersistence() + await importCodex(ctx, persistence, { ids: [main] }, root) + + appendMessages(root, 'mix', [ + { role: 'assistant', text: 'assistant-mix-a1', time: '2026-08-17T11:00:00.000Z' }, + { role: 'user', text: 'user-mix-q2', time: '2026-08-17T11:00:01.000Z' }, + { role: 'assistant', text: 'assistant-mix-a2', time: '2026-08-17T11:00:02.000Z' }, + ]) + const lines = await importCodex(ctx, persistence, { ids: [main] }, root) + assert.match(lines.join('\n'), /updated 1/) + const events = store.get(main) + const textOf = (e) => JSON.stringify(e.data?.message?.content ?? e.data?.content ?? []) + const assistants = events.filter((e) => e.type === 'assistant/message').map(textOf) + assert.equal(assistants.length, 2, 'both assistant messages stored') + assert.ok(assistants.some((t) => t.includes('assistant-mix-a1')) && assistants.some((t) => t.includes('assistant-mix-a2'))) + const users = events.filter((e) => e.type === 'user/message').map(textOf) + assert.equal(users.length, 2, 'no duplicated user message') + const { restoreReleasedV4Artifact } = await import('@deepseek-ai/dsh-session-format-v3-to-v4') + const { KNOWN_SESSION_EVENT_TYPES } = await import('@deepseek-ai/dsh-session') + restoreReleasedV4Artifact({ header: metas.get(main), events, inheritedEventCount: 0 }, KNOWN_SESSION_EVENT_TYPES) +}) + +test('import-codex: a reply to a turn without an assistant is stored even after earlier complete turns', async () => { + // Same counting defect, multi-turn shape: stored [q1, a1, q2] (turn 2 still + // pending) — the old code matched neither "the oldAssistants-th assistant" + // (it sits in turn 1) nor the seen===match-1 guard, so a2 was dropped. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = writeRollout(root, 'late', [ + { role: 'user', text: 'user-late-q1', time: '2026-08-17T10:00:01.000Z' }, + { role: 'assistant', text: 'assistant-late-a1', time: '2026-08-17T10:00:02.000Z' }, + { role: 'user', text: 'user-late-q2', time: '2026-08-17T10:00:03.000Z' }, + ]) + const { persistence, ctx, store, metas } = stubPersistence() + await importCodex(ctx, persistence, { ids: [main] }, root) + + appendMessages(root, 'late', [ + { role: 'assistant', text: 'assistant-late-a2', time: '2026-08-17T11:00:00.000Z' }, + ]) + const lines = await importCodex(ctx, persistence, { ids: [main] }, root) + assert.match(lines.join('\n'), /updated 1/, 'the pending reply must be stored, not skipped') + const events = store.get(main) + const assistants = events.filter((e) => e.type === 'assistant/message') + assert.equal(assistants.length, 2) + assert.ok(JSON.stringify(assistants[1].data.message.content).includes('assistant-late-a2')) + const { restoreReleasedV4Artifact } = await import('@deepseek-ai/dsh-session-format-v3-to-v4') + const { KNOWN_SESSION_EVENT_TYPES } = await import('@deepseek-ai/dsh-session') + restoreReleasedV4Artifact({ header: metas.get(main), events, inheritedEventCount: 0 }, KNOWN_SESSION_EVENT_TYPES) + const again = await importCodex(ctx, persistence, { ids: [main] }, root) + assert.match(again.join('\n'), /updated 0, skipped 1/, 'idempotent on the next unchanged import') +}) + +test('import-codex: new-turn re-import combined artifact restores cleanly', async () => { + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = makeSession(root, 'main') + const { persistence, ctx, store, metas } = stubPersistence() + await importCodex(ctx, persistence, { ids: [main] }, root) + const file = join(root, 'sessions', '2026', '08', '17', 'rollout-main.jsonl') + appendFileSync(file, [ + { type: 'response_item', timestamp: '2026-08-17T12:00:00.000Z', payload: { type: 'message', id: 'm-main-2', role: 'user', content: [{ type: 'input_text', text: 'user-main-2' }] } }, + { type: 'response_item', timestamp: '2026-08-17T12:00:01.000Z', payload: { type: 'message', id: 'm-main-3', role: 'assistant', content: [{ type: 'output_text', text: 'assistant-main-2' }] } }, + ].map((e) => JSON.stringify(e)).join('\n') + '\n') + + const lines = await importCodex(ctx, persistence, { ids: [main] }, root) + assert.match(lines.join('\n'), /updated 1/) + // COMBINED old + appended new turn must pass the real current-format restorer. + const { restoreReleasedV4Artifact } = await import('@deepseek-ai/dsh-session-format-v3-to-v4') + const { KNOWN_SESSION_EVENT_TYPES } = await import('@deepseek-ai/dsh-session') + restoreReleasedV4Artifact( + { header: metas.get(main), events: store.get(main), inheritedEventCount: 0 }, + KNOWN_SESSION_EVENT_TYPES, + ) +}) + +test('import-codex: a failed read skips the session instead of appending to it', async () => { + // Review issue 3: inspect() used to swallow read errors as empty history, + // which would append the whole source onto an existing session. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + const main = makeSession(root, 'main') + const appended = [] + const persistence = { + async list() { return [{ id: main }] }, // session already exists + async inspect() { throw new Error('simulated disk read failure') }, + async append(id, events) { appended.push([id, events]) }, + async create() { throw new Error('create must not be reached') }, + } + const lines = await importCodex({ get: () => undefined }, persistence, {}, root) + assert.equal(appended.length, 0, 'no append after a failed read') + assert.match(lines.join('\n'), /skipped 1/) +}) + +test('import-codex: a failed flush surfaces instead of reporting success', async () => { + // Review issue 4: createAndAppend used to swallow flush/close failures and + // resolve successfully on a disk-full. Cleanup is still attempted, then the + // durability error propagates. + const root = mkdtempSync(join(tmpdir(), 'cx-sync-import-')) + makeSession(root, 'main') + const ops = [] + const persistence = { + async list() { return [] }, + async create(header) { + return { + async append() { ops.push('append') }, + async flush() { ops.push('flush'); throw new Error('disk full') }, + async close() { ops.push('close') }, + header, + } + }, + async open() { throw new Error('not opened') }, + } + await assert.rejects( + () => importCodex({ get: () => undefined }, persistence, {}, root), + /disk full/, + ) + assert.deepEqual(ops, ['append', 'flush', 'close'], 'cleanup attempted before surfacing the error') +}) diff --git a/test/item-sync.test.mjs b/test/item-sync.test.mjs index e2a3a2c..6f450b1 100644 --- a/test/item-sync.test.mjs +++ b/test/item-sync.test.mjs @@ -80,6 +80,7 @@ test('skills: provider list() hides user-disabled entries', async () => { }) test('mirror: sync() gates servers by per-item preference and refresh() re-applies', async () => { + let mirror const home = freshHome() const codexHome = mkdtempSync(join(tmpdir(), 'cx-sync-mcphome-')) try { @@ -94,7 +95,7 @@ command = "echo" // Distinct fixture dir: node --test runs test FILES concurrently, and // host.smoke.mjs owns the canonical FAKE path — sharing it races the // two files' install/remove cycles. - const fakeDir = join(PROJECT, 'node_modules', '.cx-sync-item-fixture', '@deepseek-ai', 'dsh-mcp-client') + const fakeDir = join(PROJECT, 'node_modules', '.cx-sync-item-fixture', 'node_modules', '@deepseek-ai', 'dsh-mcp-client') mkdirSync(fakeDir, { recursive: true }) writeFileSync(join(fakeDir, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-mcp-client', version: '0.0.0-fake', type: 'module', main: 'index.js' })) writeFileSync(join(fakeDir, 'index.js'), ` @@ -113,7 +114,7 @@ FakeMcpClient.instances = [] logger: { info() {}, warn() {} }, plugin: async () => { mounted.push(1); return () => {} }, } - const mirror = startMcpMirror(ctx, codexHome, {}) + mirror = startMcpMirror(ctx, codexHome, {}) await mirror.refresh() let reasons = Object.fromEntries(mirror.getStatus().servers.map((s) => [s.name, s.reason])) assert.equal(reasons.alpha, 'mounted') @@ -131,8 +132,8 @@ FakeMcpClient.instances = [] assert.equal(reasons.beta, 'mounted') assert.equal(effectiveItemSync('mcp', 'beta'), true) - mirror.dispose() } finally { + mirror?.dispose() rmSync(home, { recursive: true, force: true }) rmSync(codexHome, { recursive: true, force: true }) rmSync(join(PROJECT, 'node_modules', '.cx-sync-item-fixture'), { recursive: true, force: true }) diff --git a/test/session-repair.test.mjs b/test/session-repair.test.mjs index 0f2299c..a0f59a9 100644 --- a/test/session-repair.test.mjs +++ b/test/session-repair.test.mjs @@ -63,3 +63,75 @@ test('repairEvents merges stale-cursor seams and remaps citations', () => { assert.ok(Array.isArray(tailMsg.sourceEventSeqs), 'tail citation kept') for (const s of tailMsg.sourceEventSeqs) assert.equal(fixed[s].type, 'assistant/chunk') }) + +test('repairEvents opens a step before an orphan user/message (v0→v3 migration invariant)', () => { + // 旧版导入器生成 turn/start → user/message(无前置 step/start)。DSH 的 + // format v0→v3 迁移要求任何 surface 事件出现在首个 step/start 之后,否则抛 + // "format v2 surface before first step cannot acquire a system head ..."。 + // 修复后 user/message 之前必须补一个 step/start。 + const evs = [ + { type: 'turn/start', seq: 0, time: 1000, data: { turn: 1 } }, + { type: 'user/message', seq: 1, time: 1000, data: { role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'q' }], id: 'u1' }, surfaceOp: 'append' }, + { type: 'assistant/message', seq: 2, time: 1100, data: { turn: 1, step: 1, message: { role: 'assistant', content: [{ type: 'text', text: 'a' }], id: 'a1' } }, surfaceOp: 'append' }, + { type: 'turn/end', seq: 3, time: 1200, data: { turn: 1, reason: { kind: 'completed' } } }, + ] + const fixed = repairEvents(evs) + fixed.forEach((e, i) => assert.equal(e.seq, i, `seq dense at ${i}`)) + // 每个 surface(user/message / assistant/message)都必须落在 open step 内 + let open = null + let firstUserSeen = false + for (const e of fixed) { + if (e.type === 'step/start') open = e.data + else if (e.type === 'step/end' || e.type === 'turn/end') open = null + if (e.type === 'user/message') { firstUserSeen = true; assert.ok(open, 'user/message is inside a step region') } + if (e.type === 'assistant/message') assert.ok(open, 'assistant/message is inside a step region') + } + assert.ok(firstUserSeen, 'user/message present') + // 首个 step/start 必须出现在第一个 user/message 之前(满足 v2→v3 迁移不变式) + const firstStep = fixed.findIndex((e) => e.type === 'step/start') + const firstUser = fixed.findIndex((e) => e.type === 'user/message') + assert.ok(firstStep !== -1 && firstStep < firstUser, 'step/start precedes first user/message') +}) + +test('listSessionFiles prefers the versioned current-format log over the legacy name', async () => { + // DSH 0.10.x writes session.v4.jsonl.zstd; older builds wrote + // session.jsonl.zstd. A dir holding both must yield exactly the versioned + // one (the legacy file is a superseded pre-repair state), and legacy-only + // dirs keep working. + const { listSessionFiles } = await import('../lib/session-repair.mjs') + const { mkdtempSync, mkdirSync, writeFileSync } = await import('node:fs') + const { tmpdir } = await import('node:os') + const { join } = await import('node:path') + const root = mkdtempSync(join(tmpdir(), 'cx-sync-repair-')) + const both = join(root, 'ws-a', 'sess-both') + mkdirSync(both, { recursive: true }) + writeFileSync(join(both, 'session.jsonl.zstd'), 'x') + writeFileSync(join(both, 'session.v4.jsonl.zstd'), 'x') + const legacyOnly = join(root, 'ws-a', 'sess-legacy') + mkdirSync(legacyOnly, { recursive: true }) + writeFileSync(join(legacyOnly, 'session.jsonl.zstd'), 'x') + const files = listSessionFiles(root) + assert.equal(files.length, 2) + assert.ok(files.includes(join(both, 'session.v4.jsonl.zstd')), 'versioned log preferred when both exist') + assert.ok(!files.some((f) => f === join(both, 'session.jsonl.zstd')), 'superseded legacy log not listed') + assert.ok(files.includes(join(legacyOnly, 'session.jsonl.zstd')), 'legacy-only dir still scanned') +}) + +test('migrateToCurrent starts the chain at the stored version and normalizeTitleMessageSeqs clears user-title citations', async () => { + const { normalizeTitleMessageSeqs } = await import('../lib/session-repair.mjs') + const { migrateToCurrent } = await import('../lib/session-migrate.mjs') + // Old importer damage: user-kind title citing messageSeqs (legal v3, illegal v4). + const evs = [ + { type: 'user/message', seq: 0, time: 1, data: { role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'q' }], id: 'u1' } }, + { type: 'session/title', seq: 1, time: 2, data: { title: 't', messageSeqs: [0], source: { kind: 'user' } } }, + ] + const normalized = normalizeTitleMessageSeqs(evs) + assert.equal(normalized[1].data.messageSeqs.length, 0, 'user-kind title citations cleared') + assert.equal(normalized[0], evs[0], 'non-title events untouched') + // A v3 stored artifact must migrate through v3→v4 ONLY (no v0 re-run). + const probe = migrateToCurrent({ version: 3, id: 'probe', createdAt: 1, cwd: '/tmp', isSeeded: false, delegationDepth: 0 }, []) + assert.equal(probe.header.version, 4, 'v3 artifact migrates straight to the current format') + // v0 input keeps working end-to-end through the whole chain. + const fromV0 = migrateToCurrent({ version: 0, id: 'probe', createdAt: 1, cwd: '/tmp' }, []) + assert.equal(fromV0.header.version, 4, 'v0 artifact migrates through the full chain') +}) diff --git a/test/zstd-frame.test.mjs b/test/zstd-frame.test.mjs new file mode 100644 index 0000000..3a1ccf0 --- /dev/null +++ b/test/zstd-frame.test.mjs @@ -0,0 +1,16 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { compressChecksummedFrame } from '../lib/zstd-frame.mjs' + +test('checksummed Zstandard frames round-trip independently and when concatenated', () => { + const first = Buffer.from('{"type":"session","version":4}\n') + const second = Buffer.from('{"type":"turn/start","seq":0}\n') + const frames = [compressChecksummedFrame(first), compressChecksummedFrame(second)] + const decode = input => execFileSync('zstd', ['--quiet', '--decompress', '--stdout'], { input }) + assert.deepEqual(decode(frames[0]), first) + assert.deepEqual(decode(Buffer.concat(frames)), Buffer.concat([first, second])) + const corrupt = Buffer.from(frames[1]) + corrupt[corrupt.length - 1] ^= 1 + assert.throws(() => decode(corrupt), 'a corrupted checksum must fail') +})