dsh-compact-pi 0.2.3-b3 → 0.2.3-b4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +7 -5
- package/bin/dcp-session.ts +25 -18
- package/dist/codec.mjs +45 -9
- package/dist/dcp-session.mjs +1061 -605
- package/dist/index.js +9 -3
- package/docs/compatibility.md +1 -1
- package/docs/help.md +14 -4
- package/docs/publishing.md +4 -4
- package/docs/testing.md +2 -0
- package/package.json +2 -2
- package/skills/dcp-migrate-to-dsh/SKILL.md +10 -8
- package/skills/dcp-migrate-to-dsh/references/commands.md +29 -0
- package/src/codec.ts +40 -6
- package/src/dsh/convert.ts +11 -5
- package/src/dsh/import.ts +53 -24
- package/src/dsh/migration-cli.ts +129 -0
- package/src/dsh/migration-web.ts +44 -0
- package/src/dsh/migration.ts +216 -0
- package/src/dsh/sync.ts +9 -1
- package/test/convert.test.ts +37 -0
- package/test/migration.test.ts +72 -0
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { promises as fs } from 'node:fs'
|
|
3
|
+
import { homedir, hostname } from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { exportPiSession, type PiSessionFile } from './convert.ts'
|
|
6
|
+
import { DestinationConflict, escapeSegment, importPiToDsh, nativeDestination } from './import.ts'
|
|
7
|
+
|
|
8
|
+
export const migrationTargets = ['portable', 'windows-desktop', 'linux-desktop', 'web', 'tui'] as const
|
|
9
|
+
export const dshVersions = ['0.2.2-rc.1', '0.2.2-rc.5', '0.2.3-alpha.2'] as readonly string[]
|
|
10
|
+
|
|
11
|
+
export function migrationEnvironment() {
|
|
12
|
+
const piHome = path.resolve(process.env.PI_CODING_AGENT_DIR ?? path.join(homedir(), '.pi', 'agent'))
|
|
13
|
+
const dshHome = path.resolve(process.env.DSH_HOME ?? path.join(homedir(), '.dsh'))
|
|
14
|
+
return { host: hostname(), platform: process.platform, piHome, suggestedDshHome: dshHome, suggestedSessionRoot: path.join(dshHome, 'sessions') }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
type Target = typeof migrationTargets[number]
|
|
18
|
+
type Encoding = 'zstd' | 'plain'
|
|
19
|
+
export interface MigrationOptions {
|
|
20
|
+
source: string
|
|
21
|
+
target: Target
|
|
22
|
+
workspace?: string
|
|
23
|
+
profile?: string
|
|
24
|
+
dshVersion?: string
|
|
25
|
+
dshHome?: string
|
|
26
|
+
sessionRoot?: string
|
|
27
|
+
encoding?: Encoding
|
|
28
|
+
exportDir?: string
|
|
29
|
+
recoverPiEntries?: boolean
|
|
30
|
+
onConflict?: 'stop' | 'copy'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export class MixedSession extends Error {}
|
|
34
|
+
|
|
35
|
+
const piEntryTypes = new Set([
|
|
36
|
+
'message', 'model_change', 'thinking_level_change', 'custom', 'custom_message',
|
|
37
|
+
'context_edit', 'compaction', 'branch_summary', 'session_info', 'label',
|
|
38
|
+
])
|
|
39
|
+
|
|
40
|
+
function absolute(value: string | undefined, label: string): string {
|
|
41
|
+
if (!value || !path.isAbsolute(value)) throw new Error(`${label} must be an absolute path on this host`)
|
|
42
|
+
return path.resolve(value)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function directory(value: string | undefined, label: string): Promise<string> {
|
|
46
|
+
const dir = absolute(value, label)
|
|
47
|
+
if (!(await fs.stat(dir)).isDirectory()) throw new Error(`${label} must be a directory: ${dir}`)
|
|
48
|
+
return fs.realpath(dir)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function targetRoot(value: string | undefined): Promise<string> {
|
|
52
|
+
const root = absolute(value, 'Target session root')
|
|
53
|
+
const remaining: string[] = []
|
|
54
|
+
for (let current = root;; current = path.dirname(current)) {
|
|
55
|
+
try {
|
|
56
|
+
return path.join(await directory(current, 'Target session root'), ...remaining)
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || current === path.dirname(current)) throw error
|
|
59
|
+
remaining.unshift(path.basename(current))
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function digest(value: string | Buffer): string {
|
|
65
|
+
return createHash('sha256').update(value).digest('hex')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function findPiSources({ piHome, cwd, id }: { piHome?: string; cwd?: string; id?: string }) {
|
|
69
|
+
if (!cwd && !id) throw new Error('Pass --cwd or --id to select Pi sessions')
|
|
70
|
+
const root = path.join(absolute(piHome ?? process.env.PI_CODING_AGENT_DIR ?? path.join(homedir(), '.pi', 'agent'), 'Pi agent directory'), 'sessions')
|
|
71
|
+
const matches = []
|
|
72
|
+
for await (const file of fs.glob('*/*.jsonl', { cwd: root })) {
|
|
73
|
+
const input = path.join(root, file)
|
|
74
|
+
const handle = await fs.open(input, 'r')
|
|
75
|
+
try {
|
|
76
|
+
const buffer = Buffer.alloc(65536)
|
|
77
|
+
const { bytesRead } = await handle.read(buffer)
|
|
78
|
+
const header = JSON.parse(buffer.subarray(0, bytesRead).toString('utf8').split('\n', 1)[0]!)
|
|
79
|
+
if (header.type !== 'session' || !header.id || (id && header.id !== id) || (cwd && header.cwd !== cwd)) continue
|
|
80
|
+
matches.push({ path: input, id: header.id, cwd: header.cwd, timestamp: header.timestamp ?? header.createdAt, updated: (await handle.stat()).mtimeMs })
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (!(error instanceof SyntaxError)) throw error
|
|
83
|
+
} finally {
|
|
84
|
+
await handle.close()
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return matches.sort((a, b) => b.updated - a.updated)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function loadSource(input: string, recover: boolean) {
|
|
91
|
+
const bytes = await fs.readFile(input)
|
|
92
|
+
const [header, ...entries] = bytes.toString('utf8').split('\n').filter(line => line.trim()).map(line => JSON.parse(line))
|
|
93
|
+
if (header?.type !== 'session' || typeof header.id !== 'string' || !header.id)
|
|
94
|
+
throw new Error('Source must have a session header with an ID')
|
|
95
|
+
if (entries.some(row => !row || typeof row !== 'object' || Array.isArray(row)))
|
|
96
|
+
throw new Error('Source contains an invalid session row')
|
|
97
|
+
const mirrors = entries.filter(row => 'seq' in row)
|
|
98
|
+
if (mirrors.length && !recover) throw new MixedSession(
|
|
99
|
+
`Source contains ${mirrors.length} DSH event rows. Choose a native Pi file or explicitly approve --recover-pi-entries.`,
|
|
100
|
+
)
|
|
101
|
+
const native = entries.filter(row => !('seq' in row))
|
|
102
|
+
if (!mirrors.length && header.version !== 3)
|
|
103
|
+
throw new Error('This workflow requires a Pi v3 header or a supported mixed log')
|
|
104
|
+
if (mirrors.length && (header.version !== 4 || !mirrors.every(row =>
|
|
105
|
+
Number.isSafeInteger(row.seq) && row.seq >= 0 && typeof row.type === 'string' && ('data' in row),
|
|
106
|
+
))) throw new Error('Mixed source has an unsupported header or event shapes')
|
|
107
|
+
const ids = new Set()
|
|
108
|
+
for (const row of native) {
|
|
109
|
+
// A known mixed-log writer omitted parentId on its initial model entry.
|
|
110
|
+
const legacyRoot = mirrors.length && ids.size === 0 && row.type === 'model_change' && row.parentId === undefined
|
|
111
|
+
if (!piEntryTypes.has(row.type) || typeof row.id !== 'string' || !row.id || ids.has(row.id)
|
|
112
|
+
|| (!legacyRoot && row.parentId !== null && !ids.has(row.parentId)))
|
|
113
|
+
throw new Error('Source has ambiguous Pi entries or parent links')
|
|
114
|
+
ids.add(row.id)
|
|
115
|
+
}
|
|
116
|
+
if (!native.some(row => row.type === 'message')) throw new Error('Source has no native Pi messages')
|
|
117
|
+
const timestamp = header.timestamp ?? (mirrors.length && Number.isFinite(header.createdAt) ? new Date(header.createdAt).toISOString() : undefined)
|
|
118
|
+
if (typeof timestamp !== 'string' || !Number.isFinite(Date.parse(timestamp))) throw new Error('Source has no valid creation time')
|
|
119
|
+
const pi: PiSessionFile = {
|
|
120
|
+
header: mirrors.length
|
|
121
|
+
? { type: 'session', version: 3, id: header.id, timestamp, cwd: header.cwd }
|
|
122
|
+
: header,
|
|
123
|
+
entries: native,
|
|
124
|
+
}
|
|
125
|
+
return { pi, sha256: digest(bytes), mirrorRows: mirrors.length }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function portableOutput(dir: string, sessionId: string) {
|
|
129
|
+
const folder = path.join(dir, 'dcp-' + escapeSegment(sessionId))
|
|
130
|
+
try {
|
|
131
|
+
await fs.lstat(folder)
|
|
132
|
+
throw new DestinationConflict(`Export directory already exists: ${folder}`)
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
|
135
|
+
}
|
|
136
|
+
return path.join(folder, 'session.dsh.jsonl')
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function prepare(options: MigrationOptions, copyId?: string) {
|
|
140
|
+
const { target, dshVersion, profile, encoding } = options
|
|
141
|
+
if (!migrationTargets.includes(target)) throw new Error('Choose an explicit migration target')
|
|
142
|
+
if ((target === 'windows-desktop' && process.platform !== 'win32') ||
|
|
143
|
+
(target === 'linux-desktop' && process.platform !== 'linux'))
|
|
144
|
+
throw new Error(`Run this migration on the native host for ${target}`)
|
|
145
|
+
const source = await fs.realpath(absolute(options.source, 'Pi source'))
|
|
146
|
+
const { pi, sha256, mirrorRows } = await loadSource(source, options.recoverPiEntries === true)
|
|
147
|
+
const portable = target === 'portable'
|
|
148
|
+
if (portable && [dshVersion, profile, encoding, options.dshHome, options.sessionRoot, options.workspace].some(Boolean))
|
|
149
|
+
throw new Error('A portable export only takes --export-dir for its target')
|
|
150
|
+
if (!portable && options.exportDir) throw new Error('Use --session-root for a direct import')
|
|
151
|
+
if (!portable && (!dshVersion || !dshVersions.includes(dshVersion)))
|
|
152
|
+
throw new Error(`Confirm an exact tested DSH backend version: ${dshVersions.join(', ')}`)
|
|
153
|
+
if (!portable && (!profile?.trim() || (encoding !== 'zstd' && encoding !== 'plain')))
|
|
154
|
+
throw new Error('Confirm the target profile or instance and its encoding (zstd or plain)')
|
|
155
|
+
if (options.onConflict && options.onConflict !== 'stop' && options.onConflict !== 'copy')
|
|
156
|
+
throw new Error('Choose a conflict policy of stop or copy')
|
|
157
|
+
const cwd = portable ? pi.header.cwd : await directory(options.workspace, 'Target workspace')
|
|
158
|
+
if (typeof cwd !== 'string' || !cwd) throw new Error('Source does not name a project directory')
|
|
159
|
+
const dshHome = portable ? undefined : await directory(options.dshHome, 'Target DSH home')
|
|
160
|
+
const sessionRoot = portable ? undefined : await targetRoot(options.sessionRoot)
|
|
161
|
+
const exportDir = portable ? await directory(options.exportDir, 'Export directory') : undefined
|
|
162
|
+
const resolveOutput = (id: string) => portable
|
|
163
|
+
? portableOutput(exportDir!, id)
|
|
164
|
+
: nativeDestination(sessionRoot!, id, cwd, encoding === 'plain')
|
|
165
|
+
let sessionId = pi.header.id
|
|
166
|
+
let output
|
|
167
|
+
let conflict
|
|
168
|
+
try {
|
|
169
|
+
output = await resolveOutput(sessionId)
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (!(error instanceof DestinationConflict) || options.onConflict !== 'copy') throw error
|
|
172
|
+
conflict = error.message
|
|
173
|
+
sessionId = copyId ?? randomUUID()
|
|
174
|
+
if (!/^[0-9a-f-]{36}$/i.test(sessionId) || sessionId === pi.header.id)
|
|
175
|
+
throw new Error('Invalid new session ID in the migration plan')
|
|
176
|
+
output = await resolveOutput(sessionId)
|
|
177
|
+
}
|
|
178
|
+
const plan = {
|
|
179
|
+
host: hostname(), platform: process.platform, source, sourceSessionId: pi.header.id, sourceCwd: pi.header.cwd,
|
|
180
|
+
sha256, sourceMessages: pi.entries.filter(row => row.type === 'message').length, mirrorRows,
|
|
181
|
+
target, dshVersion, profile, encoding, dshHome, sessionRoot, exportDir,
|
|
182
|
+
sessionId, cwd, output, conflict,
|
|
183
|
+
attachmentHome: dshHome ?? path.dirname(output),
|
|
184
|
+
}
|
|
185
|
+
return { pi, plan }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export async function planMigration(options: MigrationOptions) {
|
|
189
|
+
const { plan } = await prepare(options)
|
|
190
|
+
return { schema: 1, options, ...plan, confirmation: digest(JSON.stringify(plan)).slice(0, 12) }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export type MigrationPlan = Awaited<ReturnType<typeof planMigration>>
|
|
194
|
+
|
|
195
|
+
export async function applyMigration(saved: MigrationPlan, confirmation: string) {
|
|
196
|
+
if (saved.schema !== 1 || !confirmation || confirmation !== saved.confirmation)
|
|
197
|
+
throw new Error('Apply requires the confirmation code from the approved plan')
|
|
198
|
+
const { plan, pi } = await prepare(saved.options, saved.sessionId)
|
|
199
|
+
if (digest(JSON.stringify(plan)).slice(0, 12) !== confirmation)
|
|
200
|
+
throw new Error('The source, target, or conflict changed. Generate and confirm a new plan.')
|
|
201
|
+
const { source, sessionId, cwd, output, dshHome, sessionRoot, encoding } = plan
|
|
202
|
+
const destination = { id: sessionId, cwd }
|
|
203
|
+
if (sessionRoot && dshHome) {
|
|
204
|
+
const report = await importPiToDsh(source, sessionRoot, encoding === 'plain', { pi, sessionId, cwd, dshHome })
|
|
205
|
+
return { ...report, target: plan.target, attachmentHome: plan.attachmentHome, status: 'written', verification: 'open-and-check-target-history' }
|
|
206
|
+
}
|
|
207
|
+
const folder = path.dirname(output)
|
|
208
|
+
await fs.mkdir(folder, { mode: 0o700 })
|
|
209
|
+
try {
|
|
210
|
+
const report = await exportPiSession(pi, output, { dshHome: folder, destination })
|
|
211
|
+
return { ...report, output, sessionId, cwd, target: plan.target, attachmentHome: folder, status: 'exported' }
|
|
212
|
+
} catch (error) {
|
|
213
|
+
await fs.rm(folder, { recursive: true, force: true })
|
|
214
|
+
throw error
|
|
215
|
+
}
|
|
216
|
+
}
|
package/src/dsh/sync.ts
CHANGED
|
@@ -10,18 +10,20 @@ export interface SyncState {
|
|
|
10
10
|
turnStarted: boolean
|
|
11
11
|
systemSeq: number | undefined
|
|
12
12
|
stepOpen: boolean
|
|
13
|
+
persistent: boolean
|
|
13
14
|
seen: Set<string>
|
|
14
15
|
toolCalls: Map<string, number>
|
|
15
16
|
appended: number
|
|
16
17
|
}
|
|
17
18
|
|
|
18
|
-
export function createSyncState(): SyncState {
|
|
19
|
+
export function createSyncState({ persistent = false }: { persistent?: boolean } = {}): SyncState {
|
|
19
20
|
return {
|
|
20
21
|
turn: 1,
|
|
21
22
|
step: 0,
|
|
22
23
|
turnStarted: false,
|
|
23
24
|
systemSeq: undefined,
|
|
24
25
|
stepOpen: false,
|
|
26
|
+
persistent,
|
|
25
27
|
seen: new Set(),
|
|
26
28
|
toolCalls: new Map(),
|
|
27
29
|
appended: 0,
|
|
@@ -58,6 +60,12 @@ function appendSystem(
|
|
|
58
60
|
): void {
|
|
59
61
|
if (state.systemSeq !== undefined) return
|
|
60
62
|
ensureTurn(session, state)
|
|
63
|
+
// Persisted V4 system messages must belong to an open step.
|
|
64
|
+
if (state.persistent && !state.stepOpen) {
|
|
65
|
+
state.step += 1
|
|
66
|
+
append(session, 'step/start', { turn: state.turn, step: state.step })
|
|
67
|
+
state.stepOpen = true
|
|
68
|
+
}
|
|
61
69
|
let content = piContentToDsh(
|
|
62
70
|
systemPrompt && systemPrompt.trim().length > 0
|
|
63
71
|
? systemPrompt
|
package/test/convert.test.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { promises as fs } from 'node:fs'
|
|
|
5
5
|
import os from 'node:os'
|
|
6
6
|
import path from 'node:path'
|
|
7
7
|
import { zstdDecompressSync } from 'node:zlib'
|
|
8
|
+
import { dshRowsFromPi, archivedPi } from '../src/codec.ts'
|
|
8
9
|
import { dshToPi, piToDsh, readPiSession } from '../src/dsh/convert.ts'
|
|
9
10
|
import { importPiToDsh } from '../src/dsh/import.ts'
|
|
10
11
|
import { readDshFile } from '../src/dsh/store.ts'
|
|
@@ -96,6 +97,42 @@ for (const plain of [false, true]) {
|
|
|
96
97
|
assert.deepEqual(await fs.readFile(imported.output), bytes)
|
|
97
98
|
}
|
|
98
99
|
|
|
100
|
+
const [header, user, assistant] = piRows
|
|
101
|
+
const system = {
|
|
102
|
+
...user, id: 'system', message: { role: 'system', content: 'Historical system prompt' },
|
|
103
|
+
}
|
|
104
|
+
const withTools = {
|
|
105
|
+
...assistant,
|
|
106
|
+
message: {
|
|
107
|
+
...assistant!.message,
|
|
108
|
+
stopReason: 'toolUse',
|
|
109
|
+
content: [
|
|
110
|
+
{ type: 'text', text: 'Still visible' },
|
|
111
|
+
{ type: 'toolCall', id: 'finished', name: 'read', arguments: {} },
|
|
112
|
+
{ type: 'toolCall', id: 'unfinished', name: 'read', arguments: {} },
|
|
113
|
+
],
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
const toolResult = {
|
|
117
|
+
...assistant, id: 'result', parentId: assistant!.id,
|
|
118
|
+
message: { role: 'toolResult', toolCallId: 'finished', toolName: 'read', content: [{ type: 'text', text: 'OK' }] },
|
|
119
|
+
}
|
|
120
|
+
const entries = [
|
|
121
|
+
system, { ...user, parentId: system.id }, withTools, toolResult,
|
|
122
|
+
{ ...toolResult, id: 'orphan', parentId: toolResult.id, message: { ...toolResult.message, toolCallId: 'missing' } },
|
|
123
|
+
]
|
|
124
|
+
const [dshHeader, ...log] = sessionRows(Buffer.from(
|
|
125
|
+
dshRowsFromPi(header as Parameters<typeof dshRowsFromPi>[0], entries),
|
|
126
|
+
))
|
|
127
|
+
const systemIndex = log.findIndex((event) => event.type === 'system/message')
|
|
128
|
+
assert.ok(systemIndex > 0)
|
|
129
|
+
assert.equal(log[systemIndex - 1].type, 'step/start')
|
|
130
|
+
for (const coordinate of ['turn', 'step'])
|
|
131
|
+
assert.equal(log[systemIndex].data[coordinate], log[systemIndex - 1].data[coordinate])
|
|
132
|
+
assert.deepEqual(log.filter((e) => e.type === 'tool/call').map((e) => e.data.callId), ['finished'])
|
|
133
|
+
assert.deepEqual(log.filter((e) => e.type === 'tool/result').map((e) => e.data.message.toolCallId), ['finished'])
|
|
134
|
+
assert.deepEqual(archivedPi(dshHeader, log)?.entries, JSON.parse(JSON.stringify(entries)))
|
|
135
|
+
|
|
99
136
|
console.log('convert ok', {
|
|
100
137
|
dshEvents: dsh!.events.length,
|
|
101
138
|
backEntries: back.entries.length,
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { promises as fs } from 'node:fs'
|
|
3
|
+
import { tmpdir } from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { test } from 'node:test'
|
|
6
|
+
import { applyMigration, findPiSources, planMigration, type MigrationOptions } from '../src/dsh/migration.ts'
|
|
7
|
+
import { readDshFile } from '../src/dsh/store.ts'
|
|
8
|
+
|
|
9
|
+
test('plan and apply require explicit paths and preserve conflicts and source changes', async () => {
|
|
10
|
+
const temp = await fs.mkdtemp(path.join(tmpdir(), 'dcp-migration-test-'))
|
|
11
|
+
try {
|
|
12
|
+
const project = path.join(temp, 'Project 中文')
|
|
13
|
+
const piHome = path.join(temp, 'pi')
|
|
14
|
+
const source = path.join(piHome, 'sessions', 'project', 'session.jsonl')
|
|
15
|
+
const dshHome = path.join(temp, 'dsh')
|
|
16
|
+
for (const dir of [project, path.dirname(source), dshHome]) await fs.mkdir(dir, { recursive: true })
|
|
17
|
+
const timestamp = new Date().toISOString()
|
|
18
|
+
const header = { type: 'session', version: 3, id: 'source-id', cwd: project, timestamp }
|
|
19
|
+
const user = {
|
|
20
|
+
type: 'message', id: 'u', parentId: null, timestamp,
|
|
21
|
+
message: { role: 'user', content: 'Migration fixture' },
|
|
22
|
+
}
|
|
23
|
+
const rows = [header, user].map(JSON.stringify).join('\n') + '\n'
|
|
24
|
+
await fs.writeFile(source, rows)
|
|
25
|
+
const listed = await findPiSources({ piHome, id: header.id })
|
|
26
|
+
assert.deepEqual(listed.map(entry => entry.path), [source])
|
|
27
|
+
const sessionRoot = path.join(dshHome, 'sessions')
|
|
28
|
+
const options: MigrationOptions = {
|
|
29
|
+
source, workspace: project, dshHome, sessionRoot,
|
|
30
|
+
target: process.platform === 'win32' ? 'windows-desktop'
|
|
31
|
+
: process.platform === 'linux' ? 'linux-desktop' : 'web',
|
|
32
|
+
profile: 'desktop', dshVersion: '0.2.3-alpha.2', encoding: 'plain',
|
|
33
|
+
}
|
|
34
|
+
await assert.rejects(planMigration({ ...options, profile: undefined }), /profile/)
|
|
35
|
+
const first = await planMigration(options)
|
|
36
|
+
await assert.rejects(fs.stat(sessionRoot), { code: 'ENOENT' })
|
|
37
|
+
await assert.rejects(applyMigration(first, 'wrong'), /confirmation code/)
|
|
38
|
+
await fs.appendFile(source, '\n')
|
|
39
|
+
await assert.rejects(applyMigration(first, first.confirmation), /changed/)
|
|
40
|
+
await assert.rejects(fs.stat(sessionRoot), { code: 'ENOENT' })
|
|
41
|
+
const approved = await planMigration(options)
|
|
42
|
+
const receipt = await applyMigration(approved, approved.confirmation)
|
|
43
|
+
assert.equal(receipt.status, 'written')
|
|
44
|
+
const original = await fs.readFile(receipt.output)
|
|
45
|
+
await assert.rejects(planMigration(options), /already exists/)
|
|
46
|
+
await assert.rejects(planMigration({ ...options, encoding: 'zstd' }), /different encoding/)
|
|
47
|
+
const duplicate = await planMigration({ ...options, onConflict: 'copy' })
|
|
48
|
+
assert.notEqual(duplicate.sessionId, first.sessionId)
|
|
49
|
+
const second = await applyMigration(duplicate, duplicate.confirmation)
|
|
50
|
+
assert.deepEqual(await fs.readFile(receipt.output), original)
|
|
51
|
+
assert.equal((await readDshFile(second.output))?.header.id, duplicate.sessionId)
|
|
52
|
+
|
|
53
|
+
const hybrid = path.join(temp, 'mixed.jsonl')
|
|
54
|
+
const hybridRows = [
|
|
55
|
+
{ ...header, version: 4, timestamp: undefined, createdAt: Date.parse(timestamp) },
|
|
56
|
+
{ type: 'turn/start', seq: 0, data: { turn: 1 } },
|
|
57
|
+
{ type: 'model_change', id: 'model', timestamp, modelId: 'fixture-model', provider: 'fixture' },
|
|
58
|
+
{ ...user, parentId: 'model' },
|
|
59
|
+
].map(JSON.stringify).join('\n') + '\n'
|
|
60
|
+
await fs.writeFile(hybrid, hybridRows)
|
|
61
|
+
const portable = { source: hybrid, target: 'portable', exportDir: temp } as const
|
|
62
|
+
await assert.rejects(planMigration(portable), /explicitly approve/)
|
|
63
|
+
const recover = await planMigration({ ...portable, recoverPiEntries: true })
|
|
64
|
+
assert.equal(recover.mirrorRows, 1)
|
|
65
|
+
const exported = await applyMigration(recover, recover.confirmation)
|
|
66
|
+
assert.equal(exported.status, 'exported')
|
|
67
|
+
assert.equal(exported.attachmentHome, path.dirname(exported.output))
|
|
68
|
+
assert.equal(await fs.readFile(hybrid, 'utf8'), hybridRows)
|
|
69
|
+
} finally {
|
|
70
|
+
await fs.rm(temp, { recursive: true, force: true, maxRetries: 5 })
|
|
71
|
+
}
|
|
72
|
+
})
|