@aiwayds/dsh-opentui 0.27.1 → 0.28.0

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,724 @@
1
+ /**
2
+ * T8 — one-shot migration planner (pure function; no fs / no clock / no env).
3
+ *
4
+ * Given the text of the two legacy profiles plus the current new template,
5
+ * produce everything T8b needs to write: the `externalCarry` payload consumed
6
+ * by `converge` (T8a1), the config/keybindings payloads, the backup manifest,
7
+ * the marker (minus at/version/digest, which the caller fills), and a set of
8
+ * user-visible notices.
9
+ *
10
+ * Design refs: 06 §4.5, §4.6.1, §7.1–7.5; D6; D8-Q2; handoff §二.
11
+ *
12
+ * Hard rules encoded here:
13
+ * - source priority is per-leaf (opentui-inproc first), never "fall back
14
+ * because the inproc value happens to equal the template" (06 §7.3);
15
+ * - only values that deviate from the *source-side* template default become
16
+ * ext entries (06 R21 / §4.5.1);
17
+ * - forbidden families (permission / providers / inserts / old rows) and the
18
+ * four removed model ids are reported as `dropped`, never carried;
19
+ * - a legacy patch that fails to parse is never silently treated as empty:
20
+ * it is backed up, reported as `invalid-value`, and `canWriteMarker` is
21
+ * false so T8b retries on the next start;
22
+ * - template parse failure is a build-time bug and throws (06 §4.6.1);
23
+ * - `provider-keys.json` is backed up only, never treated as live credentials
24
+ * (D8-Q2: keys live in ~/.dsh/.credentials.yaml, re-login required).
25
+ */
26
+ import { parseDocument, isMap, isSeq, isScalar, isAlias } from 'yaml'
27
+
28
+ const JS_TAG = 'tag:yaml.org,2002:js'
29
+ const jsCustomTags = [{ tag: JS_TAG, resolve: (value) => value }]
30
+
31
+ /** Known client preference keys (everything else is still kept, only warned). */
32
+ const KNOWN_CONFIG_KEYS = new Set([
33
+ 'retentionDays', 'theme', 'skinMigration', 'slashUsage', 'footerHints', 'lang', 'session',
34
+ ])
35
+
36
+ /** The four model ids removed from the new template (D2 / 06 §7.2). */
37
+ const OLD_MODEL_IDS = [
38
+ 'glm-5.4',
39
+ 'mimo-v2.6-pro-ultraspeed',
40
+ 'hy4-flash-free',
41
+ 'qwen4-max',
42
+ ]
43
+
44
+ /** 06 §4.5: defaults of source A (`opentui`) used for deviation detection. */
45
+ const OPENTUI_DEFAULTS = {
46
+ 'subagent.maxActiveSubagents': 3,
47
+ 'session-log-deepseek.enabled': true,
48
+ 'agent-default-model.provider': 'opencode-go',
49
+ 'agent-default-model.model': 'deepseek-v4.1-flash',
50
+ 'agent-default-model.reasoningEffort': 'high',
51
+ }
52
+
53
+ /** Insert ids that already exist in the template → duplicate if migrated. */
54
+ const DUPLICATE_INSERT_IDS = new Set(['tool-ask-user', 'mcp-context7', 'dsh-opentui-approval-gate'])
55
+ const APPEND_PRESET_ID = 'preset-opentui-append-system'
56
+ /** Old HTTP-only rows with no bundle in the inproc profile. */
57
+ const DEAD_ROW_IDS = new Set(['web', 'ui-settings-general'])
58
+ /** Tool/agent rows the template regenerates verbatim (06 §7.2/§7.3). */
59
+ const TEMPLATE_OWNED_ROW_IDS = new Set([
60
+ 'tool-bash', 'tool-todo', 'tool-fs', 'tool-fs-search',
61
+ 'agent-instructions', 'tool-result-pruner', 'tool-web',
62
+ ])
63
+ /** Only these leaves of a carry row are migration candidates; anything else
64
+ * is a user value we cannot carry and must be reported (06 §7.5). */
65
+ const CARRY_LEAF_KEYS = {
66
+ subagent: new Set(['maxActiveSubagents', 'maxDepth']),
67
+ 'session-log-deepseek': new Set(['enabled']),
68
+ 'agent-default-model': new Set(['provider', 'model', 'reasoningEffort']),
69
+ }
70
+
71
+ /** The one nested insert config leaf that is a migration candidate. Its ext
72
+ * path carries the literal `config` segment so converge writes it to the
73
+ * matching insert entry rather than to a top-level row. */
74
+ const APPROVAL_POLICY_ID = 'dsh-approval-policy'
75
+ const WINDOW_SECONDS_PATH = `${APPROVAL_POLICY_ID}.config.windowSeconds`
76
+ /** Insert config leaves that are migration candidates; all others are audited
77
+ * as unknown user values, just like the top-level carry rows above. */
78
+ const CARRY_INSERT_LEAF_KEYS = {
79
+ [APPROVAL_POLICY_ID]: new Set(['windowSeconds']),
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // value helpers (mirror patch-ownership projection, no fs/clock)
84
+ // ---------------------------------------------------------------------------
85
+
86
+ function jsValue(payload) {
87
+ return { $js: payload }
88
+ }
89
+ function isJsValue(v) {
90
+ return v !== null && typeof v === 'object' && !Array.isArray(v) &&
91
+ Object.keys(v).length === 1 && typeof v.$js === 'string'
92
+ }
93
+ function isPlainObject(v) {
94
+ return v !== null && typeof v === 'object' && !Array.isArray(v) && !isJsValue(v)
95
+ }
96
+ function hasOwn(obj, key) {
97
+ return isPlainObject(obj) && Object.prototype.hasOwnProperty.call(obj, key)
98
+ }
99
+
100
+ /** Project a YAML node to a comparable plain value; `!!js` -> {$js:...}. */
101
+ function projectNode(node) {
102
+ if (node === null || node === undefined) return undefined
103
+ if (isAlias(node)) return projectNode(node.resolve())
104
+ if (isMap(node)) {
105
+ const out = {}
106
+ for (const pair of node.items) {
107
+ const key = pair.key === null || pair.key === undefined ? undefined : String(pair.key.value)
108
+ if (key === undefined || hasOwn(out, key)) continue
109
+ out[key] = projectNode(pair.value)
110
+ }
111
+ return out
112
+ }
113
+ if (isSeq(node)) return node.items.map((item) => projectNode(item))
114
+ if (isScalar(node)) {
115
+ if (node.tag === JS_TAG) return jsValue(node.value)
116
+ return node.value === undefined ? null : node.value
117
+ }
118
+ return undefined
119
+ }
120
+
121
+ function scalarOf(node) {
122
+ return isScalar(node) ? node.value : undefined
123
+ }
124
+
125
+ function cloneValue(v) {
126
+ if (Array.isArray(v)) return v.map(cloneValue)
127
+ if (isJsValue(v)) return jsValue(v.$js)
128
+ if (isPlainObject(v)) {
129
+ const out = {}
130
+ for (const k of Object.keys(v)) out[k] = cloneValue(v[k])
131
+ return out
132
+ }
133
+ return v
134
+ }
135
+
136
+ function getIn(obj, parts) {
137
+ let cur = obj
138
+ for (const key of parts) {
139
+ if (!hasOwn(cur, key)) return undefined
140
+ cur = cur[key]
141
+ }
142
+ return cur
143
+ }
144
+
145
+ function deepEqual(a, b) {
146
+ if (a === b) return true
147
+ if (Array.isArray(a) && Array.isArray(b)) {
148
+ return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]))
149
+ }
150
+ if (isPlainObject(a) && isPlainObject(b)) {
151
+ const ka = Object.keys(a)
152
+ const kb = Object.keys(b)
153
+ return ka.length === kb.length && ka.every((k) => hasOwn(b, k) && deepEqual(a[k], b[k]))
154
+ }
155
+ return false
156
+ }
157
+
158
+ // ---------------------------------------------------------------------------
159
+ // patch parsing (P1-1 / P1-3)
160
+ // ---------------------------------------------------------------------------
161
+
162
+ function emptyIndex() {
163
+ // insertRows holds the projected config of nested insert entries (keyed by
164
+ // entry id), so migration can read leaves such as the approval window that
165
+ // are not top-level rows.
166
+ return { rows: new Map(), inserts: [], insertRows: new Map() }
167
+ }
168
+
169
+ /**
170
+ * Parse a patch into `{ index, parseError }`.
171
+ *
172
+ * `yaml.parseDocument` does NOT throw on most syntax errors — `doc.errors`
173
+ * holds them. A non-empty legacy patch that fails to parse, or whose top level
174
+ * is not a sequence, yields an empty index WITH `parseError: true`, so the
175
+ * caller can refuse to write a marker (06 §7.4 "迁移写失败 → 不写 marker").
176
+ */
177
+ function indexPatch(text) {
178
+ const index = emptyIndex()
179
+ if (typeof text !== 'string' || text.length === 0) return { index, parseError: false }
180
+ let doc
181
+ try {
182
+ doc = parseDocument(text, { customTags: jsCustomTags })
183
+ } catch {
184
+ return { index, parseError: true }
185
+ }
186
+ if (!doc || doc.errors.length > 0 || !isSeq(doc.contents)) {
187
+ return { index, parseError: true }
188
+ }
189
+ for (const item of doc.contents.items) {
190
+ if (!isMap(item)) continue
191
+ const insertNode = item.get('insert', true)
192
+ if (isSeq(insertNode)) {
193
+ const ids = []
194
+ for (const entry of insertNode.items) {
195
+ if (isMap(entry)) {
196
+ const id = scalarOf(entry.get('id', true))
197
+ if (id !== undefined && id !== null) {
198
+ const key = String(id)
199
+ ids.push(key)
200
+ index.insertRows.set(key, projectNode(entry.get('config', true)))
201
+ }
202
+ }
203
+ }
204
+ const target = scalarOf(item.get('id', true))
205
+ index.inserts.push({ target: target == null ? undefined : String(target), ids })
206
+ continue
207
+ }
208
+ const id = scalarOf(item.get('id', true))
209
+ if (id === undefined || id === null) continue
210
+ const cfgNode = item.get('config', true)
211
+ index.rows.set(String(id), projectNode(cfgNode))
212
+ }
213
+ return { index, parseError: false }
214
+ }
215
+
216
+ /** Template errors are build-time bugs: fail fast (06 §4.6.1). */
217
+ function parseTemplate(text) {
218
+ const { index, parseError } = indexPatch(text)
219
+ if (parseError) {
220
+ throw new Error(
221
+ '迁移模板解析失败:cordis.patch.yml 模板存在语法错误或顶层不是序列(06 §4.6.1:构建期 bug)。',
222
+ )
223
+ }
224
+ return index
225
+ }
226
+
227
+ /** Projected provider table of the current template (for ADM group validation). */
228
+ function templateProviders(templateIndex) {
229
+ const cfg = templateIndex?.rows.get('llm-pi-ai')
230
+ return isPlainObject(cfg) ? cfg.providers : undefined
231
+ }
232
+
233
+ function leafFromConfig(index, rowId, leafParts) {
234
+ const cfg = index?.rows.get(rowId)
235
+ return hasOwn(cfg, leafParts[0]) ? getIn(cfg, leafParts) : undefined
236
+ }
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // per-leaf extraction (06 §7.3 source priority)
240
+ // ---------------------------------------------------------------------------
241
+
242
+ const SIMPLE_LEAVES = [
243
+ { path: 'subagent.maxActiveSubagents', row: 'subagent', leaf: ['maxActiveSubagents'], inprocOnly: false },
244
+ { path: 'subagent.maxDepth', row: 'subagent', leaf: ['maxDepth'], inprocOnly: true },
245
+ { path: 'session-log-deepseek.enabled', row: 'session-log-deepseek', leaf: ['enabled'], inprocOnly: false },
246
+ ]
247
+
248
+ /**
249
+ * Pick the first source that *has* the leaf (inproc first). Presence, not its
250
+ * value, decides priority — an inproc value equal to the template is still a
251
+ * no-op and must NOT fall back to the older opentui value (06 §7.3).
252
+ */
253
+ function pickLeafSource(spec, inproc, opentui) {
254
+ const sources = [['opentui-inproc', inproc]]
255
+ if (!spec.inprocOnly) sources.push(['opentui', opentui])
256
+ for (const [name, index] of sources) {
257
+ if (!index) continue
258
+ const value = leafFromConfig(index, spec.row, spec.leaf)
259
+ if (value !== undefined) return { name, value }
260
+ }
261
+ return undefined
262
+ }
263
+
264
+ function validateSimpleLeaf(path, value) {
265
+ if (isJsValue(value)) return { ok: false, reason: 'invalid-value' }
266
+ if (path === 'session-log-deepseek.enabled') {
267
+ return typeof value === 'boolean' ? { ok: true } : { ok: false, reason: 'invalid-value' }
268
+ }
269
+ // subagent.maxActiveSubagents / subagent.maxDepth
270
+ if (typeof value === 'number' && Number.isInteger(value) && value >= 1) return { ok: true }
271
+ return { ok: false, reason: 'invalid-value' }
272
+ }
273
+
274
+ /** Source-side template default for a simple leaf (inproc: current template). */
275
+ function simpleDefault(path, sourceName, templateIndex) {
276
+ if (sourceName === 'opentui') return OPENTUI_DEFAULTS[path]
277
+ const spec = SIMPLE_LEAVES.find((s) => s.path === path)
278
+ const fromTemplate = spec ? leafFromConfig(templateIndex, spec.row, spec.leaf) : undefined
279
+ return fromTemplate !== undefined ? fromTemplate : OPENTUI_DEFAULTS[path]
280
+ }
281
+
282
+ // ---------------------------------------------------------------------------
283
+ // nested insert leaf: dsh-approval-policy.config.windowSeconds
284
+ // ---------------------------------------------------------------------------
285
+
286
+ /** Read windowSeconds from a source's dsh-approval-policy insert, if present. */
287
+ function approvalWindow(index) {
288
+ if (!index || !index.insertRows.has(APPROVAL_POLICY_ID)) return undefined
289
+ const cfg = index.insertRows.get(APPROVAL_POLICY_ID)
290
+ return hasOwn(cfg, 'windowSeconds') ? cfg.windowSeconds : undefined
291
+ }
292
+
293
+ /** Per-leaf source priority: inproc first, fall back to opentui only when the
294
+ * inproc insert has no such leaf (presence, not value, decides). */
295
+ function pickApprovalWindow(inproc, opentui) {
296
+ // A leaf present as `null` is still a user value (an invalid one), not an
297
+ // absent leaf: approvalWindow returns null here, which this check keeps.
298
+ const value = approvalWindow(inproc)
299
+ if (value !== undefined) return { name: 'opentui-inproc', value }
300
+ const fromOpentui = approvalWindow(opentui)
301
+ if (fromOpentui !== undefined) return { name: 'opentui', value: fromOpentui }
302
+ return undefined
303
+ }
304
+
305
+ /** Policy hard bound: finite number in [0, 86400]. Strings, NaN/Infinity and
306
+ * !!js markers are rejected so migration never widens the safety boundary. */
307
+ function validWindowSeconds(value) {
308
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 86400
309
+ }
310
+
311
+ // ---------------------------------------------------------------------------
312
+ // agent-default-model group (R22 — atomic, but per-leaf sources: 06 §7.3)
313
+ // ---------------------------------------------------------------------------
314
+
315
+ /** Mirror of converge's admGroupValid (T8a1) against the current template. */
316
+ function validateAdmGroup(group, providers) {
317
+ if (typeof group.provider !== 'string' || typeof group.model !== 'string') {
318
+ return { ok: false, reason: 'invalid-value' }
319
+ }
320
+ if (group.reasoningEffort !== undefined && typeof group.reasoningEffort !== 'string') {
321
+ return { ok: false, reason: 'invalid-value' }
322
+ }
323
+ if (!isPlainObject(providers) || !hasOwn(providers, group.provider)) {
324
+ return { ok: false, reason: 'model-id-not-in-template' }
325
+ }
326
+ const provider = providers[group.provider]
327
+ const models = Array.isArray(provider.models) ? provider.models : []
328
+ const model = models.find((m) => isPlainObject(m) && m.id === group.model)
329
+ let found = !!model
330
+ if (!found && isPlainObject(provider.modelOverrides) && hasOwn(provider.modelOverrides, group.model)) {
331
+ found = true
332
+ }
333
+ if (!found) return { ok: false, reason: 'model-id-not-in-template' }
334
+ if (group.reasoningEffort !== undefined && model && isPlainObject(model.reasoningEfforts) &&
335
+ !hasOwn(model.reasoningEfforts, group.reasoningEffort)) {
336
+ return { ok: false, reason: 'invalid-value' }
337
+ }
338
+ return { ok: true }
339
+ }
340
+
341
+ function admDefaults(sourceName, templateIndex) {
342
+ if (sourceName === 'opentui') {
343
+ return {
344
+ provider: OPENTUI_DEFAULTS['agent-default-model.provider'],
345
+ model: OPENTUI_DEFAULTS['agent-default-model.model'],
346
+ reasoningEffort: OPENTUI_DEFAULTS['agent-default-model.reasoningEffort'],
347
+ }
348
+ }
349
+ const cfg = templateIndex?.rows.get('agent-default-model')
350
+ return {
351
+ provider: hasOwn(cfg, 'provider') ? cfg.provider : OPENTUI_DEFAULTS['agent-default-model.provider'],
352
+ model: hasOwn(cfg, 'model') ? cfg.model : OPENTUI_DEFAULTS['agent-default-model.model'],
353
+ reasoningEffort: hasOwn(cfg, 'reasoningEffort')
354
+ ? cfg.reasoningEffort
355
+ : OPENTUI_DEFAULTS['agent-default-model.reasoningEffort'],
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Resolve the ADM group leaf-by-leaf (inproc first), then validate the whole
361
+ * group with R22. A bad group is dropped atomically, never half-carried.
362
+ * Returns `{ values, drop, provenance }`.
363
+ */
364
+ function planAdm(inproc, opentui, templateIndex) {
365
+ const sources = [['opentui-inproc', inproc], ['opentui', opentui]]
366
+ const group = {}
367
+ /** @type {Record<string,string>} leaf -> contributing source */
368
+ const provenance = {}
369
+ for (const key of ['provider', 'model', 'reasoningEffort']) {
370
+ for (const [name, index] of sources) {
371
+ const cfg = index?.rows.get('agent-default-model')
372
+ if (hasOwn(cfg, key)) {
373
+ group[key] = cfg[key]
374
+ provenance[key] = name
375
+ break
376
+ }
377
+ }
378
+ }
379
+ if (Object.keys(group).length === 0) {
380
+ // A present-but-unusable row is still a rejected migration, not a silent skip.
381
+ for (const [name, index] of sources) {
382
+ if (index && index.rows.has('agent-default-model') && !isPlainObject(index.rows.get('agent-default-model'))) {
383
+ return { values: undefined, drop: { path: 'agent-default-model', reason: 'invalid-value', source: name } }
384
+ }
385
+ }
386
+ return { values: undefined, drop: undefined, provenance }
387
+ }
388
+
389
+ const verdict = validateAdmGroup(group, templateProviders(templateIndex))
390
+ if (!verdict.ok) {
391
+ const source = provenance.provider || provenance.model || provenance.reasoningEffort || 'opentui-inproc'
392
+ return { values: undefined, drop: { path: 'agent-default-model', reason: verdict.reason, source }, provenance }
393
+ }
394
+
395
+ // R22 is atomic: if ANY leaf deviates from its source-side default, the
396
+ // whole group is carried (including leaves equal to the template).
397
+ const deviates = Object.keys(group).some((key) =>
398
+ !deepEqual(group[key], admDefaults(provenance[key], templateIndex)[key]))
399
+ if (!deviates) return { values: undefined, drop: undefined, provenance }
400
+
401
+ const values = {}
402
+ for (const key of Object.keys(group)) values[`agent-default-model.${key}`] = cloneValue(group[key])
403
+ return { values, drop: undefined, provenance }
404
+ }
405
+
406
+ // ---------------------------------------------------------------------------
407
+ // forbidden-item reporting (06 §7.2/§7.3, §7.5 reason codes)
408
+ // ---------------------------------------------------------------------------
409
+
410
+ function collectForbidden(sourceName, index, templateIndex, out) {
411
+ const add = (path, reason) => out.push({ id: sourceName, path, reason })
412
+
413
+ const permission = index.rows.get('permission')
414
+ if (isPlainObject(permission)) {
415
+ if (hasOwn(permission, 'defaultPreset')) add('permission.defaultPreset', 'template-authority')
416
+ if (hasOwn(permission, 'presets')) add('permission.presets', 'sandbox-loosening-forbidden')
417
+ }
418
+
419
+ const llm = index.rows.get('llm-pi-ai')
420
+ if (isPlainObject(llm) && hasOwn(llm, 'providers')) {
421
+ add('llm-pi-ai.providers', 'model-table-template-owned')
422
+ const templateProvs = templateProviders(templateIndex)
423
+ const sourceProvs = llm.providers
424
+ if (isPlainObject(sourceProvs)) {
425
+ for (const id of Object.keys(sourceProvs)) {
426
+ if (!hasOwn(templateProvs, id)) add(`providers.${id}`, 'credentials-channel-pending')
427
+ }
428
+ // P1-2: only ids that ACTUALLY occur in the source table are reported.
429
+ // Never fabricate the four removed ids into the audit array.
430
+ for (const oldId of OLD_MODEL_IDS) {
431
+ for (const provider of Object.values(sourceProvs)) {
432
+ const models = isPlainObject(provider) && Array.isArray(provider.models) ? provider.models : []
433
+ if (models.some((m) => isPlainObject(m) && m.id === oldId)) {
434
+ add(`model.${oldId}`, 'model-id-not-in-template')
435
+ break
436
+ }
437
+ }
438
+ }
439
+ }
440
+ }
441
+
442
+ for (const insert of index.inserts) {
443
+ const isAppendBlock = insert.ids.includes(APPEND_PRESET_ID)
444
+ for (const id of insert.ids) {
445
+ if (isAppendBlock) add(`insert.${id}`, 'append-preset-unused')
446
+ else if (DUPLICATE_INSERT_IDS.has(id)) add(`insert.${id}`, 'duplicate-insert')
447
+ }
448
+ }
449
+ for (const id of index.rows.keys()) {
450
+ if (DEAD_ROW_IDS.has(id)) add(id, 'dead-row-no-bundle')
451
+ // Template-owned rows DO exist in the template — they are regenerated,
452
+ // not dead. 06 §7.5 calls this `row-replaced-by-leaf` for both sources.
453
+ else if (TEMPLATE_OWNED_ROW_IDS.has(id)) add(id, 'row-replaced-by-leaf')
454
+ }
455
+ }
456
+
457
+ /** P2-3/P2-7: recognizable user values under carry rows/insert configs that
458
+ * are not whitelisted. */
459
+ function collectUnknownLeaves(sourceName, index, out, unknownPaths) {
460
+ const collect = (rowId, cfg, allowedKeys, prefix) => {
461
+ if (!allowedKeys || !isPlainObject(cfg)) return
462
+ for (const key of Object.keys(cfg)) {
463
+ if (allowedKeys.has(key)) continue
464
+ const path = `${rowId}.${prefix}${key}`
465
+ out.push({ id: sourceName, path, reason: 'invalid-value' })
466
+ unknownPaths.push(path)
467
+ }
468
+ }
469
+ for (const [rowId, cfg] of index.rows) {
470
+ const allowed = hasOwn(CARRY_LEAF_KEYS, rowId) ? CARRY_LEAF_KEYS[rowId] : undefined
471
+ collect(rowId, cfg, allowed, '')
472
+ }
473
+ for (const [rowId, cfg] of index.insertRows) {
474
+ const allowed = hasOwn(CARRY_INSERT_LEAF_KEYS, rowId) ? CARRY_INSERT_LEAF_KEYS[rowId] : undefined
475
+ collect(rowId, cfg, allowed, 'config.')
476
+ }
477
+ }
478
+
479
+ /** P2-6: pass through source A text, but flag invalid JSON instead of
480
+ * silently presenting it as a legal payload. T8b decides reject vs backup. */
481
+ function jsonPayload(text) {
482
+ if (typeof text !== 'string') return undefined
483
+ try {
484
+ JSON.parse(text)
485
+ return { source: 'opentui', text }
486
+ } catch {
487
+ return { source: 'opentui', text, invalid: true }
488
+ }
489
+ }
490
+
491
+ // ---------------------------------------------------------------------------
492
+ // main export
493
+ // ---------------------------------------------------------------------------
494
+
495
+ /**
496
+ * @param {object} input
497
+ * @returns {{
498
+ * externalCarry: {source:string, values:Record<string,unknown>, dropped:{path:string,reason:string}[]}|undefined,
499
+ * config: {source:'opentui', text:string, invalid?:boolean}|undefined,
500
+ * keybindings: {source:'opentui', text:string, invalid?:boolean}|undefined,
501
+ * backups: {source:string, kind:string, text:string}[],
502
+ * marker: {from:string[], migrated:string[], dropped:{id:string,path:string,reason:string}[]}|undefined,
503
+ * notices: string[],
504
+ * canWriteMarker: boolean
505
+ * }}
506
+ */
507
+ export function planMigration({
508
+ markerExists,
509
+ inprocPatchText,
510
+ opentuiPatchText,
511
+ templatePatchText,
512
+ opentuiConfigText,
513
+ opentuiKeybindingsText,
514
+ opentuiProviderKeysText,
515
+ } = {}) {
516
+ // Marker present: skip everything, do NOT even parse the (possibly corrupt)
517
+ // legacy text. Nothing must be written in this branch.
518
+ if (markerExists === true) {
519
+ return {
520
+ externalCarry: undefined,
521
+ config: undefined,
522
+ keybindings: undefined,
523
+ backups: [],
524
+ marker: undefined,
525
+ notices: ['检测到迁移 marker(.migration.json),此前已迁移,跳过迁移并直接收敛。'],
526
+ canWriteMarker: false,
527
+ }
528
+ }
529
+
530
+ const hasInprocPatch = typeof inprocPatchText === 'string' && inprocPatchText.length > 0
531
+ const hasOpentuiPatch = typeof opentuiPatchText === 'string' && opentuiPatchText.length > 0
532
+ const hasAnyOldPatch = hasInprocPatch || hasOpentuiPatch
533
+
534
+ const templateIndex = parseTemplate(templatePatchText)
535
+ const inprocParsed = hasInprocPatch ? indexPatch(inprocPatchText) : undefined
536
+ const opentuiParsed = hasOpentuiPatch ? indexPatch(opentuiPatchText) : undefined
537
+ const inproc = inprocParsed?.index
538
+ const opentui = opentuiParsed?.index
539
+
540
+ // ---- dropped bookkeeping (id + path + reason) --------------------------
541
+ /** @type {{id:string,path:string,reason:string}[]} */
542
+ const dropped = []
543
+ /** @type {string[]} paths of unrecognized user leaves, for the notice */
544
+ const unknownPaths = []
545
+ /** @type {string[]} sources whose legacy patch could not be parsed */
546
+ const parseFailures = []
547
+ if (inprocParsed?.parseError) {
548
+ parseFailures.push('opentui-inproc')
549
+ dropped.push({ id: 'opentui-inproc', path: 'opentui-inproc-cordis.patch.yml', reason: 'invalid-value' })
550
+ }
551
+ if (opentuiParsed?.parseError) {
552
+ parseFailures.push('opentui')
553
+ dropped.push({ id: 'opentui', path: 'opentui-cordis.patch.yml', reason: 'invalid-value' })
554
+ }
555
+ if (inproc) collectForbidden('opentui-inproc', inproc, templateIndex, dropped)
556
+ if (opentui) collectForbidden('opentui', opentui, templateIndex, dropped)
557
+ if (inproc) collectUnknownLeaves('opentui-inproc', inproc, dropped, unknownPaths)
558
+ if (opentui) collectUnknownLeaves('opentui', opentui, dropped, unknownPaths)
559
+ // P1-2: the four removed model ids appear in `dropped` ONLY when the source
560
+ // provider table actually contains them (see collectForbidden). A release
561
+ // note about the smaller selector is emitted separately, never as an audit
562
+ // entry.
563
+
564
+ // de-duplicate identical (path,reason) pairs coming from both sources
565
+ const seenDrop = new Set()
566
+ const uniqueDropped = dropped.filter((d) => {
567
+ const key = `${d.path}|${d.reason}`
568
+ if (seenDrop.has(key)) return false
569
+ seenDrop.add(key)
570
+ return true
571
+ })
572
+
573
+ // ---- externalCarry.values ---------------------------------------------
574
+ /** @type {Record<string, unknown>} */
575
+ const values = {}
576
+ /** @type {string[]} */
577
+ const migrated = []
578
+ /** @type {Record<string,string>} path -> contributing source */
579
+ const valueSource = {}
580
+ let carriedFromInproc = false
581
+
582
+ for (const spec of SIMPLE_LEAVES) {
583
+ const picked = pickLeafSource(spec, inproc, opentui)
584
+ if (!picked) continue
585
+ const verdict = validateSimpleLeaf(spec.path, picked.value)
586
+ if (!verdict.ok) {
587
+ uniqueDropped.push({ id: picked.name, path: spec.path, reason: verdict.reason })
588
+ continue
589
+ }
590
+ const def = simpleDefault(spec.path, picked.name, templateIndex)
591
+ if (def !== undefined && deepEqual(picked.value, def)) continue
592
+ values[spec.path] = cloneValue(picked.value)
593
+ valueSource[spec.path] = picked.name
594
+ migrated.push(spec.path)
595
+ if (picked.name === 'opentui-inproc') carriedFromInproc = true
596
+ }
597
+
598
+ // Nested insert leaf. The source-side default is the template's own window
599
+ // (300 in the shipped template); only a source that actually carries the
600
+ // insert leaf is a user value. Invalid values are dropped per leaf and do
601
+ // not stop the other leaves from migrating.
602
+ const tplWindowCfg = templateIndex.insertRows.get(APPROVAL_POLICY_ID)
603
+ const tplWindow = hasOwn(tplWindowCfg, 'windowSeconds') ? tplWindowCfg.windowSeconds : undefined
604
+ if (tplWindow !== undefined) {
605
+ const picked = pickApprovalWindow(inproc, opentui)
606
+ if (picked) {
607
+ if (!validWindowSeconds(picked.value)) {
608
+ uniqueDropped.push({ id: picked.name, path: WINDOW_SECONDS_PATH, reason: 'invalid-value' })
609
+ } else if (!deepEqual(picked.value, tplWindow)) {
610
+ values[WINDOW_SECONDS_PATH] = cloneValue(picked.value)
611
+ valueSource[WINDOW_SECONDS_PATH] = picked.name
612
+ migrated.push(WINDOW_SECONDS_PATH)
613
+ if (picked.name === 'opentui-inproc') carriedFromInproc = true
614
+ }
615
+ }
616
+ }
617
+
618
+ const adm = planAdm(inproc, opentui, templateIndex)
619
+ if (adm.drop) uniqueDropped.push({ id: adm.drop.source, path: adm.drop.path, reason: adm.drop.reason })
620
+ if (adm.values) {
621
+ for (const [path, value] of Object.entries(adm.values)) {
622
+ const leaf = path.slice('agent-default-model.'.length)
623
+ values[path] = value
624
+ valueSource[path] = adm.provenance[leaf] || 'opentui-inproc'
625
+ migrated.push(path)
626
+ if (valueSource[path] === 'opentui-inproc') carriedFromInproc = true
627
+ }
628
+ }
629
+
630
+ // ext is only meaningful when at least one legacy patch existed. Even a
631
+ // no-op patch still yields an ext (with `dropped`) so converge surfaces the
632
+ // forbidden items; we never fabricate ext for a clean home.
633
+ let externalCarry
634
+ if (hasAnyOldPatch) {
635
+ const fromOpentui = Object.keys(valueSource).some((p) => valueSource[p] === 'opentui')
636
+ externalCarry = {
637
+ source: carriedFromInproc || (!fromOpentui && hasInprocPatch) ? 'opentui-inproc' : 'opentui',
638
+ values: cloneValue(values),
639
+ dropped: uniqueDropped.map(({ path, reason }) => ({ path, reason })),
640
+ }
641
+ }
642
+
643
+ // ---- config / keybindings (source A only) ------------------------------
644
+ const config = jsonPayload(opentuiConfigText)
645
+ const keybindings = jsonPayload(opentuiKeybindingsText)
646
+
647
+ // ---- backups: two legacy patches + provider-keys (if present) ----------
648
+ /** @type {{source:string,kind:string,text:string}[]} */
649
+ const backups = []
650
+ if (hasInprocPatch) backups.push({ source: 'opentui-inproc', kind: 'cordis.patch.yml', text: inprocPatchText })
651
+ if (hasOpentuiPatch) backups.push({ source: 'opentui', kind: 'cordis.patch.yml', text: opentuiPatchText })
652
+ const hasProviderKeys = typeof opentuiProviderKeysText === 'string' && opentuiProviderKeysText.length > 0
653
+ if (hasProviderKeys) backups.push({ source: 'opentui', kind: 'provider-keys.json', text: opentuiProviderKeysText })
654
+
655
+ // ---- marker (caller adds at/version/digest) ----------------------------
656
+ const hasAnyLegacyArtifact = hasAnyOldPatch || !!config || !!keybindings || hasProviderKeys
657
+ /** @type {{from:string[],migrated:string[],dropped:{id:string,path:string,reason:string}[]}|undefined} */
658
+ let marker
659
+ if (hasAnyLegacyArtifact) {
660
+ const from = []
661
+ if (hasInprocPatch) from.push('opentui-inproc')
662
+ if (hasOpentuiPatch || config || keybindings || hasProviderKeys) from.push('opentui')
663
+ marker = {
664
+ from,
665
+ migrated: [...migrated],
666
+ dropped: uniqueDropped.map((d) => ({ ...d })),
667
+ }
668
+ }
669
+
670
+ // P1-1: a bad legacy patch is backed up but MUST NOT leave a marker — T8b
671
+ // uses this flag to skip the write, so the next start retries the migration.
672
+ const canWriteMarker = parseFailures.length === 0
673
+
674
+ // ---- notices (user-visible, 06 §7.5) ----------------------------------
675
+ const notices = []
676
+ for (const source of parseFailures) {
677
+ notices.push(`dropped ${source}-cordis.patch.yml reason=invalid-value`)
678
+ notices.push(`${source} 的旧 patch 解析失败,已备份但未迁移/未写入新 profile,请修复后等待下次启动重试。`)
679
+ }
680
+ // A clean home has nothing to migrate — no summary, no approval, no model note.
681
+ if (hasAnyLegacyArtifact && parseFailures.length === 0) {
682
+ notices.push(`迁移完成:迁入 ${migrated.length} 项,丢弃 ${uniqueDropped.length} 项,备份 ${backups.length} 份。`)
683
+ }
684
+ // 06 §7.5.4: only claim the approval default if it was actually discarded.
685
+ if (uniqueDropped.some((d) => d.path === 'permission.defaultPreset')) {
686
+ notices.push('审批默认档位保持 workspace-write;如需放开请在 /permission 里改。')
687
+ }
688
+ if (hasAnyOldPatch) {
689
+ // Release note only (P1-2): the selector has four fewer entries. Never a
690
+ // claim that these were read from, or dropped out of, the source table.
691
+ notices.push(`以下 4 个旧模型 id 已从新模板移除(选择器少 4 项):${OLD_MODEL_IDS.join('、')}。`)
692
+ }
693
+ if (unknownPaths.length > 0) {
694
+ notices.push(`以下未知字段未迁移(已丢弃):${[...new Set(unknownPaths)].join('、')}。`)
695
+ }
696
+ if (config) {
697
+ if (config.invalid) {
698
+ notices.push('config.json 解析失败:已备份、未写入新 profile,需人工修复;原文原样保留。')
699
+ } else {
700
+ let unknown = []
701
+ try {
702
+ const parsed = JSON.parse(opentuiConfigText)
703
+ if (isPlainObject(parsed)) unknown = Object.keys(parsed).filter((k) => !KNOWN_CONFIG_KEYS.has(k))
704
+ } catch {
705
+ notices.push('config.json 解析失败:将原文原样保留,请人工检查。')
706
+ }
707
+ if (unknown.length > 0) notices.push(`config.json 已整份保留,未知键未丢弃:${unknown.join('、')}。`)
708
+ }
709
+ }
710
+ if (keybindings) {
711
+ if (keybindings.invalid) {
712
+ notices.push('keybindings.json 解析失败:已备份、未写入新 profile,需人工修复;原文原样保留。')
713
+ } else {
714
+ notices.push('keybindings.json 已整份带回。')
715
+ }
716
+ }
717
+ if (hasProviderKeys) {
718
+ notices.push('旧 provider-keys.json 已备份;新版请重新 /login,宿主凭据在 ~/.dsh/.credentials.yaml。')
719
+ }
720
+
721
+ return { externalCarry, config, keybindings, backups, marker, notices, canWriteMarker }
722
+ }
723
+
724
+ export default planMigration