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.
@@ -0,0 +1,194 @@
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
+
25
+ export interface PatchDocumentPlan {
26
+ /** 重建后的文档条目(顺序尽量贴原文档:顶层行原位、insert 块原位、新增项追加在尾部) */
27
+ items: unknown[];
28
+ /** 落在 insert 块里的 id(按输出顺序) */
29
+ insertIds: string[];
30
+ /** 落在顶层行里的 id(按输出顺序) */
31
+ topLevelIds: string[];
32
+ }
33
+
34
+ /** 计划会把 insert 成员提升成顶层行:调用方必须放弃这次写入(零写入)。 */
35
+ export class PatchPromoteRefusedError extends Error {
36
+ readonly ids: string[];
37
+ constructor(ids: string[]) {
38
+ super('patch rebuild would promote insert members to top-level rows: ' + ids.join(', '));
39
+ this.name = 'PatchPromoteRefusedError';
40
+ this.ids = ids;
41
+ }
42
+ }
43
+
44
+ interface SlotState {
45
+ raw: unknown;
46
+ inInsert: boolean;
47
+ }
48
+
49
+ type Slot = { kind: 'row'; id: string } | { kind: 'block'; ids: string[] };
50
+
51
+ function entryId(value: unknown): string | null {
52
+ if (value === null || typeof value !== 'object') return null;
53
+ const id = (value as Record<string, unknown>)['id'];
54
+ return typeof id === 'string' && id !== '' ? id : null;
55
+ }
56
+
57
+ function blockMembers(value: unknown): Record<string, unknown>[] | null {
58
+ if (value === null || typeof value !== 'object') return null;
59
+ const insert = (value as Record<string, unknown>)['insert'];
60
+ if (!Array.isArray(insert)) return null;
61
+ return insert.filter((entry): entry is Record<string, unknown> => entry !== null && typeof entry === 'object');
62
+ }
63
+
64
+ /** 读出文档里的 insert 成员 id 与顶层行 id(自检与测试共用;不判重、保持文档顺序)。 */
65
+ export function describePatchDocument(doc: unknown): { insertIds: string[]; topLevelIds: string[] } {
66
+ const insertIds: string[] = [];
67
+ const topLevelIds: string[] = [];
68
+ if (!Array.isArray(doc)) return { insertIds, topLevelIds };
69
+ for (const item of doc) {
70
+ const members = blockMembers(item);
71
+ if (members !== null) {
72
+ for (const member of members) {
73
+ const id = entryId(member);
74
+ if (id !== null) insertIds.push(id);
75
+ }
76
+ continue;
77
+ }
78
+ const id = entryId(item);
79
+ if (id !== null) topLevelIds.push(id);
80
+ }
81
+ return { insertIds, topLevelIds };
82
+ }
83
+
84
+ /**
85
+ * 重建成 patch 文档条目。
86
+ *
87
+ * `doc` 是已解析的原文档(非数组视为空文档);顺序按原布局保留,新增项追加在尾部。
88
+ */
89
+ export function planPatchDocument(doc: unknown, changes: readonly PatchLineChange[]): PatchDocumentPlan {
90
+ const state = new Map<string, SlotState>();
91
+ const layout: Slot[] = [];
92
+
93
+ if (Array.isArray(doc)) {
94
+ for (const item of doc) {
95
+ const members = blockMembers(item);
96
+ if (members !== null) {
97
+ const ids: string[] = [];
98
+ for (const member of members) {
99
+ const id = entryId(member);
100
+ if (id === null) continue;
101
+ ids.push(id);
102
+ if (!state.has(id)) state.set(id, { raw: member, inInsert: true });
103
+ }
104
+ if (ids.length > 0) layout.push({ kind: 'block', ids });
105
+ continue;
106
+ }
107
+ const id = entryId(item);
108
+ if (id === null) continue;
109
+ layout.push({ kind: 'row', id });
110
+ if (!state.has(id)) state.set(id, { raw: item, inInsert: false });
111
+ }
112
+ }
113
+
114
+ for (const change of changes) {
115
+ if (change.action === 'remove') {
116
+ state.delete(change.lineId);
117
+ continue;
118
+ }
119
+ const previous = state.get(change.lineId);
120
+ // 归属只由**原文档**决定:更新一条既有 insert 成员不会把它搬到顶层;新增才按动作分流
121
+ const inInsert = previous !== undefined ? previous.inInsert : change.action === 'insert';
122
+ state.set(change.lineId, { raw: change.raw, inInsert });
123
+ }
124
+
125
+ const items: unknown[] = [];
126
+ const insertIds: string[] = [];
127
+ const topLevelIds: string[] = [];
128
+ const emitted = new Set<string>();
129
+
130
+ const emitRow = (id: string): void => {
131
+ const slot = state.get(id);
132
+ if (slot === undefined || emitted.has(id)) return;
133
+ emitted.add(id);
134
+ items.push(slot.raw);
135
+ topLevelIds.push(id);
136
+ };
137
+ const emitBlock = (ids: string[]): void => {
138
+ const members = ids.filter((id) => {
139
+ const slot = state.get(id);
140
+ return slot !== undefined && slot.inInsert && !emitted.has(id);
141
+ });
142
+ if (members.length === 0) return;
143
+ for (const id of members) emitted.add(id);
144
+ items.push({ insert: members.map((id) => state.get(id)!.raw) });
145
+ insertIds.push(...members);
146
+ };
147
+
148
+ for (const slot of layout) {
149
+ if (slot.kind === 'row') emitRow(slot.id);
150
+ else emitBlock(slot.ids);
151
+ }
152
+
153
+ // 新写入、且原文档布局里没有的 id:insert 动作进块,update 动作保持旧的 upsert 语义(顶层行)
154
+ for (const [id, slot] of state) {
155
+ if (emitted.has(id)) continue;
156
+ if (slot.inInsert) continue;
157
+ emitRow(id);
158
+ }
159
+ emitBlock([...state.keys()].filter((id) => !emitted.has(id)));
160
+
161
+ // 不变量③:同一 id 不得两种身份并存(正常路径不可达;坏了就拒写,别写出一份语义分裂的文件)
162
+ const promoted = insertIds.filter((id) => topLevelIds.includes(id));
163
+ if (promoted.length > 0) throw new PatchPromoteRefusedError(promoted);
164
+
165
+ return { items, insertIds, topLevelIds };
166
+ }
167
+ /**
168
+ * 计划布局与观察到的布局是否一致(写后自检用,issue #133)。
169
+ * 一致返回 `null`;不一致返回一句可直接进错误文案的差异说明(只含 id,不含值)。
170
+ */
171
+ export function describePatchLayoutDrift(
172
+ planned: { insertIds: readonly string[]; topLevelIds: readonly string[] },
173
+ observed: { insertIds: readonly string[]; topLevelIds: readonly string[] },
174
+ ): string | null {
175
+ const same = planned.insertIds.length === observed.insertIds.length
176
+ && planned.topLevelIds.length === observed.topLevelIds.length
177
+ && planned.insertIds.every((id, i) => id === observed.insertIds[i])
178
+ && planned.topLevelIds.every((id, i) => id === observed.topLevelIds[i]);
179
+ if (same) return null;
180
+ const fmt = (label: string, ids: readonly string[]): string => label + '=[' + ids.join(', ') + ']';
181
+ return 'planned ' + fmt('insert', planned.insertIds) + ' ' + fmt('top-level', planned.topLevelIds)
182
+ + '; got ' + fmt('insert', observed.insertIds) + ' ' + fmt('top-level', observed.topLevelIds);
183
+ }
184
+ /**
185
+ * 跨层提升检查(issue #133):`topLevelIds` 里哪些是**另一层文档**的 `- insert:` 成员。
186
+ *
187
+ * 命中就意味着「把新增改写成覆盖」——目标作用域里那条通常不存在,宿主会 `not found` 丢弃。
188
+ * `otherDoc` 读不到或解析不了时调用方传 `undefined`,本函数返回空(守卫只做加强)。
189
+ */
190
+ export function promotedTopLevelIds(otherDoc: unknown, topLevelIds: readonly string[]): string[] {
191
+ if (topLevelIds.length === 0) return [];
192
+ const insertMembers = new Set(describePatchDocument(otherDoc).insertIds);
193
+ return topLevelIds.filter((id) => insertMembers.has(id));
194
+ }
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import test from 'node:test';
12
12
  import assert from 'node:assert/strict';
13
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
13
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
14
  import { tmpdir } from 'node:os';
15
15
  import { join } from 'node:path';
16
16
 
@@ -1002,3 +1002,85 @@ test('#75 不存在的层仍按「本来就没有」处理(ENOENT 不是错误
1002
1002
  cleanup()
1003
1003
  }
1004
1004
  })
1005
+
1006
+ /* --------------------- issue #133:顶层行 ≠ `- insert:` 块(摊平事故) --------------------- */
1007
+
1008
+ /**
1009
+ * 真机形态:顶层行 + `- insert:` 块 + 手写注释。宿主合并循环里顶层行按 id **覆盖**(查不到就
1010
+ * `patch: entry "X" not found` 丢弃),只有 insert 块成员是**新增** —— 所以这两种形态在
1011
+ * 语义上不等价,重建时必须原样分流。
1012
+ */
1013
+ const INSERT_BLOCK_YAML = [
1014
+ '# 手写注释(重建后本来就不保留,这里只用来确认真机形态)',
1015
+ '- id: llm-pi-ai',
1016
+ ' name: "@deepseek-ai/dsh-llm-pi-ai"',
1017
+ '- insert:',
1018
+ ' - id: mcp-a',
1019
+ ' name: dsh-mcp-client',
1020
+ ' config:',
1021
+ ' transport: stdio',
1022
+ ' command: npx',
1023
+ '- id: plain-plugin',
1024
+ ' disabled: true',
1025
+ '',
1026
+ ].join('\n')
1027
+
1028
+ test('#133 applyPatchChanges:一条 update 不得把 insert 块摊平成顶层行', async () => {
1029
+ const { home, cleanup } = patchHome()
1030
+ try {
1031
+ writeFileSync(join(home, USER_PATCH_FILE), INSERT_BLOCK_YAML, 'utf8')
1032
+ const facade = new DshPatchFileFacade(home, 'web', zhMsg)
1033
+ await facade.applyPatchChanges(USER_PATCH_FILE, [
1034
+ { lineId: 'mcp-a', raw: { id: 'mcp-a', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'uvx' } }, action: 'update' },
1035
+ ])
1036
+ const text = readFileSync(join(home, USER_PATCH_FILE), 'utf8')
1037
+ assert.ok(text.includes('- insert:'), 'insert 块必须仍在(摊平 = 该条目重启后整条作废): ' + text)
1038
+ const lines = await facade.readPatchLines(USER_PATCH_FILE)
1039
+ assert.deepEqual(lines.map((l) => l.lineId), ['llm-pi-ai', 'mcp-a', 'plain-plugin'])
1040
+ const config = (lines[1]?.raw as { config?: Record<string, unknown> } | undefined)?.config
1041
+ assert.equal(config?.['command'], 'uvx')
1042
+ } finally {
1043
+ cleanup()
1044
+ }
1045
+ })
1046
+
1047
+ test('#133 applyPatchChanges:新 id 走 insert 动作时落进 insert 块(新增语义)', async () => {
1048
+ const { home, cleanup } = patchHome()
1049
+ try {
1050
+ writeFileSync(join(home, USER_PATCH_FILE), INSERT_BLOCK_YAML, 'utf8')
1051
+ const facade = new DshPatchFileFacade(home, 'web', zhMsg)
1052
+ await facade.applyPatchChanges(USER_PATCH_FILE, [
1053
+ { lineId: 'mcp-new', raw: { id: 'mcp-new', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'node' } }, action: 'insert' },
1054
+ ])
1055
+ const text = readFileSync(join(home, USER_PATCH_FILE), 'utf8')
1056
+ assert.ok(text.includes('- insert:'), '新增必须落在 insert 块里: ' + text)
1057
+ assert.equal(/^- id: mcp-new$/m.test(text), false, '新增绝不能写成顶层行(顶层行查不到就丢弃)')
1058
+ const lines = await facade.readPatchLines(USER_PATCH_FILE)
1059
+ assert.deepEqual(lines.map((l) => l.lineId), ['llm-pi-ai', 'mcp-a', 'plain-plugin', 'mcp-new'])
1060
+ } finally {
1061
+ cleanup()
1062
+ }
1063
+ })
1064
+
1065
+ test('#133 跨层提升:把另一层的 insert 成员写成顶层行必须拒写(文件不动)', async () => {
1066
+ const { home, cleanup } = patchHome()
1067
+ try {
1068
+ mkdirSync(join(home, 'profiles', 'web'), { recursive: true })
1069
+ writeFileSync(join(home, 'profiles', 'web', 'cordis.patch.yml'), INSERT_BLOCK_YAML.replace('- id: llm-pi-ai\n name: "@deepseek-ai/dsh-llm-pi-ai"\n', ''), 'utf8')
1070
+ const profileLayer = join(home, 'profiles', 'web', 'cordis.patch.yml')
1071
+ const before = readFileSync(profileLayer, 'utf8')
1072
+ const facade = new DshPatchFileFacade(home, 'web', zhMsg)
1073
+
1074
+ // 用户层此时不存在:写一条与 profile 层 insert 成员同 id 的顶层行 = 跨层语义翻转
1075
+ const err = await facade
1076
+ .applyPatchChanges(USER_PATCH_FILE, [{ lineId: 'mcp-a', raw: { id: 'mcp-a', name: 'dsh-mcp-client' }, action: 'update' }])
1077
+ .then(() => null, (e: unknown) => e as Error)
1078
+ assert.ok(err !== null, '跨层提升必须拒写')
1079
+ assert.match(String(err.message), /mcp-a/)
1080
+ assert.equal(existsSync(join(home, USER_PATCH_FILE)), false, '拒写 = 用户层文件一个字节都没写')
1081
+ assert.equal(readFileSync(profileLayer, 'utf8'), before, '另一层当然也不许动')
1082
+ } finally {
1083
+ cleanup()
1084
+ }
1085
+ })
1086
+
package/src/index.ts CHANGED
@@ -97,6 +97,7 @@ import { ImportUserSkippedError, type ConfigAdapter, type CredentialsFacade, typ
97
97
  import { PLUGIN_NPM_PACKAGE } from './core/update-check.ts'
98
98
  import { planSelfUpdate, runSelfUpdate, type SelfUpdateOutcome } from './core/self-update.ts'
99
99
  import { createAdapters } from './adapters/index.ts'
100
+ import { describePatchDocument, describePatchLayoutDrift, planPatchDocument, promotedTopLevelIds } from './core/patch-document.ts'
100
101
  import { isPatchLayerRel, profilePatchRel, readEffectivePatchLines, USER_PATCH_FILE } from './core/patch-layers.ts'
101
102
  import { createLocalPluginPackHook } from './core/local-plugin-host.ts'
102
103
  import { ENCRYPTED_CONTAINER_CODE, createEncryptionProvider, readContainerKind, encryptArchive } from './security/index.ts'
@@ -183,7 +184,7 @@ export const name = 'config-manager'
183
184
  export const inject = ['settings', 'credentials']
184
185
 
185
186
  /** Plugin version, kept in sync with package.json ("version"). */
186
- export const PLUGIN_VERSION = '0.8.0'
187
+ export const PLUGIN_VERSION = '0.8.1'
187
188
 
188
189
  /** Plugin own package name — excluded from its own exported plugins list. */
189
190
  const PLUGIN_NAME = 'dsh-config-manager'
@@ -1714,15 +1715,13 @@ export class DshPatchFileFacade implements PatchFileFacade {
1714
1715
  ): Promise<void> {
1715
1716
  const p = this.patchPath(file)
1716
1717
 
1717
- // 1. Load the current document into an ordered lineId → raw table.
1718
+ // 1. Load the current document (the ordered table itself is built by planPatchDocument).
1718
1719
  //
1719
1720
  // 读不出来的既有内容**绝不能当作空文档**(issue #75 的数据丢失点):重建后的文件只包含
1720
1721
  // 本次写入的行,等于把用户手写的其余行整段删掉。三种情况分开处理:
1721
1722
  // - 真不存在(ENOENT)→ 空文档(首次创建,既有语义);
1722
1723
  // - 存在但读不到(EACCES/EBUSY/…)→ 抛错,不改写;
1723
1724
  // - 存在但解析不了(含未知方言 / YAML 本身有错)→ 抛错,不改写。
1724
- const rows = new Map<string, unknown>()
1725
- const order: string[] = []
1726
1725
  let existing: string | null = null
1727
1726
  try {
1728
1727
  existing = await fs.readFile(p, 'utf8')
@@ -1739,55 +1738,46 @@ export class DshPatchFileFacade implements PatchFileFacade {
1739
1738
  throw new Error(this.msg('host.patchRefuseClobber', { file, reason: describePatchYamlError(err) }), { cause: err })
1740
1739
  }
1741
1740
  }
1742
- if (Array.isArray(doc)) {
1743
- for (const item of doc) {
1744
- if (item === null || typeof item !== 'object') continue
1745
- const obj = item as Record<string, unknown>
1746
- const insert = obj['insert']
1747
- if (Array.isArray(insert)) {
1748
- for (const entry of insert) {
1749
- if (entry === null || typeof entry !== 'object') continue
1750
- const id = (entry as Record<string, unknown>)['id']
1751
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1752
- rows.set(id, entry)
1753
- order.push(id)
1754
- }
1755
- }
1756
- continue
1757
- }
1758
- const id = obj['id']
1759
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1760
- rows.set(id, obj)
1761
- order.push(id)
1762
- }
1763
- }
1764
- }
1765
1741
 
1766
- // 2. Apply the changes.
1767
- for (const change of changes) {
1768
- if (change.action === 'remove') {
1769
- if (rows.delete(change.lineId)) {
1770
- const at = order.indexOf(change.lineId)
1771
- if (at >= 0) order.splice(at, 1)
1772
- }
1773
- } else if (change.action === 'insert' || change.action === 'update') {
1774
- if (!rows.has(change.lineId)) order.push(change.lineId)
1775
- rows.set(change.lineId, change.raw)
1776
- }
1742
+ // 2. Rebuild through core/patch-document.ts (issue #133): the two shapes are **not**
1743
+ // equivalent on the host side. A top-level `- id: X` row *overrides* entry X and is
1744
+ // dropped with `patch: entry "X" not found` when X does not exist; only an
1745
+ // `- insert:` block member *adds* entries. Emitting every row top-level therefore
1746
+ // turned one update into "every insert-only entry (MCP servers, most notably) is
1747
+ // gone after restart".
1748
+ const plan = planPatchDocument(doc, changes)
1749
+ const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1750
+ + dumpPatchDocument(plan.items)
1751
+
1752
+ // 3. Post-write structure self-check, before anything touches the disk: re-parse the
1753
+ // text we just serialized and require both id sets to match the plan item by item.
1754
+ // A serializer or dialect change that flattens or swallows insert blocks stops here
1755
+ // (zero write) instead of silently degrading every patch row to an override.
1756
+ const drift = describePatchLayoutDrift(plan, describePatchDocument(loadPatchDocument(text)))
1757
+ if (drift !== null) {
1758
+ throw new Error(this.msg('host.patchSemanticDrift', { file, detail: drift }))
1777
1759
  }
1778
1760
 
1779
- // 3. Rebuild: every id row is emitted as a top-level row. The loader treats
1780
- // a top-level { id, name } row exactly like an `- insert:` block member
1781
- // (dsh-base patch precedent), so the document stays semantically equal.
1782
- const out: unknown[] = []
1783
- for (const id of order) {
1784
- const raw = rows.get(id)
1785
- if (raw !== undefined) out.push(raw)
1761
+ // 4. 跨层提升守卫(issue #133):待写的顶层 id 若是**另一层**的 insert 成员,写下去就从
1762
+ // 「新增」变成「覆盖」(宿主查不到则丢弃)。对侧读不出来/解析不了只跳过守卫 —— 读护栏
1763
+ // 已在各自层报错,损坏的兄弟文件不该永久阻塞本层写入。
1764
+ const other = file === USER_PATCH_FILE ? profilePatchRel(this.profile) : USER_PATCH_FILE
1765
+ const promoted = promotedTopLevelIds(await this.readPatchDocQuietly(other), plan.topLevelIds)
1766
+ if (promoted.length > 0) {
1767
+ throw new Error(this.msg('host.patchRefusePromote', { file, ids: promoted.join(', ') }))
1786
1768
  }
1787
- const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1788
- + dumpPatchDocument(out)
1769
+
1789
1770
  await atomicWriteFile(p, text)
1790
1771
  }
1772
+
1773
+ /** 读另一层并解析;读不到/解析不了 → undefined(跨层守卫 fail-open,见 promotedTopLevelIds)。 */
1774
+ private async readPatchDocQuietly(file: string): Promise<unknown> {
1775
+ try {
1776
+ return loadPatchDocument(await fs.readFile(resolve(this.homeDir, file), 'utf8'))
1777
+ } catch {
1778
+ return undefined
1779
+ }
1780
+ }
1791
1781
  }
1792
1782
 
1793
1783
  /** File facade over $DSH_HOME, confined to the home root. */
@@ -102,7 +102,7 @@ test('接线守卫:patch 门面与 boot-safety 的 YAML 解析都必须走本
102
102
 
103
103
  assert.ok(index.includes('doc = loadPatchDocument(text)'), 'readPatchLines 必须用方言载入');
104
104
  assert.ok(index.includes('doc = loadPatchDocument(existing)'), 'applyPatchChanges 必须用方言载入既有文件');
105
- assert.ok(index.includes('+ dumpPatchDocument(out)'), '写回 patch 文件必须用方言(yaml.dump 会把 {__jsExpr} 写成普通 map)');
105
+ assert.match(index, /\+ dumpPatchDocument\((out|plan\.items)\)/, '写回 patch 文件必须用方言(yaml.dump 会把 {__jsExpr} 写成普通 map)');
106
106
  assert.match(
107
107
  index,
108
108
  /parseYaml:\s*\(text\)\s*=>\s*loadPatchDocument\(text\)/,