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