dsh-compact-pi 0.2.3-b3 → 0.2.3-b5

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/dist/index.js CHANGED
@@ -30631,8 +30631,8 @@ var SessionProjectionRegistry = class extends Service {
30631
30631
  // package.json
30632
30632
  var package_default = {
30633
30633
  name: "dsh-compact-pi",
30634
- version: "0.2.3-b3",
30635
- dcpVersion: "0.2.3b3",
30634
+ version: "0.2.3-b5",
30635
+ dcpVersion: "0.2.3b5",
30636
30636
  type: "module",
30637
30637
  description: "DeepSeek Harness context compaction for pi: upstream engine, policy, token meter and pruner",
30638
30638
  repository: {
@@ -34859,13 +34859,14 @@ function dshMessageToPi(message, time3, toolNames, imageToPi) {
34859
34859
  }
34860
34860
 
34861
34861
  // src/dsh/sync.ts
34862
- function createSyncState() {
34862
+ function createSyncState({ persistent = false } = {}) {
34863
34863
  return {
34864
34864
  turn: 1,
34865
34865
  step: 0,
34866
34866
  turnStarted: false,
34867
34867
  systemSeq: void 0,
34868
34868
  stepOpen: false,
34869
+ persistent,
34869
34870
  seen: /* @__PURE__ */ new Set(),
34870
34871
  toolCalls: /* @__PURE__ */ new Map(),
34871
34872
  appended: 0
@@ -34888,6 +34889,11 @@ function ensureTurn(session, state) {
34888
34889
  function appendSystem(session, state, entry, message, systemPrompt) {
34889
34890
  if (state.systemSeq !== void 0) return;
34890
34891
  ensureTurn(session, state);
34892
+ if (state.persistent && !state.stepOpen) {
34893
+ state.step += 1;
34894
+ append(session, "step/start", { turn: state.turn, step: state.step });
34895
+ state.stepOpen = true;
34896
+ }
34891
34897
  let content = piContentToDsh(
34892
34898
  systemPrompt && systemPrompt.trim().length > 0 ? systemPrompt : typeof message.content === "string" ? message.content : []
34893
34899
  );
@@ -1,4 +1,4 @@
1
- # DCP 共同能力契约(0.2.3b3)
1
+ # DCP 共同能力契约(0.2.3b5)
2
2
 
3
3
  目标是在双方都支持的场景中复用上游插件的行为。功能让步意味着不纳入比较场景,不模拟 DSH 的全部宿主能力,也不回滚已经完成的压缩。
4
4
 
package/docs/help.md CHANGED
@@ -9,10 +9,10 @@ pi install npm:dsh-compact-pi@latest
9
9
  Use the explicit tag while the npm release has a prerelease version. The GitHub tag is also available:
10
10
 
11
11
  ```bash
12
- pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b3
12
+ pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b5
13
13
  ```
14
14
 
15
- Restart pi or run `/reload` while idle. `/dcp-status` should show DCP `0.2.3b3` and DSH `0.2.3-alpha.2`. DCP is tested with pi 1.5.2 and 1.6.1 and needs Node.js `^24.22.3 || >=26.13.1`. Check `pi list` for duplicate installations if commands or warnings appear twice. See the [update instructions](../README.md#updating-an-existing-installation) for pinned tags and branch installs.
15
+ Restart pi or run `/reload` while idle. `/dcp-status` should show DCP `0.2.3b5` and DSH `0.2.3-alpha.2`. DCP is tested with pi 1.5.2 and 1.6.1 and needs Node.js `^24.22.3 || >=26.13.1`. Check `pi list` for duplicate installations if commands or warnings appear twice. See the [update instructions](../README.md#updating-an-existing-installation) for pinned tags and branch installs.
16
16
 
17
17
  ## Compaction and model selection
18
18
 
@@ -25,7 +25,15 @@ If a historical summary model is unavailable in pi, use the picker to select an
25
25
 
26
26
  ## Move a session between pi and DSH
27
27
 
28
- Use the CLI from the unpacked package or a development checkout with `node dist/dcp-session.mjs --help`. npm installs also expose the `dcp-session` command. Exit the active session or work from a copy and choose a separate output path.
28
+ Run `dcp-session migrate` in a terminal, or ask the `dcp-migrate-to-dsh` skill to guide you. The skill asks one key question at a time and waits for your answer. Once the destination and any conflicts are settled, it shows the exact output path and asks whether to write. Agents use `migrate plan` and `migrate apply` to keep the preview and write separate. See the [command examples](../skills/dcp-migrate-to-dsh/references/commands.md).
29
+
30
+ - **Portable export** writes a new folder under the export directory you choose. Move that whole folder to keep the JSONL and images together.
31
+ - **Direct import** uses the target backend's version, profile, data home, session directory, workspace, and encoding. Run on the target machine. On Windows, use Windows Node.js and Windows paths. On Linux, use the data paths of the backend your desktop client actually connects to.
32
+ - **Conflicts** stop the default plan. You can explicitly choose a new session ID while preserving the existing one, or recover the Pi entries from a recognized mixed log while preserving the original file. Encoding mismatches require a corrected target configuration.
33
+
34
+ The import receipt confirms a write. Open the imported history in the chosen Desktop or TUI, or run `migrate verify-web` to check both the list and history of the approved Web instance.
35
+
36
+ The CLI can also run low-level conversions for scripts. In a checkout use `node dist/dcp-session.mjs --help`. Exit the active source session or work from a copy.
29
37
 
30
38
  ```bash
31
39
  dcp-session pi2dsh-import session.pi.jsonl
@@ -36,10 +44,12 @@ pi --session imported.pi.jsonl
36
44
 
37
45
  `pi2dsh-import` writes a new session into the DSH 0.2.3-alpha.2 V4 store and prints its ID and working directory. Open it in DSH's session picker or run `dsh-tui --resume <session-id>` from that directory. The default store is `$DSH_HOME/sessions` with Zstandard encoding. Pass the configured session root as the second argument for a custom profile. Add `--plain` for profiles using plaintext JSONL. An existing session with the same ID and workspace is left intact.
38
46
 
39
- The package includes [dcp-migrate-to-dsh](../skills/dcp-migrate-to-dsh/SKILL.md). In Pi, request a migration using the skill or run `/skill:dcp-migrate-to-dsh`. To invoke it from DSH, copy its directory into `$DSH_HOME/skills` (default `~/.dsh/skills`). Both hosts need access to the converter and source file.
47
+ In Pi, request a migration or run `/skill:dcp-migrate-to-dsh`. To invoke it from DSH, copy the [skill directory](../skills/dcp-migrate-to-dsh) into `$DSH_HOME/skills` (default `~/.dsh/skills`). Both hosts need access to the converter and source file.
40
48
 
41
49
  The export archives pi entries, including the branch tree, and gives DSH the active compacted context. Reimporting an unchanged export restores the archived pi entries. Reimporting a session after continuing in DSH uses the live DSH context as a linear pi session. Keep the original file for its full history and host-specific metadata.
42
50
 
51
+ The CLI report counts archived source messages, which may exceed the number shown in DSH. Incomplete tool exchanges are kept in the Pi archive and omitted from the DSH active context.
52
+
43
53
  Image references use `DSH_HOME`, which defaults to `~/.dsh`. Keep that attachment store with the logs when moving them across machines. If image import reports a missing object, point `DSH_HOME` at the corresponding store. For compressed DSH input, install the `zstd` command.
44
54
 
45
55
  If old messages seem to disappear after a pi upgrade, confirm that the session path and branch are correct. A standard pi session shows the latest active summary and retained messages while the raw JSONL still holds the earlier entries. Files written by the v0.1 core patch need [legacy migration](native-session-codec.md). A file containing both DSH events and appended pi entries requires separate recovery of each part.
@@ -1,6 +1,6 @@
1
1
  # Publishing dsh-compact-pi
2
2
 
3
- Use Node.js `^24.22.3 || >=26.13.1`. The package version `0.2.3-b3` corresponds to the displayed version `0.2.3b3`. Keep the upstream DSH base version and increment the DCP build suffix for subsequent releases.
3
+ Use Node.js `^24.22.3 || >=26.13.1`. The package version `0.2.3-b5` corresponds to the displayed version `0.2.3b5`. Keep the upstream DSH base version and increment the DCP build suffix for subsequent releases.
4
4
 
5
5
  ## Verify a release
6
6
 
@@ -21,13 +21,13 @@ See [testing](testing.md) for the resume and migration matrix. If the source sna
21
21
  Authenticate interactively with `npm login`, then verify the intended publisher with `npm whoami`. Do not put authentication tokens in this repository.
22
22
 
23
23
  ```bash
24
- npm publish ./dsh-compact-pi-0.2.3-b3.tgz --access public --tag latest
24
+ npm publish ./dsh-compact-pi-0.2.3-b5.tgz --access public --tag latest
25
25
  ```
26
26
 
27
27
  The package's `publishConfig` defaults to the public npm registry and the `beta` tag for candidate builds. Use the tested tarball and set `--tag latest` for the public release. Verify with `npm view dsh-compact-pi dist-tags`. Users can install with `pi install npm:dsh-compact-pi@latest` or pin the exact version.
28
28
 
29
29
  ```bash
30
- pi install npm:dsh-compact-pi@0.2.3-b3
30
+ pi install npm:dsh-compact-pi@0.2.3-b5
31
31
  ```
32
32
 
33
33
  Restart pi or run `/reload`, then `/dcp-status`. Remove a previous local DCP package entry before loading the published package to avoid registering the extension twice. Run `pi list` to identify the installed source and `pi remove <source>` to remove it.
@@ -39,7 +39,7 @@ The package is listed in the [Pi package catalog](https://pi.dev/packages/dsh-co
39
39
  GitHub also hosts tagged releases:
40
40
 
41
41
  ```bash
42
- pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b3
42
+ pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b5
43
43
  ```
44
44
 
45
45
  A Git release must include `dist/`, `vendor/` and the package manifest so installing it does not require development dependencies or an upstream checkout. Tag only the verified release commit. Keep source provenance and third-party licenses in the repository and tarball.
package/docs/testing.md CHANGED
@@ -17,8 +17,25 @@ node --import tsx --test test/images-convert.test.ts test/differential.test.ts
17
17
 
18
18
  The resume test installs the built npm tarball in a temporary directory and loads its extension in the candidate pi SDK. It exercises automatic compaction and pi's manual compaction path with a retained PNG. Both paths must save a native compaction checkpoint and image assets, continue with the summary and retained image, and preserve them when the session is reopened.
19
19
 
20
+ Run `node --import tsx --test test/migration.test.ts` on Windows or Linux to test explicit destination selection, read-only planning, stale plans, duplicate IDs, encoding conflicts, and opt-in recovery of Pi entries. The GitHub Actions matrix runs this test on both hosts. For desktop release checks, also open a synthetic imported session in the target app and verify its history.
21
+
20
22
  The test also generates a native pi checkpoint and a separate snapshot cut at the DCP journal commit using an earlier DCP release. On the candidate pi it checks that the next provider request contains the old summary, a retained message and the new user request. It disables fresh summarization during replay so a lost checkpoint fails the test. It runs the CLI in both directions, checking for inactive branch leakage, native context edits, archive fidelity and continued work after adding a message in DSH.
21
23
 
22
24
  The baseline bundle comes from Git commit `1f43099c0273a3edcbe5353a4aaf32884efd1fc9`. The candidate pi package is installed from npm into a temporary directory. If a shallow clone lacks the baseline, fetch the `v0.2.2-b3` tag before running the test. Other builds and the unit suite can run without that Git history.
23
25
 
24
26
  The **Pi session compatibility** workflow runs the same test on Ubuntu and native Windows for pi 1.5.2 and the candidate version. Run it manually with an exact candidate pi version before extending the supported matrix. On Windows, run `npm ci` and `npm run test:resume -- 1.6.1` in a native terminal with Windows Node.js and Git for Windows available on `PATH`. Both platforms use stubbed provider responses to verify session behavior. Summary quality with a live model is outside the test's scope.
27
+
28
+ ## Observation: task corrections carry over after compaction
29
+
30
+ **Status: observe over time.** In a November 2026 zup session, the user clarified that a specific prompt-enhancement workflow took a reference image and used I2I. The checkpoint restated that choice as a general preference. The reported symptom was that later workflow designs also used I2I, including when the new task called for a fresh image from text. How often this occurs in normal long-running sessions remains open.
31
+
32
+ In a controlled replay, DeepSeek Flash planned a separate poster workflow whose form had exactly three text fields. Each condition ran eight times. Both checkpoint variants also preserved the reference-image input when resuming the original enhancer in all eight trials.
33
+
34
+ | Behavior on the new task | Recorded wording | Correction scoped to the original workflow | No checkpoint |
35
+ |---|---:|---:|---:|
36
+ | Added a required reference image | 5/8 | 1/8 | 0/8 |
37
+ | Included I2I in the processing steps | 7/8 | 6/8 | 0/8 |
38
+
39
+ Explicit scope reduced the extra input requirement in this fixture. I2I routing persisted in six of eight scoped trials. Keep the scope rule in the experiment and retain the existing default summary behavior while collecting more cases. For future reports, record the DCP and DSH versions, model, compaction trigger, a redacted correction with its original task, and what the subsequent plan actually did. Check both required inputs and processing steps.
40
+
41
+ The optional harness uses Pi's configured credentials and sends a de-identified fixture. Run `node --import tsx scripts/test-correction-scope.ts deepseek deepseek-flash 8 text-form` to reproduce the fixed-form test. Use `checkpoint` for the less constrained poster request or `summaries` for two successive compactions before continuation. The harness prints the checkpoints or workflow plans as JSON for review.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-compact-pi",
3
- "version": "0.2.3-b3",
4
- "dcpVersion": "0.2.3b3",
3
+ "version": "0.2.3-b5",
4
+ "dcpVersion": "0.2.3b5",
5
5
  "type": "module",
6
6
  "description": "DeepSeek Harness context compaction for pi: upstream engine, policy, token meter and pruner",
7
7
  "repository": {
@@ -0,0 +1,187 @@
1
+ /** Paired live test. Uses Pi's configured model and synthetic, de-identified dialogue. */
2
+ import assert from 'node:assert/strict'
3
+ import { mkdtemp, rm } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import path from 'node:path'
6
+ import { ModelRuntime } from '@earendil-works/pi-coding-agent'
7
+ import { createEngine, enterSession } from '../src/dsh/engine.ts'
8
+ import { createSession } from '../src/dsh/session.ts'
9
+ import { createSyncState, syncPiEntries, closeTurn } from '../src/dsh/sync.ts'
10
+
11
+ const [provider = 'deepseek', modelId = 'deepseek-flash', trials = '1', scenario = 'summaries'] = process.argv.slice(2)
12
+ const attempts = Number(trials)
13
+ assert.ok(Number.isInteger(attempts) && attempts > 0 && attempts <= 10)
14
+ assert.ok(['summaries', 'checkpoint', 'text-form'].includes(scenario), 'Choose summaries, checkpoint, or text-form')
15
+ const runtime = await ModelRuntime.create({ refreshOnCreate: false })
16
+ const model = runtime.getModel(provider, modelId)
17
+ assert.ok(model, `Missing configured model ${provider}/${modelId}`)
18
+ const root = await mkdtemp(path.join(tmpdir(), 'dcp-scope-'))
19
+ const system = 'You are a coding assistant collaborating on image-generation workflows.'
20
+ const suffix = '\n\n' + [
21
+ 'When recording a user correction, keep its object, triggering condition, and scope together.',
22
+ 'Record a correction as task-specific unless the user explicitly made it a standing preference. Name the work item even when the surrounding conversation will be removed.',
23
+ 'When merging a prior checkpoint, preserve these scope limits. If the scope of an old correction is unclear, mark it as unclear and avoid applying it to other tasks.',
24
+ ].join('\n')
25
+
26
+ type Turn = [role: 'user' | 'assistant', text: string]
27
+ // Reconstructed from the PE mini-project: a nearby, unrelated T2I preset and
28
+ // a correction about the standalone PE that receives a reference image.
29
+ const caseHistory: Turn[] = [
30
+ ['user', 'Park the seed and LoRA investigation on the existing T2I preset. I want to extract the Qwen-Image-2.1 prompt enhancer into its own standalone workflow.'],
31
+ ['assistant', 'I extracted the prompt enhancer from the image editing workflow. It rewrites prompts for Qwen Image.'],
32
+ ['user', 'Stop changing the workflow for a moment. I need the accelerated local model to turn the prompt I enter into a suitable Qwen Image prompt. Let us align on the task first.'],
33
+ ['assistant', 'If the input is just text, I would use the T2I prompt enhancer.'],
34
+ ['user', 'Who said I wanted T2I? I want I2I.'],
35
+ ['assistant', 'Will you also provide a reference image?'],
36
+ ['user', 'Of course I will provide a reference image as well.'],
37
+ ['assistant', 'Understood. Input is a reference image and an edit instruction; output is a rewritten prompt.'],
38
+ ]
39
+ // DSH rejects a framed checkpoint that is larger than its input. Supply
40
+ // compressible background in both rounds without adding scope instructions.
41
+ const background: Turn[] = [
42
+ ['user', 'The earlier build diagnostics are now complete.'],
43
+ ['assistant', Array.from({ length: 120 }, (_, index) =>
44
+ `Read-only fixture check ${index + 1}: input schema and registry diagnostic both passed.`,
45
+ ).join('\n')],
46
+ ]
47
+
48
+ async function summarize(history: Turn[], scoped: boolean) {
49
+ const signal = AbortSignal.timeout(90000)
50
+ const bundle = await createEngine({
51
+ attachmentHome: () => root,
52
+ model: () => model,
53
+ findModel: () => model,
54
+ systemPrompt: () => system,
55
+ complete: async (_model, context, options) => {
56
+ const block = context.messages.at(-1).content[0]
57
+ assert.ok(block.text.startsWith('You are now acting as a compaction engine'))
58
+ if (scoped) block.text += suffix
59
+ return runtime.complete(model, context, options)
60
+ },
61
+ }, { headroomTokens: 512, retainTokens: 32, maxTokens: 2048 })
62
+ const { session } = createSession('scope-test-' + crypto.randomUUID())
63
+ const leave = enterSession(bundle, session)
64
+ try {
65
+ const state = createSyncState()
66
+ const items: Turn[] = [
67
+ ...background,
68
+ ...history,
69
+ ['user', 'Hold there for now. I will specify which work item to continue next.'],
70
+ ]
71
+ syncPiEntries(session, [
72
+ { type: 'message', id: 'system', message: { role: 'system', content: system } },
73
+ ], state)
74
+ session.append('request/header', {
75
+ header: { config: { provider, model: modelId, maxTokens: model.maxTokens } },
76
+ reason: 'initial',
77
+ })
78
+ syncPiEntries(session, items.map(([role, text], index) => ({
79
+ type: 'message', id: `input-${index}`,
80
+ message: role === 'user' ? { role, content: text } : {
81
+ role, provider, model: modelId, stopReason: 'stop',
82
+ content: [{ type: 'text', text }],
83
+ },
84
+ })), state)
85
+ closeTurn(session, state)
86
+ bundle.flush = async () => {}
87
+ await bundle.engine.compactNow({
88
+ session, options: { provider, model: modelId },
89
+ runMaintenance: task => task(signal),
90
+ }, signal)
91
+ const checkpoint = session.surface.nodes
92
+ .map(seq => session.deriveEventMessage(session.eventAt(seq)!))
93
+ .find(message => message?.source?.kind === 'compact-checkpoint')
94
+ assert.ok(checkpoint, 'Expected compaction to produce a real checkpoint')
95
+ return checkpoint.content.map((block: { text?: string }) => block.text).join('\n')
96
+ } finally {
97
+ leave()
98
+ await bundle.ctx.fiber.dispose()
99
+ }
100
+ }
101
+
102
+ const followups = [
103
+ ['resumeA', 'Resume the standalone prompt enhancer we aligned on. Which kind of input should I wire up?', 'I2I'],
104
+ ['newB', 'New work item: generate an entirely new product poster from a text brief. I have no input image. What workflow mode should this work item use?', 'T2I'],
105
+ ['newUnspecified', 'Separate new workflow for product posters. I have not said whether there will be an input image. Is either workflow mode already required for this new work item?', 'UNCLEAR'],
106
+ ]
107
+
108
+ async function completeText(checkpoint: string | undefined, request: string) {
109
+ const result = await runtime.complete(model, {
110
+ systemPrompt: system,
111
+ messages: [
112
+ ...(checkpoint ? [{ role: 'user' as const, content: checkpoint, timestamp: 1 }] : []),
113
+ { role: 'user', content: request, timestamp: 2 },
114
+ ],
115
+ }, { maxTokens: 2048, signal: AbortSignal.timeout(90000) })
116
+ if (result.stopReason === 'error' || result.stopReason === 'aborted')
117
+ throw new Error(result.errorMessage ?? result.stopReason)
118
+ return result.content.flatMap(block => block.type === 'text' ? [block.text.trim()] : []).join('\n')
119
+ }
120
+
121
+ // A redacted extract of the recorded zup checkpoint. Change only the scope
122
+ // of the two statements that generalized the correction.
123
+ const checkpoint = `This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.
124
+
125
+ <compacted-summary>
126
+ ## Primary Request and Intent
127
+ - Extract the prompt enhancer into its own standalone workflow.
128
+ - The assistant suggested T2I. The user corrected the choice to I2I.
129
+ ## Key Technical Concepts
130
+ - Qwen Image has separate PE-I2I (reference image and edit instruction) and PE-T2I (text brief) prompt enhancers. User wants **I2I only**.
131
+ ## Critical Context
132
+ - Work on the existing T2I preset is parked.
133
+ - User explicitly wants **I2I**, not T2I; will always supply a reference image.
134
+ </compacted-summary>`
135
+ const scopedCheckpoint = checkpoint
136
+ .replace('User wants **I2I only**.', 'For the standalone prompt enhancer, the user wants **I2I only**.')
137
+ .replace('User explicitly wants **I2I**, not T2I; will always supply a reference image.', 'For this standalone prompt enhancer, the user wants **I2I**, not T2I, and will supply a reference image.')
138
+
139
+ async function comparePlans(trial: number, arm: 'recorded' | 'scoped' | 'no-checkpoint') {
140
+ const newWorkflow = scenario === 'text-form'
141
+ ? '另做一个读书会活动海报工作流。表单固定就三个字段:活动名称、主题、配色。输出一张新的活动海报。先列出运行所需的输入项和主要处理节点。'
142
+ : '另做一个商品宣传海报工作流,从表单里填商品名称、卖点和画面风格,输出一张新的宣传海报。先列出我需要填写或上传的输入项和主要处理节点。'
143
+ const probes = [
144
+ ['resumeA', '继续做刚才那个独立提示词增强工作流。先列出我需要填写或上传的输入项和主要处理节点。', true],
145
+ ['newB', newWorkflow, false],
146
+ ] as const
147
+ const selected = arm === 'no-checkpoint' ? probes.slice(1) : probes
148
+ const context = arm === 'scoped' ? scopedCheckpoint : arm === 'recorded' ? checkpoint : undefined
149
+ const results = await Promise.all(selected.map(async ([name, request, expectedImage]) => {
150
+ const answer = await completeText(context, request +
151
+ '\n只输出 JSON:{"requiredInputs":[{"name":"输入名称","type":"text/image/number/other"}],"steps":["处理步骤"]}。requiredInputs 只列运行所需输入。')
152
+ const json = answer.trim().replace(/^\x60\x60\x60(?:json)?\s*|\s*\x60\x60\x60$/gi, '')
153
+ const plan = JSON.parse(json)
154
+ assert.ok(Array.isArray(plan.requiredInputs) && Array.isArray(plan.steps), 'Expected workflow plan JSON')
155
+ const requiredImage = plan.requiredInputs.some((input: { type: string }) => input.type.toLowerCase() === 'image')
156
+ const editingSteps = plan.steps.filter((step: string) => /\bi2i\b|图生图|image-to-image|img2img/i.test(step))
157
+ return { name, expectedImage, requiredImage, editingSteps, plan }
158
+ }))
159
+ console.log(JSON.stringify({ trial, arm, results }))
160
+ }
161
+
162
+ try {
163
+ for (let trial = 1; trial <= attempts; trial++) {
164
+ if (scenario !== 'summaries') {
165
+ await Promise.all([comparePlans(trial, 'recorded'), comparePlans(trial, 'scoped')])
166
+ await comparePlans(trial, 'no-checkpoint')
167
+ continue
168
+ }
169
+ await Promise.all([false, true].map(async scoped => {
170
+ const first = await summarize(caseHistory, scoped)
171
+ const second = await summarize([
172
+ ['user', first],
173
+ ['assistant', 'The standalone workflow design is aligned. We can continue once a work item is specified.'],
174
+ ], scoped)
175
+ const results = await Promise.all(followups.map(async ([name, request, expected]) => {
176
+ const answer = await completeText(second, request! + '\nStart your answer with exactly one of: I2I, T2I, or UNCLEAR. Then give a one-sentence reason.')
177
+ return { name, expected, actual: answer.match(/\b(I2I|T2I|UNCLEAR)\b/i)?.[0]?.toUpperCase(), answer }
178
+ }))
179
+ console.log(JSON.stringify({
180
+ trial, arm: scoped ? 'scoped' : 'upstream',
181
+ summary1: first, summary2: second, results,
182
+ }))
183
+ }))
184
+ }
185
+ } finally {
186
+ await rm(root, { recursive: true, force: true })
187
+ }
@@ -1,14 +1,21 @@
1
1
  ---
2
2
  name: dcp-migrate-to-dsh
3
- description: Migrate a selected pi conversation into DeepSeek Harness so the user can resume it, including DCP summaries, retained messages, and images. Use when asked to continue a pi session in DSH or to export it for a DSH host.
3
+ description: Guide a user through exporting a selected Pi session or importing it into a confirmed DeepSeek Harness Desktop, Web, or TUI target. Use for Pi-to-DSH session migration and portable exports.
4
4
  ---
5
5
 
6
- # Migrate a pi session to DSH
6
+ # Migrate a Pi session to DSH
7
7
 
8
- 1. Resolve the source to one native pi session JSONL file. Use the path the user or host provides. If given a session ID, match the ID in a pi session header under the relevant pi agent directory (`PI_CODING_AGENT_DIR` or `~/.pi/agent`). When only the project is specified, match its `cwd` and ask which session to use if there are multiple candidates. Read header metadata only for selection. Let DCP read the conversation.
9
- 2. Find the converter. Use `dcp-session` if available, or run `node <dsh-compact-pi-package>/dist/dcp-session.mjs`. When loading this bundled skill, the package root is two directories above this skill folder. In a standard pi npm install it is also under `<pi-agent-dir>/npm/node_modules/dsh-compact-pi`. Check `--help` for `pi2dsh-import` before importing.
10
- 3. Verify the target DSH version and session store. This importer targets the DSH 0.2.3-alpha.2 V4 JSONL layout. Use the target DSH process's `DSH_HOME` for attachments and the target profile's JSONL session root and compression. The defaults are `$DSH_HOME/sessions` (or `~/.dsh/sessions`) and Zstandard. Use `--plain` only when the profile uses plaintext.
11
- 4. Import with `dcp-session pi2dsh-import "<pi-jsonl>"`. Append the configured session root when it differs from the default. Append `--plain` for plaintext. If DCP reports an existing session ID, preserve the existing session and report the conflict. If the target runs on a different machine, run the import there using a securely copied source and a target workspace path valid on that machine. For a portable export, use `dcp-session pi2dsh "<pi-jsonl>" "<new-export.jsonl>"` and keep the corresponding DSH attachment store with it.
12
- 5. Report the returned session ID and project path. Resume from that project using the target UI's session picker or its explicit resume option, for example `dsh-tui --resume "<session-id>"` for the DSH TUI. The import creates a separate DSH session. The current agent session stays open. Ask before sending a first prompt in the imported session.
8
+ Use `dcp-session migrate` or `node <package-root>/dist/dcp-session.mjs migrate`. Check `--help`. The bundled skill is two directories below the package root. When installed under a skill home, resolve its symlink or locate the DCP package from Pi's package list.
13
9
 
14
- DCP projects the persisted pi branch into DSH and archives the original pi entries. A portable export and an immediate reverse conversion preserve the pi archive. A continued DSH session imports back as the effective DSH context. Avoid printing raw session rows or attachment data in tool output.
10
+ ## Ask one question and wait for the answer
11
+
12
+ Ask in the user's language. Use the host's user-input tool when available, or ask in chat and end the turn. Offer short choices when known. Never present a configuration table, a questionnaire covering multiple decisions, or raw plan JSON to the user. Skip questions whose answers the user already provided explicitly. Detection and defaults supply suggestions. A missing or ambiguous answer stays unresolved until the user answers.
13
+
14
+ 1. **Source.** Ask which Pi session to use if it is unclear. Use `migrate sources --id <id>` or `migrate sources --cwd <absolute-project>` to find candidates. Even a single match is a suggestion when the user has only named the project.
15
+ 2. **Destination.** Ask whether to export a portable folder or import directly. For portable export, ask where to put the folder. For direct import, ask which machine and DSH instance to use. If that still leaves the profile or client ambiguous, ask which one. Confirm the destination workspace, then ask separately about each unresolved storage detail. Use [target details](references/commands.md#target-details) to identify what needs verification.
16
+ 3. **Conflict.** Run `migrate plan` with the confirmed selection and a fresh `--plan-file`. Ask about one conflict at a time. For a duplicate, ask whether to stop or use a separate ID (`--on-conflict copy`). For a mixed log, ask whether to stop, choose another file, or recover only the Pi entries (`--recover-pi-entries`). Recovery leaves the source intact. Ask for corrected input on an encoding or format mismatch. Rerun the plan only after the user decides.
17
+ 4. **Write approval.** Show the source session, target and exact output path in a short sentence or a few lines. Include the separate attachment location, new ID or recovery choice only when relevant. Ask a single question, such as “现在写入这个位置吗?” Wait for explicit approval of this plan. Then run `migrate apply --plan-file <file> --confirm <code>` using the saved plan and its code. If the plan becomes stale, preview it again and ask for fresh approval.
18
+
19
+ Report the receipt. For Web, use `migrate verify-web` with an approved launch-URL file when available. For Desktop or TUI, verify the imported history using the session picker. If app access is unavailable, report the write with UI verification pending. Leave the imported session idle until the user asks to send a prompt.
20
+
21
+ The scripts handle reading, recovery, paths, conflict checks, attachments, and conversion. Keep session contents and Web credentials out of the conversation.
@@ -0,0 +1,33 @@
1
+ # Migration commands
2
+
3
+ Run from the target OS, using an absolute path to the source copy accessible there. A Windows destination uses Windows paths and Windows Node.js. Quote paths with spaces.
4
+
5
+ ## Direct import
6
+
7
+ ```text
8
+ dcp-session migrate plan --source "<pi.jsonl>" --target windows-desktop --profile desktop --dsh-version 0.2.2-rc.5 --dsh-home "<DSH home>" --session-root "<session directory>" --workspace "<existing workspace>" --encoding zstd --plan-file "<new plan.json>"
9
+ dcp-session migrate apply --plan-file "<plan.json>" --confirm "<code>"
10
+ ```
11
+
12
+ Use `linux-desktop` for a Linux desktop client on the same machine as its compatible DSH backend. Use the backend's version and storage settings. For Web or TUI use that instance or profile's settings. Distribution version and backend version can differ.
13
+
14
+ For Desktop and Web, choose a workspace already shown in the target app. Refresh the session list if the app was already open when the file was written.
15
+
16
+ ## Target details
17
+
18
+ The direct-import plan needs the target machine and client, instance or profile, backend version, DSH home for attachments, session root, workspace, and encoding. Read the selected instance's settings when available. Use `migrate environment` to identify the current host and suggest paths. Ask separately before using any unresolved value. A Windows Desktop import runs under Windows Node.js. WSL is a separate environment, even on the same machine.
19
+
20
+ ## Portable export
21
+
22
+ ```text
23
+ dcp-session migrate plan --source "<pi.jsonl>" --target portable --export-dir "<existing directory>" --plan-file "<new plan.json>"
24
+ ```
25
+
26
+ After approval, use the same apply command. Move the complete output folder to keep the DSH JSONL and attachments together. Its directory is the attachment home for that copy.
27
+
28
+ ## Checks
29
+
30
+ - `migrate sources` reads only headers. Use `--pi-home` when the source uses a non-default Pi agent directory.
31
+ - `migrate environment` shows the script's current host and paths to use as suggestions.
32
+ - `migrate verify-web --url-file "<launch URL file>" --session-id "<id>" --events <count>` checks the list and history. Use the receipt's event count. The private file contains one launch URL belonging to the confirmed Web instance.
33
+ - `written` confirms the disk write. `verified` confirms both Web reads.
package/src/codec.ts CHANGED
@@ -79,6 +79,38 @@ export function projectPiForDsh(entries: readonly SessionEntry[]) {
79
79
  return convertToLlm(system ? [system, ...conversation] : conversation)
80
80
  .map((message, index) => ({ type: 'message', id: `projected-${index}`, message }))
81
81
  }
82
+
83
+ /** A native DSH step can only carry tools with both an advertised call and a result. */
84
+ function settledTools(projected: ReturnType<typeof projectPiForDsh>) {
85
+ const result: typeof projected = []
86
+ const pending = new Set<string>()
87
+ for (const [index, entry] of projected.entries()) {
88
+ const { message } = entry
89
+ if (message.role === 'toolResult') {
90
+ if (pending.delete(message.toolCallId)) result.push(entry)
91
+ continue
92
+ }
93
+ pending.clear()
94
+ if (message.role !== 'assistant' || message.stopReason === 'error' || message.stopReason === 'aborted') {
95
+ result.push(entry)
96
+ continue
97
+ }
98
+ const followingResults = new Set<string>()
99
+ for (let next = index + 1; next < projected.length; next++) {
100
+ const following = projected[next]!.message
101
+ if (following.role !== 'toolResult') break
102
+ followingResults.add(following.toolCallId)
103
+ }
104
+ const content = message.content.filter((block) => {
105
+ if (block.type !== 'toolCall') return true
106
+ if (!block.id || !followingResults.delete(block.id)) return false
107
+ pending.add(block.id)
108
+ return true
109
+ })
110
+ if (content.length) result.push({ ...entry, message: { ...message, content } })
111
+ }
112
+ return result
113
+ }
82
114
  function piHeader(header: DshHeader): PiHeader {
83
115
  return {
84
116
  type: 'session',
@@ -128,21 +160,22 @@ export function dshRowsFromPi(
128
160
  _file?: string,
129
161
  imageToDsh?: (image: any) => any,
130
162
  projected = projectPiForDsh(entries),
163
+ destination?: Pick<DshHeader, 'id' | 'cwd'>,
131
164
  ): string {
132
165
  const header: DshHeader = {
133
166
  type: 'session',
134
167
  version: SESSION_FORMAT_VERSION,
135
- id: pi.id,
168
+ id: destination?.id ?? pi.id,
136
169
  createdAt: Date.parse(pi.timestamp),
137
- cwd: pi.cwd,
170
+ cwd: destination?.cwd ?? pi.cwd,
138
171
  isSeeded: false,
139
172
  delegationDepth: 0,
140
- ...(pi.parentSession ? { parentSession: pi.parentSession } : {}),
173
+ ...(!destination && pi.parentSession ? { parentSession: pi.parentSession } : {}),
141
174
  }
142
175
  const session = Session.create(header.id, [], headerForSession(header))
143
176
  appendPluginRecord(session, PI_HEADER, JSON.parse(JSON.stringify(pi)))
144
- const state = createSyncState()
145
- syncPiEntries(session, projected, state, { imageToDsh })
177
+ const state = createSyncState({ persistent: true })
178
+ syncPiEntries(session, settledTools(projected), state, { imageToDsh })
146
179
  closeTurn(session, state)
147
180
  // Preserve every entry, its original id, parent and metadata. DSH's message
148
181
  // surface is an export view; pi resumes from the lossless archive records.
@@ -162,9 +195,10 @@ export function writeDshFromPi(
162
195
  entries: readonly any[],
163
196
  imageToDsh?: (image: any) => any,
164
197
  projected?: ReturnType<typeof projectPiForDsh>,
198
+ destination?: Pick<DshHeader, 'id' | 'cwd'>,
165
199
  ): void {
166
200
  mkdirSync(path.dirname(file), { recursive: true })
167
- const body = dshRowsFromPi(header, entries, file, imageToDsh, projected)
201
+ const body = dshRowsFromPi(header, entries, file, imageToDsh, projected, destination)
168
202
  const tmp = `${file}.${process.pid}.tmp`
169
203
  writeFileSync(tmp, body)
170
204
  renameSync(tmp, file)
@@ -3,7 +3,7 @@
3
3
  import { promises as fs } from 'node:fs'
4
4
  import * as path from 'node:path'
5
5
  import type { Session } from '../../vendor/dsh-runtime.mjs'
6
- import { createSession, DSH_FORMAT_VERSION, restoreSession } from './session.ts'
6
+ import { createSession, DSH_FORMAT_VERSION, restoreSession, type DshHeader } from './session.ts'
7
7
  import { createSyncState, syncPiEntries } from './sync.ts'
8
8
  import { openImageBridge } from './images.ts'
9
9
  import { projectSurface } from './projection.ts'
@@ -101,20 +101,26 @@ export async function piToDsh(
101
101
  if (path.resolve(input) === path.resolve(output))
102
102
  throw new Error('Choose a separate output file for session conversion')
103
103
  const pi = await readPiSession(input)
104
+ return { input, output, ...await exportPiSession(pi, output) }
105
+ }
106
+
107
+ export async function exportPiSession(
108
+ pi: PiSessionFile,
109
+ output: string,
110
+ options: { dshHome?: string; destination?: Pick<DshHeader, 'id' | 'cwd'> } = {},
111
+ ) {
104
112
  const projected = projectPiForDsh(pi.entries)
105
- const carrier = await openImageBridge()
113
+ const carrier = await openImageBridge(options.dshHome)
106
114
  try {
107
115
  await carrier.images.prepare(
108
116
  projected.map((entry) => entry.message),
109
117
  )
110
- writeDshFromPi(output, pi.header, pi.entries, carrier.images.toDsh, projected)
118
+ writeDshFromPi(output, pi.header, pi.entries, carrier.images.toDsh, projected, options.destination)
111
119
  } finally {
112
120
  await carrier.close()
113
121
  }
114
122
  const parsed = await readDshFile(output)
115
123
  return {
116
- input,
117
- output,
118
124
  messages: pi.entries.filter((entry) => entry.type === 'message').length,
119
125
  events: parsed!.events.length,
120
126
  }