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