dsh-compact-pi 0.2.3-b4 → 0.2.3-b6
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 +12 -0
- package/README.md +28 -5
- package/bin/dcp-session.ts +4 -1
- package/dist/dcp-session.mjs +619 -157
- package/dist/dcp.mjs +23 -18
- package/dist/index.js +70 -15
- package/docs/compatibility.md +1 -1
- package/docs/help.md +22 -3
- package/docs/publishing.md +4 -4
- package/docs/testing.md +17 -0
- package/package.json +2 -2
- package/scripts/smoke-package.mjs +4 -0
- package/scripts/test-correction-scope.ts +187 -0
- package/scripts/test-resume.mjs +1 -1
- package/skills/dcp-import-from-dsh/SKILL.md +17 -0
- package/skills/dcp-migrate-to-dsh/SKILL.md +10 -5
- package/skills/dcp-migrate-to-dsh/references/commands.md +4 -0
- package/src/bridge.ts +2 -1
- package/src/config.ts +61 -4
- package/src/dsh/convert.ts +14 -14
- package/src/dsh/engine.ts +3 -1
- package/src/dsh/llm.ts +29 -4
- package/src/dsh/migration-cli.ts +10 -2
- package/src/dsh/migration.ts +4 -4
- package/src/dsh/pi-destination.ts +75 -0
- package/src/dsh/reverse-migration-cli.ts +71 -0
- package/src/dsh/reverse-migration.ts +244 -0
- package/src/dsh/store.ts +14 -8
- package/src/index.ts +2 -2
- package/test/cancellation.test.ts +1 -0
- package/test/config.test.ts +33 -0
- package/test/host.test.ts +56 -0
- package/test/integration.test.ts +2 -0
- package/test/migration.test.ts +73 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { createReadStream, promises as fs } from 'node:fs'
|
|
3
|
+
import { homedir, hostname } from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { createZstdDecompress } from 'node:zlib'
|
|
6
|
+
import { loadConfig, type DshBackend } from '../config.ts'
|
|
7
|
+
import { convertDshSession, readPiSession, writePiSession } from './convert.ts'
|
|
8
|
+
import { DestinationConflict } from './import.ts'
|
|
9
|
+
import { absolute, digest, directory } from './migration.ts'
|
|
10
|
+
import { resolvePiDestination } from './pi-destination.ts'
|
|
11
|
+
import { DSH_FORMAT_VERSION } from './session.ts'
|
|
12
|
+
import { parseDshFile } from './store.ts'
|
|
13
|
+
|
|
14
|
+
interface BackendSelection {
|
|
15
|
+
project: string
|
|
16
|
+
backend?: string
|
|
17
|
+
dshHome?: string
|
|
18
|
+
sessionRoot?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function checkBackend(name: string, backend: DshBackend, origin: 'config' | 'environment' | 'default' | 'custom') {
|
|
22
|
+
const sessionRoot = backend.sessionRoot ?? path.join(backend.home, 'sessions')
|
|
23
|
+
const details = { name, origin, home: backend.home, sessionRoot }
|
|
24
|
+
try {
|
|
25
|
+
const home = await directory(backend.home, 'DSH home')
|
|
26
|
+
const root = await directory(sessionRoot, 'DSH session root')
|
|
27
|
+
await fs.access(home, fs.constants.R_OK | fs.constants.X_OK)
|
|
28
|
+
await fs.access(root, fs.constants.R_OK | fs.constants.X_OK)
|
|
29
|
+
return { ...details, home, sessionRoot: root, available: true as const }
|
|
30
|
+
} catch (error) {
|
|
31
|
+
return { ...details, available: false as const, reason: (error as Error).message }
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function probeDshBackends(project: string) {
|
|
36
|
+
const { dshBackends = {} } = await loadConfig(await directory(project, 'Current project'))
|
|
37
|
+
const recorded = await Promise.all(Object.entries(dshBackends).map(([name, backend]) => checkBackend(name, backend, 'config')))
|
|
38
|
+
const defaultHome = path.join(homedir(), '.dsh')
|
|
39
|
+
const suggestions = [
|
|
40
|
+
...(process.env.DSH_HOME ? [await checkBackend('environment', { home: path.resolve(process.env.DSH_HOME) }, 'environment')] : []),
|
|
41
|
+
await checkBackend('default', { home: defaultHome }, 'default'),
|
|
42
|
+
]
|
|
43
|
+
const backendKey = (backend: DshBackend) => JSON.stringify([backend.home, backend.sessionRoot])
|
|
44
|
+
const seen = new Set(recorded.filter(backend => backend.available).map(backendKey))
|
|
45
|
+
return {
|
|
46
|
+
host: hostname(), platform: process.platform,
|
|
47
|
+
status: recorded.length ? 'configured' : 'no-configured-backend', recorded,
|
|
48
|
+
suggestions: suggestions.filter(backend => {
|
|
49
|
+
const key = backendKey(backend)
|
|
50
|
+
if (seen.has(key) || Object.hasOwn(dshBackends, backend.name)) return false
|
|
51
|
+
seen.add(key)
|
|
52
|
+
return true
|
|
53
|
+
}),
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function selectBackend(options: BackendSelection) {
|
|
58
|
+
const { backend: name, dshHome, sessionRoot } = options
|
|
59
|
+
let backend
|
|
60
|
+
if (dshHome) {
|
|
61
|
+
if (name) throw new Error('Choose a named backend or pass a custom DSH home')
|
|
62
|
+
backend = await checkBackend('custom', {
|
|
63
|
+
home: absolute(dshHome, 'DSH home'),
|
|
64
|
+
sessionRoot: sessionRoot && absolute(sessionRoot, 'DSH session root'),
|
|
65
|
+
}, 'custom')
|
|
66
|
+
} else {
|
|
67
|
+
if (!name || sessionRoot) throw new Error('Select --backend or pass --dsh-home with an optional --session-root')
|
|
68
|
+
const { recorded, suggestions } = await probeDshBackends(options.project)
|
|
69
|
+
backend = [...recorded, ...suggestions].find(value => value.name === name)
|
|
70
|
+
if (!backend) throw new Error(`Unknown DSH backend: ${name}. Run probe and confirm a backend.`)
|
|
71
|
+
}
|
|
72
|
+
if (!backend.available) throw new Error(`DSH backend ${backend.name} is unavailable: ${backend.reason}`)
|
|
73
|
+
return backend
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function readHeader(file: string) {
|
|
77
|
+
const input = createReadStream(file)
|
|
78
|
+
const decoder = file.endsWith('.zstd') ? createZstdDecompress() : undefined
|
|
79
|
+
if (decoder) input.on('error', error => decoder.destroy(error))
|
|
80
|
+
const stream = decoder ? input.pipe(decoder) : input
|
|
81
|
+
try {
|
|
82
|
+
let header = Buffer.alloc(0)
|
|
83
|
+
for await (const chunk of stream) {
|
|
84
|
+
const bytes = Buffer.from(chunk)
|
|
85
|
+
const newline = bytes.indexOf(0x0a)
|
|
86
|
+
const prefix = newline === -1 ? bytes : bytes.subarray(0, newline)
|
|
87
|
+
if (header.length + prefix.length > 65536) throw new Error('DSH session header is too large')
|
|
88
|
+
header = Buffer.concat([header, prefix])
|
|
89
|
+
if (newline !== -1) return JSON.parse(header.toString('utf8'))
|
|
90
|
+
}
|
|
91
|
+
throw new Error('Missing DSH session header')
|
|
92
|
+
} finally {
|
|
93
|
+
stream.destroy()
|
|
94
|
+
input.destroy()
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const logFilename = /^session(?:\.v([1-9]\d*))?\.jsonl(\.zstd)?$/
|
|
99
|
+
|
|
100
|
+
async function scanDshSessions(root: string) {
|
|
101
|
+
const generations = new Map<string, { version: number; file: string; encodings: Set<boolean> }>()
|
|
102
|
+
for await (const file of fs.glob('*/*/session*.jsonl{,.zstd}', { cwd: root })) {
|
|
103
|
+
const match = logFilename.exec(path.basename(file))
|
|
104
|
+
if (!match) continue
|
|
105
|
+
const generation = Number(match[1] ?? 1)
|
|
106
|
+
const folder = path.dirname(file)
|
|
107
|
+
const latest = generations.get(folder)
|
|
108
|
+
const encodings = latest?.encodings ?? new Set<boolean>()
|
|
109
|
+
encodings.add(Boolean(match[2]))
|
|
110
|
+
if (!latest || generation > latest.version) generations.set(folder, { version: generation, file, encodings })
|
|
111
|
+
}
|
|
112
|
+
const sessions = []
|
|
113
|
+
const skipped = []
|
|
114
|
+
for (const { file: relative, version, encodings } of generations.values()) {
|
|
115
|
+
const file = path.join(root, relative)
|
|
116
|
+
if (encodings.size > 1 || version !== DSH_FORMAT_VERSION) {
|
|
117
|
+
skipped.push({ file, reason: encodings.size > 1 ? 'ambiguous encoding' : `unsupported generation v${version}` })
|
|
118
|
+
continue
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const realFile = await fs.realpath(file)
|
|
122
|
+
if (realFile !== file) throw new Error('session log is a symlink')
|
|
123
|
+
const header = await readHeader(file)
|
|
124
|
+
if (header?.type !== 'session' || header.version !== DSH_FORMAT_VERSION ||
|
|
125
|
+
typeof header.id !== 'string' || !header.id || !Number.isFinite(header.createdAt))
|
|
126
|
+
throw new Error('invalid DSH v4 session header')
|
|
127
|
+
const updated = (await fs.stat(file)).mtimeMs
|
|
128
|
+
sessions.push({ id: header.id as string, cwd: header.cwd as string | undefined, createdAt: header.createdAt as number, updated, file })
|
|
129
|
+
} catch (error) {
|
|
130
|
+
skipped.push({ file, reason: (error as Error).message })
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
sessions.sort((a, b) => b.updated - a.updated || a.id.localeCompare(b.id))
|
|
134
|
+
const counts = new Map<string, number>()
|
|
135
|
+
for (const session of sessions) counts.set(session.id, (counts.get(session.id) ?? 0) + 1)
|
|
136
|
+
return {
|
|
137
|
+
sessions: sessions.filter(session => counts.get(session.id) === 1),
|
|
138
|
+
skipped: [...skipped, ...sessions.filter(session => counts.get(session.id)! > 1)
|
|
139
|
+
.map(({ file }) => ({ file, reason: 'duplicate DSH session ID' }))],
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function listDshSessions(options: BackendSelection & { cwd?: string; limit?: number; offset?: number }) {
|
|
144
|
+
const backend = await selectBackend(options)
|
|
145
|
+
const { sessions, skipped } = await scanDshSessions(backend.sessionRoot)
|
|
146
|
+
const selected = options.cwd ? sessions.filter(session => session.cwd === options.cwd) : sessions
|
|
147
|
+
const offset = options.offset ?? 0
|
|
148
|
+
const limit = options.limit ?? 20
|
|
149
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100)
|
|
150
|
+
throw new Error('Use a non-negative offset and a limit between 1 and 100')
|
|
151
|
+
return { backend, total: selected.length, skipped: skipped.length, offset, sessions: selected.slice(offset, offset + limit) }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface ReverseOptions extends BackendSelection {
|
|
155
|
+
id: string
|
|
156
|
+
workspace: string
|
|
157
|
+
piHome?: string
|
|
158
|
+
sessionDir?: string
|
|
159
|
+
onConflict?: 'copy'
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function prepare(options: ReverseOptions, copyId?: string) {
|
|
163
|
+
if (!options.id) throw new Error('Confirm the DSH session ID')
|
|
164
|
+
if (options.onConflict && options.onConflict !== 'copy') throw new Error('Use --on-conflict copy or choose another session')
|
|
165
|
+
const backend = await selectBackend(options)
|
|
166
|
+
const { sessions } = await scanDshSessions(backend.sessionRoot)
|
|
167
|
+
const selected = sessions.find(session => session.id === options.id)
|
|
168
|
+
if (!selected) throw new Error('The selected DSH session is no longer uniquely available. Refresh the list.')
|
|
169
|
+
const raw = await fs.readFile(selected.file)
|
|
170
|
+
const { sdk, ...destination } = await resolvePiDestination(options)
|
|
171
|
+
const timestamp = new Date(selected.createdAt).toISOString().replace(/[:.]/g, '-')
|
|
172
|
+
const outputFor = (id: string) => path.join(destination.sessionDir, `${timestamp}_${id}.jsonl`)
|
|
173
|
+
const available = async (id: string) => {
|
|
174
|
+
if (sdk.SessionManager.findById(destination.workspace, id, destination.sessionDir)) return false
|
|
175
|
+
try {
|
|
176
|
+
await fs.lstat(outputFor(id))
|
|
177
|
+
return false
|
|
178
|
+
} catch (error) {
|
|
179
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true
|
|
180
|
+
throw error
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
let sessionId = selected.id
|
|
184
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(sessionId))
|
|
185
|
+
throw new Error('Unsupported DSH session ID for Pi import')
|
|
186
|
+
const conflict = !await available(sessionId)
|
|
187
|
+
if (conflict) {
|
|
188
|
+
if (options.onConflict !== 'copy') throw new DestinationConflict(`Pi already has session ${sessionId} at the selected destination; ask whether to import a copy with a new ID.`)
|
|
189
|
+
sessionId = copyId ?? randomUUID()
|
|
190
|
+
if (!/^[0-9a-f-]{36}$/i.test(sessionId) || sessionId === selected.id || !await available(sessionId))
|
|
191
|
+
throw new DestinationConflict('The copy ID is unavailable. Generate and approve a new plan.')
|
|
192
|
+
}
|
|
193
|
+
const plan = {
|
|
194
|
+
host: hostname(), platform: process.platform, backend, source: selected.file,
|
|
195
|
+
sourceSessionId: selected.id, sourceCwd: selected.cwd, sha256: digest(raw),
|
|
196
|
+
...destination, output: outputFor(sessionId), sessionId, conflict,
|
|
197
|
+
}
|
|
198
|
+
return { sdk, raw, plan }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export async function planReverseMigration(options: ReverseOptions) {
|
|
202
|
+
const { plan } = await prepare(options)
|
|
203
|
+
return { schema: 1, options, ...plan, confirmation: digest(JSON.stringify(plan)).slice(0, 12) }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
type ReversePlan = Awaited<ReturnType<typeof planReverseMigration>>
|
|
207
|
+
|
|
208
|
+
export async function applyReverseMigration(saved: ReversePlan, confirmation: string) {
|
|
209
|
+
if (saved.schema !== 1 || !confirmation || confirmation !== saved.confirmation)
|
|
210
|
+
throw new Error('Apply requires the confirmation code from the approved plan')
|
|
211
|
+
const { plan, sdk, raw } = await prepare(saved.options, saved.sessionId)
|
|
212
|
+
if (digest(JSON.stringify(plan)).slice(0, 12) !== confirmation)
|
|
213
|
+
throw new Error('The source or destination changed. Generate and confirm a new plan.')
|
|
214
|
+
const dsh = await parseDshFile(plan.source, raw)
|
|
215
|
+
if (!dsh || dsh.header.id !== plan.sourceSessionId) throw new Error('The selected DSH session changed')
|
|
216
|
+
const { header, entries } = await convertDshSession(dsh, plan.backend.home)
|
|
217
|
+
await fs.mkdir(plan.sessionDir, { recursive: true, mode: 0o700 })
|
|
218
|
+
if (await fs.realpath(plan.sessionDir) !== plan.sessionDir)
|
|
219
|
+
throw new Error('Pi session directory changed. Generate and confirm a new plan.')
|
|
220
|
+
const stage = await fs.mkdtemp(path.join(plan.sessionDir, '.dcp-import-'))
|
|
221
|
+
try {
|
|
222
|
+
const staged = path.join(stage, 'session.jsonl')
|
|
223
|
+
await writePiSession(staged, { ...header, id: plan.sessionId, cwd: plan.workspace }, entries)
|
|
224
|
+
if (process.platform !== 'win32') await fs.chmod(staged, 0o600)
|
|
225
|
+
const pi = await readPiSession(staged)
|
|
226
|
+
const messages = sdk.SessionManager.open(staged, stage, plan.workspace).buildSessionProjection().messages.length
|
|
227
|
+
if (pi.header.id !== plan.sessionId || pi.header.cwd !== plan.workspace || !messages)
|
|
228
|
+
throw new Error('Converted history could not be opened by Pi')
|
|
229
|
+
if (sdk.SessionManager.findById(plan.workspace, plan.sessionId, plan.sessionDir))
|
|
230
|
+
throw new DestinationConflict('The destination session ID was taken after approval')
|
|
231
|
+
await fs.link(staged, plan.output)
|
|
232
|
+
const row = (await sdk.SessionManager.list(plan.workspace, plan.sessionDir))
|
|
233
|
+
.find(item => item.id === plan.sessionId && path.resolve(item.path) === plan.output)
|
|
234
|
+
if (!row?.messageCount)
|
|
235
|
+
throw new Error(`Written to ${plan.output}, but Pi could not list the imported history`)
|
|
236
|
+
return {
|
|
237
|
+
status: 'verified', checks: ['pi-history', 'pi-session-list'], output: plan.output,
|
|
238
|
+
workspace: plan.workspace, piHome: plan.piHome, sessionDir: plan.sessionDir, sessionId: plan.sessionId,
|
|
239
|
+
messages: row.messageCount, resumeArgs: [...plan.launchArgs, '--session', plan.output],
|
|
240
|
+
}
|
|
241
|
+
} finally {
|
|
242
|
+
await fs.rm(stage, { force: true, recursive: true })
|
|
243
|
+
}
|
|
244
|
+
}
|
package/src/dsh/store.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
/** DSH session JSONL persistence (schema-compatible v4 rows). */
|
|
2
2
|
|
|
3
|
-
import { execFileSync } from 'node:child_process'
|
|
4
3
|
import { readFileSync } from 'node:fs'
|
|
5
4
|
import { promises as fs } from 'node:fs'
|
|
6
5
|
import * as path from 'node:path'
|
|
6
|
+
import { promisify } from 'node:util'
|
|
7
|
+
import { zstdDecompress } from 'node:zlib'
|
|
7
8
|
import type { Session } from '../../vendor/dsh-runtime.mjs'
|
|
8
9
|
import {
|
|
9
10
|
DSH_FORMAT_VERSION,
|
|
@@ -44,19 +45,24 @@ export function dshFileFor(
|
|
|
44
45
|
return path.join(dir, `${base}.jsonl`)
|
|
45
46
|
}
|
|
46
47
|
|
|
48
|
+
const decompress = promisify(zstdDecompress)
|
|
49
|
+
|
|
47
50
|
export async function readDshFile(file: string): Promise<DshFile | undefined> {
|
|
48
|
-
let
|
|
51
|
+
let bytes: Buffer
|
|
49
52
|
try {
|
|
50
|
-
|
|
51
|
-
? execFileSync('zstd', ['-dc', file], {
|
|
52
|
-
encoding: 'utf8',
|
|
53
|
-
maxBuffer: 512 * 1024 * 1024,
|
|
54
|
-
})
|
|
55
|
-
: await fs.readFile(file, 'utf8')
|
|
53
|
+
bytes = await fs.readFile(file)
|
|
56
54
|
} catch (error: any) {
|
|
57
55
|
if (error?.code === 'ENOENT') return undefined
|
|
58
56
|
throw error
|
|
59
57
|
}
|
|
58
|
+
return parseDshFile(file, bytes)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function parseDshFile(file: string, bytes: Buffer): Promise<DshFile | undefined> {
|
|
62
|
+
const decoded = file.endsWith('.zstd')
|
|
63
|
+
? await decompress(bytes, { maxOutputLength: 512 * 1024 * 1024 })
|
|
64
|
+
: bytes
|
|
65
|
+
const text = decoded.toString('utf8')
|
|
60
66
|
const rows = text.split('\n').filter((line) => line.trim().length > 0)
|
|
61
67
|
if (rows.length === 0) return undefined
|
|
62
68
|
const headerRow = JSON.parse(rows[0])
|
package/src/index.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type {
|
|
|
4
4
|
ExtensionContext,
|
|
5
5
|
} from '@earendil-works/pi-coding-agent'
|
|
6
6
|
import { DshBridge } from './bridge.ts'
|
|
7
|
-
import {
|
|
7
|
+
import { loadCompactionConfig, saveSummaryModel, summaryModelLabel } from './config.ts'
|
|
8
8
|
import { describeSummary } from './compaction-info.ts'
|
|
9
9
|
|
|
10
10
|
export default function dcp(pi: ExtensionAPI): void {
|
|
@@ -25,7 +25,7 @@ export default function dcp(pi: ExtensionAPI): void {
|
|
|
25
25
|
bridge = undefined
|
|
26
26
|
displayContext = ctx
|
|
27
27
|
try {
|
|
28
|
-
bridge = new DshBridge(pi, ctx, await
|
|
28
|
+
bridge = new DshBridge(pi, ctx, await loadCompactionConfig(ctx.cwd))
|
|
29
29
|
} catch (error) {
|
|
30
30
|
ctx.ui.notify(`dcp: initialization failed: ${String(error)}`, 'error')
|
|
31
31
|
}
|
|
@@ -22,6 +22,7 @@ for (const phase of ['tool', 'summary'] as const) {
|
|
|
22
22
|
const dir = mkdtempSync(path.join(os.tmpdir(), 'dcp-cancel-'))
|
|
23
23
|
mkdirSync(path.join(dir, '.pi'))
|
|
24
24
|
writeFileSync(path.join(dir, '.pi/dcp.json'), JSON.stringify({
|
|
25
|
+
summaryPrompt: { mode: 'native' },
|
|
25
26
|
policy: { headroomTokens: 512, retainTokens: 256, maxTokens: 1024 },
|
|
26
27
|
}))
|
|
27
28
|
const errors: any[] = []
|
package/test/config.test.ts
CHANGED
|
@@ -11,9 +11,11 @@ test('summary model command saves and resets the project default without losing
|
|
|
11
11
|
try {
|
|
12
12
|
mkdirSync(path.join(dir, '.pi'))
|
|
13
13
|
const modelPolicies = [{ provider: 'other', model: 'chat', summarizationProvider: 'other', summarizationModel: 'summary' }]
|
|
14
|
+
const summaryPrompt = { mode: 'append', text: 'Keep task-specific corrections scoped.' }
|
|
14
15
|
writeFileSync(path.join(dir, '.pi/zcp.json'), JSON.stringify({
|
|
15
16
|
audit: false,
|
|
16
17
|
policy: { retainTokens: 123, modelPolicies },
|
|
18
|
+
summaryPrompt,
|
|
17
19
|
}))
|
|
18
20
|
const commands = new Map<string, any>()
|
|
19
21
|
const events = new Map<string, any>()
|
|
@@ -53,6 +55,7 @@ test('summary model command saves and resets the project default without losing
|
|
|
53
55
|
await select('', ctx)
|
|
54
56
|
await commands.get('dcp-status').handler('', ctx)
|
|
55
57
|
assert.match(notices.at(-1)!, /Summary model default: local\/summary\/v1/)
|
|
58
|
+
assert.match(notices.at(-1)!, /Summary prompt: append/)
|
|
56
59
|
assert.equal(ctx.model.id, 'main')
|
|
57
60
|
assert.equal((await loadConfig(dir)).policy.summarizationModel, 'summary/v1')
|
|
58
61
|
await select('reset', ctx)
|
|
@@ -60,6 +63,7 @@ test('summary model command saves and resets the project default without losing
|
|
|
60
63
|
assert.deepEqual(await loadConfig(dir), {
|
|
61
64
|
audit: false,
|
|
62
65
|
policy: { retainTokens: 123, modelPolicies },
|
|
66
|
+
summaryPrompt,
|
|
63
67
|
})
|
|
64
68
|
} finally {
|
|
65
69
|
rmSync(dir, { recursive: true, force: true })
|
|
@@ -96,6 +100,12 @@ test('configuration validates upstream policy fields and exact model overrides',
|
|
|
96
100
|
{ policy: { summarizationProvider: 'only-provider' } },
|
|
97
101
|
{ policy: { misspelled: 1 } },
|
|
98
102
|
{ audit: 'yes' },
|
|
103
|
+
{ summaryPrompt: null },
|
|
104
|
+
{ summaryPrompt: { mode: 'replace', text: 'text' } },
|
|
105
|
+
{ summaryPrompt: { mode: 'native', text: 'unused' } },
|
|
106
|
+
{ summaryPrompt: { mode: 'override' } },
|
|
107
|
+
{ summaryPrompt: { mode: 'append', text: ' \n ' } },
|
|
108
|
+
{ summaryPrompt: { mode: 'append', text: 'text', typo: true } },
|
|
99
109
|
]) {
|
|
100
110
|
writeFileSync(file, JSON.stringify(invalid))
|
|
101
111
|
await assert.rejects(loadConfig(dir))
|
|
@@ -104,3 +114,26 @@ test('configuration validates upstream policy fields and exact model overrides',
|
|
|
104
114
|
rmSync(dir, { recursive: true, force: true })
|
|
105
115
|
}
|
|
106
116
|
})
|
|
117
|
+
|
|
118
|
+
test('the user summary prompt is a fallback and the project can restore native mode', async () => {
|
|
119
|
+
const dir = mkdtempSync(path.join(os.tmpdir(), 'dcp-user-prompt-'))
|
|
120
|
+
try {
|
|
121
|
+
const agentDir = path.join(dir, 'agent')
|
|
122
|
+
mkdirSync(agentDir)
|
|
123
|
+
const summaryPrompt = { mode: 'override', text: 'Preserve facts and record the scope of decisions.' }
|
|
124
|
+
writeFileSync(path.join(agentDir, 'dcp.json'), JSON.stringify({
|
|
125
|
+
summaryPrompt, audit: false, policy: { retainTokens: 42 },
|
|
126
|
+
}))
|
|
127
|
+
assert.deepEqual(await loadConfig(dir, agentDir), { summaryPrompt, audit: true, policy: {} })
|
|
128
|
+
assert.deepEqual(await loadConfig(dir), { audit: true, policy: {} })
|
|
129
|
+
mkdirSync(path.join(dir, '.pi'))
|
|
130
|
+
writeFileSync(path.join(dir, '.pi/dcp.json'), JSON.stringify({
|
|
131
|
+
summaryPrompt: { mode: 'native' }, policy: { retainTokens: 123 },
|
|
132
|
+
}))
|
|
133
|
+
assert.deepEqual(await loadConfig(dir, agentDir), {
|
|
134
|
+
summaryPrompt: { mode: 'native' }, audit: true, policy: { retainTokens: 123 },
|
|
135
|
+
})
|
|
136
|
+
} finally {
|
|
137
|
+
rmSync(dir, { recursive: true, force: true })
|
|
138
|
+
}
|
|
139
|
+
})
|
package/test/host.test.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import assert from 'node:assert/strict'
|
|
3
3
|
import { test } from 'node:test'
|
|
4
4
|
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
|
5
|
+
import { mkdir, writeFile } from 'node:fs/promises'
|
|
5
6
|
import os from 'node:os'
|
|
6
7
|
import path from 'node:path'
|
|
7
8
|
import {
|
|
@@ -11,6 +12,7 @@ import {
|
|
|
11
12
|
} from '@earendil-works/pi-coding-agent'
|
|
12
13
|
import type { AgentMessage } from '@earendil-works/pi-agent-core'
|
|
13
14
|
import { DshBridge, JOURNAL } from '../src/bridge.ts'
|
|
15
|
+
import { loadConfig } from '../src/config.ts'
|
|
14
16
|
|
|
15
17
|
const usage = {
|
|
16
18
|
input: 0,
|
|
@@ -123,6 +125,60 @@ test('summary uses the last model that answered, not the current request route',
|
|
|
123
125
|
}
|
|
124
126
|
})
|
|
125
127
|
|
|
128
|
+
test('configured summary prompt changes only the final compaction request message', async () => {
|
|
129
|
+
const prompts = new Map<string, { text: string; prefix: unknown[]; systemPrompt: string }>()
|
|
130
|
+
const text = 'Record corrections together with the task they apply to.'
|
|
131
|
+
for (const summaryPrompt of [
|
|
132
|
+
undefined,
|
|
133
|
+
{ mode: 'native' },
|
|
134
|
+
{ mode: 'override', text },
|
|
135
|
+
{ mode: 'append', text },
|
|
136
|
+
]) {
|
|
137
|
+
const h = setup(20000)
|
|
138
|
+
let bridge: DshBridge | undefined
|
|
139
|
+
try {
|
|
140
|
+
await mkdir(path.join(h.dir, '.pi'))
|
|
141
|
+
await writeFile(path.join(h.dir, '.pi/dcp.json'), JSON.stringify({
|
|
142
|
+
policy: { headroomTokens: 512, retainTokens: 256, maxTokens: 1024 },
|
|
143
|
+
summaryPrompt,
|
|
144
|
+
}))
|
|
145
|
+
bridge = new DshBridge(h.api, h.ctx, await loadConfig(h.dir))
|
|
146
|
+
h.manager.appendMessage(user('First task'))
|
|
147
|
+
h.manager.appendMessage(assistant('Completed first task'))
|
|
148
|
+
h.manager.appendMessage(user('Second task '.repeat(1000)))
|
|
149
|
+
h.manager.appendMessage(assistant('Latest answer'))
|
|
150
|
+
const checkpoint = await bridge.prepareNative({
|
|
151
|
+
reason: 'manual',
|
|
152
|
+
signal: new AbortController().signal,
|
|
153
|
+
preparation: { tokensBefore: 5000 },
|
|
154
|
+
} as any)
|
|
155
|
+
assert.ok(checkpoint)
|
|
156
|
+
assert.match(checkpoint.summary, /COMPACTED SUMMARY/)
|
|
157
|
+
assert.equal(h.calls.length, 1)
|
|
158
|
+
const { messages, systemPrompt } = h.calls[0].context
|
|
159
|
+
const directive = messages.at(-1)
|
|
160
|
+
assert.equal(directive.role, 'user')
|
|
161
|
+
assert.equal(directive.content[0].type, 'text')
|
|
162
|
+
const prefix = messages.slice(0, -1).map(({ timestamp, ...message }: any) => message)
|
|
163
|
+
assert.match(JSON.stringify(prefix), /First task/)
|
|
164
|
+
prompts.set(summaryPrompt?.mode ?? 'default', {
|
|
165
|
+
text: directive.content[0].text,
|
|
166
|
+
prefix,
|
|
167
|
+
systemPrompt,
|
|
168
|
+
})
|
|
169
|
+
} finally {
|
|
170
|
+
await bridge?.close()
|
|
171
|
+
h.cleanup()
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const native = prompts.get('default')
|
|
175
|
+
assert.ok(native)
|
|
176
|
+
assert.match(native.text, /You are now acting as a compaction engine/)
|
|
177
|
+
assert.deepEqual(prompts.get('native'), native)
|
|
178
|
+
assert.deepEqual(prompts.get('override'), { ...native, text })
|
|
179
|
+
assert.deepEqual(prompts.get('append'), { ...native, text: native.text + '\n\n' + text })
|
|
180
|
+
})
|
|
181
|
+
|
|
126
182
|
test('prune-only progress is durable across restart and preserves metadata', async () => {
|
|
127
183
|
const h = setup()
|
|
128
184
|
try {
|
package/test/integration.test.ts
CHANGED
|
@@ -33,6 +33,7 @@ test('built installable extension summarizes images and resumes in the real pi a
|
|
|
33
33
|
writeFileSync(
|
|
34
34
|
path.join(dir, '.pi/dcp.json'),
|
|
35
35
|
JSON.stringify({
|
|
36
|
+
summaryPrompt: { mode: 'native' },
|
|
36
37
|
policy: { headroomTokens: 512, retainTokens: 256, maxTokens: 1024 },
|
|
37
38
|
}),
|
|
38
39
|
)
|
|
@@ -270,6 +271,7 @@ for (const keepsFailing of [false, true])
|
|
|
270
271
|
writeFileSync(
|
|
271
272
|
path.join(dir, '.pi/dcp.json'),
|
|
272
273
|
JSON.stringify({
|
|
274
|
+
summaryPrompt: { mode: 'native' },
|
|
273
275
|
policy: { headroomTokens: 512, retainTokens: 256, maxTokens: 1024 },
|
|
274
276
|
}),
|
|
275
277
|
)
|
package/test/migration.test.ts
CHANGED
|
@@ -5,6 +5,9 @@ import path from 'node:path'
|
|
|
5
5
|
import { test } from 'node:test'
|
|
6
6
|
import { applyMigration, findPiSources, planMigration, type MigrationOptions } from '../src/dsh/migration.ts'
|
|
7
7
|
import { readDshFile } from '../src/dsh/store.ts'
|
|
8
|
+
import { importPiToDsh } from '../src/dsh/import.ts'
|
|
9
|
+
import { applyReverseMigration, listDshSessions, planReverseMigration, probeDshBackends } from '../src/dsh/reverse-migration.ts'
|
|
10
|
+
import { resolvePiDestination } from '../src/dsh/pi-destination.ts'
|
|
8
11
|
|
|
9
12
|
test('plan and apply require explicit paths and preserve conflicts and source changes', async () => {
|
|
10
13
|
const temp = await fs.mkdtemp(path.join(tmpdir(), 'dcp-migration-test-'))
|
|
@@ -70,3 +73,73 @@ test('plan and apply require explicit paths and preserve conflicts and source ch
|
|
|
70
73
|
await fs.rm(temp, { recursive: true, force: true, maxRetries: 5 })
|
|
71
74
|
}
|
|
72
75
|
})
|
|
76
|
+
|
|
77
|
+
test('DSH import validates profiles and opens the approved workspace history in Pi', async () => {
|
|
78
|
+
const temp = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'dcp-reverse-test-')))
|
|
79
|
+
const previousPiHome = process.env.PI_CODING_AGENT_DIR
|
|
80
|
+
const previousSessionDir = process.env.PI_CODING_AGENT_SESSION_DIR
|
|
81
|
+
delete process.env.PI_CODING_AGENT_SESSION_DIR
|
|
82
|
+
try {
|
|
83
|
+
const sourceWorkspace = path.join(temp, 'DSH project 中文')
|
|
84
|
+
const workspace = path.join(temp, 'Pi project 中文')
|
|
85
|
+
const piHome = path.join(temp, 'profile')
|
|
86
|
+
process.env.PI_CODING_AGENT_DIR = piHome
|
|
87
|
+
const dshHome = path.join(temp, 'dsh')
|
|
88
|
+
const sessionRoot = path.join(temp, 'custom-store')
|
|
89
|
+
for (const dir of [sourceWorkspace, path.join(workspace, '.pi'), piHome, dshHome])
|
|
90
|
+
await fs.mkdir(dir, { recursive: true })
|
|
91
|
+
assert.equal((await probeDshBackends(workspace)).status, 'no-configured-backend')
|
|
92
|
+
await fs.writeFile(path.join(workspace, '.pi', 'dcp.json'), JSON.stringify({
|
|
93
|
+
dshBackends: { desktop: { home: dshHome, sessionRoot }, missing: { home: path.join(temp, 'missing') } },
|
|
94
|
+
}))
|
|
95
|
+
assert.deepEqual((await probeDshBackends(workspace)).recorded.map(row => row.available), [false, false])
|
|
96
|
+
await assert.rejects(listDshSessions({ project: workspace, backend: 'missing' }), /unavailable/)
|
|
97
|
+
const source = path.join(temp, 'original.pi.jsonl')
|
|
98
|
+
const timestamp = '2026-10-15T06:02:22.493Z'
|
|
99
|
+
const header = { type: 'session', version: 3, id: 'dsh-source-id', cwd: sourceWorkspace, timestamp }
|
|
100
|
+
const message = {
|
|
101
|
+
type: 'message', id: 'u', parentId: null, timestamp,
|
|
102
|
+
message: { role: 'user', content: 'Only the destination Pi project should list this migration' },
|
|
103
|
+
}
|
|
104
|
+
await fs.writeFile(source, JSON.stringify(header) + '\n' + JSON.stringify(message) + '\n')
|
|
105
|
+
const exportReceipt = await importPiToDsh(source, sessionRoot, false, { dshHome })
|
|
106
|
+
const original = await fs.readFile(exportReceipt.output)
|
|
107
|
+
const store = { project: workspace, backend: 'desktop' }
|
|
108
|
+
assert.deepEqual((await probeDshBackends(workspace)).recorded.map(row => row.available), [true, false])
|
|
109
|
+
const listed = await listDshSessions({ ...store, cwd: sourceWorkspace })
|
|
110
|
+
assert.equal(listed.total, 1)
|
|
111
|
+
assert.equal(listed.sessions[0]?.id, header.id)
|
|
112
|
+
assert.equal((await listDshSessions({ ...store, offset: 1 })).sessions.length, 0)
|
|
113
|
+
assert.equal((await listDshSessions({ project: workspace, dshHome, sessionRoot })).total, 1)
|
|
114
|
+
const options = { ...store, id: header.id, workspace, piHome }
|
|
115
|
+
const { sdk, sessionDir } = await resolvePiDestination(options)
|
|
116
|
+
const plan = await planReverseMigration(options)
|
|
117
|
+
assert.equal(plan.workspace, workspace)
|
|
118
|
+
assert.equal(path.dirname(plan.output), sessionDir)
|
|
119
|
+
await assert.rejects(fs.stat(sessionDir), { code: 'ENOENT' })
|
|
120
|
+
await assert.rejects(applyReverseMigration(plan, 'wrong'), /confirmation code/)
|
|
121
|
+
await fs.appendFile(exportReceipt.output, Buffer.from([0]))
|
|
122
|
+
await assert.rejects(applyReverseMigration(plan, plan.confirmation), /changed/)
|
|
123
|
+
await assert.rejects(fs.stat(sessionDir), { code: 'ENOENT' })
|
|
124
|
+
await fs.writeFile(exportReceipt.output, original)
|
|
125
|
+
const receipt = await applyReverseMigration(plan, plan.confirmation)
|
|
126
|
+
assert.equal(receipt.status, 'verified')
|
|
127
|
+
assert.equal(receipt.messages, 1)
|
|
128
|
+
const before = await fs.readFile(receipt.output)
|
|
129
|
+
assert.equal(JSON.parse(before.toString().split('\n', 1)[0]!).cwd, workspace)
|
|
130
|
+
assert.equal(sdk.SessionManager.open(receipt.output).buildSessionProjection().messages[0]?.content, message.message.content)
|
|
131
|
+
assert.ok((await sdk.SessionManager.list(workspace)).some(item => item.id === header.id))
|
|
132
|
+
assert.ok(!(await sdk.SessionManager.list(sourceWorkspace)).some(item => item.id === header.id))
|
|
133
|
+
await assert.rejects(planReverseMigration(options), /already has session/)
|
|
134
|
+
const copy = await planReverseMigration({ ...options, onConflict: 'copy' })
|
|
135
|
+
assert.notEqual(copy.sessionId, receipt.sessionId)
|
|
136
|
+
assert.equal((await applyReverseMigration(copy, copy.confirmation)).status, 'verified')
|
|
137
|
+
assert.deepEqual(await fs.readFile(receipt.output), before)
|
|
138
|
+
assert.deepEqual(await fs.readFile(exportReceipt.output), original)
|
|
139
|
+
} finally {
|
|
140
|
+
if (previousPiHome === undefined) delete process.env.PI_CODING_AGENT_DIR
|
|
141
|
+
else process.env.PI_CODING_AGENT_DIR = previousPiHome
|
|
142
|
+
if (previousSessionDir !== undefined) process.env.PI_CODING_AGENT_SESSION_DIR = previousSessionDir
|
|
143
|
+
await fs.rm(temp, { recursive: true, force: true, maxRetries: 5 })
|
|
144
|
+
}
|
|
145
|
+
})
|