@aiwayds/dsh-model-sync 0.9.0 → 0.11.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.
Files changed (74) hide show
  1. package/README.md +20 -3
  2. package/README.zh-CN.md +20 -3
  3. package/lib/builtin-catalog-snapshot.js +6 -3
  4. package/lib/builtin-catalog-snapshot.js.map +1 -1
  5. package/lib/index.d.ts +379 -0
  6. package/lib/index.js +897 -13
  7. package/lib/index.js.map +1 -1
  8. package/lib/opencode-go-diagnose.d.ts +74 -0
  9. package/lib/opencode-go-diagnose.js +146 -0
  10. package/lib/opencode-go-diagnose.js.map +1 -0
  11. package/lib/opencode-go-grouping.d.ts +29 -0
  12. package/lib/opencode-go-grouping.js +77 -0
  13. package/lib/opencode-go-grouping.js.map +1 -0
  14. package/lib/opencode-go-journal.d.ts +110 -0
  15. package/lib/opencode-go-journal.js +406 -0
  16. package/lib/opencode-go-journal.js.map +1 -0
  17. package/lib/opencode-go-migrate.d.ts +343 -0
  18. package/lib/opencode-go-migrate.js +1300 -0
  19. package/lib/opencode-go-migrate.js.map +1 -0
  20. package/lib/opencode-go-migration.d.ts +227 -0
  21. package/lib/opencode-go-migration.js +384 -0
  22. package/lib/opencode-go-migration.js.map +1 -0
  23. package/lib/opencode-go-one-shot.d.ts +276 -0
  24. package/lib/opencode-go-one-shot.js +1094 -0
  25. package/lib/opencode-go-one-shot.js.map +1 -0
  26. package/lib/opencode-go-patch-file.d.ts +123 -0
  27. package/lib/opencode-go-patch-file.js +1185 -0
  28. package/lib/opencode-go-patch-file.js.map +1 -0
  29. package/lib/opencode-go-planner.d.ts +153 -0
  30. package/lib/opencode-go-planner.js +339 -0
  31. package/lib/opencode-go-planner.js.map +1 -0
  32. package/lib/opencode-go-profile.d.ts +57 -0
  33. package/lib/opencode-go-profile.js +103 -0
  34. package/lib/opencode-go-profile.js.map +1 -0
  35. package/lib/opencode-go-scheduler.d.ts +128 -0
  36. package/lib/opencode-go-scheduler.js +241 -0
  37. package/lib/opencode-go-scheduler.js.map +1 -0
  38. package/lib/opencode-go-source.d.ts +117 -0
  39. package/lib/opencode-go-source.js +331 -0
  40. package/lib/opencode-go-source.js.map +1 -0
  41. package/lib/opencode-go-store.d.ts +18 -0
  42. package/lib/opencode-go-store.js +68 -0
  43. package/lib/opencode-go-store.js.map +1 -0
  44. package/lib/opencode-go-sync.d.ts +94 -0
  45. package/lib/opencode-go-sync.js +364 -0
  46. package/lib/opencode-go-sync.js.map +1 -0
  47. package/lib/opencode-go-writer.d.ts +132 -0
  48. package/lib/opencode-go-writer.js +966 -0
  49. package/lib/opencode-go-writer.js.map +1 -0
  50. package/lib/provider-native.d.ts +3 -1
  51. package/lib/provider-native.js +4 -2
  52. package/lib/provider-native.js.map +1 -1
  53. package/lib/remote-catalog.d.ts +61 -0
  54. package/lib/remote-catalog.js +307 -3
  55. package/lib/remote-catalog.js.map +1 -1
  56. package/package.json +15 -15
  57. package/src/builtin-catalog-snapshot.ts +6 -3
  58. package/src/index.ts +1060 -12
  59. package/src/opencode-go-diagnose.ts +222 -0
  60. package/src/opencode-go-grouping.ts +97 -0
  61. package/src/opencode-go-journal.ts +458 -0
  62. package/src/opencode-go-migrate.ts +1694 -0
  63. package/src/opencode-go-migration.ts +552 -0
  64. package/src/opencode-go-one-shot.ts +1354 -0
  65. package/src/opencode-go-patch-file.ts +1168 -0
  66. package/src/opencode-go-planner.ts +505 -0
  67. package/src/opencode-go-profile.ts +114 -0
  68. package/src/opencode-go-scheduler.ts +315 -0
  69. package/src/opencode-go-source.ts +424 -0
  70. package/src/opencode-go-store.ts +73 -0
  71. package/src/opencode-go-sync.ts +503 -0
  72. package/src/opencode-go-writer.ts +1189 -0
  73. package/src/provider-native.ts +3 -1
  74. package/src/remote-catalog.ts +359 -3
@@ -0,0 +1,1694 @@
1
+ // P1d-2: the two-stage `/model-sync migrate plan|apply|rollback|status` surface.
2
+ //
3
+ // This is the ONLY entry point that is allowed to touch the go routes' config
4
+ // after explicit user consent (design §14.0 M-1/M-2/M-3). Hard rules baked into
5
+ // this module:
6
+ // - `buildMigrationPlan` is PURE: no settings write, no store write, no fetch.
7
+ // Its inputs are injected, so a plan can be produced entirely offline.
8
+ // - `applyMigration` refuses unless BOTH the planHash AND the 6-digit confirm
9
+ // code match a freshly rebuilt plan of the CURRENT settings. There is no
10
+ // `--yes` / `--auto` / env bypass anywhere in this file.
11
+ // - write order is settings → ledger → appliedFingerprint (§14.7.4), and the
12
+ // applied flag is persisted BEFORE the first mutate so the go scheduler
13
+ // drops any round that races the apply (M-5 single writer).
14
+ // - `rollbackMigration` refuses on a missing backup or a post-apply hash edit,
15
+ // and never overwrites ids the user added after apply.
16
+ //
17
+ // Design refs: §14.1 (states), §14.2 (three input shapes), §14.4 (references),
18
+ // §14.5 (commands), §14.6 (order + single flight), §14.7 (write authority),
19
+ // V16/V17/V19/V20/V22. No timer, no network, no real ~/.dsh lives here.
20
+
21
+ import { createHash } from 'node:crypto'
22
+ import {
23
+ GO_SLOT_ROUTES,
24
+ groupGoModelsByProtocol,
25
+ type GoRouteSlot,
26
+ } from './opencode-go-grouping.ts'
27
+ import {
28
+ goOwnershipKey,
29
+ mapGoModelToProfile,
30
+ planGoRouteFields,
31
+ profileHash,
32
+ type GoManagedModel,
33
+ type GoOwnershipEntry,
34
+ type GoPlannedRouteFields,
35
+ } from './opencode-go-planner.ts'
36
+ import type { GoModelRecord } from './opencode-go-source.ts'
37
+ import type { SettingsModelProfile } from './translate.ts'
38
+ import {
39
+ appliedFingerprintOf,
40
+ fingerprintGoIdentity,
41
+ fingerprintSection,
42
+ readGoProviderSections,
43
+ routeWriter,
44
+ unclaimedRecordState,
45
+ type MigrationBackup,
46
+ type MigrationRecord,
47
+ type MigrationState,
48
+ type MigrationStateStore,
49
+ type RouteWriterConfig,
50
+ type UnclaimedMigrationRecord,
51
+ } from './opencode-go-migration.ts'
52
+ import type { GoOwnershipStore } from './opencode-go-writer.ts'
53
+ import type { GoJournalStore } from './opencode-go-journal.ts'
54
+ import type { Logger, SettingsDescriptor, SettingsMutationOp, SettingsService } from './writer.ts'
55
+
56
+ const OWNED_FIELDS = ['api', 'baseURL', 'displayName', 'apiKeyEnv'] as const
57
+ const PLAN_VERSION = 1
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Plan types
61
+ // ---------------------------------------------------------------------------
62
+
63
+ /** What apply will do with one route. */
64
+ export type MigrationAction = 'create' | 'update' | 'keep' | 'unset'
65
+
66
+ /** Classification of one id that exists in the current route (design §14.2). */
67
+ export type MigrationIdKind =
68
+ | 'desired-chat'
69
+ | 'desired-msg'
70
+ | 'desired-resp'
71
+ | 'desired-google'
72
+ | 'legacy-other-protocol'
73
+ | 'unknown-retired'
74
+ | 'user-extra'
75
+ /** Public catalog unavailable (offline/401/403) — fail-closed, never deleted (§14.2). */
76
+ | 'unclassified'
77
+
78
+ export interface MigrationIdClass {
79
+ id: string
80
+ kind: MigrationIdKind
81
+ /** Conservative (adopt=false) keeps every existing id; adopt may move/delete. */
82
+ action: 'keep' | 'move' | 'delete' | 'adopt'
83
+ reason: string
84
+ }
85
+
86
+ export interface MigrationDeletion {
87
+ route: string
88
+ id: string
89
+ kind: MigrationIdKind
90
+ /** The three deletion gates (§6.2.4 / ADR-005), reported with the reason. */
91
+ gates: {
92
+ managedHash: string
93
+ override: string
94
+ pinned: string
95
+ }
96
+ /** Only an explicitly confirmed id in adopt mode is actually deleted. */
97
+ willDelete: boolean
98
+ reason: string
99
+ }
100
+
101
+ /**
102
+ * One row of the plan's per-id action table (design §14.2 / 31 B2). This is the
103
+ * SINGLE source of truth consumed by apply: it is hashed into planHash, so a
104
+ * plan and its apply can never disagree. `keep` rows are never destructive.
105
+ */
106
+ export type MigrationIdActionOp = 'keep' | 'add' | 'update' | 'move' | 'delete'
107
+
108
+ export interface MigrationIdPlan {
109
+ id: string
110
+ op: MigrationIdActionOp
111
+ /** Route the op operates on (source route for `move`/`delete`). */
112
+ route: string
113
+ /** Destination route for `move` (the id is removed from `route`). */
114
+ to?: string
115
+ kind: MigrationIdKind
116
+ /** True when the id is in pinnedModels — forced `keep`, never moved/deleted. */
117
+ pinned: boolean
118
+ /** Exact profile to write for add/move. Set on `update` rows as the official
119
+ * target only for the plan's before/after report — apply never writes it. */
120
+ profile?: SettingsModelProfile
121
+ /** Current profile on an `update` row (user-modified) — for before/after output. */
122
+ before?: SettingsModelProfile
123
+ /** True iff applying this row puts the id under plugin ownership (managed ledger).
124
+ * `update` and user-owned `keep` rows are false by construction (B6 + user ruling). */
125
+ managed?: boolean
126
+ reason: string
127
+ }
128
+
129
+ export type RewriteRefMode = 'none' | 'default-model' | 'config'
130
+
131
+ /** A reference candidate reported by plan. Only verified config keys may be rewritten. */
132
+ export interface ReferenceCandidate {
133
+ surface: string
134
+ location: string
135
+ before: string
136
+ after: string
137
+ verified: boolean
138
+ rewritable: boolean
139
+ /** Session storage / external config: always report-only (never rewritten). */
140
+ reportOnly: boolean
141
+ }
142
+
143
+ /** A rewrite request that an injected patch accessor can execute (opt-in only). */
144
+ export interface ReferenceRewrite {
145
+ surface: string
146
+ location: string
147
+ before: string
148
+ after: string
149
+ }
150
+
151
+ /** The hashed body of the plan. `planHash`/`confirmCode` are derived, not hashed. */
152
+ export interface MigrationPlanBody {
153
+ version: 1
154
+ keyFingerprint: string
155
+ adopt: boolean
156
+ rewriteRefs: RewriteRefMode
157
+ /** Fingerprint of the pre-apply go sections — apply refuses if it changed. */
158
+ preFingerprint: string
159
+ state: MigrationState
160
+ stateByRoute: Record<string, MigrationState>
161
+ routes: MigrationPlannedRoute[]
162
+ deletions: MigrationDeletion[]
163
+ /** The complete per-id action table apply executes verbatim (31 B2). */
164
+ idActions: MigrationIdPlan[]
165
+ /** Fixed B6 informed-consent text; hashed into planHash so edits invalidate it. */
166
+ managedAfterMigration: string
167
+ /** True when the official public catalog was unavailable at plan time. Every
168
+ * non-desired id is then `unclassified` and never deleted (fail-closed). */
169
+ publicCatalogAvailable: boolean
170
+ /** True when apply cannot guarantee verbatim action-table execution: plan mode
171
+ * is `adopt-disabled` and `--adopt` is rejected at the command layer (§14.2). */
172
+ adoptDisabled: boolean
173
+ references: ReferenceCandidate[]
174
+ pinnedSuggestions: string[]
175
+ backupPath: string
176
+ rollbackCommand: string
177
+ unverified: string[]
178
+ }
179
+
180
+ export interface MigrationPlan extends MigrationPlanBody {
181
+ planHash: string
182
+ confirmCode: string
183
+ }
184
+
185
+ export interface MigrationPlannedRoute {
186
+ slot: GoRouteSlot
187
+ route: string
188
+ state: MigrationState
189
+ action: MigrationAction
190
+ fields: GoPlannedRouteFields
191
+ desired: SettingsModelProfile[]
192
+ existing: MigrationIdClass[]
193
+ }
194
+
195
+ export interface BuildPlanInput {
196
+ descriptor: SettingsDescriptor | undefined
197
+ entries: readonly GoModelRecord[]
198
+ routes: Partial<Record<GoRouteSlot, string>>
199
+ ref: string
200
+ keyFingerprint: string
201
+ adopt?: boolean
202
+ rewriteRefs?: RewriteRefMode
203
+ record?: MigrationRecord
204
+ /** Reference candidates from the (offline) reference-surface scan. Report-only by default. */
205
+ references?: ReferenceCandidate[]
206
+ /** go.pinnedModels: ids forced to `keep` (never moved or deleted, 31 B2). */
207
+ pinnedModels?: readonly string[]
208
+ /** Only with this flag may user-extra ids be deleted — and only if plan-listed. */
209
+ pruneUserExtra?: boolean
210
+ /** Official *public* catalog ids (may include ids the current key cannot use).
211
+ * Ids present here but absent from `entries` are `unknown-retired`; ids in
212
+ * neither set are `user-extra` (user-written, never auto-deleted). `undefined`
213
+ * means the catalog was unavailable → fail-closed `unclassified`. */
214
+ publicCatalogIds?: readonly string[]
215
+ /** Apply cannot execute the per-id table → plan mode `adopt-disabled` and
216
+ * `--adopt` rejected at the command layer (design §14.2 fallback). */
217
+ adoptDisabled?: boolean
218
+ now: number
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // Pure helpers: canonical hash + confirmation code (V16 / V17)
223
+ // ---------------------------------------------------------------------------
224
+
225
+ function isRecord(value: unknown): value is Record<string, unknown> {
226
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
227
+ }
228
+
229
+ function canonicalize(value: unknown): unknown {
230
+ if (Array.isArray(value)) return value.map(canonicalize)
231
+ if (!isRecord(value)) return value
232
+ const out: Record<string, unknown> = {}
233
+ for (const key of Object.keys(value).sort()) out[key] = canonicalize(value[key])
234
+ return out
235
+ }
236
+
237
+ /** sha256 of canonical JSON — the planHash algorithm (V17: changes with the plan). */
238
+ export function hashCanonical(value: unknown): string {
239
+ return createHash('sha256').update(JSON.stringify(canonicalize(value))).digest('hex')
240
+ }
241
+
242
+ /** Deterministic 6-digit confirmation code derived from a planHash. */
243
+ export function confirmCodeOf(planHash: string): string {
244
+ return String(Number.parseInt(planHash.slice(0, 12), 16) % 1_000_000).padStart(6, '0')
245
+ }
246
+
247
+ export function planHashOf(body: MigrationPlanBody): string {
248
+ return hashCanonical(body)
249
+ }
250
+
251
+ /** The action-table subset both plan-time simulation and apply consume. */
252
+ export interface MigrationActionTable {
253
+ routes: readonly MigrationPlannedRoute[]
254
+ idActions: readonly MigrationIdPlan[]
255
+ }
256
+
257
+ /**
258
+ * THE single source of truth for the per-route "managed after apply" id set.
259
+ *
260
+ * It simulates the action table against the SAME settings descriptor apply
261
+ * will use, so the ids the plan advertises are exactly the ids apply actually
262
+ * writes or adopts into the ownership ledger. An id already sitting on its
263
+ * target with a user-edited value (an `update` row, or a `move` onto a
264
+ * different-valued target) is NEVER claimed: it is not written, so it must not
265
+ * be advertised as managed anywhere (B6 + user ruling: update never overwrites
266
+ * and never manages).
267
+ *
268
+ * `buildMigrationPlan` derives the informed-consent text from this function,
269
+ * and `applyMigration` derives the ledger `managed` / `appliedManagedIds` from
270
+ * the very same `buildRouteWriteStates` computation, so the four surfaces
271
+ * cannot disagree.
272
+ */
273
+ export function managedIdsAfterApply(
274
+ table: MigrationActionTable,
275
+ desc: SettingsDescriptor | undefined,
276
+ ): Record<string, string[]> {
277
+ const { byRoute } = buildRouteWriteStates(table, desc)
278
+ return Object.fromEntries(
279
+ [...byRoute].map(([route, state]) => [
280
+ route,
281
+ Object.keys(state.managed).sort((a, b) => a.localeCompare(b)),
282
+ ]),
283
+ )
284
+ }
285
+
286
+ const KNOWN_ACTION_OPS: ReadonlySet<string> = new Set<string>(['keep', 'add', 'update', 'move', 'delete'])
287
+
288
+ /**
289
+ * Fail-closed guard: any op outside the closed `MigrationIdActionOp` union is
290
+ * rejected before a single write. Returns the first offending row, if any.
291
+ */
292
+ export function findUnknownAction(actions: readonly MigrationIdPlan[]): { id: string; op: string } | undefined {
293
+ for (const action of actions) {
294
+ if (!KNOWN_ACTION_OPS.has(String(action.op))) return { id: action.id, op: String(action.op) }
295
+ }
296
+ return undefined
297
+ }
298
+
299
+ export type ConsentResult =
300
+ | { ok: true }
301
+ | { ok: false; reason: 'consent-required' | 'plan-hash-mismatch' | 'confirm-code-mismatch' | 'ack-required' }
302
+
303
+ /**
304
+ * The consent gate (V17 + 31 B6). THREE values are mandatory: the matching
305
+ * planHash, the 6-digit confirmCode and `--ack-managed` (acknowledgement of the
306
+ * `[managed-after-migration]` notice). A missing/incorrect value never reaches
307
+ * a write. Deliberately there is no accept-anything branch — `--yes`/`--auto`
308
+ * cannot be expressed.
309
+ */
310
+ export function verifyConsent(
311
+ plan: MigrationPlan,
312
+ planHash: string | undefined,
313
+ confirmCode: string | undefined,
314
+ ackManaged?: boolean,
315
+ ): ConsentResult {
316
+ if (typeof planHash !== 'string' || planHash === ''
317
+ || typeof confirmCode !== 'string' || confirmCode === '') {
318
+ return { ok: false, reason: 'consent-required' }
319
+ }
320
+ if (planHash !== plan.planHash) return { ok: false, reason: 'plan-hash-mismatch' }
321
+ if (confirmCode !== plan.confirmCode) return { ok: false, reason: 'confirm-code-mismatch' }
322
+ if (ackManaged !== true) return { ok: false, reason: 'ack-required' }
323
+ return { ok: true }
324
+ }
325
+
326
+ // ---------------------------------------------------------------------------
327
+ // Pure plan builder (V16: zero writes / zero external calls)
328
+ // ---------------------------------------------------------------------------
329
+
330
+ /** Per-route state, refined from the full-set state (§14.1). */
331
+ function detectRouteStates(
332
+ sections: Record<string, unknown> | undefined,
333
+ record: MigrationRecord | undefined,
334
+ routeIds: readonly string[],
335
+ overall: MigrationState,
336
+ ): Record<string, MigrationState> {
337
+ const identityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {})
338
+ const out: Record<string, MigrationState> = {}
339
+ for (const route of routeIds) {
340
+ const present = sections?.[route]
341
+ if (!isRecord(present)) {
342
+ out[route] = 'absent'
343
+ } else if (overall === 'drifted') {
344
+ // A drift anywhere closes the gate for the whole route set; report it per route too.
345
+ out[route] = identityRoutes.includes(route) ? 'drifted' : 'legacy-inline'
346
+ } else if (overall === 'applied' || (record?.appliedIdentity !== undefined && identityRoutes.includes(route))) {
347
+ out[route] = 'applied'
348
+ } else {
349
+ out[route] = Array.isArray(present.models) ? 'legacy-inline' : 'legacy-inherit'
350
+ }
351
+ }
352
+ return out
353
+ }
354
+
355
+ /** Default reference report when the caller has no offline scan result to inject. */
356
+ function defaultReferences(targets: readonly string[], rewriteRefs: RewriteRefMode): ReferenceCandidate[] {
357
+ const refs = targets.length > 0 ? targets.join(' / ') : 'qwen4-max / grok-4.7'
358
+ const candidates: ReferenceCandidate[] = [
359
+ {
360
+ surface: 'agent-default-model (profile patch)',
361
+ location: '~/.dsh/profiles/<profile>/cordis.patch.yml',
362
+ before: `opencode-go/${refs}`,
363
+ after: 'see pinnedModels / new route',
364
+ verified: true,
365
+ rewritable: rewriteRefs === 'default-model' || rewriteRefs === 'config',
366
+ reportOnly: rewriteRefs === 'none',
367
+ },
368
+ {
369
+ surface: 'favoriteModels / hiddenModels (profile patch)',
370
+ location: '~/.dsh/profiles/<profile>/cordis.patch.yml',
371
+ before: `opencode-go/${refs}`,
372
+ after: 'see pinnedModels / new route',
373
+ verified: true,
374
+ rewritable: rewriteRefs === 'config',
375
+ reportOnly: rewriteRefs === 'none',
376
+ },
377
+ {
378
+ surface: 'session/conversation {provider,model}',
379
+ location: '~/.dsh/sessions/**/session.v4.jsonl.zstd',
380
+ before: `opencode-go/${refs}`,
381
+ after: 'manual / new session',
382
+ verified: false,
383
+ rewritable: false,
384
+ reportOnly: true,
385
+ },
386
+ ]
387
+ return candidates
388
+ }
389
+
390
+ /** Build the full change plan. Pure: identical inputs → identical plan/hash. */
391
+ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
392
+ const routes = { ...GO_SLOT_ROUTES, ...input.routes }
393
+ const routeIds = Object.values(routes)
394
+ const sections = readGoProviderSections(input.descriptor, routeIds)
395
+ const prior = input.record
396
+ const state = migrationStateForPlan(sections, prior, routes.chat)
397
+ const stateByRoute = detectRouteStates(sections, prior, routeIds, state)
398
+ // Fail-closed capability gate (§14.2): when the executor cannot guarantee the
399
+ // action table, adopt is reported as disabled and plan rows stay conservative.
400
+ const adoptDisabled = input.adoptDisabled === true
401
+ const adopt = input.adopt === true && !adoptDisabled
402
+ const rewriteRefs = input.rewriteRefs ?? 'none'
403
+
404
+ const grouping = groupGoModelsByProtocol(input.entries)
405
+ const entryById = new Map(input.entries.map((entry) => [entry.id, entry]))
406
+
407
+ const desiredBySlot = new Map<GoRouteSlot, SettingsModelProfile[]>()
408
+ for (const slot of ['chat', 'msg', 'resp', 'google'] as const) {
409
+ desiredBySlot.set(slot, grouping.slots[slot]
410
+ .map((id) => entryById.get(id))
411
+ .filter((entry): entry is GoModelRecord => entry !== undefined)
412
+ .map(mapGoModelToProfile)
413
+ .sort((a, b) => a.id.localeCompare(b.id)))
414
+ }
415
+ const desiredIds = new Set([...desiredBySlot.values()].flat().map((profile) => profile.id))
416
+
417
+ // The two ids that move out of chat into dedicated protocol routes (§14.4).
418
+ const targets = grouping.slots.msg.concat(grouping.slots.resp)
419
+ const references = input.references ?? defaultReferences(targets, rewriteRefs)
420
+
421
+ // Routes actually in scope for this plan (a conditional, empty google slot
422
+ // with no pre-existing section is skipped — §9.4).
423
+ const scopedRoutes: {
424
+ slot: GoRouteSlot
425
+ route: string
426
+ state: MigrationState
427
+ fields: GoPlannedRouteFields
428
+ desired: SettingsModelProfile[]
429
+ currentModels: SettingsModelProfile[]
430
+ }[] = []
431
+ for (const slot of ['chat', 'msg', 'resp', 'google'] as const) {
432
+ if (slot === 'google' && desiredBySlot.get(slot)!.length === 0 && sections?.[routes[slot]] === undefined) continue
433
+ const route = routes[slot]
434
+ const section = sections?.[route]
435
+ const routeState = stateByRoute[route] ?? 'absent'
436
+ const fields = planGoRouteFields(slot, input.entries.filter((entry) => grouping.slots[slot].includes(entry.id)), input.ref)
437
+ const desired = desiredBySlot.get(slot) ?? []
438
+ const currentModels: SettingsModelProfile[] = isRecord(section) && Array.isArray(section.models)
439
+ ? section.models as SettingsModelProfile[]
440
+ : []
441
+ scopedRoutes.push({ slot, route, state: routeState, fields, desired, currentModels })
442
+ }
443
+
444
+ // desired id → its official target route + exact profile.
445
+ const desiredTarget = new Map<string, { slot: GoRouteSlot; route: string; profile: SettingsModelProfile }>()
446
+ for (const scope of scopedRoutes) {
447
+ for (const profile of scope.desired) {
448
+ desiredTarget.set(profile.id, { slot: scope.slot, route: scope.route, profile })
449
+ }
450
+ }
451
+
452
+ // Every id currently in settings, with all the routes it occupies.
453
+ const currentLocations = new Map<string, { route: string; profile: SettingsModelProfile }[]>()
454
+ for (const scope of scopedRoutes) {
455
+ for (const profile of scope.currentModels) {
456
+ const list = currentLocations.get(profile.id) ?? []
457
+ list.push({ route: scope.route, profile })
458
+ currentLocations.set(profile.id, list)
459
+ }
460
+ }
461
+
462
+ const pinnedIds = new Set(input.pinnedModels ?? [])
463
+ // `undefined` is materially different from an empty list: empty means the
464
+ // catalog was fetched and truly has no such id (→ user-extra); undefined means
465
+ // it could not be fetched at all (→ unclassified, never deleted).
466
+ const publicCatalogAvailable = input.publicCatalogIds !== undefined
467
+ const publicIds = new Set(input.publicCatalogIds ?? [])
468
+ const pruneUserExtra = input.pruneUserExtra === true
469
+
470
+ const kindOf = (id: string): MigrationIdKind => {
471
+ const target = desiredTarget.get(id)
472
+ if (target !== undefined) return `desired-${target.slot}` as MigrationIdKind
473
+ // Fail-closed (§14.2): no public catalog → never guess "user-written".
474
+ if (!publicCatalogAvailable) return 'unclassified'
475
+ // Ids in the official public catalog but not in the current key's authorized
476
+ // list are unknown-retired; ids in neither set are user-written extras.
477
+ return publicIds.has(id) ? 'unknown-retired' : 'user-extra'
478
+ }
479
+
480
+ // ---- The per-id action table: the SINGLE source of truth for apply (31 B2) ----
481
+ const idActions: MigrationIdPlan[] = []
482
+ const idsInScope = new Set<string>([...currentLocations.keys(), ...desiredTarget.keys()])
483
+ for (const id of [...idsInScope].sort((a, b) => a.localeCompare(b))) {
484
+ const kind = kindOf(id)
485
+ const target = desiredTarget.get(id)
486
+ const locations = currentLocations.get(id) ?? []
487
+ const isPinned = pinnedIds.has(id)
488
+
489
+ if (isPinned) {
490
+ // User ruling "pinned = 两边都放": every existing copy is kept in place AND
491
+ // a copy is added to the official target route (duplicate display allowed).
492
+ // A pinned desired id is never moved/deleted, even in adopt mode.
493
+ if (locations.length === 0) {
494
+ if (target !== undefined) idActions.push({
495
+ id, op: 'add', route: target.route, kind, pinned: true, profile: target.profile, managed: true,
496
+ reason: 'pinnedModels: added to its official route (never moved/deleted)',
497
+ })
498
+ } else {
499
+ for (const loc of locations) idActions.push({
500
+ id, op: 'keep', route: loc.route, kind, pinned: true, profile: loc.profile,
501
+ reason: 'pinnedModels: forced keep (not moved, not deleted)',
502
+ })
503
+ if (target !== undefined && !locations.some((loc) => loc.route === target.route)) {
504
+ idActions.push({
505
+ id, op: 'add', route: target.route, kind, pinned: true, profile: target.profile, managed: true,
506
+ reason: 'pinnedModels: old copy kept; also added to its official route (duplicate display allowed)',
507
+ })
508
+ }
509
+ }
510
+ continue
511
+ }
512
+
513
+ if (target !== undefined) {
514
+ // Official desired id: make sure it ends up on its target route.
515
+ const targetLoc = locations.find((loc) => loc.route === target.route)
516
+ if (targetLoc === undefined) {
517
+ if (locations.length === 0) {
518
+ idActions.push({ id, op: 'add', route: target.route, kind, pinned: false, profile: target.profile, managed: true,
519
+ reason: 'desired id missing from its official route' })
520
+ } else if (adopt) {
521
+ for (const loc of locations) idActions.push({
522
+ id, op: 'move', route: loc.route, to: target.route, kind, pinned: false, profile: target.profile, managed: true,
523
+ reason: 'adopt: move desired id from its legacy route (old copy removed)',
524
+ })
525
+ } else {
526
+ idActions.push({ id, op: 'add', route: target.route, kind, pinned: false, profile: target.profile, managed: true,
527
+ reason: 'conservative: keep existing copy, add desired id to its official route' })
528
+ for (const loc of locations) idActions.push({
529
+ id, op: 'keep', route: loc.route, kind, pinned: false, profile: loc.profile,
530
+ reason: 'conservative: existing copy kept as user-owned',
531
+ })
532
+ }
533
+ } else {
534
+ // Already on the target route. A user-edited profile is reported as an
535
+ // UPDATE/drift row with before→after, but apply NEVER overwrites it and
536
+ // NEVER claims it as managed (user ruling).
537
+ if (profileHash(targetLoc.profile) !== profileHash(target.profile)) {
538
+ idActions.push({ id, op: 'update', route: target.route, kind, pinned: false,
539
+ profile: target.profile, before: targetLoc.profile,
540
+ reason: 'user-modified desired value: plan shows before→after; apply leaves it untouched and unmanaged' })
541
+ } else {
542
+ idActions.push({ id, op: 'keep', route: target.route, kind, pinned: false, profile: target.profile, managed: true,
543
+ reason: 'desired id already matches the official value (adopted into ledger)' })
544
+ }
545
+ if (adopt) {
546
+ for (const loc of locations) {
547
+ if (loc.route === target.route) continue
548
+ idActions.push({ id, op: 'move', route: loc.route, to: target.route, kind, pinned: false, profile: target.profile, managed: true,
549
+ reason: 'adopt: remove duplicate desired id from the wrong route' })
550
+ }
551
+ }
552
+ }
553
+ continue
554
+ }
555
+
556
+ // Non-desired id: user-extra / unknown-retired / unclassified. Default keep.
557
+ // Delete only when the classification's own flag is set AND the row is in
558
+ // this plan. `unclassified` (no public catalog) is never deletable.
559
+ const mayDelete = kind === 'user-extra' ? pruneUserExtra : kind === 'unknown-retired' ? adopt : false
560
+ for (const loc of locations) {
561
+ if (mayDelete) {
562
+ idActions.push({ id, op: 'delete', route: loc.route, kind, pinned: false, profile: loc.profile,
563
+ reason: kind === 'user-extra'
564
+ ? '--prune-user-extra: explicitly listed for deletion in this plan'
565
+ : 'adopt: unknown-retired id explicitly listed for deletion in this plan' })
566
+ } else {
567
+ idActions.push({ id, op: 'keep', route: loc.route, kind, pinned: false, profile: loc.profile,
568
+ reason: kind === 'unclassified'
569
+ ? 'public catalog unavailable (unclassified): never deleted (fail-closed)'
570
+ : describeId(kind, adopt) })
571
+ }
572
+ }
573
+ }
574
+
575
+ // Deletions are reported with the three-gate explanation, driven from the
576
+ // SAME action table (so the report cannot disagree with apply). `move` rows
577
+ // are NOT deletions — they are listed in the per-id table with a destination.
578
+ const deletions: MigrationDeletion[] = idActions
579
+ .filter((action) => action.op === 'delete')
580
+ .map((action) => ({
581
+ route: action.route,
582
+ id: action.id,
583
+ kind: action.kind,
584
+ gates: {
585
+ managedHash: 'plan-confirmed: id removed by this migration',
586
+ override: 'no modelOverrides on legacy section',
587
+ pinned: action.pinned ? 'pinned — never removed' : 'not pinned',
588
+ },
589
+ willDelete: true,
590
+ reason: action.reason,
591
+ }))
592
+
593
+ const plannedRoutes: MigrationPlannedRoute[] = scopedRoutes.map((scope) => {
594
+ const seen = new Set<string>()
595
+ const existing: MigrationIdClass[] = []
596
+ for (const profile of scope.currentModels) {
597
+ if (seen.has(profile.id)) continue
598
+ seen.add(profile.id)
599
+ const row = idActions.find((action) => action.route === scope.route && action.id === profile.id)
600
+ const legacyAction: MigrationIdClass['action'] = row?.op === 'move' ? 'move'
601
+ : row?.op === 'delete' ? 'delete'
602
+ : row?.op === 'keep' ? 'keep' : 'adopt'
603
+ existing.push({
604
+ id: profile.id,
605
+ kind: row?.kind ?? 'user-extra',
606
+ action: legacyAction,
607
+ reason: row?.reason ?? describeId('user-extra', adopt),
608
+ })
609
+ }
610
+ let action: MigrationAction
611
+ if (scope.state === 'absent') action = 'create'
612
+ else if (scope.state === 'applied') action = 'keep'
613
+ else action = 'update'
614
+ return { slot: scope.slot, route: scope.route, state: scope.state, action, fields: scope.fields, desired: scope.desired, existing }
615
+ })
616
+
617
+ const pinnedSuggestions = new Set<string>()
618
+ const reversibleTargets = targets.filter((id) => !grouping.slots.chat.includes(id))
619
+ for (const id of reversibleTargets) pinnedSuggestions.add(id)
620
+ for (const id of pinnedIds) pinnedSuggestions.add(id)
621
+
622
+ // B6 informed-consent text — part of the hashed body: any edit to this notice
623
+ // changes planHash and invalidates the old confirmCode/ack. The id list comes
624
+ // from `managedIdsAfterApply`, the SAME simulation apply uses for the ledger,
625
+ // so a user-modified `update` row or a move onto a different-valued target is
626
+ // never advertised as managed.
627
+ const managedByRoute = managedIdsAfterApply({ routes: plannedRoutes, idActions }, input.descriptor)
628
+ // N2: no row may claim management on paper if the simulation shows apply
629
+ // will not actually write/adopt that id. Normalise the per-id `managed`
630
+ // flags to the simulated set so even the printed `[managed]` marker cannot
631
+ // disagree with the ledger. (Turning a flag OFF cannot change the simulation
632
+ // that produced `managedByRoute`, so plan ↔ apply stay deterministic.)
633
+ for (const action of idActions) {
634
+ if (action.managed !== true) continue
635
+ const targetRoute = action.op === 'move' ? action.to : action.route
636
+ if (targetRoute === undefined || !(managedByRoute[targetRoute] ?? []).includes(action.id)) {
637
+ action.managed = false
638
+ }
639
+ }
640
+ const managedAfterMigration = [
641
+ '[managed-after-migration] 以下模型将交由插件管理:',
642
+ ` ${scopedRoutes.map((s) => `${s.route}: ${managedByRoute[s.route]?.join(', ') || '(none)'}`).join(';')}`,
643
+ '官方下架时,这些模型会在满足「归属账本 + 现值哈希 + 无 override/pin」三闸门且连续 2 轮确认后自动从列表移除。',
644
+ ].join('\n')
645
+
646
+ const preFingerprint = fingerprintSection(sections ?? {})
647
+ const body: MigrationPlanBody = {
648
+ version: PLAN_VERSION,
649
+ keyFingerprint: input.keyFingerprint,
650
+ adopt,
651
+ rewriteRefs,
652
+ preFingerprint,
653
+ state,
654
+ stateByRoute,
655
+ routes: plannedRoutes,
656
+ deletions,
657
+ idActions,
658
+ managedAfterMigration,
659
+ publicCatalogAvailable,
660
+ adoptDisabled,
661
+ references,
662
+ pinnedSuggestions: [...pinnedSuggestions].sort(),
663
+ backupPath: `models-store:migration:backup:${input.keyFingerprint}`,
664
+ rollbackCommand: `/model-sync migrate rollback --plan <planHash>`,
665
+ unverified: [
666
+ 'session/conversation storage: report-only (checksummed zstd, append-only, revision drift, FTS invalidation)',
667
+ 'external scripts / third-party config: report-only',
668
+ ],
669
+ }
670
+ const planHash = planHashOf(body)
671
+ return { ...body, planHash, confirmCode: confirmCodeOf(planHash) }
672
+ }
673
+
674
+ function describeId(kind: MigrationIdKind, adopt: boolean): string {
675
+ switch (kind) {
676
+ case 'desired-chat': return 'official chat-completions target'
677
+ case 'desired-msg': return 'official messages target (dedicated -msg route)'
678
+ case 'desired-resp': return 'official responses target (dedicated -resp route)'
679
+ case 'desired-google': return 'official google target'
680
+ case 'legacy-other-protocol': return adopt ? 'legacy id on the wrong protocol route' : 'legacy id kept in conservative mode'
681
+ case 'unknown-retired': return adopt ? 'unknown/retired id, delete only if confirmed in plan' : 'unknown/retired id kept as user-owned'
682
+ case 'user-extra': return 'user-written id, never auto-deleted'
683
+ case 'unclassified': return 'public catalog unavailable (unclassified): never deleted'
684
+ }
685
+ }
686
+
687
+ /** Local state detection mirroring `migrationStateOf` (kept here to stay import-light). */
688
+ function migrationStateForPlan(
689
+ sections: Record<string, unknown> | undefined,
690
+ record: MigrationRecord | undefined,
691
+ chatRoute: string,
692
+ ): MigrationState {
693
+ if (sections === undefined || Object.keys(sections).length === 0) return 'absent'
694
+ const fingerprint = fingerprintSection(sections)
695
+ if (record?.appliedIdentity !== undefined) {
696
+ return fingerprintGoIdentity(sections, record.appliedIdentityRoutes) === record.appliedIdentity ? 'applied' : 'drifted'
697
+ }
698
+ if (record?.appliedFingerprint !== undefined && fingerprint === record.appliedFingerprint) return 'applied'
699
+ if (record !== undefined && (record.appliedFingerprint !== undefined || record.legacyFingerprint !== undefined)) {
700
+ if (record.legacyFingerprint !== undefined && fingerprint === record.legacyFingerprint) {
701
+ const chat = sections[chatRoute]
702
+ return isRecord(chat) && Array.isArray(chat.models) ? 'legacy-inline' : 'legacy-inherit'
703
+ }
704
+ return 'drifted'
705
+ }
706
+ const chat = sections[chatRoute]
707
+ return isRecord(chat) && Array.isArray(chat.models) ? 'legacy-inline' : 'legacy-inherit'
708
+ }
709
+
710
+ // ---------------------------------------------------------------------------
711
+ // Human-readable reports (V16 / V19)
712
+ // ---------------------------------------------------------------------------
713
+
714
+ function profileLabel(profile: SettingsModelProfile | undefined): string {
715
+ if (profile === undefined) return '(none)'
716
+ return `${profile.name ?? profile.id} [${profileHash(profile).slice(0, 8)}]`
717
+ }
718
+
719
+ export function formatMigrationPlan(plan: MigrationPlan): string {
720
+ const mode = plan.adoptDisabled
721
+ ? 'adopt-disabled (--adopt rejected: apply cannot guarantee the action table)'
722
+ : plan.adopt ? 'adopt' : 'conservative'
723
+ const lines: string[] = [
724
+ `model-sync migrate plan (v${plan.version}) — ${plan.state} (read-only, nothing written)`,
725
+ ` mode: ${mode} rewrite-refs: ${plan.rewriteRefs}`,
726
+ ` sections fingerprint: ${plan.preFingerprint.slice(0, 16)}…`,
727
+ ` public catalog: ${plan.publicCatalogAvailable ? 'available (ids classified)' : 'UNAVAILABLE — unclassified ids are never deleted (fail-closed)'}`,
728
+ '',
729
+ 'Routes:',
730
+ ]
731
+ for (const route of plan.routes) {
732
+ const fields = route.fields
733
+ lines.push(` ${route.route} [${route.slot}/${route.state}] ${route.action.toUpperCase()}`)
734
+ lines.push(` api=${fields.api} baseURL=${fields.baseURL} displayName=${fields.displayName} apiKeyEnv=${fields.apiKeyEnv}`)
735
+ lines.push(` desired (${route.desired.length}): ${route.desired.map((profile) => profile.id).join(', ') || '(none)'}`)
736
+ if (route.existing.length > 0) {
737
+ lines.push(` existing: ${route.existing.map((entry) => `${entry.id}=${entry.kind}/${entry.action}`).join(', ')}`)
738
+ }
739
+ }
740
+ lines.push('', 'Deletions (three-gate explanation):')
741
+ if (plan.deletions.length === 0) lines.push(' (none)')
742
+ for (const del of plan.deletions) {
743
+ lines.push(` ${del.route}/${del.id} [${del.kind}] willDelete=${del.willDelete}`)
744
+ lines.push(` gates: managedHash=${del.gates.managedHash}; override=${del.gates.override}; pinned=${del.gates.pinned}`)
745
+ lines.push(` why: ${del.reason}`)
746
+ }
747
+ lines.push('', 'Per-id actions (apply consumes this table verbatim; keep/update/pin are non-destructive):')
748
+ if (plan.idActions.length === 0) lines.push(' (none)')
749
+ for (const action of plan.idActions) {
750
+ const dest = action.to !== undefined ? ` → ${action.to}` : ''
751
+ const beforeAfter = action.op === 'update'
752
+ ? ` before=${profileLabel(action.before)} → official=${profileLabel(action.profile)} (apply keeps current value, not managed)`
753
+ : ''
754
+ lines.push(` ${action.op.toUpperCase().padEnd(6)} ${action.route}/${action.id}${dest} [${action.kind}]${action.pinned ? ' [pinned]' : ''}${action.managed === true ? ' [managed]' : ''}${beforeAfter}`)
755
+ lines.push(` why: ${action.reason}`)
756
+ }
757
+ lines.push('', plan.managedAfterMigration)
758
+ lines.push('', 'Reference rewrites (report-only by default; sessions are NEVER rewritten):')
759
+ for (const ref of plan.references) {
760
+ lines.push(` ${ref.verified ? 'verified' : 'unverified'}/${ref.reportOnly ? 'report-only' : 'rewritable'} ${ref.surface} @ ${ref.location}`)
761
+ lines.push(` ${ref.before} → ${ref.after}`)
762
+ }
763
+ if (plan.pinnedSuggestions.length > 0) {
764
+ lines.push('', `pinnedModels suggestion: ${plan.pinnedSuggestions.join(', ')}`)
765
+ }
766
+ lines.push('', `Backup: ${plan.backupPath}`)
767
+ lines.push(`Rollback: ${plan.rollbackCommand}`)
768
+ if (plan.unverified.length > 0) {
769
+ lines.push('', 'Unverified (report-only):')
770
+ for (const item of plan.unverified) lines.push(` - ${item}`)
771
+ }
772
+ lines.push('', `planHash: ${plan.planHash}`)
773
+ lines.push(`confirmCode: ${plan.confirmCode}`)
774
+ lines.push('apply: /model-sync migrate apply --plan <planHash> --confirm <confirmCode> --ack-managed')
775
+ return lines.join('\n')
776
+ }
777
+
778
+ // ---------------------------------------------------------------------------
779
+ // Orchestration deps + result types
780
+ // ---------------------------------------------------------------------------
781
+
782
+ export interface MigrateDeps {
783
+ settings: SettingsService | undefined
784
+ ownershipStore: GoOwnershipStore
785
+ migrationStore: MigrationStateStore
786
+ logger: Logger
787
+ /** Frozen official listing captured for plan/apply/rollback (no live network here). */
788
+ entries: readonly GoModelRecord[]
789
+ routes: Partial<Record<GoRouteSlot, string>>
790
+ ref: string
791
+ keyFingerprint: string
792
+ adopt?: boolean
793
+ rewriteRefs?: RewriteRefMode
794
+ references?: ReferenceCandidate[]
795
+ /** go.pinnedModels: forced `keep` (31 B2). */
796
+ pinnedModels?: readonly string[]
797
+ /** Only with this flag may user-extra ids be deleted — and only if plan-listed. */
798
+ pruneUserExtra?: boolean
799
+ /** Official public catalog ids, used to distinguish unknown-retired from user-extra.
800
+ * `undefined` → fail-closed `unclassified` (never deleted). */
801
+ publicCatalogIds?: readonly string[]
802
+ /** Capability flag: `--adopt` is refused at the command layer when the per-id
803
+ * action table cannot be executed verbatim (design §14.2 fallback). */
804
+ adoptDisabled?: boolean
805
+ /** TEST FAULT INJECTION ONLY. When set, `applyMigration` appends one bogus
806
+ * action with this op to the rebuilt table so the fail-closed gate can be
807
+ * exercised. Production callers never set it. */
808
+ faultInjectOp?: string
809
+ now: number
810
+ /** M-5: true when a go sync round currently holds the single-flight lock. */
811
+ isSyncInFlight?: () => boolean
812
+ /** Optional: execute an opt-in rewrite of a verified reference key. Default: none. */
813
+ applyReferenceRewrite?: (rewrite: ReferenceRewrite) => Promise<void>
814
+ /**
815
+ * O1/C2: after apply/rollback the profile's write-ahead journals are stale
816
+ * (the migration rewrote or undid those settings). Clearing them prevents a
817
+ * later round re-accounting a journal left by the pre-migration writer.
818
+ */
819
+ journalStore?: GoJournalStore
820
+ /** O1/C2: stable profile key whose journals are cleared. */
821
+ profileKey?: string
822
+ }
823
+
824
+ /** Best-effort: drop every write-ahead journal of this profile. */
825
+ async function clearProfileJournals(deps: MigrateDeps): Promise<void> {
826
+ if (deps.journalStore === undefined || deps.profileKey === undefined) return
827
+ try {
828
+ await deps.journalStore.clearProfile(deps.profileKey)
829
+ } catch (err) {
830
+ // Advisory only: a surviving slot is re-validated (and discarded) by the
831
+ // next reconciliation, never replayed blindly. Never fail a migration for it.
832
+ deps.logger.warn('journal cleanup after migration failed: %s', errorText(err))
833
+ }
834
+ }
835
+
836
+ /**
837
+ * The ONE plan-construction path used by both `/migrate plan` and `apply`.
838
+ * Sharing it is what makes the printed plan and the plan apply re-builds
839
+ * byte-identical — a prerequisite for the consent gate (V17) and V19.
840
+ */
841
+ export function buildMigrationPlanFromDeps(deps: MigrateDeps, record: MigrationRecord | undefined): MigrationPlan {
842
+ return buildMigrationPlan({
843
+ descriptor: deps.settings?.describe().find((desc) => desc.ns === 'llm-pi-ai'),
844
+ entries: deps.entries,
845
+ routes: deps.routes,
846
+ ref: deps.ref,
847
+ keyFingerprint: deps.keyFingerprint,
848
+ adopt: deps.adopt,
849
+ rewriteRefs: deps.rewriteRefs,
850
+ record,
851
+ references: deps.references,
852
+ pinnedModels: deps.pinnedModels,
853
+ pruneUserExtra: deps.pruneUserExtra,
854
+ publicCatalogIds: deps.publicCatalogIds,
855
+ adoptDisabled: deps.adoptDisabled,
856
+ now: deps.now,
857
+ })
858
+ }
859
+
860
+ async function readRecord(deps: { migrationStore: MigrationStateStore }): Promise<MigrationRecord | undefined> {
861
+ try {
862
+ return await deps.migrationStore.read()
863
+ } catch {
864
+ return undefined
865
+ }
866
+ }
867
+
868
+ function llmDescriptor(settings: SettingsService | undefined): SettingsDescriptor | undefined {
869
+ return settings?.describe().find((desc) => desc.ns === 'llm-pi-ai')
870
+ }
871
+
872
+ function rawRoute(desc: SettingsDescriptor | undefined, route: string): Record<string, unknown> | undefined {
873
+ const providers = desc?.user?.providers
874
+ if (!isRecord(providers)) return undefined
875
+ const data = providers[route]
876
+ return isRecord(data) ? data : undefined
877
+ }
878
+
879
+ function rawModels(desc: SettingsDescriptor | undefined, route: string): SettingsModelProfile[] {
880
+ const models = rawRoute(desc, route)?.models
881
+ return Array.isArray(models) ? models as SettingsModelProfile[] : []
882
+ }
883
+
884
+ function isConflictError(err: unknown): boolean {
885
+ return (err as Record<string, unknown> | undefined)?.code === 'SETTINGS_CONFLICT'
886
+ }
887
+
888
+ function errorText(err: unknown): string {
889
+ // Prefer a structured `message` so re-wrapped plain-object errors still carry
890
+ // the actionable text (lock path / retry advice) instead of "[object Object]".
891
+ // Error instances already expose `message`; everything else falls back to
892
+ // String(err) exactly as before.
893
+ const message = (err as { message?: unknown } | null | undefined)?.message
894
+ return typeof message === 'string' ? message : String(err)
895
+ }
896
+
897
+ /** Set ops that write exactly the target fields + models for one route. */
898
+ function routeOps(
899
+ desc: SettingsDescriptor | undefined,
900
+ route: string,
901
+ fields: GoPlannedRouteFields,
902
+ models: SettingsModelProfile[],
903
+ ): SettingsMutationOp[] {
904
+ const data = rawRoute(desc, route)
905
+ const ops: SettingsMutationOp[] = []
906
+ for (const field of OWNED_FIELDS) {
907
+ if (data?.[field] !== fields[field]) {
908
+ ops.push({ op: 'set', path: ['providers', route, field], value: fields[field] })
909
+ }
910
+ }
911
+ const sorted = [...models].sort((a, b) => a.id.localeCompare(b.id))
912
+ const current = [...rawModels(desc, route)].sort((a, b) => a.id.localeCompare(b.id))
913
+ if (current.length !== sorted.length || current.some((profile, index) => profileHash(profile) !== profileHash(sorted[index]))) {
914
+ ops.push({ op: 'set', path: ['providers', route, 'models'], value: sorted })
915
+ }
916
+ return ops
917
+ }
918
+
919
+ interface RouteWriteState {
920
+ /** Desired end state of this route's models, seeded from the live section. */
921
+ models: Map<string, SettingsModelProfile>
922
+ /** ids under plugin ownership after this apply (B6 ledger `managed`). */
923
+ managed: Record<string, GoManagedModel>
924
+ /** ids this apply actually created on this route (ledger `appliedAddedIds`). */
925
+ addedIds: Set<string>
926
+ }
927
+
928
+ /**
929
+ * Translate the plan's per-id action table into per-route desired states. This
930
+ * is the ONLY place that decides what apply writes: there is no
931
+ * `merged = [...desired]` re-derivation anywhere (31 B2). Every row yields
932
+ * exactly one result, in table order, so plan ↔ apply is checkable row by row.
933
+ *
934
+ * This same function powers plan-time simulation (`managedIdsAfterApply`) and
935
+ * apply-time execution, so "will be managed" and "was managed" use ONE source.
936
+ *
937
+ * Semantics (user rulings + §14.2/§14.3):
938
+ * keep → untouched; adopted only when the row is flagged `managed` AND the
939
+ * id is actually present on the route.
940
+ * add → write the official profile unless the id is already present; an
941
+ * already-present id is only adopted (managed) if its value matches.
942
+ * update → NOTHING written, never managed (user-edited value is preserved).
943
+ * move → remove from source route; on the destination, write/adopt the
944
+ * official profile ONLY if the target is empty or already holds the
945
+ * same value. A different-valued target is a user edit: never
946
+ * overwritten, never claimed, and reported as `skipped`.
947
+ * delete → remove from the route (only rows explicitly listed in the plan).
948
+ * pinned → expressed by keep (+ add on the target) rows; never moved/deleted.
949
+ * default → FAIL-CLOSED: an unknown op throws, it is never silently skipped.
950
+ */
951
+ export function buildRouteWriteStates(
952
+ table: MigrationActionTable,
953
+ desc: SettingsDescriptor | undefined,
954
+ ): { byRoute: Map<string, RouteWriteState>; results: MigrateApplyActionResult[] } {
955
+ const byRoute = new Map<string, RouteWriteState>()
956
+ for (const planned of table.routes) {
957
+ byRoute.set(planned.route, {
958
+ models: new Map(rawModels(desc, planned.route).map((profile) => [profile.id, structuredClone(profile)])),
959
+ managed: {},
960
+ addedIds: new Set(),
961
+ })
962
+ }
963
+ const results: MigrateApplyActionResult[] = []
964
+
965
+ const claim = (state: RouteWriteState | undefined, action: MigrationIdPlan): void => {
966
+ if (action.managed !== true || state === undefined || action.profile === undefined) return
967
+ // Never claim an id that is not actually on the route after this action.
968
+ if (!state.models.has(action.id)) return
969
+ state.managed[action.id] = { hash: profileHash(action.profile) }
970
+ }
971
+
972
+ for (const action of table.idActions) {
973
+ const source = byRoute.get(action.route)
974
+ const result = (status: MigrateApplyActionResult['status'], reason: string): void => {
975
+ results.push({ id: action.id, op: action.op, route: action.route, ...(action.to !== undefined ? { to: action.to } : {}), status, reason })
976
+ }
977
+ switch (action.op) {
978
+ case 'keep':
979
+ claim(source, action)
980
+ result('kept', action.reason)
981
+ break
982
+ case 'add': {
983
+ if (source === undefined || action.profile === undefined) {
984
+ result('skipped', 'route or profile unavailable; nothing written')
985
+ break
986
+ }
987
+ if (source.models.has(action.id)) {
988
+ // Idempotent: never overwrite an existing value (C4 / update ruling).
989
+ const existing = source.models.get(action.id)!
990
+ if (action.managed === true && profileHash(existing) === profileHash(action.profile)) claim(source, action)
991
+ result('kept', `already present on ${action.route}; not overwritten`)
992
+ } else {
993
+ source.models.set(action.id, structuredClone(action.profile))
994
+ source.addedIds.add(action.id)
995
+ claim(source, action)
996
+ result('applied', action.reason)
997
+ }
998
+ break
999
+ }
1000
+ case 'update':
1001
+ // User ruling: report before→after, but write nothing and claim nothing.
1002
+ result('skipped', `${action.reason} (before=${profileLabel(action.before)}; official=${profileLabel(action.profile)})`)
1003
+ break
1004
+ case 'move': {
1005
+ source?.models.delete(action.id)
1006
+ const dest = action.to !== undefined ? byRoute.get(action.to) : undefined
1007
+ const suffix = action.to !== undefined ? ` → ${action.to}` : ''
1008
+ if (dest === undefined || action.profile === undefined) {
1009
+ result('skipped', `${action.reason}${suffix}: destination/profile unavailable; source copy removed, nothing written to target`)
1010
+ break
1011
+ }
1012
+ if (dest.models.has(action.id)) {
1013
+ const existing = dest.models.get(action.id)!
1014
+ if (action.managed === true && profileHash(existing) === profileHash(action.profile)) {
1015
+ claim(dest, action)
1016
+ result('kept', `${action.reason}${suffix}: target already holds the official value; adopted into ledger`)
1017
+ } else {
1018
+ // Different value = user edit on the target. Do not overwrite and
1019
+ // do NOT claim as managed — truthful result + ledger + notice.
1020
+ result('skipped', `${action.reason}${suffix}: target holds a user-modified value; not overwritten, not managed`)
1021
+ }
1022
+ } else {
1023
+ dest.models.set(action.id, structuredClone(action.profile))
1024
+ dest.addedIds.add(action.id)
1025
+ claim(dest, action)
1026
+ result('applied', `${action.reason}${suffix}`)
1027
+ }
1028
+ break
1029
+ }
1030
+ case 'delete':
1031
+ source?.models.delete(action.id)
1032
+ result('applied', action.reason)
1033
+ break
1034
+ default: {
1035
+ // Fail-closed (N4): an unknown op must never silently disappear. Throwing
1036
+ // here means neither plan simulation nor apply can report success on a
1037
+ // table it did not fully execute. `applyMigration` rejects earlier with a
1038
+ // typed reason; this is the last line of defence.
1039
+ const bad = action as MigrationIdPlan
1040
+ throw new Error(`unknown migration action op '${String(bad.op)}' on id ${bad.id}; refusing (adopt-disabled: action table not executable)`)
1041
+ }
1042
+ }
1043
+ }
1044
+ return { byRoute, results }
1045
+ }
1046
+
1047
+ async function mutateWithRetry(
1048
+ deps: MigrateDeps,
1049
+ ops: SettingsMutationOp[],
1050
+ ): Promise<void> {
1051
+ const settings = deps.settings
1052
+ if (settings === undefined) throw new Error('settings service unavailable')
1053
+ const desc = llmDescriptor(settings)
1054
+ if (desc === undefined) throw new Error('llm-pi-ai namespace unavailable')
1055
+ try {
1056
+ await settings.mutate('llm-pi-ai', ops, desc.revision)
1057
+ } catch (err) {
1058
+ if (!isConflictError(err)) throw err
1059
+ const fresh = llmDescriptor(settings)
1060
+ if (fresh === undefined) throw new Error('llm-pi-ai namespace disappeared on retry')
1061
+ await settings.mutate('llm-pi-ai', ops, fresh.revision)
1062
+ }
1063
+ }
1064
+
1065
+ // ---------------------------------------------------------------------------
1066
+ // apply (V17 / V19 / V22): consent gate → backup → settings → ledger → fingerprint
1067
+ // ---------------------------------------------------------------------------
1068
+
1069
+ export type MigrateApplyReason =
1070
+ | 'applied'
1071
+ | 'consent-required'
1072
+ | 'plan-hash-mismatch'
1073
+ | 'confirm-code-mismatch'
1074
+ | 'ack-required'
1075
+ | 'adopt-disabled'
1076
+ | 'unknown-action'
1077
+ | 'nothing-to-apply'
1078
+ | 'sync-in-flight'
1079
+ | 'write-failed'
1080
+
1081
+ /** Result of ONE row of the plan's action table — mirrors it one-to-one (V19). */
1082
+ export interface MigrateApplyActionResult {
1083
+ id: string
1084
+ op: MigrationIdActionOp
1085
+ route: string
1086
+ to?: string
1087
+ status: 'applied' | 'kept' | 'skipped' | 'failed'
1088
+ reason: string
1089
+ }
1090
+
1091
+ export interface MigrateApplyResult {
1092
+ ok: boolean
1093
+ reason: MigrateApplyReason
1094
+ planHash: string
1095
+ confirmCode: string
1096
+ routes: { route: string; status: 'wrote' | 'failed' | 'skipped'; reason?: string }[]
1097
+ /** One entry per `plan.idActions` row, in the same order. */
1098
+ actions: MigrateApplyActionResult[]
1099
+ backupPath?: string
1100
+ text: string
1101
+ }
1102
+
1103
+ function applyFailure(reason: MigrateApplyReason, planHash: string, confirmCode: string, detail: string, writesReverted = false): MigrateApplyResult {
1104
+ // O1-minimal: "zero writes" is only true for a refusal BEFORE the first
1105
+ // mutate. When settings were written and then byte-restored, say so instead
1106
+ // of misreporting a clean zero-write no-op.
1107
+ const outcome = writesReverted
1108
+ ? 'settings writes were rolled back to the pre-apply snapshot (bytes restored; no net change)'
1109
+ : 'zero writes'
1110
+ return { ok: false, reason, planHash, confirmCode, routes: [], actions: [], text: `migrate apply refused (${reason}): ${detail}; ${outcome}` }
1111
+ }
1112
+
1113
+ export async function applyMigration(
1114
+ args: { planHash?: string; confirmCode?: string; ackManaged?: boolean },
1115
+ deps: MigrateDeps,
1116
+ ): Promise<MigrateApplyResult> {
1117
+ const prior = await readRecord(deps)
1118
+ const plan = buildMigrationPlanFromDeps(deps, prior)
1119
+
1120
+ // 1. Consent — every rejection below is ZERO writes. `--ack-managed` is a
1121
+ // mandatory third token (B6); no bypass flag exists.
1122
+ const consent = verifyConsent(plan, args.planHash, args.confirmCode, args.ackManaged)
1123
+ if (!consent.ok) return applyFailure(consent.reason, plan.planHash, plan.confirmCode, `${consent.reason}`)
1124
+
1125
+ // N4 fail-closed: an op outside the closed union can never be executed
1126
+ // verbatim. Reject BEFORE the applying flag, any settings write, or any
1127
+ // ledger write. `faultInjectOp` is a test-only seam; production uses only
1128
+ // plan.idActions (which the builder always keeps inside the union).
1129
+ const actionsToRun: MigrationIdPlan[] = deps.faultInjectOp === undefined
1130
+ ? [...plan.idActions]
1131
+ : [...plan.idActions, {
1132
+ id: '__fault-injected__', op: deps.faultInjectOp as MigrationIdPlan['op'],
1133
+ route: plan.routes[0]?.route ?? 'opencode-go', kind: 'user-extra', pinned: false,
1134
+ reason: 'fault-injected unknown action op',
1135
+ }]
1136
+ const unknown = findUnknownAction(actionsToRun)
1137
+ if (unknown !== undefined) {
1138
+ return applyFailure('unknown-action', plan.planHash, plan.confirmCode,
1139
+ `unknown action op '${unknown.op}' on id '${unknown.id}'; refusing (adopt-disabled: action table not executable)`)
1140
+ }
1141
+
1142
+ // Fail-closed fallback (§14.2): if the executor cannot guarantee verbatim
1143
+ // table execution, adopt is refused here as well as at the command layer.
1144
+ if (deps.adopt === true && (deps.adoptDisabled === true || plan.adoptDisabled)) {
1145
+ return applyFailure('adopt-disabled', plan.planHash, plan.confirmCode,
1146
+ '--adopt disabled: apply cannot execute the per-id action table; use conservative mode')
1147
+ }
1148
+
1149
+ if (plan.state !== 'legacy-inherit' && plan.state !== 'legacy-inline' && plan.state !== 'drifted') {
1150
+ return applyFailure('nothing-to-apply', plan.planHash, plan.confirmCode, `state=${plan.state} (nothing needs migration)`)
1151
+ }
1152
+
1153
+ // 2. Single flight against the go sync round (V22). The scheduler drops its
1154
+ // own rounds once `applying` is persisted (step 3); this check rejects apply
1155
+ // while a round already holds the lock.
1156
+ if (deps.isSyncInFlight?.() === true) {
1157
+ return applyFailure('sync-in-flight', plan.planHash, plan.confirmCode, 'a go sync round is in flight; retry when it finishes')
1158
+ }
1159
+ if (typeof deps.migrationStore.write !== 'function') {
1160
+ return applyFailure('write-failed', plan.planHash, plan.confirmCode, 'migration store is read-only')
1161
+ }
1162
+
1163
+ const desc = llmDescriptor(deps.settings)
1164
+ if (desc === undefined || deps.settings === undefined) {
1165
+ return applyFailure('write-failed', plan.planHash, plan.confirmCode, 'settings/llm-pi-ai unavailable')
1166
+ }
1167
+
1168
+ // Simulate the action table BEFORE any write. It is pure, and its fail-closed
1169
+ // default throws on an unknown op — doing it here guarantees such a throw
1170
+ // cannot leave a persisted `applying` flag with no restore snapshot.
1171
+ const { byRoute, results: actionResults } = buildRouteWriteStates(
1172
+ { routes: plan.routes, idActions: actionsToRun }, desc,
1173
+ )
1174
+
1175
+ // 3. Capture the audit backup and persist `applying` BEFORE the first mutate.
1176
+ // If we crash mid-apply, the record still carries the restore snapshot.
1177
+ const backup = captureBackup(plan, desc, deps.now)
1178
+ const applyingRecord: MigrationRecord = {
1179
+ ...(prior ?? {}),
1180
+ applying: true,
1181
+ backup,
1182
+ planHash: plan.planHash,
1183
+ legacyFingerprint: plan.preFingerprint,
1184
+ }
1185
+ try {
1186
+ await deps.migrationStore.write!(applyingRecord)
1187
+ } catch (err) {
1188
+ return applyFailure('write-failed', plan.planHash, plan.confirmCode, `could not persist applying flag: ${errorText(err)}`)
1189
+ }
1190
+
1191
+ const routesResult: MigrateApplyResult['routes'] = []
1192
+ const committedLedgerKeys: string[] = []
1193
+ const writtenRoutes: string[] = []
1194
+ const managedByRoute: Record<string, string[]> = {}
1195
+ let failure: string | undefined
1196
+
1197
+ // The action table is the ONLY write source (31 B2): apply writes exactly the
1198
+ // simulated states above, never re-deriving from `planned.desired`. The SAME
1199
+ // simulation drives the plan's informed text (`managedIdsAfterApply`), so
1200
+ // "will manage" and "did manage" are one computation.
1201
+ try {
1202
+ for (const planned of plan.routes) {
1203
+ const state = byRoute.get(planned.route)
1204
+ if (state === undefined) {
1205
+ routesResult.push({ route: planned.route, status: 'skipped', reason: 'no write state' })
1206
+ continue
1207
+ }
1208
+ const touched = actionsToRun.some((action) => action.route === planned.route || action.to === planned.route)
1209
+ if (planned.action === 'keep' && !touched) {
1210
+ // No row touches this route: do not write settings, do not write a
1211
+ // ledger entry, and do not list it in appliedManagedIds. Listing it
1212
+ // here used to fabricate a "+route: []" entry never backed by a ledger.
1213
+ routesResult.push({ route: planned.route, status: 'skipped', reason: 'already-applied (no rows touched this route)' })
1214
+ continue
1215
+ }
1216
+ const current = rawModels(desc, planned.route)
1217
+ // Write only ops that actually change fields/models. keep/update/delete-no
1218
+ // rows leave the section byte-identical, so no mutate happens for them.
1219
+ const ops = routeOps(desc, planned.route, planned.fields, [...state.models.values()])
1220
+ let wroteThisRoute = false
1221
+ if (ops.length > 0) {
1222
+ try {
1223
+ await mutateWithRetry(deps, ops)
1224
+ writtenRoutes.push(planned.route)
1225
+ wroteThisRoute = true
1226
+ } catch (err) {
1227
+ failure = `${planned.route}: settings mutate failed (${errorText(err)})`
1228
+ routesResult.push({ route: planned.route, status: 'failed', reason: errorText(err) })
1229
+ break
1230
+ }
1231
+ }
1232
+
1233
+ // B6: ledger `managed` is EXACTLY the set of ids this simulation claimed
1234
+ // on this route — the same set the plan advertised. Ids not written or
1235
+ // adopted (user-edited `update`, different-valued `move` target) are
1236
+ // absent. `managedByRoute` is the sole source for `appliedManagedIds`.
1237
+ const managed = state.managed
1238
+ managedByRoute[planned.route] = Object.keys(managed).sort((a, b) => a.localeCompare(b))
1239
+ const ledgerKey = goOwnershipKey(planned.route, deps.keyFingerprint)
1240
+ const preManagedSection = backup.routes[planned.route]?.section
1241
+ const entry: GoOwnershipEntry = {
1242
+ routeFields: planned.fields,
1243
+ managed,
1244
+ // Audit-only pre-managed ids; rollback uses preManagedSection below.
1245
+ preManagedSnapshot: current.map((profile) => ({ ...profile })),
1246
+ // §14.3 whole-section snapshot: the exact pre-apply section (null when
1247
+ // the route did not exist) plus the ids this apply introduced.
1248
+ preManagedSection: preManagedSection === undefined ? null : structuredClone(preManagedSection),
1249
+ appliedAddedIds: [...state.addedIds].sort((a, b) => a.localeCompare(b)),
1250
+ }
1251
+ try {
1252
+ await deps.ownershipStore.write(ledgerKey, entry)
1253
+ committedLedgerKeys.push(ledgerKey)
1254
+ } catch (err) {
1255
+ failure = `${planned.route}: ledger write failed (${errorText(err)})`
1256
+ routesResult.push({ route: planned.route, status: 'failed', reason: errorText(err) })
1257
+ break
1258
+ }
1259
+ // N1: a route is "wrote" only when settings actually changed. A pure
1260
+ // ledger adoption (keep row, zero ops) is a no-op on settings and must
1261
+ // not inflate the success count.
1262
+ routesResult.push({
1263
+ route: planned.route,
1264
+ status: wroteThisRoute ? 'wrote' : 'skipped',
1265
+ ...(wroteThisRoute ? {} : { reason: 'no-op: route already matches the plan (no settings write)' }),
1266
+ })
1267
+ }
1268
+ } catch (err) {
1269
+ failure = errorText(err)
1270
+ }
1271
+
1272
+ if (failure === undefined) {
1273
+ // 4. Fingerprint LAST (§14.7.4): only after settings + ledger both landed.
1274
+ const identityRoutes = Object.keys(readGoProviderSections(llmDescriptor(deps.settings), Object.values(routesOf(deps))) ?? {})
1275
+ const liveSections = readGoProviderSections(llmDescriptor(deps.settings), Object.values(routesOf(deps)))
1276
+ const identity = fingerprintGoIdentity(liveSections, identityRoutes)
1277
+ // N3: `appliedManagedIds` mirrors ONLY the ledger entries actually written
1278
+ // above. No fallback to `managedIdsForRoute` for routes skipped by the plan
1279
+ // (e.g. an empty google slot): that used to fabricate a route -> [] entry
1280
+ // with no backing ledger record.
1281
+ const managedIds: Record<string, string[]> = { ...managedByRoute }
1282
+ const applied: MigrationRecord = {
1283
+ ...(prior ?? {}),
1284
+ applying: false,
1285
+ // Keep the captured whole-section backup: it is the audit copy and the
1286
+ // crash-window fallback for rollback. The authoritative copy also lives
1287
+ // on each ledger entry (preManagedSection), so neither is discarded.
1288
+ backup,
1289
+ planHash: plan.planHash,
1290
+ backupPath: plan.backupPath,
1291
+ appliedAt: deps.now,
1292
+ appliedIdentity: identity,
1293
+ appliedIdentityRoutes: identityRoutes,
1294
+ appliedManagedIds: managedIds,
1295
+ appliedFingerprint: appliedFingerprintOf(identity, managedIds),
1296
+ // Moves are relocations, not deletions: report them separately from the
1297
+ // delete rows so rollback/audit can tell the two apart (V19).
1298
+ movedIds: [...new Set(plan.idActions.filter((action) => action.op === 'move').map((action) => action.id))],
1299
+ legacyFingerprint: undefined,
1300
+ }
1301
+ try {
1302
+ await deps.migrationStore.write!(applied)
1303
+ } catch (err) {
1304
+ failure = `appliedFingerprint persist failed (${errorText(err)})`
1305
+ }
1306
+
1307
+ // 5. Opt-in reference rewrite — only verified config keys, never sessions.
1308
+ if (failure === undefined && plan.rewriteRefs !== 'none' && deps.applyReferenceRewrite !== undefined) {
1309
+ for (const ref of plan.references) {
1310
+ if (!ref.verified || !ref.rewritable || ref.reportOnly) continue
1311
+ try {
1312
+ await deps.applyReferenceRewrite({ surface: ref.surface, location: ref.location, before: ref.before, after: ref.after })
1313
+ } catch (err) {
1314
+ deps.logger.warn('reference rewrite failed for %s: %s', ref.surface, errorText(err))
1315
+ }
1316
+ }
1317
+ }
1318
+ }
1319
+
1320
+ if (failure !== undefined) {
1321
+ // Best-effort restore from the captured snapshot; re-lock and keep no fingerprint.
1322
+ await restoreOnApplyFailure(deps, backup, writtenRoutes, committedLedgerKeys, prior)
1323
+ // O1/C2: settings were restored to the pre-apply snapshot; any journal from
1324
+ // the pre-migration writer is now stale. Drop it so a later round cannot
1325
+ // re-account settings the apply just rolled back.
1326
+ await clearProfileJournals(deps)
1327
+ deps.logger.warn('migrate apply rolled back after failure: %s', failure)
1328
+ return applyFailure('write-failed', plan.planHash, plan.confirmCode, failure, writtenRoutes.length > 0)
1329
+ }
1330
+
1331
+ // O1/C2: apply succeeded — its settings writes are fully accounted by the
1332
+ // migration record + ledger. Any pre-migration journal is stale now.
1333
+ await clearProfileJournals(deps)
1334
+
1335
+ // N1: count the settings writes that actually happened (`writtenRoutes`),
1336
+ // not the per-route result rows (which now include truthful no-op `skipped`
1337
+ // routes). Zero writes must say so explicitly instead of "N routes written".
1338
+ const writtenCount = writtenRoutes.length
1339
+ const headline = writtenCount === 0
1340
+ ? 'migrate apply: 0 routes written (no settings writes; all routes already match / ledger-only adoptions), fingerprint persisted'
1341
+ : `migrate apply: ${writtenCount} routes written, fingerprint persisted`
1342
+ const text = [
1343
+ headline,
1344
+ ...routesResult.map((r) => ` ${r.route}: ${r.status}${r.reason !== undefined ? ` (${r.reason})` : ''}`),
1345
+ 'Per-id results (one per plan action row):',
1346
+ ...actionResults.map((a) => ` ${a.status.toUpperCase().padEnd(7)} ${a.op.toUpperCase().padEnd(6)} ${a.route}/${a.id}${a.to !== undefined ? ` → ${a.to}` : ''} — ${a.reason}`),
1347
+ ` backup: ${plan.backupPath}`,
1348
+ ` rollback: /model-sync migrate rollback --plan ${plan.planHash}`,
1349
+ ].join('\n')
1350
+ return {
1351
+ ok: true,
1352
+ reason: 'applied',
1353
+ planHash: plan.planHash,
1354
+ confirmCode: plan.confirmCode,
1355
+ routes: routesResult,
1356
+ actions: actionResults,
1357
+ backupPath: plan.backupPath,
1358
+ text,
1359
+ }
1360
+ }
1361
+
1362
+ function routesOf(deps: MigrateDeps): Partial<Record<GoRouteSlot, string>> {
1363
+ return { ...GO_SLOT_ROUTES, ...deps.routes }
1364
+ }
1365
+
1366
+ function captureBackup(plan: MigrationPlan, desc: SettingsDescriptor, now: number): MigrationBackup {
1367
+ const backup: MigrationBackup = { planHash: plan.planHash, capturedAt: now, routes: {} }
1368
+ for (const planned of plan.routes) {
1369
+ const section = rawRoute(desc, planned.route)
1370
+ backup.routes[planned.route] = {
1371
+ ...(section === undefined ? {} : { section: structuredClone(section) as Record<string, unknown> }),
1372
+ }
1373
+ }
1374
+ return backup
1375
+ }
1376
+
1377
+ /** Best-effort undo of a partial apply: restore route sections, drop new ledger entries, clear applying. */
1378
+ async function restoreOnApplyFailure(
1379
+ deps: MigrateDeps,
1380
+ backup: MigrationBackup,
1381
+ writtenRoutes: string[],
1382
+ ledgerKeys: string[],
1383
+ prior: MigrationRecord | undefined,
1384
+ ): Promise<void> {
1385
+ const desc = llmDescriptor(deps.settings)
1386
+ for (const route of writtenRoutes) {
1387
+ if (desc === undefined) continue
1388
+ const original = backup.routes[route]?.section
1389
+ const ops: SettingsMutationOp[] = []
1390
+ if (original === undefined) {
1391
+ ops.push({ op: 'unset', path: ['providers', route] })
1392
+ } else {
1393
+ // Restore via field-level ops (never replace the whole section): unset the
1394
+ // route first so plugin-created sections disappear, then reapply the
1395
+ // original fields/models. This keeps the operation compatible with the
1396
+ // writer's path-based mutate contract (§14.3: no whole-section write-back).
1397
+ ops.push({ op: 'unset', path: ['providers', route] })
1398
+ for (const [field, value] of Object.entries(original)) {
1399
+ if (field === 'models' && !Array.isArray(value)) continue
1400
+ ops.push({ op: 'set', path: ['providers', route, field], value: structuredClone(value) })
1401
+ }
1402
+ }
1403
+ try {
1404
+ await mutateWithRetry(deps, ops)
1405
+ } catch (err) {
1406
+ deps.logger.warn('apply-failure restore failed for %s: %s', route, errorText(err))
1407
+ }
1408
+ }
1409
+ for (const key of ledgerKeys) {
1410
+ try {
1411
+ const original = backup.routes[key.split('#')[0]]?.ledger
1412
+ if (original === undefined) await deps.ownershipStore.delete(key)
1413
+ else await deps.ownershipStore.write(key, original as unknown as GoOwnershipEntry)
1414
+ } catch (err) {
1415
+ deps.logger.warn('apply-failure ledger restore failed for %s: %s', key, errorText(err))
1416
+ }
1417
+ }
1418
+ if (typeof deps.migrationStore.write === 'function') {
1419
+ try {
1420
+ await deps.migrationStore.write({ ...(prior ?? {}), applying: false })
1421
+ } catch (err) {
1422
+ deps.logger.warn('apply-failure applying flag clear failed: %s', errorText(err))
1423
+ }
1424
+ }
1425
+ }
1426
+
1427
+ // ---------------------------------------------------------------------------
1428
+ // rollback (V20): restore snapshot, clear ledger+fingerprint, re-lock
1429
+ // ---------------------------------------------------------------------------
1430
+
1431
+ export type MigrateRollbackReason =
1432
+ | 'rolled-back'
1433
+ | 'consent-required'
1434
+ | 'plan-hash-mismatch'
1435
+ | 'no-record'
1436
+ | 'snapshot-missing'
1437
+ | 'hash-mismatch'
1438
+
1439
+ export interface MigrateRollbackResult {
1440
+ ok: boolean
1441
+ reason: MigrateRollbackReason
1442
+ routes: string[]
1443
+ text: string
1444
+ }
1445
+
1446
+ export async function rollbackMigration(
1447
+ args: { planHash?: string },
1448
+ deps: MigrateDeps,
1449
+ ): Promise<MigrateRollbackResult> {
1450
+ const refuse = (reason: MigrateRollbackReason, detail: string): MigrateRollbackResult => ({
1451
+ ok: false, reason, routes: [], text: `migrate rollback refused (${reason}): ${detail}; zero writes`,
1452
+ })
1453
+
1454
+ const record = await readRecord(deps)
1455
+ if (record === undefined) return refuse('no-record', 'no migration record to roll back')
1456
+ if (typeof args.planHash !== 'string' || args.planHash === '') return refuse('consent-required', 'a --plan <hash> is required')
1457
+ if (record.planHash !== args.planHash) return refuse('plan-hash-mismatch', `record hash != ${args.planHash}`)
1458
+ // A crashed apply leaves `applying:true` + the captured backup but no
1459
+ // fingerprint; rollback must still be able to restore from that backup.
1460
+ if (record.appliedFingerprint === undefined && record.backup === undefined) {
1461
+ return refuse('no-record', 'record has neither appliedFingerprint nor a captured backup')
1462
+ }
1463
+
1464
+ const desc = llmDescriptor(deps.settings)
1465
+ if (desc === undefined || deps.settings === undefined) return refuse('snapshot-missing', 'settings/llm-pi-ai unavailable')
1466
+
1467
+ const routeIds = Object.values(routesOf(deps))
1468
+ // Hash check: every plugin-managed id still present in settings must match the
1469
+ // hash we wrote. An external edit → refuse (never clobber user changes).
1470
+ for (const route of routeIds) {
1471
+ const entry = await deps.ownershipStore.read(goOwnershipKey(route, deps.keyFingerprint)).catch(() => undefined)
1472
+ if (entry === undefined) continue
1473
+ const currentById = new Map(rawModels(desc, route).map((profile) => [profile.id, profile]))
1474
+ for (const [id, managed] of Object.entries(entry.managed ?? {})) {
1475
+ const model = currentById.get(id)
1476
+ if (model !== undefined && profileHash(model) !== managed.hash) {
1477
+ return refuse('hash-mismatch', `${route}/${id} changed after apply (managed hash mismatch)`)
1478
+ }
1479
+ }
1480
+ }
1481
+
1482
+ // Reconstruct each route from the WHOLE pre-apply section (§14.3), not from a
1483
+ // models-only list. Restore its exact fields/values/order, remove ids this
1484
+ // migration introduced, and keep ids the user added after apply.
1485
+ const rollbackOps: { route: string; ops: SettingsMutationOp[] }[] = []
1486
+ for (const route of routeIds) {
1487
+ const entry = await deps.ownershipStore.read(goOwnershipKey(route, deps.keyFingerprint)).catch(() => undefined)
1488
+ const backupRoute = record.backup?.routes[route]
1489
+ if (entry === undefined && backupRoute === undefined) continue
1490
+ // Authoritative snapshot: the ledger copy written by apply, or the captured
1491
+ // backup for a crash before the ledger commit. `null`/`undefined` section
1492
+ // means the route did not exist before the migration; a written-but-missing
1493
+ // field is the snapshot-missing refusal below.
1494
+ const hasSectionSnapshot = entry !== undefined
1495
+ ? entry.preManagedSection !== undefined
1496
+ : backupRoute !== undefined
1497
+ if (!hasSectionSnapshot) return refuse('snapshot-missing', `${route} has no preManagedSection`)
1498
+ const originalSection = entry !== undefined ? entry.preManagedSection : backupRoute?.section
1499
+
1500
+ const originalModels: SettingsModelProfile[] = Array.isArray(originalSection?.models)
1501
+ ? originalSection.models as SettingsModelProfile[]
1502
+ : []
1503
+ const originalIds = new Set(originalModels.map((profile) => profile.id))
1504
+ const current = rawModels(desc, route)
1505
+ // Ids introduced by the migration itself: recorded at apply time when a
1506
+ // ledger exists. For a crash-window rollback every current id absent from
1507
+ // the captured snapshot was written by the half-finished apply.
1508
+ const addedIds = entry !== undefined
1509
+ ? new Set(entry.appliedAddedIds ?? [])
1510
+ : new Set(current.filter((profile) => !originalIds.has(profile.id)).map((profile) => profile.id))
1511
+ // A post-apply id is neither in the original section nor one of ours — keep
1512
+ // it (never clobber user edits, even if it sits on a plugin-created route).
1513
+ const userAdded = current.filter((profile) => !originalIds.has(profile.id) && !addedIds.has(profile.id))
1514
+ const finalModels = [...originalModels, ...userAdded]
1515
+
1516
+ const ops: SettingsMutationOp[] = []
1517
+ if (originalSection === null || originalSection === undefined) {
1518
+ // Route did not exist before apply: drop everything the plugin created,
1519
+ // keeping only models the user added afterwards.
1520
+ ops.push({ op: 'unset', path: ['providers', route] })
1521
+ if (finalModels.length > 0) ops.push({ op: 'set', path: ['providers', route, 'models'], value: finalModels })
1522
+ } else {
1523
+ // Rebuild field-by-field in the ORIGINAL key order with the ORIGINAL values
1524
+ // so the restored bytes match the pre-apply section exactly: fields that
1525
+ // existed before are restored (never unset), fields apply wrote that were
1526
+ // absent before disappear with the whole-section reset, and the models
1527
+ // array keeps its original order with user-added ids appended.
1528
+ ops.push({ op: 'unset', path: ['providers', route] })
1529
+ const hasModelsKey = Object.prototype.hasOwnProperty.call(originalSection, 'models')
1530
+ for (const [field, value] of Object.entries(originalSection)) {
1531
+ if (field === 'models') {
1532
+ if (hasModelsKey) ops.push({ op: 'set', path: ['providers', route, 'models'], value: finalModels })
1533
+ } else {
1534
+ ops.push({ op: 'set', path: ['providers', route, field], value: structuredClone(value) })
1535
+ }
1536
+ }
1537
+ if (!hasModelsKey && finalModels.length > 0) {
1538
+ ops.push({ op: 'set', path: ['providers', route, 'models'], value: finalModels })
1539
+ }
1540
+ }
1541
+ if (ops.length > 0) rollbackOps.push({ route, ops })
1542
+ }
1543
+
1544
+ for (const item of rollbackOps) {
1545
+ try {
1546
+ await mutateWithRetry(deps, item.ops)
1547
+ } catch (err) {
1548
+ // Some rollback ops may already have landed. Drop this profile's journals
1549
+ // so a later round cannot re-commit ledger/record for settings rollback
1550
+ // is in the middle of undoing.
1551
+ await clearProfileJournals(deps)
1552
+ return refuse('hash-mismatch', `${item.route}: settings mutate failed (${errorText(err)})`)
1553
+ }
1554
+ }
1555
+ for (const route of routeIds) {
1556
+ try {
1557
+ await deps.ownershipStore.delete(goOwnershipKey(route, deps.keyFingerprint))
1558
+ } catch (err) {
1559
+ deps.logger.warn('rollback ledger cleanup failed for %s: %s', route, errorText(err))
1560
+ }
1561
+ }
1562
+ if (typeof deps.migrationStore.write === 'function') {
1563
+ // Clear the applied marker + fingerprint; the state falls back to legacy-*
1564
+ // from the restored sections, so go sync write authority is re-locked.
1565
+ await deps.migrationStore.write({
1566
+ ...(record.legacyFingerprint !== undefined ? { legacyFingerprint: record.legacyFingerprint } : {}),
1567
+ applying: false,
1568
+ })
1569
+ }
1570
+ // O1/C2: rollback rewrote settings back to the pre-migration snapshot; every
1571
+ // journal of this profile describes a now-obsolete write. Clear them (this
1572
+ // also removes key-rotation orphans) so no later round re-accounts them.
1573
+ await clearProfileJournals(deps)
1574
+
1575
+ return {
1576
+ ok: true,
1577
+ reason: 'rolled-back',
1578
+ routes: rollbackOps.map((item) => item.route),
1579
+ text: `migrate rollback: restored ${rollbackOps.length} routes, cleared ledger + fingerprint, write authority re-locked`,
1580
+ }
1581
+ }
1582
+
1583
+ // ---------------------------------------------------------------------------
1584
+ // status (read-only): per-route state + write authority (V16)
1585
+ // ---------------------------------------------------------------------------
1586
+
1587
+ export interface MigrationRouteStatus {
1588
+ route: string
1589
+ state: MigrationState
1590
+ owner: string
1591
+ decision: 'write' | 'skip'
1592
+ reason: string
1593
+ }
1594
+
1595
+ export interface MigrateStatusResult {
1596
+ overall: MigrationState
1597
+ /**
1598
+ * D6: structured write-authority summary for automation. `none` whenever an
1599
+ * unclaimed record is present (gate closed), otherwise whether any route was
1600
+ * granted write authority. Per-route authority is in `routes[].owner`.
1601
+ */
1602
+ writeAuthority: 'none' | 'go'
1603
+ /** D6: unclaimed migration records (foreign profile / legacy shape) — never claimed. */
1604
+ unclaimed: UnclaimedMigrationRecord[]
1605
+ applying: boolean
1606
+ routes: MigrationRouteStatus[]
1607
+ text: string
1608
+ }
1609
+
1610
+ export async function migrationStatusReport(
1611
+ deps: Pick<MigrateDeps, 'settings' | 'migrationStore' | 'keyFingerprint' | 'routes' | 'now'>,
1612
+ config?: Partial<RouteWriterConfig>,
1613
+ ): Promise<MigrateStatusResult> {
1614
+ const details = deps.settings?.describe().find((desc) => desc.ns === 'llm-pi-ai')
1615
+ const record = await readRecord(deps)
1616
+ const routeIds = Object.values({ ...GO_SLOT_ROUTES, ...deps.routes })
1617
+ const sections = readGoProviderSections(details, routeIds)
1618
+ const sectionState = migrationStateForPlan(sections, record, routeIds[0])
1619
+ // D6: the store hides unreadable records from read() (B1). Ask it separately
1620
+ // for provenance so status can name the two unclaimable cases WITHOUT
1621
+ // changing the gate: both keep write authority `none`, claim nothing, and
1622
+ // never authorize rollback deletion. Detection is advisory and read-only.
1623
+ //
1624
+ // Only when read() found NO record for this profile: another profile's own
1625
+ // valid record is normal multi-profile coexistence and must not relabel a
1626
+ // profile that already has its own applied/drifted record (B1 isolation).
1627
+ let unclaimed: UnclaimedMigrationRecord[] = []
1628
+ if (record === undefined) {
1629
+ try {
1630
+ unclaimed = await deps.migrationStore.unclaimedRecords?.() ?? []
1631
+ } catch {
1632
+ // An unreadable store never changes status (same rule as legacyKeys).
1633
+ }
1634
+ }
1635
+ const recordState: MigrationState | undefined = unclaimedRecordState(unclaimed)
1636
+ const overall = recordState ?? sectionState
1637
+ const states = detectRouteStates(sections, record, routeIds, sectionState)
1638
+ const authority: RouteWriterConfig = {
1639
+ caller: config?.caller ?? 'go',
1640
+ goEnabled: config?.goEnabled ?? true,
1641
+ goRoutes: routeIds,
1642
+ zenMode: config?.zenMode,
1643
+ zenRoutes: config?.zenRoutes,
1644
+ }
1645
+ const stub = {
1646
+ state: overall,
1647
+ fingerprint: fingerprintSection(sections ?? {}),
1648
+ identity: fingerprintGoIdentity(sections, record?.appliedIdentityRoutes),
1649
+ appliedIdentity: record?.appliedIdentity,
1650
+ appliedFingerprint: record?.appliedFingerprint,
1651
+ applying: record?.applying === true,
1652
+ fingerprintHealed: false,
1653
+ expectedFingerprint: '',
1654
+ }
1655
+ const routes = routeIds.map((route) => {
1656
+ const decision = routeWriter(route, authority, stub)
1657
+ return {
1658
+ route,
1659
+ // An unclaimed record closes the gate for the whole route set; surface
1660
+ // that label on every go route instead of the misleading legacy-inline.
1661
+ state: recordState ?? states[route] ?? 'absent',
1662
+ owner: decision.owner,
1663
+ decision: decision.decision,
1664
+ reason: decision.reason,
1665
+ }
1666
+ })
1667
+ const writeAuthority: MigrateStatusResult['writeAuthority'] = unclaimed.length > 0
1668
+ ? 'none'
1669
+ : routes.some((r) => r.owner === 'go' && r.decision === 'write') ? 'go' : 'none'
1670
+ const lines = [
1671
+ `model-sync migrate status: ${overall}${stub.applying ? ' (applying)' : ''}`,
1672
+ ...routes.map((r) => ` ${r.route}: state=${r.state} owner=${r.owner} ${r.decision}${r.reason !== undefined ? ` (${r.reason})` : ''}`),
1673
+ ]
1674
+ if (recordState !== undefined) {
1675
+ lines.push(` unclaimed: ${recordState} writeAuthority=none (不认领 / 不开门 / 不可回滚删除;请在归属 profile 重新运行 /model-sync migrate plan/apply)`)
1676
+ for (const item of unclaimed) {
1677
+ lines.push(` ${item.kind}: ${item.key}${item.profileKey !== undefined ? ` (profileKey=${item.profileKey})` : ''}`)
1678
+ }
1679
+ }
1680
+ // B1 compatibility: unscoped legacy keys are reported but NEVER claimed.
1681
+ // A pre-fix record has no profile stamp, so its owner is unknown; adopting
1682
+ // it could open the gate for a profile that never consented. Tell the user
1683
+ // to re-migrate in the owning profile instead of silently using the record.
1684
+ let legacy: string[] = []
1685
+ try {
1686
+ legacy = await deps.migrationStore.legacyKeys?.() ?? []
1687
+ } catch {
1688
+ // Detection is advisory — an unreadable store never changes status.
1689
+ }
1690
+ if (legacy.length > 0) {
1691
+ lines.push(` 警告: 检测到 ${legacy.length} 个无 profile 前缀的旧键(归属未知,未认领): ${legacy.join(', ')};请在归属 profile 重新运行 /model-sync migrate plan/apply`)
1692
+ }
1693
+ return { overall, writeAuthority, unclaimed, applying: stub.applying, routes, text: lines.join('\n') }
1694
+ }