From 19ec6467d8092bc0f04416d635b290fc2611ce6f Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 21 Sep 2026 12:46:04 +0800 Subject: [PATCH 01/16] fix: open step/start before first surface event so imported sessions open Imported Codex sessions were emitted as turn/start -> user/message with no step region, but DSH's format v0->v1->v2->v3 migration only acquires its "system head" at the first step/start. Any surface event before that was rejected with "format v2 surface before first step cannot acquire a system head without changing chronology", so sessions imported before DSH 0.9.0 failed to open (issue #2). buildDshEvents now opens a step/start before the first surface event of each turn (user/message when the turn starts with a user message, and for the coordinate-less surface events in general), matching the native agent-loop ordering. The first assistant reuses that leading step; subsequent assistants advance to their own step, preserving the existing step-pairing invariants the token meter enforces. Validated by running the fixed converter output through the real @deepseek-ai/dsh-session-format v0->v1->v2->v3 migration chain (passes) and added regression tests (test/convert-order.test.mjs) asserting every surface event is preceded by a step/start. Refs #2 --- lib/convert.mjs | 30 +++++++++-- scripts/run-tests.mjs | 1 + test/codex-reader.test.mjs | 5 +- test/convert-order.test.mjs | 104 ++++++++++++++++++++++++++++++++++++ 4 files changed, 135 insertions(+), 5 deletions(-) create mode 100644 test/convert-order.test.mjs diff --git a/lib/convert.mjs b/lib/convert.mjs index 33b81da..aba16fa 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, diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs index 0ef042f..335c920 100644 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -14,6 +14,7 @@ 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', ] diff --git a/test/codex-reader.test.mjs b/test/codex-reader.test.mjs index c760fe3..6067af1 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') 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`) + } +}) From a316c310b95fc55b647790c08fb0d87ac7363588 Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 21 Sep 2026 15:44:34 +0800 Subject: [PATCH 02/16] fix: write imported sessions as format v3 so DSH 0.9.0 import works The previous step-ordering fix addressed the read-side migration failure, but DSH 0.9.0's session-persistence backend now WRITES only the current v3 format: encodeCurrentHeader throws "encodeCurrent requires Session format v3" for a v0 header, so the importer's `persistence.create({ version: 0, ... })` aborts and `/import-codex` fails with that error. The importer now migrates the imported v0 header + events through the real @deepseek-ai/dsh-session-format v0->v1->v2->v3 chain (the same one the harness runs on read) before create/append, so the stored artifact is genuine v3: - new lib/session-migrate.mjs: migrateToCurrent(header, events) resolves the migration packages from the DSH app install (or DSH_CHECKOUT / profile node_modules), chains migrateHeader for the header and runs each stage over the events, producing a v3 header (isSeeded=false) and v3 events (promoted system/message head + embedded assistant/message stream that v3 restore requires). - lib/import-service.js: builds the header, migrates it + events to v3, then create(currentHeader) / append(id, currentEvents). Falls back to v0 when the migration runtime is unavailable (e.g. bare unit tests). - test/import-service.test.mjs: regression asserting an imported session is written as v3 (header version 3, isSeeded=false, assistant stream, and a promoted system/message) when the migration resolves. Validated: full v0->v1->v2->v3 migration chain passes on the fixed converter output; the migrated v3 output carries the required stream/system fields; the full 45-test suite is green. Refs #2 --- lib/import-service.js | 42 +++++++++++++------ lib/session-migrate.mjs | 81 ++++++++++++++++++++++++++++++++++++ test/import-service.test.mjs | 30 +++++++++++++ 3 files changed, 140 insertions(+), 13 deletions(-) create mode 100644 lib/session-migrate.mjs diff --git a/lib/import-service.js b/lib/import-service.js index 7261d26..a41a8b1 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -24,6 +24,7 @@ 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 { attachSessionsToWorkspaces, listImportedSessions } from './attach-workspaces.mjs' const DEFAULT_MAX_SESSION_BYTES = 256 * 1024 * 1024 @@ -219,6 +220,29 @@ 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', + } + let currentHeader = importHeader + let currentEvents = events + try { + ;({ header: currentHeader, events: currentEvents } = migrateToCurrent(importHeader, events)) + } catch { + // Migration resolution unavailable (e.g. tests without the DSH runtime): + // fall back to the v0 shape; real DSH runs will use the migrated v3 form. + currentHeader = importHeader + currentEvents = events + } if (existing.has(candidate.id)) { let oldEvents = [] try { @@ -227,7 +251,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 +268,13 @@ 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.create(currentHeader) + await persistence.append(candidate.id, 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}`) diff --git a/lib/session-migrate.mjs b/lib/session-migrate.mjs new file mode 100644 index 0000000..d272193 --- /dev/null +++ b/lib/session-migrate.mjs @@ -0,0 +1,81 @@ +/** + * Session-format migration helper for imported (v0) sessions. + * + * DSH 0.9.0's `session-persistence` backend now *writes* only the current + * (v3) format: `encodeCurrentHeader` throws + * "encodeCurrent requires Session format v3" + * for a v0 header, so the importer can no longer hand `persistence.create` + * a v0 header + v0 events. This module runs the imported artifact through the + * same `@deepseek-ai/dsh-session-format` v0→v1→v2→v3 chain the harness uses on + * read, producing a v3 header and v3 events (with the promoted system/message + * head and the embedded assistant/message stream that v3 restore requires). + * + * The migration packages are resolved from the DSH app install (or DSH_CHECKOUT + * / the profile node_modules), matching the resolver used by session-repair. + */ + +import { createRequire } from 'node:module' +import { homedir } from 'node:os' +import { dirname, join } from 'node:path' + +/** + * Resolve the three adjacent migration packages from a resolvable base. + * The running DSH app bundles them under its `Contents/Resources/app/node_modules`; + * derive that from the executable path when possible, else fall back to the + * well-known install path / DSH_CHECKOUT / the profile node_modules. + */ +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 + env/profile fallbacks. + candidates.push('/Applications/DSH Desktop.app/Contents/Resources/app/node_modules') + candidates.push(process.env.DSH_CHECKOUT || '') + candidates.push(join(homedir(), '.dsh', 'profiles', 'node_modules')) + const bases = candidates.filter(Boolean) + for (const base of bases) { + const anchor = `${base}/@deepseek-ai/dsh/lib/index.js` + let r + try { r = createRequire(anchor) } catch { continue } + try { + const v01 = r('@deepseek-ai/dsh-session-format-v0-to-v1') + const v12 = r('@deepseek-ai/dsh-session-format-v1-to-v2') + const v23 = r('@deepseek-ai/dsh-session-format-v2-to-v3') + if (v01 && v12 && v23) return { v01, v12, v23 } + } catch { /* try next base */ } + } + throw new Error('cannot resolve @deepseek-ai/dsh-session-format-* migration packages') +} + +/** + * Migrate a released v0 session header + event list to the current (v3) format. + * The source input is not mutated; a fresh header/event list is returned. + * @param {object} header - v0 header ({version:0, id, createdAt, cwd, …}). + * @param {Array} events - canonical v0 event rows (each with `seq`). + * @returns {{ header: object, events: Array }} the v3 header and v3 events. + */ +export function migrateToCurrent(header, events) { + const { v01, v12, v23 } = loadChain() + const stages = [ + { mig: v01.sessionFormatV0ToV1, from: 0 }, + { mig: v12.sessionFormatV1ToV2, from: 1 }, + { mig: v23.sessionFormatV2ToV3, from: 2 }, + ] + // Derive a migrated v3 header by chaining `migrateHeader`. + let h = { ...header, version: 0, isSeeded: false } + for (const { mig } of stages) 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 stages) { + const sourceHeader = { ...header, version: from, isSeeded: false } + 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/test/import-service.test.mjs b/test/import-service.test.mjs index dafd690..87203a5 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -144,3 +144,33 @@ 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: writes the session as format v3, not v0 (issue #2)', async () => { + // DSH 0.9.0 persistence rejects a v0 header on write ("encodeCurrent requires + // Session format v3"), so the importer must migrate the imported v0 artifact + // to the current v3 format via session-migrate. When the DSH runtime is + // reachable (DSH_CHECKOUT or the app install) the migration resolves; only + // then can we assert the v3 shape on the written session. + 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) + assert.ok(meta, 'session created') + let migrationAvailable = false + try { + const { migrateToCurrent } = await import('../lib/session-migrate.mjs') + migrateToCurrent({ version: 0, id: 'probe', createdAt: 1, cwd: '/tmp' }, []) + migrationAvailable = true + } catch { + migrationAvailable = false + } + if (!migrationAvailable) return // no DSH runtime; importer fell back to v0 + // Migration resolved → the importer MUST have written v3. + assert.equal(meta.version, 3, 'imported session header must be v3 (not v0)') + assert.equal(meta.isSeeded, false, 'v3 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), 'v3 assistant/message carries a stream') + assert.ok(events.some((e) => e.type === 'system/message'), 'v3 session carries a promoted system/message head') +}) From 4f4c757fd4ab3da907a6585320507ea3764c6c94 Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 21 Sep 2026 16:30:16 +0800 Subject: [PATCH 03/16] fix: normalize delegationDepth on the migrate source header The v0 logical header requires `delegationDepth` (HEADER_REQUIRED in dsh-session-format-v0-to-v1), but the importer's minimal header omits it, so the v0->v1 migrateHeader throws 'format v1 header lacks required member delegationDepth' and migrateToCurrent catches it and falls back to v0, re-triggering 'encodeCurrent requires Session format v3' (issue #2). Normalize the source header (default delegationDepth 0) for both the chained migrateHeader and the per-stage createStage source header. --- lib/session-migrate.mjs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/session-migrate.mjs b/lib/session-migrate.mjs index d272193..8949820 100644 --- a/lib/session-migrate.mjs +++ b/lib/session-migrate.mjs @@ -65,13 +65,22 @@ export function migrateToCurrent(header, events) { { mig: v23.sessionFormatV2ToV3, from: 2 }, ] // Derive a migrated v3 header by chaining `migrateHeader`. - let h = { ...header, version: 0, isSeeded: false } + // The v0 logical header requires `delegationDepth`, which the importer's + // minimal header does not carry; normalize it (default 0) so the v0->v1 + // `migrateHeader` does not throw "lacks required member delegationDepth". + const normalized = { + ...header, + version: 0, + isSeeded: false, + delegationDepth: header.delegationDepth ?? 0, + } + let h = { ...normalized } for (const { mig } of stages) 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 stages) { - const sourceHeader = { ...header, version: from, isSeeded: false } + 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) }) From c1b3eed6e8fc7bbf4607295688fce899d41542de Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 21 Sep 2026 22:45:38 +0800 Subject: [PATCH 04/16] fix: heal pre-v3 imported sessions so DSH 0.9.x can open them DSH 0.9.0+ session-persistence writes only v3 and migrates pre-v3 artifacts on read via the v0->v1->v2->v3 chain, which acquires its 'system head' at the FIRST step/start. Any surface event (user/message / assistant/message / tool/result) before it makes the migration throw 'format v2 surface before first step cannot acquire a system head ...', leaving imported sessions unreadable (symptom: 'encodeCurrent requires Session format v3', 'session already exists', 'V2' display, and 'Failed to load history ... surface before first step'). Old-imported v0 logs emitted turn/start -> user/message with no leading step region, exactly this case. - repairEvents: STEP_TYPES now includes user/message and opens a step/start before any orphan surface, so the v0->v3 migration invariant holds (track currentTurn from turn/start; user/message carries no data.turn/step). - loadEvents: dsh-session no longer exports decodeStorageRecord in DSH 0.9.1; decode logical rows directly (plugin-written artifacts are logical {type,seq,time,data,surfaceOp}). - migrateArtifactToCurrent (new): repair + migrate v0->v3 and rewrite the artifact in current format, validating every row encodes via the real session-format catalog before writing (keeps .bak). - repairSessionStore: auto-migrate pre-v3 artifacts, and default root to /Users/kenleo/Library/Application Support/dsh-desktop/harness/sessions (was ~/.dsh/sessions which never exists for DSH Desktop). --- lib/session-repair.mjs | 123 ++++++++++++++++++++++++++++++++--- test/session-repair.test.mjs | 29 +++++++++ 2 files changed, 142 insertions(+), 10 deletions(-) diff --git a/lib/session-repair.mjs b/lib/session-repair.mjs index d30d3e0..4ba1c7d 100644 --- a/lib/session-repair.mjs +++ b/lib/session-repair.mjs @@ -29,6 +29,8 @@ import { homedir } from 'node:os' import { zstdCompressSync, constants as zstdConstants } from 'node:zlib' import { createRequire } from 'node:module' +import { migrateToCurrent } from './session-migrate.mjs' + const require = createRequire(import.meta.url) /** @@ -65,14 +67,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. */ @@ -130,15 +147,25 @@ 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 for (const e of evs) { - if (STEP_TYPES.has(e.type) && e.data && typeof e.data.turn === 'number' && typeof e.data.step === 'number') { + if (e.type === 'turn/start' && e.data && typeof e.data.turn === 'number') currentTurn = e.data.turn + if (STEP_TYPES.has(e.type)) { + // user/message 不携带 data.turn/step,回退到当前 turn 与默认 step 1。 + const turn = (e.data && typeof e.data.turn === 'number') ? e.data.turn : currentTurn + const step = (e.data && typeof e.data.step === 'number') ? e.data.step : 1 const open = openStepOf(fixed) - if (!open || open.data.turn !== e.data.turn || open.data.step !== e.data.step) { + if (!open || open.data.turn !== turn || open.data.step !== 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 } }) + fixed.push({ type: 'step/start', time: e.time, data: { turn, step } }) } } if (e.type === 'turn/start' || e.type === 'turn/end') { @@ -221,18 +248,94 @@ function listSessionFiles(root) { 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 +} + +/** + * Rewrite one stored artifact to the CURRENT (v3) 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}` } } + 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(evs) + let migrated + try { + migrated = migrateToCurrent(header, repaired) + } catch (e) { return { ok: false, reason: `migrate: ${e?.message}`, from: header.version } } + + // Validate the migrated v3 artifact encodes end-to-end before touching disk. + try { + cat.encodeCurrentHeader({ ...migrated.header, delegationDepth: migrated.header.delegationDepth ?? 0 }, 0) + for (const e of migrated.events) cat.encodeCurrentEvent(e) + } catch (e) { return { ok: false, reason: `encode: ${e?.message}`, from: header.version } } + + if (!writeOut) return { ok: true, from: header.version, to: cat.currentVersion, dry: true } + + // Rebuild the artifact exactly like the JSONL backend: one header frame, one events frame. + const headerLineV3 = JSON.stringify(cat.encodeCurrentHeader({ ...migrated.header, delegationDepth: migrated.header.delegationDepth ?? 0 }, 0)) + '\n' + const bodyV3 = migrated.events.map((e) => JSON.stringify(cat.encodeCurrentEvent(e))).join('\n') + '\n' + const frameOpts = { params: { [zstdConstants.ZSTD_c_checksumFlag]: 1 } } + const bytes = Buffer.concat([ + zstdCompressSync(Buffer.from(headerLineV3), frameOpts), + zstdCompressSync(Buffer.from(bodyV3), frameOpts), + ]) + copyFileSync(file, `${file}.bak`) // always keep a backup + writeFileSync(file, bytes) + 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 for (const f of files) { - let evs - try { ({ evs } = loadEvents(f)) } catch { continue } // non-dsh file: ignore + let evs, header + try { ({ evs, header } = loadEvents(f)) } catch { continue } // non-dsh file: ignore + // Pre-v3 (typically v0) artifact: rewrite to current format so DSH 0.9.x can + // open it; the on-read v0→v3 migration throws when a surface event precedes + // the first step/start (the "encodeCurrent requires Session format v3" + // symptom), so we heal it here instead of relying on DSH's migration. + 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 bad.push(f) + continue + } if (isClean(evs)) { ok += 1; continue } bad.push(f) if (!options.fix) continue diff --git a/test/session-repair.test.mjs b/test/session-repair.test.mjs index 0f2299c..55507ff 100644 --- a/test/session-repair.test.mjs +++ b/test/session-repair.test.mjs @@ -63,3 +63,32 @@ 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') +}) From fe84f349eff2f00f4fe50aa8bf16b9a90d04514c Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 21 Sep 2026 22:59:56 +0800 Subject: [PATCH 05/16] fix: repair-sessions --fix must not rewrite working v3 sessions The token meter (isClean/measure) cannot read token-usage for imported content and throws on cold replay ('Cannot read properties of undefined (reading get)' / invalid settlement fields), so it gave a false 'bad' signal for already-v3 sessions. Running --fix would then try to rewrite them based on that false signal and risk breaking sessions that open fine. - measure(): Session.create now uses SESSION_FORMAT_VERSION and isSeeded/delegationDepth (DSH 0.9.1 rejects version:0 headers). - repairSessionStore(): already-v3 artifacts are counted as ok and left untouched; meter-based step-pairing repair only runs when options.meterRepair is explicitly set (--fix now purely does the needed v0->v3 migration). --- lib/session-repair.mjs | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/lib/session-repair.mjs b/lib/session-repair.mjs index 4ba1c7d..c100c75 100644 --- a/lib/session-repair.mjs +++ b/lib/session-repair.mjs @@ -97,8 +97,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 @@ -336,15 +341,25 @@ export function repairSessionStore(options = {}) { else bad.push(f) continue } - 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) + // 已是最新(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 } } From 9d6a83840e286fc749b928b0524101cabe0332a1 Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 21 Sep 2026 23:08:53 +0800 Subject: [PATCH 06/16] feat: adapt import/export to DSH 0.9.0 handle-based persistence API 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} snapshots, and there is no append(id,...)/inspect(id) on the service object. - persistence-facade.mjs (new): normalizePersistence detects the legacy vs 0.9.0 shape and returns a facade exposing the plugin's familiar calls (list/inspect/append/createAndAppend) mapped onto the handle API; legacy services are proxied with createAndAppend added. - import-service.js / attach-workspaces.mjs / export-codex.js: normalize the persistence object at each entry point and write new sessions via createAndAppend (create+append through one handle). --- lib/attach-workspaces.mjs | 3 + lib/export-codex.js | 3 + lib/import-service.js | 6 +- lib/persistence-facade.mjs | 130 +++++++++++++++++++++++++++++++++++ test/import-service.test.mjs | 49 +++++++++++++ 5 files changed, 189 insertions(+), 2 deletions(-) create mode 100644 lib/persistence-facade.mjs 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/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 a41a8b1..84d9b02 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -25,6 +25,7 @@ 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 @@ -142,6 +143,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)) @@ -271,8 +273,7 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo lines.push(` [would-import] ${candidate.id} ${candidate.cwd ?? '(no cwd)'} ${messages.length} messages -> ${currentEvents.length} events`) continue } - await persistence.create(currentHeader) - await persistence.append(candidate.id, currentEvents) + await persistence.createAndAppend(currentHeader, currentEvents) imported += 1 lines.push(` [imported] ${candidate.id} ${candidate.cwd ?? '(no cwd)'} ${messages.length} messages -> ${currentEvents.length} events`) } @@ -299,6 +300,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..eb2b15b --- /dev/null +++ b/lib/persistence-facade.mjs @@ -0,0 +1,130 @@ +/** + * 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()) + async inspect(id) { + let handle + try { + handle = await persistence.open(id, 'read') + } catch { + return { meta: { id }, events: [] } + } + try { + const read = await handle.read(0) + const events = read && Array.isArray(read.events) ? read.events : [] + return { meta: { ...(handle.header ?? {}), id }, events } + } catch { + return { meta: { id }, events: [] } + } finally { + try { await handle.close() } catch { /* 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') + try { + await handle.append(events) + } finally { + try { await handle.close() } catch { /* best-effort */ } + } + }, + + // 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. + async createAndAppend(header, events) { + const handle = await persistence.create(header, { inheritedEventCount: 0 }) + try { + if (Array.isArray(events) && events.length > 0) await handle.append(events) + } finally { + try { await handle.flush() } catch { /* best-effort */ } + try { await handle.close() } catch { /* best-effort */ } + } + }, + } +} + +/** + * 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/test/import-service.test.mjs b/test/import-service.test.mjs index 87203a5..cba4d49 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -174,3 +174,52 @@ test('import-codex: writes the session as format v3, not v0 (issue #2)', async ( assert.ok(asst !== undefined && Array.isArray(asst.data.stream), 'v3 assistant/message carries a stream') assert.ok(events.some((e) => e.type === 'system/message'), 'v3 session carries a promoted system/message head') }) + +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) { + 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()') +}) From cdac3b8b8ea4ad3aad331f0c23b2e6a51da00083 Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 5 Oct 2026 12:37:37 +0800 Subject: [PATCH 07/16] fix: write imported sessions in the installed current format (DSH 0.10.0 v4) - session-migrate discovers the dsh-session-format-vN-to-v{N+1} chain dynamically and migrates to the highest stage the resolved base ships (v3 on 0.9.x, v4 on 0.10.x); V3-to-V4 uses the createSessionFormatV3ToV4([]) child-evidence factory (imported sessions are roots). The running DSH app wins the base tie-break so package versions never mix; the plugin's own node_modules is the dev/test fallback (real packages now devDependencies @ 0.1.7-rc.2). - import-codex no longer falls back to a v0 write: migration failures fail loudly with the session id and root cause (review item 1). - buildDshEvents: user-kind titles must carry EMPTY messageSeqs (v4 assertReleasedV4Relationships); fallback titles cite the first user message. Caught by the new reopen validation (review item 2). - tests: stub persistence rejects pre-v3 writes like real DSH; the current-format write path is REQUIRED (no early return); new write-gate test encodes the header+events through the real catalog and restores the artifact via restoreReleasedV4Artifact. Full suite 48/48. --- lib/convert.mjs | 12 +- lib/import-service.js | 21 +- lib/session-migrate.mjs | 117 +++++++---- package-lock.json | 381 +++++++++++++++++++++++++++++++++-- package.json | 5 + test/import-service.test.mjs | 79 ++++++-- 6 files changed, 530 insertions(+), 85 deletions(-) diff --git a/lib/convert.mjs b/lib/convert.mjs index aba16fa..b00dead 100644 --- a/lib/convert.mjs +++ b/lib/convert.mjs @@ -193,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/import-service.js b/lib/import-service.js index 84d9b02..0a91a5a 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -235,16 +235,17 @@ export async function importCodex(ctx, persistence, options = {}, codexHome = jo ? options.agentPreset : 'cordis', } - let currentHeader = importHeader - let currentEvents = events - try { - ;({ header: currentHeader, events: currentEvents } = migrateToCurrent(importHeader, events)) - } catch { - // Migration resolution unavailable (e.g. tests without the DSH runtime): - // fall back to the v0 shape; real DSH runs will use the migrated v3 form. - currentHeader = importHeader - currentEvents = events - } + // 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 { diff --git a/lib/session-migrate.mjs b/lib/session-migrate.mjs index 8949820..6d530c6 100644 --- a/lib/session-migrate.mjs +++ b/lib/session-migrate.mjs @@ -1,28 +1,74 @@ /** * Session-format migration helper for imported (v0) sessions. * - * DSH 0.9.0's `session-persistence` backend now *writes* only the current - * (v3) format: `encodeCurrentHeader` throws - * "encodeCurrent requires Session format v3" - * for a v0 header, so the importer can no longer hand `persistence.create` - * a v0 header + v0 events. This module runs the imported artifact through the - * same `@deepseek-ai/dsh-session-format` v0→v1→v2→v3 chain the harness uses on - * read, producing a v3 header and v3 events (with the promoted system/message - * head and the embedded assistant/message stream that v3 restore requires). + * 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 migration packages are resolved from the DSH app install (or DSH_CHECKOUT - * / the profile node_modules), matching the resolver used by session-repair. + * 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 three adjacent migration packages from a resolvable base. - * The running DSH app bundles them under its `Contents/Resources/app/node_modules`; - * derive that from the executable path when possible, else fall back to the - * well-known install path / DSH_CHECKOUT / the profile node_modules. + * 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 = [] @@ -31,40 +77,39 @@ function loadChain() { if (execDir) { candidates.push(join(execDir, 'Resources', 'app', 'node_modules')) } - // 2. Standard macOS install + env/profile fallbacks. + // 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')) - const bases = candidates.filter(Boolean) - for (const base of bases) { - const anchor = `${base}/@deepseek-ai/dsh/lib/index.js` + let best = [] + for (const base of candidates.filter(Boolean)) { let r - try { r = createRequire(anchor) } catch { continue } - try { - const v01 = r('@deepseek-ai/dsh-session-format-v0-to-v1') - const v12 = r('@deepseek-ai/dsh-session-format-v1-to-v2') - const v23 = r('@deepseek-ai/dsh-session-format-v2-to-v3') - if (v01 && v12 && v23) return { v01, v12, v23 } - } catch { /* try next base */ } + 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') } - throw new Error('cannot resolve @deepseek-ai/dsh-session-format-* migration packages') + return best } /** - * Migrate a released v0 session header + event list to the current (v3) format. - * The source input is not mutated; a fresh header/event list is returned. + * Migrate a released v0 session header + event list to the installed CURRENT + * format. The source input is not mutated; a fresh header/event list is + * returned. * @param {object} header - v0 header ({version:0, id, createdAt, cwd, …}). * @param {Array} events - canonical v0 event rows (each with `seq`). - * @returns {{ header: object, events: Array }} the v3 header and v3 events. + * @returns {{ header: object, events: Array }} the current-format header and events. */ export function migrateToCurrent(header, events) { - const { v01, v12, v23 } = loadChain() - const stages = [ - { mig: v01.sessionFormatV0ToV1, from: 0 }, - { mig: v12.sessionFormatV1ToV2, from: 1 }, - { mig: v23.sessionFormatV2ToV3, from: 2 }, - ] - // Derive a migrated v3 header by chaining `migrateHeader`. + const stages = loadChain() + // Derive the migrated header by chaining `migrateHeader`. // The v0 logical header requires `delegationDepth`, which the importer's // minimal header does not carry; normalize it (default 0) so the v0->v1 // `migrateHeader` does not throw "lacks required member delegationDepth". diff --git a/package-lock.json b/package-lock.json index b74f7c0..0b3f92c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,23 +1,28 @@ { "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", @@ -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..f1a99d2 100644 --- a/package.json +++ b/package.json @@ -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/test/import-service.test.mjs b/test/import-service.test.mjs index cba4d49..759c185 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,18 @@ function makeSession(root, name, metaExtra = {}) { return `codex-sess-${name}` } +/** + * 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 +54,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) ?? [] } }, }, @@ -145,34 +159,54 @@ test('import-codex: re-import appends new Codex turns onto an existing session', assert.ok(users.some((t) => t.includes('user-main-2'))) }) -test('import-codex: writes the session as format v3, not v0 (issue #2)', async () => { - // DSH 0.9.0 persistence rejects a v0 header on write ("encodeCurrent requires - // Session format v3"), so the importer must migrate the imported v0 artifact - // to the current v3 format via session-migrate. When the DSH runtime is - // reachable (DSH_CHECKOUT or the app install) the migration resolves; only - // then can we assert the v3 shape on the written 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') - let migrationAvailable = false - try { - const { migrateToCurrent } = await import('../lib/session-migrate.mjs') - migrateToCurrent({ version: 0, id: 'probe', createdAt: 1, cwd: '/tmp' }, []) - migrationAvailable = true - } catch { - migrationAvailable = false - } - if (!migrationAvailable) return // no DSH runtime; importer fell back to v0 - // Migration resolved → the importer MUST have written v3. - assert.equal(meta.version, 3, 'imported session header must be v3 (not v0)') - assert.equal(meta.isSeeded, false, 'v3 header carries isSeeded=false') + 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), 'v3 assistant/message carries a stream') - assert.ok(events.some((e) => e.type === 'system/message'), 'v3 session carries a promoted system/message head') + 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 () => { @@ -187,6 +221,7 @@ test('import-codex: writes through the DSH 0.9.0 handle-based persistence API (n 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) }, From 70e430e0cb25cb8cc1985dd625e7eb0e968ad72f Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:58:45 +0800 Subject: [PATCH 08/16] fix: heal stale-format store logs and merge paginated rollout segments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - repair-sessions now scans session.v.jsonl.zstd (DSH 0.10.x naming) alongside the legacy session.jsonl.zstd, prefers the versioned log when both exist, writes migrated artifacts under the versioned name (an old-named rewrite stayed invisible to the new persistence), and reports stale/migratable logs in dry runs instead of counting them nowhere. dshPackage resolution gains the macOS app bundle base. - import-codex merges paginated continuation rollout segments (rollout--_.jsonl, same session id, delta-only) into ONE candidate per id: the second segment used to call create() again and abort the whole batch with 'session … already exists'. - tests: segment merge + listSessionFiles preference; 50/50. --- lib/import-service.js | 17 +++++++++- lib/session-repair.mjs | 60 ++++++++++++++++++++++++------------ test/import-service.test.mjs | 23 ++++++++++++++ test/session-repair.test.mjs | 24 +++++++++++++++ 4 files changed, 104 insertions(+), 20 deletions(-) diff --git a/lib/import-service.js b/lib/import-service.js index 0a91a5a..696a69b 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -191,7 +191,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)) diff --git a/lib/session-repair.mjs b/lib/session-repair.mjs index c100c75..bf397f7 100644 --- a/lib/session-repair.mjs +++ b/lib/session-repair.mjs @@ -23,8 +23,8 @@ * 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 { createRequire } from 'node:module' @@ -46,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 { @@ -238,7 +241,8 @@ function encodeLog(headerLine, evs) { ]) } -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)) { @@ -246,7 +250,16 @@ 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) } } @@ -310,8 +323,13 @@ export function migrateArtifactToCurrent(file, options = {}) { zstdCompressSync(Buffer.from(headerLineV3), frameOpts), zstdCompressSync(Buffer.from(bodyV3), frameOpts), ]) - copyFileSync(file, `${file}.bak`) // always keep a backup - writeFileSync(file, bytes) + 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 } } @@ -326,19 +344,22 @@ export function repairSessionStore(options = {}) { // ~/.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, header - try { ({ evs, header } = loadEvents(f)) } catch { continue } // non-dsh file: ignore - // Pre-v3 (typically v0) artifact: rewrite to current format so DSH 0.9.x can - // open it; the on-read v0→v3 migration throws when a surface event precedes - // the first step/start (the "encodeCurrent requires Session format v3" - // symptom), so we heal it here instead of relying on DSH's migration. + 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 bad.push(f) + if (res.ok) { + if (options.fix === true) fixed.push(f) + else stale.push(f) + } else bad.push(f) continue } // 已是最新(v3)格式:不再用 token meter 重写。导入/迁移出来的会话往往缺乏 @@ -361,7 +382,7 @@ export function repairSessionStore(options = {}) { 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 ]`. */ @@ -369,8 +390,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/test/import-service.test.mjs b/test/import-service.test.mjs index 759c185..2f23a6a 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -159,6 +159,29 @@ test('import-codex: re-import appends new Codex turns onto an existing session', 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 diff --git a/test/session-repair.test.mjs b/test/session-repair.test.mjs index 55507ff..c0291ff 100644 --- a/test/session-repair.test.mjs +++ b/test/session-repair.test.mjs @@ -92,3 +92,27 @@ test('repairEvents opens a step before an orphan user/message (v0→v3 migration 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') +}) From c29b88f249827c6f62d1d3eb88f7dd324b6d3ffe Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:02:25 +0800 Subject: [PATCH 09/16] fix: migrate stored artifacts from their actual version; normalize user-title citations - migrateToCurrent now starts the chain at header.version (v3 store artifacts go straight to v4) instead of force-resetting to v0, which failed stored-log repair with 'format v0 contains unknown historical event type system/message'. - repair pre-step clears messageSeqs on user-kind session/title events (legal under v3, rejected by the v4 relationship rule) so migrated artifacts restore cleanly. - 51/51. --- lib/session-migrate.mjs | 29 ++++++++++++++++------------- lib/session-repair.mjs | 23 +++++++++++++++++++++-- test/session-repair.test.mjs | 19 +++++++++++++++++++ 3 files changed, 56 insertions(+), 15 deletions(-) diff --git a/lib/session-migrate.mjs b/lib/session-migrate.mjs index 6d530c6..3218624 100644 --- a/lib/session-migrate.mjs +++ b/lib/session-migrate.mjs @@ -100,31 +100,34 @@ function loadChain() { } /** - * Migrate a released v0 session header + event list to the installed CURRENT - * format. The source input is not mutated; a fresh header/event list is - * returned. - * @param {object} header - v0 header ({version:0, id, createdAt, cwd, …}). - * @param {Array} events - canonical v0 event rows (each with `seq`). + * 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() - // Derive the migrated header by chaining `migrateHeader`. - // The v0 logical header requires `delegationDepth`, which the importer's - // minimal header does not carry; normalize it (default 0) so the v0->v1 - // `migrateHeader` does not throw "lacks required member delegationDepth". + // 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: 0, - isSeeded: false, + version: fromVersion, + isSeeded: header.isSeeded ?? false, delegationDepth: header.delegationDepth ?? 0, } let h = { ...normalized } - for (const { mig } of stages) h = mig.migrateHeader(h) + 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 stages) { + for (const { mig, from } of applicable) { const sourceHeader = { ...normalized, version: from } const stage = mig.createStage({ sourceHeader, sourceInheritedEventCount: 0 }) const out = [] diff --git a/lib/session-repair.mjs b/lib/session-repair.mjs index bf397f7..6e8595f 100644 --- a/lib/session-repair.mjs +++ b/lib/session-repair.mjs @@ -274,7 +274,26 @@ function sessionFormatCatalog() { } /** - * Rewrite one stored artifact to the CURRENT (v3) format in place. + * 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 @@ -301,7 +320,7 @@ export function migrateArtifactToCurrent(file, options = {}) { // 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(evs) + const repaired = repairEvents(normalizeTitleMessageSeqs(evs)) let migrated try { migrated = migrateToCurrent(header, repaired) diff --git a/test/session-repair.test.mjs b/test/session-repair.test.mjs index c0291ff..a0f59a9 100644 --- a/test/session-repair.test.mjs +++ b/test/session-repair.test.mjs @@ -116,3 +116,22 @@ test('listSessionFiles prefers the versioned current-format log over the legacy 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') +}) From b71c86be8796f7b8489bbdb94c2515f10017cac0 Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:09:43 +0800 Subject: [PATCH 10/16] fix: continue per-turn step numbering when inserting step markers in repair repairEvents used to force inserted step/start markers to step 1; on logs that already carry their own step numbering the duplicate step failed the v4 lifecycle rule ('step/start does not match the open turn and next step'). Track the next expected step per turn (steps restart at 1 on turn/start per the v4 relationship rule) and continue from there. 51/51. --- lib/session-repair.mjs | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/lib/session-repair.mjs b/lib/session-repair.mjs index 6e8595f..bdb4249 100644 --- a/lib/session-repair.mjs +++ b/lib/session-repair.mjs @@ -163,17 +163,31 @@ export function repairEvents(input) { const STEP_TYPES = new Set(['user/message', 'assistant/message', 'tool/call', 'tool/result', 'assistant/chunk']) const fixed = [] let currentTurn = 0 + // v4 lifecycle: steps restart at 1 within each turn and increment strictly. + // Track the next expected step per turn from the log's own step/start events + // so inserted markers CONTINUE the log's numbering instead of resetting it + // to 1 (which duplicates an existing step and fails the v4 relationship + // rule "step/start does not match the open turn and next step"). + const nextStepByTurn = new Map() for (const e of evs) { - if (e.type === 'turn/start' && e.data && typeof e.data.turn === 'number') currentTurn = e.data.turn + if (e.type === 'turn/start' && e.data && typeof e.data.turn === 'number') { + currentTurn = e.data.turn + nextStepByTurn.set(currentTurn, 1) + } + if (e.type === 'step/start' && e.data && typeof e.data.turn === 'number' && typeof e.data.step === 'number') { + nextStepByTurn.set(e.data.turn, e.data.step + 1) + } if (STEP_TYPES.has(e.type)) { - // user/message 不携带 data.turn/step,回退到当前 turn 与默认 step 1。 const turn = (e.data && typeof e.data.turn === 'number') ? e.data.turn : currentTurn - const step = (e.data && typeof e.data.step === 'number') ? e.data.step : 1 const open = openStepOf(fixed) - if (!open || open.data.turn !== turn || open.data.step !== step) { - // meter only enforces pairing order: close the old step first, even across turns + if (!open || open.data.turn !== turn) { + // No open step in this turn: open the turn's NEXT step. A surface + // event without its own turn/step belongs to the already-open step of + // its turn and must not force a new numbered step. 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, step } }) + const insertedStep = nextStepByTurn.get(turn) ?? 1 + fixed.push({ type: 'step/start', time: e.time, data: { turn, step: insertedStep } }) + nextStepByTurn.set(turn, insertedStep + 1) } } if (e.type === 'turn/start' || e.type === 'turn/end') { From 8a8c8e5c2cabe983636aa474510908ee1ea0bb8a Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:21:29 +0800 Subject: [PATCH 11/16] fix: renormalize turn/step regions in repair; skip compaction logs honestly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - repairEvents now treats stored markers as REGION STRUCTURE only and renormalizes numbers: duplicate step/start opens become start…end…start, surface events re-attach to their open region, orphan surfaces after the last turn/end (bare-appended paginated segments) open a fresh turn, and an unclosed turn is closed before the next one opens. Fixes the v4 lifecycle failures ('step/start does not match the open turn and next step') on logs written by the old segment-appending importer. - migrateArtifactToCurrent skips logs containing compaction events with an explicit reason: their shadowedRange citations name exact surface spans that normalization would invalidate; they need compaction-aware restructuring and are left untouched. - verified on the real store: 146/146 session.v4.jsonl.zstd pass the real catalog createRestore(validation:'current') decode path. 51/51 tests. --- lib/session-repair.mjs | 93 +++++++++++++++++++++++++++++++----------- 1 file changed, 70 insertions(+), 23 deletions(-) diff --git a/lib/session-repair.mjs b/lib/session-repair.mjs index bdb4249..6afa22a 100644 --- a/lib/session-repair.mjs +++ b/lib/session-repair.mjs @@ -163,37 +163,77 @@ export function repairEvents(input) { const STEP_TYPES = new Set(['user/message', 'assistant/message', 'tool/call', 'tool/result', 'assistant/chunk']) const fixed = [] let currentTurn = 0 - // v4 lifecycle: steps restart at 1 within each turn and increment strictly. - // Track the next expected step per turn from the log's own step/start events - // so inserted markers CONTINUE the log's numbering instead of resetting it - // to 1 (which duplicates an existing step and fails the v4 relationship - // rule "step/start does not match the open turn and next step"). - const nextStepByTurn = new Map() + 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 (e.type === 'turn/start' && e.data && typeof e.data.turn === 'number') { + // A turn must be closed before the next one opens. + if (inTurn) fixed.push({ type: 'turn/end', time: e.time, data: { turn: currentTurn, reason: { kind: 'completed' } } }) currentTurn = e.data.turn - nextStepByTurn.set(currentTurn, 1) + lastTurn = Math.max(lastTurn, e.data.turn) + inTurn = true + nextStep.set(currentTurn, 1) + emitStepEnd(e.time) // no step region crosses a turn boundary } - if (e.type === 'step/start' && e.data && typeof e.data.turn === 'number' && typeof e.data.step === 'number') { - nextStepByTurn.set(e.data.turn, e.data.step + 1) + if (e.type === 'turn/end') { + inTurn = false + emitStepEnd(e.time) // turn/end requires no open step } - if (STEP_TYPES.has(e.type)) { - const turn = (e.data && typeof e.data.turn === 'number') ? e.data.turn : currentTurn - const open = openStepOf(fixed) - if (!open || open.data.turn !== turn) { - // No open step in this turn: open the turn's NEXT step. A surface - // event without its own turn/step belongs to the already-open step of - // its turn and must not force a new numbered step. - if (open) fixed.push({ type: 'step/end', time: e.time, data: { turn: open.data.turn, step: open.data.step } }) - const insertedStep = nextStepByTurn.get(turn) ?? 1 - fixed.push({ type: 'step/start', time: e.time, data: { turn, step: insertedStep } }) - nextStepByTurn.set(turn, insertedStep + 1) + 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) } @@ -330,6 +370,13 @@ 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 } From de5e5b05d85aea4ef4698851f1be7a845144ac28 Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 5 Oct 2026 16:49:10 +0800 Subject: [PATCH 12/16] =?UTF-8?q?fix:=20address=20review=20round=202=20?= =?UTF-8?q?=E2=80=94=20continuation=20repacking,=20full=20restore=20valida?= =?UTF-8?q?tion,=20error=20propagation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - diffImportEvents: a same-turn assistant continuation (or any slice starting mid-structure) is now repacked into ONE fresh self-contained turn (turn = oldTurn+1, steps re-derived, seqs continuing the old log) — the old wrap produced turn/start(2) followed by step/end(1) and step-2 events still referring to turn 1, failing the real restorer on old.events + suffix. - repairEvents: the synthetic turn/end for an implied boundary is emitted AFTER closing the open step (v4: turn/end requires no open step). - migrateArtifactToCurrent: before touching the store the migrated artifact is now replayed through the catalog's own reader with validation:'current' (full restoration + relationship check) — encoding alone passed artifacts the real restorer rejects. - persistence-facade: a failed inspect() propagates instead of returning empty history (the importer skips the session rather than appending the whole source); createAndAppend/append surface flush/close failures after cleanup. - tests: same-turn and new-turn combined-artifact restore assertions, failed read skips, failed flush surfaces. 56/56. --- lib/import-service.js | 60 ++++++++++++++++++++--- lib/persistence-facade.mjs | 29 +++++------ lib/session-repair.mjs | 33 +++++++++---- test/import-service.test.mjs | 93 ++++++++++++++++++++++++++++++++++++ 4 files changed, 184 insertions(+), 31 deletions(-) diff --git a/lib/import-service.js b/lib/import-service.js index 696a69b..7386560 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -61,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. @@ -124,14 +168,16 @@ export function diffImportEvents(oldEvents, nextEvents) { } } } - const leftover = nextEvents.slice(cut).filter((e) => e.type !== 'session/title' && e.type !== 'turn/end') + const leftover = nextEvents.slice(cut).filter((e) => e.type !== 'session/title') 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) + // The slice may start at ANY structural boundary (a same-turn continuation + // starts mid-turn: step/end + step/start of the old turn). Repack it into + // one fresh turn so old.events + suffix is a strictly valid artifact, and + // continue the old seq numbering so the combined log stays dense. + const baseSeq = (typeof oldEvents.at(-1)?.seq === 'number' ? oldEvents.at(-1).seq : oldEvents.length - 1) + 1 + const suffix = wrapAsFreshTurn(leftover, oldTurn + 1) + suffix.forEach((e, i) => { e.seq = baseSeq + i }) + return suffix } /** diff --git a/lib/persistence-facade.mjs b/lib/persistence-facade.mjs index eb2b15b..5977aee 100644 --- a/lib/persistence-facade.mjs +++ b/lib/persistence-facade.mjs @@ -50,22 +50,17 @@ function buildFacade(persistence) { return snapshots.map(flattenSnapshot) }, - // inspect(id) -> { meta, events } (0.9.0 uses open(id,'read') + handle.read()) + // 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) { - let handle - try { - handle = await persistence.open(id, 'read') - } catch { - return { meta: { id }, events: [] } - } + 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 } - } catch { - return { meta: { id }, events: [] } } finally { - try { await handle.close() } catch { /* best-effort */ } + try { await handle.close() } catch { /* cleanup is best-effort */ } } }, @@ -73,25 +68,31 @@ function buildFacade(persistence) { 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 { /* best-effort */ } + 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. + // 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 { /* best-effort */ } - try { await handle.close() } catch { /* best-effort */ } + try { await handle.flush() } catch (error) { cleanupError = error } + try { await handle.close() } catch (error) { if (cleanupError === undefined) cleanupError = error } } + if (cleanupError !== undefined) throw cleanupError }, } } diff --git a/lib/session-repair.mjs b/lib/session-repair.mjs index 6afa22a..7cdec12 100644 --- a/lib/session-repair.mjs +++ b/lib/session-repair.mjs @@ -198,13 +198,14 @@ export function repairEvents(input) { } for (const e of evs) { if (e.type === 'turn/start' && e.data && typeof e.data.turn === 'number') { - // A turn must be closed before the next one opens. + // 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) - emitStepEnd(e.time) // no step region crosses a turn boundary } if (e.type === 'turn/end') { inTurn = false @@ -387,21 +388,33 @@ export function migrateArtifactToCurrent(file, options = {}) { migrated = migrateToCurrent(header, repaired) } catch (e) { return { ok: false, reason: `migrate: ${e?.message}`, from: header.version } } - // Validate the migrated v3 artifact encodes end-to-end before touching disk. + // Encode the migrated artifact into the exact physical frames the JSONL + // backend persists (one header frame, one events frame). + let headerLine, bodyLines try { - cat.encodeCurrentHeader({ ...migrated.header, delegationDepth: migrated.header.delegationDepth ?? 0 }, 0) - for (const e of migrated.events) cat.encodeCurrentEvent(e) + 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 } - // Rebuild the artifact exactly like the JSONL backend: one header frame, one events frame. - const headerLineV3 = JSON.stringify(cat.encodeCurrentHeader({ ...migrated.header, delegationDepth: migrated.header.delegationDepth ?? 0 }, 0)) + '\n' - const bodyV3 = migrated.events.map((e) => JSON.stringify(cat.encodeCurrentEvent(e))).join('\n') + '\n' const frameOpts = { params: { [zstdConstants.ZSTD_c_checksumFlag]: 1 } } const bytes = Buffer.concat([ - zstdCompressSync(Buffer.from(headerLineV3), frameOpts), - zstdCompressSync(Buffer.from(bodyV3), frameOpts), + zstdCompressSync(Buffer.from(headerLineText), frameOpts), + zstdCompressSync(Buffer.from(bodyText), frameOpts), ]) copyFileSync(file, `${file}.bak`) // always keep a backup of the original artifact // DSH 0.10.x names current-format logs `session.v.jsonl.zstd`; diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index 2f23a6a..341d90a 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -281,3 +281,96 @@ test('import-codex: writes through the DSH 0.9.0 handle-based persistence API (n 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: 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') +}) From 33f196485c0efc298cac3be9dd401f16bd66aa46 Mon Sep 17 00:00:00 2001 From: altruistOS <283170948+altruistOS@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:26:38 +0800 Subject: [PATCH 13/16] fix: store the reply to a question imported while still pending diffImportEvents' equal-user-count branch incremented its assistant counter before comparing it with oldAssistants, so whenever old's last turn had no assistant yet the cut position never matched and the whole continuation was dropped (reported 'updated 0, skipped 1' with the answer silently lost). The same defect also dropped the reply when an earlier complete turn existed, and the new-user branch dropped a pending turn's reply when a further user followed. Rollouts are append-only, so old's users and assistants are prefixes of next's: the first new content is now the earlier of the (oldAssistants)-th assistant (0-based) and the (match)-th user. A slice that continues old's last turn is repacked into one fresh turn (wrapAsFreshTurn); complete new turns keep their converted structure, renumbered after it. Regression tests cover pending-question, pending+new-user, and multi-turn-pending shapes, each asserting the stored answer, combined-artifact restoration through the real restoreReleasedV4Artifact, and idempotence on the next unchanged import. --- lib/import-service.js | 106 ++++++++++++++++------------ test/import-service.test.mjs | 129 +++++++++++++++++++++++++++++++++++ 2 files changed, 190 insertions(+), 45 deletions(-) diff --git a/lib/import-service.js b/lib/import-service.js index 7386560..994082f 100644 --- a/lib/import-service.js +++ b/lib/import-service.js @@ -117,66 +117,82 @@ 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 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)) } - const leftover = nextEvents.slice(cut).filter((e) => e.type !== 'session/title') - if (leftover.length === 0) return [] - // The slice may start at ANY structural boundary (a same-turn continuation - // starts mid-turn: step/end + step/start of the old turn). Repack it into - // one fresh turn so old.events + suffix is a strictly valid artifact, and - // continue the old seq numbering so the combined log stays dense. - const baseSeq = (typeof oldEvents.at(-1)?.seq === 'number' ? oldEvents.at(-1).seq : oldEvents.length - 1) + 1 - const suffix = wrapAsFreshTurn(leftover, oldTurn + 1) - suffix.forEach((e, i) => { e.seq = baseSeq + i }) return suffix } diff --git a/test/import-service.test.mjs b/test/import-service.test.mjs index 341d90a..1ac66c8 100644 --- a/test/import-service.test.mjs +++ b/test/import-service.test.mjs @@ -34,6 +34,35 @@ 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 @@ -310,6 +339,106 @@ test('import-codex: same-turn assistant continuation lands in a self-consistent 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') From 0818f914db97432a468fdb058764a057b40a017d Mon Sep 17 00:00:00 2001 From: Walvez <93713668+Walvez@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:11:50 +0800 Subject: [PATCH 14/16] fix: preserve standard function call arguments --- lib/codex-reader.mjs | 2 +- test/codex-reader.test.mjs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) 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/test/codex-reader.test.mjs b/test/codex-reader.test.mjs index 6067af1..dae3d38 100644 --- a/test/codex-reader.test.mjs +++ b/test/codex-reader.test.mjs @@ -280,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']) +}) From 360c17a87ba822097ba2d90a136921d5f81b0558 Mon Sep 17 00:00:00 2001 From: Walvez <93713668+Walvez@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:11:50 +0800 Subject: [PATCH 15/16] fix: declare verified DSH 0.2.0-rc.2 compatibility --- docs/COMPATIBILITY.md | 17 +++++++++++++++++ docs/compat.md | 5 +++++ package-lock.json | 2 +- package.json | 2 +- 4 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 docs/COMPATIBILITY.md diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md new file mode 100644 index 0000000..57ea447 --- /dev/null +++ b/docs/COMPATIBILITY.md @@ -0,0 +1,17 @@ +# 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. 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/package-lock.json b/package-lock.json index 0b3f92c..297a7ed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,7 +26,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": { diff --git a/package.json b/package.json index f1a99d2..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": { From d17b494f537ba9a12cbed20281900b2b7a175c0d Mon Sep 17 00:00:00 2001 From: Walvez <93713668+Walvez@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:16:01 +0800 Subject: [PATCH 16/16] fix: run session codec and isolated tests on Node 20 --- .github/workflows/ci.yml | 27 ++++++++++++++++++++++++--- docs/COMPATIBILITY.md | 2 ++ lib/dsh-writer.mjs | 6 ++---- lib/session-repair.mjs | 12 +++++------- lib/zstd-frame.mjs | 15 +++++++++++++++ scripts/run-tests.mjs | 1 + test/item-sync.test.mjs | 7 ++++--- test/zstd-frame.test.mjs | 16 ++++++++++++++++ 8 files changed, 69 insertions(+), 17 deletions(-) create mode 100644 lib/zstd-frame.mjs create mode 100644 test/zstd-frame.test.mjs 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 index 57ea447..652fd00 100644 --- a/docs/COMPATIBILITY.md +++ b/docs/COMPATIBILITY.md @@ -15,3 +15,5 @@ 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/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/session-repair.mjs b/lib/session-repair.mjs index 7cdec12..239c248 100644 --- a/lib/session-repair.mjs +++ b/lib/session-repair.mjs @@ -26,7 +26,7 @@ import { execFileSync } from 'node:child_process' 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' @@ -288,11 +288,10 @@ 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)), ]) } @@ -411,10 +410,9 @@ export function migrateArtifactToCurrent(file, options = {}) { const bodyText = bodyLines.join('\n') + '\n' if (!writeOut) return { ok: true, from: header.version, to: cat.currentVersion, dry: true } - const frameOpts = { params: { [zstdConstants.ZSTD_c_checksumFlag]: 1 } } const bytes = Buffer.concat([ - zstdCompressSync(Buffer.from(headerLineText), frameOpts), - zstdCompressSync(Buffer.from(bodyText), frameOpts), + 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`; 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/scripts/run-tests.mjs b/scripts/run-tests.mjs index 335c920..9bac80a 100644 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -16,6 +16,7 @@ const suites = [ '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/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/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') +})