dsh-config-manager 0.8.0 → 0.8.1

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.
@@ -195,6 +195,8 @@ export declare const zh: {
195
195
  readonly 'host.patchUnsupported': 'dsh-config-manager 仅支持管理 {user} 与 profile 的 {profile}(收到 {file})';
196
196
  readonly 'host.patchUnreadable': 'patch 层 {file} 读不出来({reason}):该层的 patch 行不会被导出/同步,也不会被改写';
197
197
  readonly 'host.patchRefuseClobber': 'patch 层 {file} 解析失败({reason}):已拒绝覆盖写入,否则会把这层里读不出来的行整体删掉';
198
+ readonly 'host.patchRefusePromote': 'patch 层 {file} 的写入会把 {ids} 从 insert(新增)改成顶层行(覆盖):已拒绝写入,文件未改动(顶层行按 id 覆盖,查不到就整条丢弃)';
199
+ readonly 'host.patchSemanticDrift': 'patch 层 {file} 写回后结构自检不通过({detail}):已拒绝写入,文件未改动';
198
200
  readonly 'host.fsPathEscape': '路径越界: {path}';
199
201
  readonly 'host.activationRowFailed': '插件 {pkg} 已安装,但激活行写入 profile 补丁失败:{reason}(重启后该插件可能未激活;修复后重试安装即可幂等补行)';
200
202
  readonly 'host.syncTokenWriteFailed': 'token 写入 DSH credentials 失败:{reason}(请在 DSH 凭据管理里配置 {ref} 后重试)';
@@ -184,6 +184,8 @@ export const zh = {
184
184
  'host.patchUnsupported': 'dsh-config-manager 仅支持管理 {user} 与 profile 的 {profile}(收到 {file})',
185
185
  'host.patchUnreadable': 'patch 层 {file} 读不出来({reason}):该层的 patch 行不会被导出/同步,也不会被改写',
186
186
  'host.patchRefuseClobber': 'patch 层 {file} 解析失败({reason}):已拒绝覆盖写入,否则会把这层里读不出来的行整体删掉',
187
+ 'host.patchRefusePromote': 'patch 层 {file} 的写入会把 {ids} 从 insert(新增)改成顶层行(覆盖):已拒绝写入,文件未改动(顶层行按 id 覆盖,查不到就整条丢弃)',
188
+ 'host.patchSemanticDrift': 'patch 层 {file} 写回后结构自检不通过({detail}):已拒绝写入,文件未改动',
187
189
  'host.fsPathEscape': '路径越界: {path}',
188
190
  'host.activationRowFailed': '插件 {pkg} 已安装,但激活行写入 profile 补丁失败:{reason}(重启后该插件可能未激活;修复后重试安装即可幂等补行)',
189
191
  'host.syncTokenWriteFailed': 'token 写入 DSH credentials 失败:{reason}(请在 DSH 凭据管理里配置 {ref} 后重试)',
@@ -697,6 +699,8 @@ export const en = {
697
699
  'host.patchUnsupported': 'dsh-config-manager only manages {user} and the profile {profile} (received {file})',
698
700
  'host.patchUnreadable': 'Cannot read patch layer {file} ({reason}): its patch rows are not exported or synced, and the file is left untouched',
699
701
  'host.patchRefuseClobber': 'Refusing to rewrite patch layer {file}: it cannot be parsed ({reason}), and rewriting would delete every row that could not be read',
702
+ 'host.patchRefusePromote': 'Refusing to write patch layer {file}: it would turn {ids} from insert (add) into top-level rows (override); the file is untouched (top-level rows override by id and are dropped entirely when not found)',
703
+ 'host.patchSemanticDrift': 'Structure self-check failed after serializing patch layer {file} ({detail}): the write was refused and the file is untouched',
700
704
  'host.fsPathEscape': 'Path outside home directory: {path}',
701
705
  'host.activationRowFailed': 'Plugin {pkg} is installed, but writing the activation row into the profile patch failed: {reason} (the plugin may be inactive until restart; retrying the install after fixing is idempotent)',
702
706
  'host.syncTokenWriteFailed': 'Failed to write the token into DSH credentials: {reason} (configure {ref} in DSH credential management, then retry)',
@@ -0,0 +1,65 @@
1
+ /**
2
+ * patch 文档的**结构重建**(issue #133)。
3
+ *
4
+ * 为什么需要独立一层:`cordis.patch.yml` 的两种形态语义**不等价**(宿主 dsh-app-boot 的
5
+ * readProfilePatches 合并循环):
6
+ * - 顶层 `- id: X` → 按 id **覆盖**已存在的条目;id 查不到时打 `patch: entry "X" not found` 丢弃;
7
+ * - `- insert:` 块成员 → **新增**条目(`data.push(...clone)`,唯一的新增路径)。
8
+ * 此前重建时把所有行(含 insert 成员)统一输出成顶层行,于是「只能靠 insert 新增」的条目
9
+ * (典型是 MCP server)在 DSH 侧全部失效 —— 一条 update 就够触发。
10
+ *
11
+ * 本模块只做**结构**:不读文件、不碰 YAML(core 层零依赖),输入是已解析的文档 + 变更清单,
12
+ * 输出是重建后的条目数组与两套 id。序列化与自检在宿主门面(DshPatchFileFacade)里做。
13
+ *
14
+ * 三条不变量:
15
+ * ① 原本是 insert 成员的 id,重建后仍在 insert 块里(update 不改变归属);
16
+ * ② 新增条目(`action:'insert'` 且文档里没有)落进 insert 块,而不是顶层行;
17
+ * ③ 任一 id 不得同时出现在顶层与 insert 两处 —— 计划阶段就抛错(防御性,正常路径不可达)。
18
+ */
19
+ export interface PatchLineChange {
20
+ lineId: string;
21
+ raw: unknown;
22
+ action: 'insert' | 'update' | 'remove';
23
+ }
24
+ export interface PatchDocumentPlan {
25
+ /** 重建后的文档条目(顺序尽量贴原文档:顶层行原位、insert 块原位、新增项追加在尾部) */
26
+ items: unknown[];
27
+ /** 落在 insert 块里的 id(按输出顺序) */
28
+ insertIds: string[];
29
+ /** 落在顶层行里的 id(按输出顺序) */
30
+ topLevelIds: string[];
31
+ }
32
+ /** 计划会把 insert 成员提升成顶层行:调用方必须放弃这次写入(零写入)。 */
33
+ export declare class PatchPromoteRefusedError extends Error {
34
+ readonly ids: string[];
35
+ constructor(ids: string[]);
36
+ }
37
+ /** 读出文档里的 insert 成员 id 与顶层行 id(自检与测试共用;不判重、保持文档顺序)。 */
38
+ export declare function describePatchDocument(doc: unknown): {
39
+ insertIds: string[];
40
+ topLevelIds: string[];
41
+ };
42
+ /**
43
+ * 重建成 patch 文档条目。
44
+ *
45
+ * `doc` 是已解析的原文档(非数组视为空文档);顺序按原布局保留,新增项追加在尾部。
46
+ */
47
+ export declare function planPatchDocument(doc: unknown, changes: readonly PatchLineChange[]): PatchDocumentPlan;
48
+ /**
49
+ * 计划布局与观察到的布局是否一致(写后自检用,issue #133)。
50
+ * 一致返回 `null`;不一致返回一句可直接进错误文案的差异说明(只含 id,不含值)。
51
+ */
52
+ export declare function describePatchLayoutDrift(planned: {
53
+ insertIds: readonly string[];
54
+ topLevelIds: readonly string[];
55
+ }, observed: {
56
+ insertIds: readonly string[];
57
+ topLevelIds: readonly string[];
58
+ }): string | null;
59
+ /**
60
+ * 跨层提升检查(issue #133):`topLevelIds` 里哪些是**另一层文档**的 `- insert:` 成员。
61
+ *
62
+ * 命中就意味着「把新增改写成覆盖」——目标作用域里那条通常不存在,宿主会 `not found` 丢弃。
63
+ * `otherDoc` 读不到或解析不了时调用方传 `undefined`,本函数返回空(守卫只做加强)。
64
+ */
65
+ export declare function promotedTopLevelIds(otherDoc: unknown, topLevelIds: readonly string[]): string[];
@@ -0,0 +1,161 @@
1
+ /** 计划会把 insert 成员提升成顶层行:调用方必须放弃这次写入(零写入)。 */
2
+ export class PatchPromoteRefusedError extends Error {
3
+ ids;
4
+ constructor(ids) {
5
+ super('patch rebuild would promote insert members to top-level rows: ' + ids.join(', '));
6
+ this.name = 'PatchPromoteRefusedError';
7
+ this.ids = ids;
8
+ }
9
+ }
10
+ function entryId(value) {
11
+ if (value === null || typeof value !== 'object')
12
+ return null;
13
+ const id = value['id'];
14
+ return typeof id === 'string' && id !== '' ? id : null;
15
+ }
16
+ function blockMembers(value) {
17
+ if (value === null || typeof value !== 'object')
18
+ return null;
19
+ const insert = value['insert'];
20
+ if (!Array.isArray(insert))
21
+ return null;
22
+ return insert.filter((entry) => entry !== null && typeof entry === 'object');
23
+ }
24
+ /** 读出文档里的 insert 成员 id 与顶层行 id(自检与测试共用;不判重、保持文档顺序)。 */
25
+ export function describePatchDocument(doc) {
26
+ const insertIds = [];
27
+ const topLevelIds = [];
28
+ if (!Array.isArray(doc))
29
+ return { insertIds, topLevelIds };
30
+ for (const item of doc) {
31
+ const members = blockMembers(item);
32
+ if (members !== null) {
33
+ for (const member of members) {
34
+ const id = entryId(member);
35
+ if (id !== null)
36
+ insertIds.push(id);
37
+ }
38
+ continue;
39
+ }
40
+ const id = entryId(item);
41
+ if (id !== null)
42
+ topLevelIds.push(id);
43
+ }
44
+ return { insertIds, topLevelIds };
45
+ }
46
+ /**
47
+ * 重建成 patch 文档条目。
48
+ *
49
+ * `doc` 是已解析的原文档(非数组视为空文档);顺序按原布局保留,新增项追加在尾部。
50
+ */
51
+ export function planPatchDocument(doc, changes) {
52
+ const state = new Map();
53
+ const layout = [];
54
+ if (Array.isArray(doc)) {
55
+ for (const item of doc) {
56
+ const members = blockMembers(item);
57
+ if (members !== null) {
58
+ const ids = [];
59
+ for (const member of members) {
60
+ const id = entryId(member);
61
+ if (id === null)
62
+ continue;
63
+ ids.push(id);
64
+ if (!state.has(id))
65
+ state.set(id, { raw: member, inInsert: true });
66
+ }
67
+ if (ids.length > 0)
68
+ layout.push({ kind: 'block', ids });
69
+ continue;
70
+ }
71
+ const id = entryId(item);
72
+ if (id === null)
73
+ continue;
74
+ layout.push({ kind: 'row', id });
75
+ if (!state.has(id))
76
+ state.set(id, { raw: item, inInsert: false });
77
+ }
78
+ }
79
+ for (const change of changes) {
80
+ if (change.action === 'remove') {
81
+ state.delete(change.lineId);
82
+ continue;
83
+ }
84
+ const previous = state.get(change.lineId);
85
+ // 归属只由**原文档**决定:更新一条既有 insert 成员不会把它搬到顶层;新增才按动作分流
86
+ const inInsert = previous !== undefined ? previous.inInsert : change.action === 'insert';
87
+ state.set(change.lineId, { raw: change.raw, inInsert });
88
+ }
89
+ const items = [];
90
+ const insertIds = [];
91
+ const topLevelIds = [];
92
+ const emitted = new Set();
93
+ const emitRow = (id) => {
94
+ const slot = state.get(id);
95
+ if (slot === undefined || emitted.has(id))
96
+ return;
97
+ emitted.add(id);
98
+ items.push(slot.raw);
99
+ topLevelIds.push(id);
100
+ };
101
+ const emitBlock = (ids) => {
102
+ const members = ids.filter((id) => {
103
+ const slot = state.get(id);
104
+ return slot !== undefined && slot.inInsert && !emitted.has(id);
105
+ });
106
+ if (members.length === 0)
107
+ return;
108
+ for (const id of members)
109
+ emitted.add(id);
110
+ items.push({ insert: members.map((id) => state.get(id).raw) });
111
+ insertIds.push(...members);
112
+ };
113
+ for (const slot of layout) {
114
+ if (slot.kind === 'row')
115
+ emitRow(slot.id);
116
+ else
117
+ emitBlock(slot.ids);
118
+ }
119
+ // 新写入、且原文档布局里没有的 id:insert 动作进块,update 动作保持旧的 upsert 语义(顶层行)
120
+ for (const [id, slot] of state) {
121
+ if (emitted.has(id))
122
+ continue;
123
+ if (slot.inInsert)
124
+ continue;
125
+ emitRow(id);
126
+ }
127
+ emitBlock([...state.keys()].filter((id) => !emitted.has(id)));
128
+ // 不变量③:同一 id 不得两种身份并存(正常路径不可达;坏了就拒写,别写出一份语义分裂的文件)
129
+ const promoted = insertIds.filter((id) => topLevelIds.includes(id));
130
+ if (promoted.length > 0)
131
+ throw new PatchPromoteRefusedError(promoted);
132
+ return { items, insertIds, topLevelIds };
133
+ }
134
+ /**
135
+ * 计划布局与观察到的布局是否一致(写后自检用,issue #133)。
136
+ * 一致返回 `null`;不一致返回一句可直接进错误文案的差异说明(只含 id,不含值)。
137
+ */
138
+ export function describePatchLayoutDrift(planned, observed) {
139
+ const same = planned.insertIds.length === observed.insertIds.length
140
+ && planned.topLevelIds.length === observed.topLevelIds.length
141
+ && planned.insertIds.every((id, i) => id === observed.insertIds[i])
142
+ && planned.topLevelIds.every((id, i) => id === observed.topLevelIds[i]);
143
+ if (same)
144
+ return null;
145
+ const fmt = (label, ids) => label + '=[' + ids.join(', ') + ']';
146
+ return 'planned ' + fmt('insert', planned.insertIds) + ' ' + fmt('top-level', planned.topLevelIds)
147
+ + '; got ' + fmt('insert', observed.insertIds) + ' ' + fmt('top-level', observed.topLevelIds);
148
+ }
149
+ /**
150
+ * 跨层提升检查(issue #133):`topLevelIds` 里哪些是**另一层文档**的 `- insert:` 成员。
151
+ *
152
+ * 命中就意味着「把新增改写成覆盖」——目标作用域里那条通常不存在,宿主会 `not found` 丢弃。
153
+ * `otherDoc` 读不到或解析不了时调用方传 `undefined`,本函数返回空(守卫只做加强)。
154
+ */
155
+ export function promotedTopLevelIds(otherDoc, topLevelIds) {
156
+ if (topLevelIds.length === 0)
157
+ return [];
158
+ const insertMembers = new Set(describePatchDocument(otherDoc).insertIds);
159
+ return topLevelIds.filter((id) => insertMembers.has(id));
160
+ }
161
+ //# sourceMappingURL=patch-document.js.map
package/lib/index.d.ts CHANGED
@@ -75,7 +75,7 @@ export declare const name = "config-manager";
75
75
  /** Services required before the engine can mount (present in every profile). */
76
76
  export declare const inject: string[];
77
77
  /** Plugin version, kept in sync with package.json ("version"). */
78
- export declare const PLUGIN_VERSION = "0.8.0";
78
+ export declare const PLUGIN_VERSION = "0.8.1";
79
79
  /**
80
80
  * Star 引导弹窗指向的 GitHub 仓库(用户引导点 Star 的目标)。
81
81
  * 与 package.json 的 repository 字段保持一致;界面不可改(硬编码,参照
@@ -574,6 +574,8 @@ export declare class DshPatchFileFacade implements PatchFileFacade {
574
574
  raw: unknown;
575
575
  action: 'insert' | 'update' | 'remove';
576
576
  }[]): Promise<void>;
577
+ /** 读另一层并解析;读不到/解析不了 → undefined(跨层守卫 fail-open,见 promotedTopLevelIds)。 */
578
+ private readPatchDocQuietly;
577
579
  }
578
580
  /** File facade over $DSH_HOME, confined to the home root. */
579
581
  export declare class DshFileSystemFacade implements FileSystemFacade {
package/lib/index.js CHANGED
@@ -80,6 +80,7 @@ import { ImportUserSkippedError } from './core/types.js';
80
80
  import { PLUGIN_NPM_PACKAGE } from './core/update-check.js';
81
81
  import { planSelfUpdate, runSelfUpdate } from './core/self-update.js';
82
82
  import { createAdapters } from './adapters/index.js';
83
+ import { describePatchDocument, describePatchLayoutDrift, planPatchDocument, promotedTopLevelIds } from './core/patch-document.js';
83
84
  import { isPatchLayerRel, profilePatchRel, readEffectivePatchLines, USER_PATCH_FILE } from './core/patch-layers.js';
84
85
  import { createLocalPluginPackHook } from './core/local-plugin-host.js';
85
86
  import { ENCRYPTED_CONTAINER_CODE, createEncryptionProvider, readContainerKind, encryptArchive } from './security/index.js';
@@ -148,7 +149,7 @@ export const name = 'config-manager';
148
149
  /** Services required before the engine can mount (present in every profile). */
149
150
  export const inject = ['settings', 'credentials'];
150
151
  /** Plugin version, kept in sync with package.json ("version"). */
151
- export const PLUGIN_VERSION = '0.8.0';
152
+ export const PLUGIN_VERSION = '0.8.1';
152
153
  /** Plugin own package name — excluded from its own exported plugins list. */
153
154
  const PLUGIN_NAME = 'dsh-config-manager';
154
155
  /**
@@ -1487,15 +1488,13 @@ export class DshPatchFileFacade {
1487
1488
  }
1488
1489
  async applyPatchChanges(file, changes) {
1489
1490
  const p = this.patchPath(file);
1490
- // 1. Load the current document into an ordered lineId → raw table.
1491
+ // 1. Load the current document (the ordered table itself is built by planPatchDocument).
1491
1492
  //
1492
1493
  // 读不出来的既有内容**绝不能当作空文档**(issue #75 的数据丢失点):重建后的文件只包含
1493
1494
  // 本次写入的行,等于把用户手写的其余行整段删掉。三种情况分开处理:
1494
1495
  // - 真不存在(ENOENT)→ 空文档(首次创建,既有语义);
1495
1496
  // - 存在但读不到(EACCES/EBUSY/…)→ 抛错,不改写;
1496
1497
  // - 存在但解析不了(含未知方言 / YAML 本身有错)→ 抛错,不改写。
1497
- const rows = new Map();
1498
- const order = [];
1499
1498
  let existing = null;
1500
1499
  try {
1501
1500
  existing = await fs.readFile(p, 'utf8');
@@ -1514,58 +1513,41 @@ export class DshPatchFileFacade {
1514
1513
  throw new Error(this.msg('host.patchRefuseClobber', { file, reason: describePatchYamlError(err) }), { cause: err });
1515
1514
  }
1516
1515
  }
1517
- if (Array.isArray(doc)) {
1518
- for (const item of doc) {
1519
- if (item === null || typeof item !== 'object')
1520
- continue;
1521
- const obj = item;
1522
- const insert = obj['insert'];
1523
- if (Array.isArray(insert)) {
1524
- for (const entry of insert) {
1525
- if (entry === null || typeof entry !== 'object')
1526
- continue;
1527
- const id = entry['id'];
1528
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1529
- rows.set(id, entry);
1530
- order.push(id);
1531
- }
1532
- }
1533
- continue;
1534
- }
1535
- const id = obj['id'];
1536
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1537
- rows.set(id, obj);
1538
- order.push(id);
1539
- }
1540
- }
1516
+ // 2. Rebuild through core/patch-document.ts (issue #133): the two shapes are **not**
1517
+ // equivalent on the host side. A top-level `- id: X` row *overrides* entry X and is
1518
+ // dropped with `patch: entry "X" not found` when X does not exist; only an
1519
+ // `- insert:` block member *adds* entries. Emitting every row top-level therefore
1520
+ // turned one update into "every insert-only entry (MCP servers, most notably) is
1521
+ // gone after restart".
1522
+ const plan = planPatchDocument(doc, changes);
1523
+ const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1524
+ + dumpPatchDocument(plan.items);
1525
+ // 3. Post-write structure self-check, before anything touches the disk: re-parse the
1526
+ // text we just serialized and require both id sets to match the plan item by item.
1527
+ // A serializer or dialect change that flattens or swallows insert blocks stops here
1528
+ // (zero write) instead of silently degrading every patch row to an override.
1529
+ const drift = describePatchLayoutDrift(plan, describePatchDocument(loadPatchDocument(text)));
1530
+ if (drift !== null) {
1531
+ throw new Error(this.msg('host.patchSemanticDrift', { file, detail: drift }));
1532
+ }
1533
+ // 4. 跨层提升守卫(issue #133):待写的顶层 id 若是**另一层**的 insert 成员,写下去就从
1534
+ // 「新增」变成「覆盖」(宿主查不到则丢弃)。对侧读不出来/解析不了只跳过守卫 —— 读护栏
1535
+ // 已在各自层报错,损坏的兄弟文件不该永久阻塞本层写入。
1536
+ const other = file === USER_PATCH_FILE ? profilePatchRel(this.profile) : USER_PATCH_FILE;
1537
+ const promoted = promotedTopLevelIds(await this.readPatchDocQuietly(other), plan.topLevelIds);
1538
+ if (promoted.length > 0) {
1539
+ throw new Error(this.msg('host.patchRefusePromote', { file, ids: promoted.join(', ') }));
1541
1540
  }
1542
- // 2. Apply the changes.
1543
- for (const change of changes) {
1544
- if (change.action === 'remove') {
1545
- if (rows.delete(change.lineId)) {
1546
- const at = order.indexOf(change.lineId);
1547
- if (at >= 0)
1548
- order.splice(at, 1);
1549
- }
1550
- }
1551
- else if (change.action === 'insert' || change.action === 'update') {
1552
- if (!rows.has(change.lineId))
1553
- order.push(change.lineId);
1554
- rows.set(change.lineId, change.raw);
1555
- }
1541
+ await atomicWriteFile(p, text);
1542
+ }
1543
+ /** 读另一层并解析;读不到/解析不了 → undefined(跨层守卫 fail-open,见 promotedTopLevelIds)。 */
1544
+ async readPatchDocQuietly(file) {
1545
+ try {
1546
+ return loadPatchDocument(await fs.readFile(resolve(this.homeDir, file), 'utf8'));
1556
1547
  }
1557
- // 3. Rebuild: every id row is emitted as a top-level row. The loader treats
1558
- // a top-level { id, name } row exactly like an `- insert:` block member
1559
- // (dsh-base patch precedent), so the document stays semantically equal.
1560
- const out = [];
1561
- for (const id of order) {
1562
- const raw = rows.get(id);
1563
- if (raw !== undefined)
1564
- out.push(raw);
1548
+ catch {
1549
+ return undefined;
1565
1550
  }
1566
- const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1567
- + dumpPatchDocument(out);
1568
- await atomicWriteFile(p, text);
1569
1551
  }
1570
1552
  }
1571
1553
  /** File facade over $DSH_HOME, confined to the home root. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-config-manager",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "license": "MIT",
5
5
  "description": "Backup, restore, export, import, migrate and sync your DeepSeek Harness (DSH) configuration: settings, plugins, MCP servers, skills, agent presets and workspaces. One-click migration to another machine. DSH 配置一键备份、恢复、导出、导入、迁移与同步插件。",
6
6
  "icon": "./icon.svg",
@@ -41,11 +41,31 @@ test('mcp: extractMcpServers 兼容单行与 insert 块', () => {
41
41
  assert.equal(http?.sourceLineId, 'mcp-http');
42
42
  });
43
43
 
44
- test('mcp: buildMcpPatchLine 构造写回行', () => {
44
+ test('mcp: buildMcpPatchLine 构造写回行(scoped 包名 + 显式 transport)', () => {
45
45
  const line = buildMcpPatchLine('mcp-fs', { serverName: 'filesystem', type: 'stdio', command: 'npx', args: ['-y', 'x'] });
46
46
  assert.equal(line.id, 'mcp-fs');
47
- assert.equal(line.name, 'dsh-mcp-client');
47
+ assert.equal(line.name, '@deepseek-ai/dsh-mcp-client', '宿主按 bundle id 解析 name,裸名不保证被接受(#133)');
48
+ assert.equal((line.config as Record<string, unknown>)['transport'], 'stdio', 'stdio 必须显式写 transport(此前只能靠 url 缺省猜)');
48
49
  assert.equal((line.config as Record<string, unknown>)['command'], 'npx');
50
+
51
+ const http = buildMcpPatchLine('mcp-remote', { serverName: 'remote', type: 'streamable-http', url: 'https://mcp.example.com/sse' });
52
+ const httpConfig = http.config as Record<string, unknown>;
53
+ assert.equal(httpConfig['transport'], 'streamable-http');
54
+ assert.equal(httpConfig['url'], 'https://mcp.example.com/sse');
55
+ });
56
+
57
+ test('mcp: extractMcpServers 以 transport 为准,缺该字段的旧行才回落 url 猜测', () => {
58
+ const withTransport = extractMcpServers([{
59
+ lineId: 'mcp-stdio-with-url',
60
+ raw: { id: 'mcp-stdio-with-url', name: '@deepseek-ai/dsh-mcp-client', config: { serverName: 's1', transport: 'stdio', command: 'node', url: 'http://127.0.0.1:1/mcp' } },
61
+ }]);
62
+ assert.equal(withTransport[0]?.type, 'stdio', 'transport 在就不该被 url 覆盖');
63
+
64
+ const legacy = extractMcpServers([{
65
+ lineId: 'legacy',
66
+ raw: { id: 'legacy', name: 'dsh-mcp-client', config: { serverName: 's2', url: 'https://mcp.example.com/sse' } },
67
+ }]);
68
+ assert.equal(legacy[0]?.type, 'streamable-http', '没有 transport 的旧行仍按原口径回落');
49
69
  });
50
70
 
51
71
  test('mcp: export 提取 + analyzeImport Create/Skip/Conflict + applyItem 写 patch(needsRestart)', async () => {
@@ -69,7 +89,7 @@ test('mcp: export 提取 + analyzeImport Create/Skip/Conflict + applyItem 写 pa
69
89
  assert.equal(r.ok, true);
70
90
  assert.equal(r.needsRestart, true, 'MCP 写 patch 必须重启生效');
71
91
  assert.ok(dst.patchFile.lines.has('mcp-fs'));
72
- assert.equal((dst.patchFile.lines.get('mcp-fs')?.raw as Record<string, unknown>)['name'], 'dsh-mcp-client');
92
+ assert.equal((dst.patchFile.lines.get('mcp-fs')?.raw as Record<string, unknown>)['name'], '@deepseek-ai/dsh-mcp-client');
73
93
 
74
94
  // 幂等:同 serverName 同内容 → Skip
75
95
  items = await adapter.analyzeImport(exported.data, makeImportContext(dst, sections));
@@ -65,7 +65,8 @@ export function extractMcpServers(lines: { lineId: string; raw: unknown; file?:
65
65
  const c = config as Record<string, unknown>;
66
66
  const serverName = c['serverName'];
67
67
  if (typeof serverName !== 'string' || serverName === '') continue;
68
- const type = typeof c['url'] === 'string' && c['url'] !== '' ? 'streamable-http' : 'stdio';
68
+ // transport 优先(写回时一定有);老行没有该字段才回落「有 url = 远程」的猜测
69
+ const type = mcpTransportOf(c) ?? (typeof c['url'] === 'string' && c['url'] !== '' ? 'streamable-http' : 'stdio');
69
70
  servers.push({
70
71
  serverName,
71
72
  type,
@@ -107,6 +108,12 @@ export function stripMcpEntries(raw: unknown): unknown | undefined {
107
108
  return isMcpEntry(single[0]) ? undefined : raw;
108
109
  }
109
110
 
111
+ /** `config.transport` 的合法取值;读不出来(缺字段/写错)返回 undefined,由调用方回落 url 判定。 */
112
+ function mcpTransportOf(c: Record<string, unknown>): McpServerEntry['type'] | undefined {
113
+ const transport = c['transport'];
114
+ return transport === 'stdio' || transport === 'streamable-http' ? transport : undefined;
115
+ }
116
+
110
117
  /** 单个 patch entry 是否是 MCP 服务器行(与 extractMcpServers 的判定同口径) */
111
118
  function isMcpEntry(entry: unknown): boolean {
112
119
  if (entry === null || typeof entry !== 'object') return false;
@@ -131,9 +138,22 @@ function entriesOf(raw: unknown): { id?: unknown; name?: unknown; config?: unkno
131
138
  return [];
132
139
  }
133
140
 
134
- /** 由导出条目构造写回 patch 行 raw(单行形态,与 dsh-mcp-client 组合 config 语义一致) */
141
+ /**
142
+ * MCP server 行的包名(bundle id,**必须带 scope**)。
143
+ *
144
+ * 宿主按 bundle id 解析 patch 行的 `name`;裸名 `dsh-mcp-client` 是否被归一化未经验证,
145
+ * 而用户机上的真实行都是 `@deepseek-ai/dsh-mcp-client`(issue #133 报告的原始行)。
146
+ */
147
+ const MCP_BUNDLE_NAME = '@deepseek-ai/dsh-mcp-client';
148
+
149
+ /**
150
+ * 由导出条目构造写回 patch 行 raw(单行形态,与 dsh-mcp-client 组合 config 语义一致)。
151
+ *
152
+ * `config.transport` 必须显式写:读侧靠它判定 server 类型,只在「没有 transport 的旧行」
153
+ * 上才回落 url 猜测(issue #133:此前写回丢了这个字段,stdio/http 只能靠 url 有没有值猜)。
154
+ */
135
155
  export function buildMcpPatchLine(lineId: string, server: McpServerEntry): Record<string, unknown> {
136
- const config: Record<string, unknown> = { serverName: server.serverName };
156
+ const config: Record<string, unknown> = { serverName: server.serverName, transport: server.type };
137
157
  if (server.type === 'streamable-http') {
138
158
  config['url'] = server.url;
139
159
  if (server.headers !== undefined) config['headers'] = server.headers;
@@ -143,7 +163,7 @@ export function buildMcpPatchLine(lineId: string, server: McpServerEntry): Recor
143
163
  if (server.env !== undefined) config['env'] = server.env;
144
164
  if (server.cwd !== undefined) config['cwd'] = server.cwd;
145
165
  }
146
- return { id: lineId, name: 'dsh-mcp-client', config };
166
+ return { id: lineId, name: MCP_BUNDLE_NAME, config };
147
167
  }
148
168
 
149
169
  /** 连接器计划项的 id 前缀(导入时按前缀分派到 applyConnectorItem) */
@@ -209,6 +209,8 @@ export const zh = {
209
209
  'host.patchUnsupported': 'dsh-config-manager 仅支持管理 {user} 与 profile 的 {profile}(收到 {file})',
210
210
  'host.patchUnreadable': 'patch 层 {file} 读不出来({reason}):该层的 patch 行不会被导出/同步,也不会被改写',
211
211
  'host.patchRefuseClobber': 'patch 层 {file} 解析失败({reason}):已拒绝覆盖写入,否则会把这层里读不出来的行整体删掉',
212
+ 'host.patchRefusePromote': 'patch 层 {file} 的写入会把 {ids} 从 insert(新增)改成顶层行(覆盖):已拒绝写入,文件未改动(顶层行按 id 覆盖,查不到就整条丢弃)',
213
+ 'host.patchSemanticDrift': 'patch 层 {file} 写回后结构自检不通过({detail}):已拒绝写入,文件未改动',
212
214
  'host.fsPathEscape': '路径越界: {path}',
213
215
  'host.activationRowFailed': '插件 {pkg} 已安装,但激活行写入 profile 补丁失败:{reason}(重启后该插件可能未激活;修复后重试安装即可幂等补行)',
214
216
  'host.syncTokenWriteFailed': 'token 写入 DSH credentials 失败:{reason}(请在 DSH 凭据管理里配置 {ref} 后重试)',
@@ -735,6 +737,8 @@ export const en: Record<keyof typeof zh, string> = {
735
737
  'host.patchUnsupported': 'dsh-config-manager only manages {user} and the profile {profile} (received {file})',
736
738
  'host.patchUnreadable': 'Cannot read patch layer {file} ({reason}): its patch rows are not exported or synced, and the file is left untouched',
737
739
  'host.patchRefuseClobber': 'Refusing to rewrite patch layer {file}: it cannot be parsed ({reason}), and rewriting would delete every row that could not be read',
740
+ 'host.patchRefusePromote': 'Refusing to write patch layer {file}: it would turn {ids} from insert (add) into top-level rows (override); the file is untouched (top-level rows override by id and are dropped entirely when not found)',
741
+ 'host.patchSemanticDrift': 'Structure self-check failed after serializing patch layer {file} ({detail}): the write was refused and the file is untouched',
738
742
  'host.fsPathEscape': 'Path outside home directory: {path}',
739
743
  'host.activationRowFailed': 'Plugin {pkg} is installed, but writing the activation row into the profile patch failed: {reason} (the plugin may be inactive until restart; retrying the install after fixing is idempotent)',
740
744
  'host.syncTokenWriteFailed': 'Failed to write the token into DSH credentials: {reason} (configure {ref} in DSH credential management, then retry)',
@@ -0,0 +1,107 @@
1
+ /**
2
+ * patch 文档结构重建(issue #133):顶层行 ≠ `- insert:` 块成员。
3
+ *
4
+ * 宿主合并循环里,顶层 `- id: X` 按 id **覆盖**(查不到就 `patch: entry "X" not found` 丢弃),
5
+ * 只有 insert 块成员是**新增**。旧实现把所有行统一输出成顶层行 —— 一条 update 就把只能靠
6
+ * insert 新增的条目(MCP server 最典型)在重启后整段作废。本文件钉住三条不变量:
7
+ * ① 既有 insert 成员更新后**归属不变**;② 新增(action:'insert')落进 insert 块;
8
+ * ③ 任一 id 不得同时具备两种身份。
9
+ */
10
+ import test from 'node:test';
11
+ import assert from 'node:assert/strict';
12
+
13
+ import {
14
+ describePatchDocument, describePatchLayoutDrift, PatchPromoteRefusedError, planPatchDocument,
15
+ } from './patch-document.ts';
16
+
17
+ const DOC = [
18
+ { id: 'top-a', name: '@deepseek-ai/dsh-top', disabled: false },
19
+ { insert: [
20
+ { id: 'mcp-a', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'npx' } },
21
+ { id: 'mcp-b', name: 'dsh-mcp-client', config: { transport: 'streamable-http', url: 'http://127.0.0.1:1/mcp' } },
22
+ ] },
23
+ { id: 'top-b', name: '@deepseek-ai/dsh-other' },
24
+ ];
25
+
26
+ test('#133 insert 块保真:更新一条 insert 成员后仍留在块里,成员集合不变', () => {
27
+ const plan = planPatchDocument(DOC, [
28
+ { lineId: 'mcp-a', raw: { id: 'mcp-a', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'uvx' } }, action: 'update' },
29
+ ]);
30
+ assert.deepEqual(plan.insertIds, ['mcp-a', 'mcp-b']);
31
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b']);
32
+ const block = plan.items.find((item) => Array.isArray((item as Record<string, unknown>)['insert'])) as { insert: { id: string; config: { command: string } }[] };
33
+ assert.ok(block !== undefined, 'insert 块必须仍然存在(旧实现会把它摊平成两条顶层行)');
34
+ assert.deepEqual(block.insert.map((e) => e.id), ['mcp-a', 'mcp-b']);
35
+ assert.equal(block.insert[0]?.config.command, 'uvx', '更新后的值写进块成员');
36
+ });
37
+
38
+ test('#133 顶层行更新不改归属(也不会掉进 insert 块)', () => {
39
+ const plan = planPatchDocument(DOC, [
40
+ { lineId: 'top-a', raw: { id: 'top-a', name: '@deepseek-ai/dsh-top', disabled: true }, action: 'update' },
41
+ ]);
42
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b']);
43
+ assert.deepEqual(plan.insertIds, ['mcp-a', 'mcp-b']);
44
+ assert.equal((plan.items[0] as { disabled: boolean }).disabled, true, '顶层行保持原位');
45
+ });
46
+
47
+ test('#133 新增条目走 insert 动作时落进 insert 块(新增语义,而不是覆盖)', () => {
48
+ const plan = planPatchDocument(DOC, [
49
+ { lineId: 'mcp-new', raw: { id: 'mcp-new', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'node' } }, action: 'insert' },
50
+ ]);
51
+ assert.deepEqual(plan.insertIds, ['mcp-a', 'mcp-b', 'mcp-new']);
52
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b'], '新增绝不能出现在顶层行里');
53
+ });
54
+
55
+ test('#133 update 动作写新 id 时保持旧的 upsert 语义(顶层行,不改既有契约)', () => {
56
+ const plan = planPatchDocument(DOC, [
57
+ { lineId: 'plain', raw: { id: 'plain', disabled: true }, action: 'update' },
58
+ ]);
59
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b', 'plain']);
60
+ assert.deepEqual(plan.insertIds, ['mcp-a', 'mcp-b']);
61
+ });
62
+
63
+ test('#133 remove 删掉 insert 成员后块仍保留其余成员', () => {
64
+ const plan = planPatchDocument(DOC, [{ lineId: 'mcp-a', raw: null, action: 'remove' }]);
65
+ assert.deepEqual(plan.insertIds, ['mcp-b']);
66
+ const blocks = plan.items.filter((item) => Array.isArray((item as Record<string, unknown>)['insert']));
67
+ assert.equal(blocks.length, 1);
68
+ });
69
+
70
+ test('#133 remove 删光 insert 成员后不留空块(空块会被宿主当空 insert)', () => {
71
+ const plan = planPatchDocument(DOC, [
72
+ { lineId: 'mcp-a', raw: null, action: 'remove' },
73
+ { lineId: 'mcp-b', raw: null, action: 'remove' },
74
+ ]);
75
+ assert.deepEqual(plan.insertIds, []);
76
+ assert.equal(plan.items.some((item) => Array.isArray((item as Record<string, unknown>)['insert'])), false);
77
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b']);
78
+ });
79
+
80
+ test('#133 空文档 + insert 动作:落成 insert 块(MCP 从零新建的路径)', () => {
81
+ const plan = planPatchDocument(undefined, [
82
+ { lineId: 'first', raw: { id: 'first', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'npx' } }, action: 'insert' },
83
+ ]);
84
+ assert.deepEqual(plan.insertIds, ['first']);
85
+ assert.deepEqual(plan.topLevelIds, []);
86
+ assert.equal(plan.items.length, 1);
87
+ });
88
+
89
+ test('#133 同一 id 不得同时具备两种身份(防御性不变量)', () => {
90
+ // 文档里同一 id 既在块里又在顶层:以首次出现为准,绝不产生「两种身份并存」的输出
91
+ const plan = planPatchDocument([
92
+ { insert: [{ id: 'dup', name: 'a' }] },
93
+ { id: 'dup', name: 'b' },
94
+ ], []);
95
+ assert.deepEqual(plan.insertIds, ['dup']);
96
+ assert.deepEqual(plan.topLevelIds, []);
97
+ assert.equal(new PatchPromoteRefusedError(['x']).ids[0], 'x');
98
+ });
99
+
100
+ test('#133 写后自检:布局不一致时给出可读差异(一致返回 null)', () => {
101
+ const planned = describePatchDocument(DOC);
102
+ assert.equal(describePatchLayoutDrift(planned, describePatchDocument(DOC)), null);
103
+ const drift = describePatchLayoutDrift(planned, { insertIds: [], topLevelIds: ['top-a', 'mcp-a', 'mcp-b', 'top-b'] });
104
+ assert.ok(drift !== null);
105
+ assert.match(String(drift), /insert=\[mcp-a, mcp-b\]/);
106
+ assert.match(String(drift), /got insert=\[\]/);
107
+ });