dsh-compact-pi 0.2.3-b4 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.3-b5]
4
+
5
+ - Guide session migration one decision at a time. Confirm the target, resolve conflicts individually, and approve the exact output path before writing.
6
+ - Show a short destination preview in the terminal wizard. Scripted plans still return JSON.
7
+ - Record the compaction scope observation and provide an opt-in comparison harness. The default summary prompt remains the upstream prompt.
8
+
3
9
  ## [0.2.3-b4]
4
10
 
5
11
  - Add `dcp-session migrate` and update the packaged skill to confirm the source, host, profile, and destination before writing. Support portable exports and direct imports for Windows Desktop, Linux desktop clients, Web, and TUI.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  An installable pi extension hosting **unmodified DeepSeek Harness compaction plugins in real Cordis**. DCP adapts a defined common subset of pi and DSH; its source updater copies upstream files without rewriting imports or patching the compression algorithm.
4
4
 
5
- Tested with pi 1.5.2 and 1.6.1. Node.js must satisfy `^24.22.3 || >=26.13.1`. DCP **0.2.3b4** uses DeepSeek Harness **0.2.3-alpha.2**. `/dcp-status` shows both versions and the upstream commit recorded in [vendor/manifest.json](vendor/manifest.json). The Git tag and npm version use the SemVer spelling `0.2.3-b4`. The source snapshot is included in the package.
5
+ Tested with pi 1.5.2 and 1.6.1. Node.js must satisfy `^24.22.3 || >=26.13.1`. DCP **0.2.3b5** uses DeepSeek Harness **0.2.3-alpha.2**. `/dcp-status` shows both versions and the upstream commit recorded in [vendor/manifest.json](vendor/manifest.json). The Git tag and npm version use the SemVer spelling `0.2.3-b5`. The source snapshot is included in the package.
6
6
 
7
7
  ## Install and use
8
8
 
@@ -15,7 +15,7 @@ pi install npm:dsh-compact-pi@latest
15
15
  The explicit tag selects the currently published prerelease. To pin the GitHub release, use:
16
16
 
17
17
  ```bash
18
- pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b4
18
+ pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b5
19
19
  ```
20
20
 
21
21
  Restart pi or `/reload`, then `/dcp-status`. The Git tag pins this release. To follow future releases on the default branch, use `pi install git:github.com/HanqingTony/dsh-compact-pi`. Before switching from a local DCP installation, use `pi list` and `pi remove <old-source>` to remove the old package entry and avoid loading DCP twice. To install a development checkout, use `pi install /absolute/path/to/dsh-compact-pi`. For one run:
@@ -42,14 +42,14 @@ In pi 1.5.2, `pi update` alone updates **pi itself**. Use `pi update --extension
42
42
 
43
43
  | Installed source | Update behavior |
44
44
  |---|---|
45
- | `git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b4` | Stays on this tag until you install a different tag |
45
+ | `git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b5` | Stays on this tag until you install a different tag |
46
46
  | `git:github.com/HanqingTony/dsh-compact-pi` | Follows the default branch (`main`), including changes between tagged releases |
47
47
  | Local checkout | Uses local files; pi does not fetch a new release for that path |
48
48
 
49
49
  To upgrade a pinned 0.2.2 installation, install the new tag on the machine where pi runs.
50
50
 
51
51
  ```bash
52
- pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b4
52
+ pi install git:github.com/HanqingTony/dsh-compact-pi@v0.2.3-b5
53
53
  ```
54
54
 
55
55
  To follow `main` instead, replace the pinned source once, then update packages as needed:
@@ -148,7 +148,7 @@ npm run test:package # package, isolated install, copied-source rebuild, pi in
148
148
 
149
149
  Differential tests compare the adapter with direct upstream Cordis plugin execution: summary input/budget, logical selected spans, prune/replace events, final surfaces, no-op/failure results, flush checkpoints and retry decisions. Runtime IDs/timestamps and host-specific seed offsets are excluded. Other tests cover real TypeBox tool schemas, usage pricing, durability, branches, Ctrl+O, cancellation, scope rejection and input rejection. Provider replies are deterministic stubs; paid live-model fidelity benchmarks are not implied.
150
150
 
151
- The distributable is `dsh-compact-pi-0.2.3-b4.tgz`. It can be installed with `npm install ./dsh-compact-pi-0.2.3-b4.tgz`, followed by `pi install /absolute/path/to/node_modules/dsh-compact-pi`. It contains the copied source closure and built extension.
151
+ The distributable is `dsh-compact-pi-0.2.3-b5.tgz`. It can be installed with `npm install ./dsh-compact-pi-0.2.3-b5.tgz`, followed by `pi install /absolute/path/to/node_modules/dsh-compact-pi`. It contains the copied source closure and built extension.
152
152
 
153
153
  See [testing](docs/testing.md), [publishing](docs/publishing.md), and [release notes](CHANGELOG.md).
154
154
 
@@ -629,8 +629,8 @@ var ValidationError = class _ValidationError extends TypeError {
629
629
  * @param path — the standard-schema issue path; segments may be `{ key }` objects.
630
630
  * @returns the property keys, or an empty array when the issue has no path.
631
631
  */
632
- static normalizePath(path5 = []) {
633
- return path5.map((segment) => typeof segment === "object" ? segment.key : segment);
632
+ static normalizePath(path6 = []) {
633
+ return path6.map((segment) => typeof segment === "object" ? segment.key : segment);
634
634
  }
635
635
  /**
636
636
  * Format an issue path as a dotted string.
@@ -638,8 +638,8 @@ var ValidationError = class _ValidationError extends TypeError {
638
638
  * @param path — the standard-schema issue path.
639
639
  * @returns the keys joined with `.`.
640
640
  */
641
- static formatPath(path5) {
642
- return _ValidationError.normalizePath(path5).map(String).join(".");
641
+ static formatPath(path6) {
642
+ return _ValidationError.normalizePath(path6).map(String).join(".");
643
643
  }
644
644
  };
645
645
  Object.defineProperty(ValidationError.prototype, kValidationError, {
@@ -3328,10 +3328,10 @@ var EXCEEDS_MODEL_CONTEXT = new RegExp(
3328
3328
  "i"
3329
3329
  );
3330
3330
  function errorChain(value) {
3331
- const path5 = /* @__PURE__ */ new Set();
3331
+ const path6 = /* @__PURE__ */ new Set();
3332
3332
  const render = (current) => {
3333
- if (path5.has(current)) return "<circular cause>";
3334
- path5.add(current);
3333
+ if (path6.has(current)) return "<circular cause>";
3334
+ path6.add(current);
3335
3335
  try {
3336
3336
  if (!(current instanceof Error)) {
3337
3337
  if (typeof current === "object" && current !== null) {
@@ -3350,7 +3350,7 @@ function errorChain(value) {
3350
3350
  } catch {
3351
3351
  return "<unrenderable value>";
3352
3352
  } finally {
3353
- path5.delete(current);
3353
+ path6.delete(current);
3354
3354
  }
3355
3355
  };
3356
3356
  return render(value);
@@ -3656,25 +3656,25 @@ Schema.prototype.volatile = function volatile() {
3656
3656
  };
3657
3657
  var resolvers = {};
3658
3658
  var checkedVolatile = /* @__PURE__ */ Symbol("checked-volatile-schema");
3659
- function validateVolatileSchema(schema, path5 = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
3659
+ function validateVolatileSchema(schema, path6 = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
3660
3660
  const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
3661
3661
  if (states.has(blocked)) return;
3662
3662
  states.add(blocked);
3663
3663
  seen.set(schema, states);
3664
3664
  if (schema.meta?.volatile && blocked) {
3665
- throw new ValidationError2("volatile fields require a fixed object path without an enclosing volatile field", { path: path5 });
3665
+ throw new ValidationError2("volatile fields require a fixed object path without an enclosing volatile field", { path: path6 });
3666
3666
  }
3667
3667
  const nested = blocked || !!schema.meta?.volatile;
3668
3668
  if (schema.dict) {
3669
- for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path5, key], nested, seen);
3669
+ for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path6, key], nested, seen);
3670
3670
  }
3671
- if (schema.sKey) validateVolatileSchema(schema.sKey, [...path5, "<key>"], true, seen);
3671
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path6, "<key>"], true, seen);
3672
3672
  if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) {
3673
- validateVolatileSchema(schema.inner, [...path5, "*"], true, seen);
3673
+ validateVolatileSchema(schema.inner, [...path6, "*"], true, seen);
3674
3674
  }
3675
3675
  if (schema.list) {
3676
3676
  for (let index = 0; index < schema.list.length; index++) {
3677
- validateVolatileSchema(schema.list[index], [...path5, String(index)], true, seen);
3677
+ validateVolatileSchema(schema.list[index], [...path6, String(index)], true, seen);
3678
3678
  }
3679
3679
  }
3680
3680
  }
@@ -4137,71 +4137,71 @@ var ALWAYS_POLICY_KEYS = /* @__PURE__ */ new Set([
4137
4137
  "backoff"
4138
4138
  ]);
4139
4139
  var BACKOFF_KEYS = /* @__PURE__ */ new Set(["initialDelayMs", "maxDelayMs", "jitterRatio"]);
4140
- function validateKeys(value, allowed, path5) {
4140
+ function validateKeys(value, allowed, path6) {
4141
4141
  for (const key of Object.keys(value)) {
4142
- if (!allowed.has(key)) throw new Error(`${path5}: unknown key "${key}"`);
4142
+ if (!allowed.has(key)) throw new Error(`${path6}: unknown key "${key}"`);
4143
4143
  }
4144
4144
  }
4145
- function resolveBackoff(config2, path5) {
4146
- if (config2 !== void 0) validateKeys(config2, BACKOFF_KEYS, path5);
4145
+ function resolveBackoff(config2, path6) {
4146
+ if (config2 !== void 0) validateKeys(config2, BACKOFF_KEYS, path6);
4147
4147
  const initialDelayMs = config2?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
4148
4148
  const maxDelayMs = config2?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
4149
4149
  const jitterRatio = config2?.jitterRatio ?? DEFAULT_JITTER_RATIO;
4150
4150
  if (!Number.isFinite(initialDelayMs) || initialDelayMs <= 0 || initialDelayMs > MAX_TIMER_DELAY_MS) {
4151
- throw new Error(`${path5}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4151
+ throw new Error(`${path6}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4152
4152
  }
4153
4153
  if (!Number.isFinite(maxDelayMs) || maxDelayMs <= 0 || maxDelayMs > MAX_TIMER_DELAY_MS) {
4154
- throw new Error(`${path5}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4154
+ throw new Error(`${path6}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4155
4155
  }
4156
4156
  if (initialDelayMs > maxDelayMs) {
4157
- throw new Error(`${path5}.initialDelayMs must be less than or equal to maxDelayMs`);
4157
+ throw new Error(`${path6}.initialDelayMs must be less than or equal to maxDelayMs`);
4158
4158
  }
4159
4159
  if (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) {
4160
- throw new Error(`${path5}.jitterRatio must be between 0 and 1`);
4160
+ throw new Error(`${path6}.jitterRatio must be between 0 and 1`);
4161
4161
  }
4162
4162
  return Object.freeze({ initialDelayMs, maxDelayMs, jitterRatio });
4163
4163
  }
4164
- function resolveRetryPolicy(config2, path5) {
4164
+ function resolveRetryPolicy(config2, path6) {
4165
4165
  if (config2 === void 0) {
4166
4166
  return Object.freeze({
4167
4167
  mode: "normal",
4168
4168
  maxRetries: DEFAULT_MAX_RETRIES,
4169
4169
  retryableCodes: DEFAULT_RETRYABLE_CODES,
4170
- ...resolveBackoff(void 0, `${path5}.backoff`)
4170
+ ...resolveBackoff(void 0, `${path6}.backoff`)
4171
4171
  });
4172
4172
  }
4173
4173
  switch (config2.mode) {
4174
4174
  case "normal": {
4175
- validateKeys(config2, NORMAL_POLICY_KEYS, path5);
4175
+ validateKeys(config2, NORMAL_POLICY_KEYS, path6);
4176
4176
  const maxRetries = config2.maxRetries ?? DEFAULT_MAX_RETRIES;
4177
4177
  const retryableCodes = config2.retryableCodes ?? [...DEFAULT_RETRYABLE_CODES];
4178
4178
  if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) {
4179
- throw new Error(`${path5}.maxRetries must be a non-negative safe integer`);
4179
+ throw new Error(`${path6}.maxRetries must be a non-negative safe integer`);
4180
4180
  }
4181
4181
  if (retryableCodes.length === 0) {
4182
- throw new Error(`${path5}.retryableCodes must not be empty`);
4182
+ throw new Error(`${path6}.retryableCodes must not be empty`);
4183
4183
  }
4184
4184
  if (retryableCodes.some((code) => typeof code !== "string" || code.length === 0)) {
4185
- throw new Error(`${path5}.retryableCodes must contain only non-empty strings`);
4185
+ throw new Error(`${path6}.retryableCodes must contain only non-empty strings`);
4186
4186
  }
4187
4187
  if (new Set(retryableCodes).size !== retryableCodes.length) {
4188
- throw new Error(`${path5}.retryableCodes must not contain duplicates`);
4188
+ throw new Error(`${path6}.retryableCodes must not contain duplicates`);
4189
4189
  }
4190
4190
  return Object.freeze({
4191
4191
  mode: "normal",
4192
4192
  maxRetries,
4193
4193
  retryableCodes: Object.freeze([...retryableCodes]),
4194
- ...resolveBackoff(config2.backoff, `${path5}.backoff`)
4194
+ ...resolveBackoff(config2.backoff, `${path6}.backoff`)
4195
4195
  });
4196
4196
  }
4197
4197
  case "always":
4198
- validateKeys(config2, ALWAYS_POLICY_KEYS, path5);
4198
+ validateKeys(config2, ALWAYS_POLICY_KEYS, path6);
4199
4199
  return Object.freeze({
4200
4200
  mode: "always",
4201
- ...resolveBackoff(config2.backoff, `${path5}.backoff`)
4201
+ ...resolveBackoff(config2.backoff, `${path6}.backoff`)
4202
4202
  });
4203
4203
  default:
4204
- throw new Error(`${path5}.mode must be "normal" or "always"`);
4204
+ throw new Error(`${path6}.mode must be "normal" or "always"`);
4205
4205
  }
4206
4206
  }
4207
4207
  function callConfigEquals(a, b) {
@@ -5649,10 +5649,10 @@ var DEFAULT_AGENTS_HOME_DISPLAY = `~/${AGENTS_HOME_DIR_NAME}`;
5649
5649
  function defaultDshHome() {
5650
5650
  return join(homedir(), DSH_HOME_DIR_NAME);
5651
5651
  }
5652
- function expandHomePath(path5) {
5653
- if (path5 === "~") return homedir();
5654
- if (path5.startsWith("~/") || path5.startsWith("~\\")) return join(homedir(), path5.slice(2));
5655
- return path5;
5652
+ function expandHomePath(path6) {
5653
+ if (path6 === "~") return homedir();
5654
+ if (path6.startsWith("~/") || path6.startsWith("~\\")) return join(homedir(), path6.slice(2));
5655
+ return path6;
5656
5656
  }
5657
5657
  function resolveRoot(configured, env, envName, fallback) {
5658
5658
  const fromEnv = env[envName];
@@ -5910,17 +5910,17 @@ async function prepareImageFile(input2, limits, policy) {
5910
5910
  }
5911
5911
  };
5912
5912
  }
5913
- async function syncDirectory(path5) {
5913
+ async function syncDirectory(path6) {
5914
5914
  if (process.platform === "win32") return;
5915
- const handle = await open(path5, constants.O_RDONLY);
5915
+ const handle = await open(path6, constants.O_RDONLY);
5916
5916
  try {
5917
5917
  await handle.sync();
5918
5918
  } finally {
5919
5919
  await handle.close();
5920
5920
  }
5921
5921
  }
5922
- async function ensureDurableDirectory(path5, boundary) {
5923
- const target = resolve3(path5);
5922
+ async function ensureDurableDirectory(path6, boundary) {
5923
+ const target = resolve3(path6);
5924
5924
  const stop = resolve3(boundary);
5925
5925
  await mkdir(target, { recursive: true, mode: 448 });
5926
5926
  await chmod(target, 448);
@@ -5932,8 +5932,8 @@ async function ensureDurableDirectory(path5, boundary) {
5932
5932
  level = parent;
5933
5933
  }
5934
5934
  }
5935
- async function ensureDurableHome(path5) {
5936
- const home = resolve3(path5);
5935
+ async function ensureDurableHome(path6) {
5936
+ const home = resolve3(path6);
5937
5937
  if (!durableHomes.has(home)) {
5938
5938
  await ensureDurableDirectory(home, parse(home).root);
5939
5939
  durableHomes.add(home);
@@ -6053,13 +6053,13 @@ async function publishStagedObject(root, target, staged) {
6053
6053
  throw new AttachmentError("Unable to persist attachment.", "ATTACHMENT_WRITE_FAILED", { cause: error62 });
6054
6054
  }
6055
6055
  }
6056
- async function digestFile(path5) {
6056
+ async function digestFile(path6) {
6057
6057
  const hash2 = createHash("sha256");
6058
- for await (const chunk of createReadStream(path5)) hash2.update(chunk);
6058
+ for await (const chunk of createReadStream(path6)) hash2.update(chunk);
6059
6059
  return hash2.digest("hex");
6060
6060
  }
6061
- async function removeTemporary(path5) {
6062
- await unlink(path5).catch(
6061
+ async function removeTemporary(path6) {
6062
+ await unlink(path6).catch(
6063
6063
  /* v8 ignore next -- Cleanup can observe a staging name already removed after successful linking. */
6064
6064
  (cleanupError) => {
6065
6065
  if (!(cleanupError instanceof Error && "code" in cleanupError && cleanupError.code === "ENOENT")) throw cleanupError;
@@ -6278,9 +6278,9 @@ async function createRequestImage(attachment, target, hasAlpha, policy, signal)
6278
6278
  function cachePath(root, hash2) {
6279
6279
  return join4(root, "request-images", hash2.slice(0, 2), hash2);
6280
6280
  }
6281
- async function readCached(path5, target, expectedAlpha, signal) {
6281
+ async function readCached(path6, target, expectedAlpha, signal) {
6282
6282
  try {
6283
- const data = new Uint8Array(await readFile2(path5, { signal }));
6283
+ const data = new Uint8Array(await readFile2(path6, { signal }));
6284
6284
  if (data.byteLength > target.maxImageBytes) return void 0;
6285
6285
  const detected = await probeImage(data);
6286
6286
  if (detected.depth !== "uchar" || detected.space !== "srgb" || detected.width > target.width || detected.height > target.height || !encodedAlphaIsCompatible(expectedAlpha, detected)) return void 0;
@@ -6301,12 +6301,12 @@ async function verifyRequestImage(image, expectedAlpha) {
6301
6301
  }
6302
6302
  return { ...image, hasAlpha: detected.hasAlpha };
6303
6303
  }
6304
- async function writeCached(path5, data) {
6305
- await mkdir2(dirname3(path5), { recursive: true, mode: 448 });
6306
- const temporary = `${path5}.${randomUUID3()}.tmp`;
6304
+ async function writeCached(path6, data) {
6305
+ await mkdir2(dirname3(path6), { recursive: true, mode: 448 });
6306
+ const temporary = `${path6}.${randomUUID3()}.tmp`;
6307
6307
  try {
6308
6308
  await writeFile(temporary, data, { mode: 384, flag: "wx" });
6309
- await rename(temporary, path5);
6309
+ await rename(temporary, path6);
6310
6310
  } finally {
6311
6311
  await rm(temporary, { force: true });
6312
6312
  }
@@ -6317,12 +6317,12 @@ async function readRequestImageFile(root, attachment, target, policy, signal) {
6317
6317
  const source = await probeImage(attachment.data);
6318
6318
  const variantId = requestImageVariantId(attachment.ref, target, policy);
6319
6319
  const hash2 = String(variantId).slice("sha256:".length);
6320
- const path5 = cachePath(root, hash2);
6321
- const cached2 = await readCached(path5, target, source.hasAlpha, signal);
6320
+ const path6 = cachePath(root, hash2);
6321
+ const cached2 = await readCached(path6, target, source.hasAlpha, signal);
6322
6322
  const created = cached2 ?? await createRequestImage(attachment, target, source.hasAlpha, policy, signal);
6323
6323
  const version3 = cached2 ?? (created.data === attachment.data ? { ...created, hasAlpha: source.hasAlpha } : await verifyRequestImage(created, source.hasAlpha));
6324
6324
  signal?.throwIfAborted();
6325
- if (cached2 === void 0 && version3.data !== attachment.data) await writeCached(path5, version3.data);
6325
+ if (cached2 === void 0 && version3.data !== attachment.data) await writeCached(path6, version3.data);
6326
6326
  return {
6327
6327
  variantId,
6328
6328
  attachment: attachment.ref,
@@ -7547,10 +7547,10 @@ function mergeDefs(...defs) {
7547
7547
  function cloneDef(schema) {
7548
7548
  return mergeDefs(schema._zod.def);
7549
7549
  }
7550
- function getElementAtPath(obj, path5) {
7551
- if (!path5)
7550
+ function getElementAtPath(obj, path6) {
7551
+ if (!path6)
7552
7552
  return obj;
7553
- return path5.reduce((acc, key) => acc?.[key], obj);
7553
+ return path6.reduce((acc, key) => acc?.[key], obj);
7554
7554
  }
7555
7555
  function promiseAllObject(promisesObj) {
7556
7556
  const keys = Object.keys(promisesObj);
@@ -7890,11 +7890,11 @@ function explicitlyAborted(x, startIndex = 0) {
7890
7890
  }
7891
7891
  return false;
7892
7892
  }
7893
- function prefixIssues(path5, issues) {
7893
+ function prefixIssues(path6, issues) {
7894
7894
  return issues.map((iss) => {
7895
7895
  var _a4;
7896
7896
  (_a4 = iss).path ?? (_a4.path = []);
7897
- iss.path.unshift(path5);
7897
+ iss.path.unshift(path6);
7898
7898
  return iss;
7899
7899
  });
7900
7900
  }
@@ -8352,16 +8352,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
8352
8352
  }
8353
8353
  function formatError(error62, mapper = (issue2) => issue2.message) {
8354
8354
  const fieldErrors = { _errors: [] };
8355
- const processError = (error63, path5 = []) => {
8355
+ const processError = (error63, path6 = []) => {
8356
8356
  for (const issue2 of error63.issues) {
8357
8357
  if (issue2.code === "invalid_union" && issue2.errors.length) {
8358
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
8358
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
8359
8359
  } else if (issue2.code === "invalid_key") {
8360
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
8360
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
8361
8361
  } else if (issue2.code === "invalid_element") {
8362
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
8362
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
8363
8363
  } else {
8364
- const fullpath = [...path5, ...issue2.path];
8364
+ const fullpath = [...path6, ...issue2.path];
8365
8365
  if (fullpath.length === 0) {
8366
8366
  fieldErrors._errors.push(mapper(issue2));
8367
8367
  } else {
@@ -8400,17 +8400,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
8400
8400
  }
8401
8401
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
8402
8402
  const result = { errors: [] };
8403
- const processError = (error63, path5 = []) => {
8403
+ const processError = (error63, path6 = []) => {
8404
8404
  var _a4;
8405
8405
  for (const issue2 of error63.issues) {
8406
8406
  if (issue2.code === "invalid_union" && issue2.errors.length) {
8407
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
8407
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
8408
8408
  } else if (issue2.code === "invalid_key") {
8409
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
8409
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
8410
8410
  } else if (issue2.code === "invalid_element") {
8411
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
8411
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
8412
8412
  } else {
8413
- const fullpath = [...path5, ...issue2.path];
8413
+ const fullpath = [...path6, ...issue2.path];
8414
8414
  if (fullpath.length === 0) {
8415
8415
  result.errors.push(mapper(issue2));
8416
8416
  continue;
@@ -8449,8 +8449,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
8449
8449
  }
8450
8450
  function toDotPath(_path) {
8451
8451
  const segs = [];
8452
- const path5 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
8453
- for (const seg of path5) {
8452
+ const path6 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
8453
+ for (const seg of path6) {
8454
8454
  if (typeof seg === "number")
8455
8455
  segs.push(`[${seg}]`);
8456
8456
  else if (typeof seg === "symbol")
@@ -25416,13 +25416,13 @@ function resolveRef(ref, ctx) {
25416
25416
  if (!ref.startsWith("#")) {
25417
25417
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
25418
25418
  }
25419
- const path5 = ref.slice(1).split("/").filter(Boolean);
25420
- if (path5.length === 0) {
25419
+ const path6 = ref.slice(1).split("/").filter(Boolean);
25420
+ if (path6.length === 0) {
25421
25421
  return ctx.rootSchema;
25422
25422
  }
25423
25423
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
25424
- if (path5[0] === defsKey) {
25425
- const key = path5[1] === void 0 ? void 0 : decodeJSONPointerSegment(path5[1]);
25424
+ if (path6[0] === defsKey) {
25425
+ const key = path6[1] === void 0 ? void 0 : decodeJSONPointerSegment(path6[1]);
25426
25426
  if (!key || !ctx.defs[key]) {
25427
25427
  throw new Error(`Reference not found: ${ref}`);
25428
25428
  }
@@ -30301,19 +30301,19 @@ function buildSessionPath(entries, leafId, byId) {
30301
30301
  if (!leaf) {
30302
30302
  return [];
30303
30303
  }
30304
- const path5 = [];
30304
+ const path6 = [];
30305
30305
  let current = leaf;
30306
30306
  while (current) {
30307
- path5.push(current);
30307
+ path6.push(current);
30308
30308
  current = current.parentId ? index.get(current.parentId) : void 0;
30309
30309
  }
30310
- path5.reverse();
30311
- return path5;
30310
+ path6.reverse();
30311
+ return path6;
30312
30312
  }
30313
- function getSessionContextSettings(path5) {
30313
+ function getSessionContextSettings(path6) {
30314
30314
  let thinkingLevel = "off";
30315
30315
  let model = null;
30316
- for (const entry of path5) {
30316
+ for (const entry of path6) {
30317
30317
  if (entry.type === "thinking_level_change") {
30318
30318
  thinkingLevel = entry.thinkingLevel;
30319
30319
  } else if (entry.type === "model_change") {
@@ -30349,24 +30349,24 @@ function sessionEntryToContextMessages(entry) {
30349
30349
  return [];
30350
30350
  }
30351
30351
  function buildContextEntries(entries, leafId, byId) {
30352
- const path5 = buildSessionPath(entries, leafId, byId);
30352
+ const path6 = buildSessionPath(entries, leafId, byId);
30353
30353
  let compaction = null;
30354
- for (const entry of path5) {
30354
+ for (const entry of path6) {
30355
30355
  if (entry.type === "compaction") {
30356
30356
  compaction = entry;
30357
30357
  }
30358
30358
  }
30359
30359
  if (!compaction) {
30360
- return path5;
30360
+ return path6;
30361
30361
  }
30362
- const compactionIdx = path5.findIndex((entry) => entry.id === compaction.id);
30362
+ const compactionIdx = path6.findIndex((entry) => entry.id === compaction.id);
30363
30363
  if (compactionIdx < 0) {
30364
- return path5;
30364
+ return path6;
30365
30365
  }
30366
30366
  const contextEntries = [compaction];
30367
30367
  let foundFirstKept = false;
30368
30368
  for (let i = 0; i < compactionIdx; i++) {
30369
- const entry = path5[i];
30369
+ const entry = path6[i];
30370
30370
  if (entry.id === compaction.firstKeptEntryId) {
30371
30371
  foundFirstKept = true;
30372
30372
  }
@@ -30374,7 +30374,7 @@ function buildContextEntries(entries, leafId, byId) {
30374
30374
  contextEntries.push(entry);
30375
30375
  }
30376
30376
  }
30377
- contextEntries.push(...path5.slice(compactionIdx + 1));
30377
+ contextEntries.push(...path6.slice(compactionIdx + 1));
30378
30378
  return contextEntries;
30379
30379
  }
30380
30380
  function projectContextEntry(entry, edit) {
@@ -30393,8 +30393,8 @@ function projectContextEntry(entry, edit) {
30393
30393
  });
30394
30394
  }
30395
30395
  function buildSessionProjection(entries, leafId, byId) {
30396
- const path5 = buildSessionPath(entries, leafId, byId);
30397
- const { thinkingLevel, model } = getSessionContextSettings(path5);
30396
+ const path6 = buildSessionPath(entries, leafId, byId);
30397
+ const { thinkingLevel, model } = getSessionContextSettings(path6);
30398
30398
  const contextEntries = buildContextEntries(entries, leafId, byId);
30399
30399
  const edits = /* @__PURE__ */ new Map();
30400
30400
  for (const entry of contextEntries) {
@@ -30785,6 +30785,7 @@ async function importPiToDsh(input2, root = path3.join(process.env.DSH_HOME || p
30785
30785
  // src/dsh/migration-cli.ts
30786
30786
  import { promises as fs6 } from "node:fs";
30787
30787
  import { createInterface } from "node:readline/promises";
30788
+ import path5 from "node:path";
30788
30789
  import { parseArgs } from "node:util";
30789
30790
 
30790
30791
  // src/dsh/migration.ts
@@ -31084,8 +31085,15 @@ async function interactive(source) {
31084
31085
  } else throw error62;
31085
31086
  }
31086
31087
  }
31087
- print(plan);
31088
- const code = await ask("Review the destination above and type the confirmation code to write:");
31088
+ console.log(`Session ${plan.sourceSessionId} \u2192 ${plan.target} on ${plan.host}`);
31089
+ console.log(`Output: ${plan.output}`);
31090
+ if (plan.attachmentHome !== path5.dirname(plan.output))
31091
+ console.log(`Attachments: ${plan.attachmentHome}`);
31092
+ if (plan.sessionId !== plan.sourceSessionId)
31093
+ console.log(`New session ID: ${plan.sessionId}`);
31094
+ if (plan.mirrorRows)
31095
+ console.log(`Recover Pi entries only, leaving ${plan.mirrorRows} DSH rows in the source.`);
31096
+ const code = await ask(`Write to this location? Enter ${plan.confirmation} to confirm, or press Enter to cancel.`);
31089
31097
  if (!code) return;
31090
31098
  print(await applyMigration(plan, code));
31091
31099
  } finally {
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-b4",
30635
- dcpVersion: "0.2.3b4",
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: {
@@ -1,4 +1,4 @@
1
- # DCP 共同能力契约(0.2.3b4)
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-b4
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.3b4` 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,7 @@ 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
- Run `dcp-session migrate` in a terminal, or ask the `dcp-migrate-to-dsh` skill to guide you. The wizard asks for a source and target, shows the exact output and attachment paths, then waits for confirmation. Agents use `migrate plan` and `migrate apply` so you can review the same information before any session or image is written. See the [command examples](../skills/dcp-migrate-to-dsh/references/commands.md).
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
29
 
30
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
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.
@@ -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-b4` corresponds to the displayed version `0.2.3b4`. 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-b4.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-b4
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-b4
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
@@ -24,3 +24,18 @@ The test also generates a native pi checkpoint and a separate snapshot cut at th
24
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.
25
25
 
26
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-b4",
4
- "dcpVersion": "0.2.3b4",
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
+ }
@@ -7,10 +7,15 @@ description: Guide a user through exporting a selected Pi session or importing i
7
7
 
8
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.
9
9
 
10
- 1. Ask the user to identify the source and the destination. Use `migrate sources --id <id>` or `migrate sources --cwd <absolute-project>` to show candidate headers when the source path is unclear. Let the user choose when more than one matches.
11
- 2. Confirm the target on the machine that will write it. For a portable export, ask for the export directory. For direct import, ask for Windows Desktop, Linux Desktop, Web, or TUI, the instance or profile name, DSH backend version, DSH home (images), session directory, workspace, and storage encoding. `migrate environment` supplies host information and suggestions to confirm. Run Windows Desktop imports with Windows Node.js. A WSL shell describes a separate environment.
12
- 3. Run `migrate plan` with the confirmed fields and a fresh `--plan-file`. Show the exact output and attachment paths, destination session ID, and any conflict. See [command examples](references/commands.md). For a duplicate, offer to stop or create a separate ID with `--on-conflict copy`. For a mixed Pi/DSH log, offer to stop, select another file, or explicitly recover just the Pi entries with `--recover-pi-entries`. Recovery leaves the original file intact. Encoding and unsupported-format errors need corrected input.
13
- 4. After the user approves the resulting plan, call `migrate apply --plan-file <file> --confirm <code>`. Only use the approved plan and code. If the source or destination changed, rerun the preview and confirm again. For a local interactive terminal, the user can run `dcp-session migrate` and answer the same questions directly.
14
- 5. Report the receipt. For Web, use `migrate verify-web` with an approved launch-URL file when available. For Desktop or TUI, verify that the selected app can open the imported history using its session picker. If app access is unavailable, report the write as complete with UI verification pending. Leave an imported session idle until the user asks to send a prompt.
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.
15
20
 
16
21
  The scripts handle reading, recovery, paths, conflict checks, attachments, and conversion. Keep session contents and Web credentials out of the conversation.
@@ -13,6 +13,10 @@ Use `linux-desktop` for a Linux desktop client on the same machine as its compat
13
13
 
14
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
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
+
16
20
  ## Portable export
17
21
 
18
22
  ```text
@@ -1,5 +1,6 @@
1
1
  import { promises as fs } from 'node:fs'
2
2
  import { createInterface } from 'node:readline/promises'
3
+ import path from 'node:path'
3
4
  import { parseArgs } from 'node:util'
4
5
  import { DestinationConflict } from './import.ts'
5
6
  import {
@@ -61,8 +62,15 @@ async function interactive(source?: string) {
61
62
  } else throw error
62
63
  }
63
64
  }
64
- print(plan)
65
- const code = await ask('Review the destination above and type the confirmation code to write:')
65
+ console.log(`Session ${plan.sourceSessionId} → ${plan.target} on ${plan.host}`)
66
+ console.log(`Output: ${plan.output}`)
67
+ if (plan.attachmentHome !== path.dirname(plan.output))
68
+ console.log(`Attachments: ${plan.attachmentHome}`)
69
+ if (plan.sessionId !== plan.sourceSessionId)
70
+ console.log(`New session ID: ${plan.sessionId}`)
71
+ if (plan.mirrorRows)
72
+ console.log(`Recover Pi entries only, leaving ${plan.mirrorRows} DSH rows in the source.`)
73
+ const code = await ask(`Write to this location? Enter ${plan.confirmation} to confirm, or press Enter to cancel.`)
66
74
  if (!code) return
67
75
  print(await applyMigration(plan, code))
68
76
  } finally {