@aiwayds/dsh-model-sync 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/lib/index.d.ts +8 -0
  2. package/lib/index.js +90 -24
  3. package/lib/index.js.map +1 -1
  4. package/lib/opencode-go-diagnose.d.ts +43 -21
  5. package/lib/opencode-go-diagnose.js +87 -56
  6. package/lib/opencode-go-diagnose.js.map +1 -1
  7. package/lib/opencode-go-grouping.d.ts +4 -26
  8. package/lib/opencode-go-grouping.js +12 -68
  9. package/lib/opencode-go-grouping.js.map +1 -1
  10. package/lib/opencode-go-host-catalog.d.ts +42 -0
  11. package/lib/opencode-go-host-catalog.js +98 -0
  12. package/lib/opencode-go-host-catalog.js.map +1 -0
  13. package/lib/opencode-go-journal.d.ts +6 -2
  14. package/lib/opencode-go-journal.js +1 -1
  15. package/lib/opencode-go-journal.js.map +1 -1
  16. package/lib/opencode-go-migrate.d.ts +40 -5
  17. package/lib/opencode-go-migrate.js +313 -84
  18. package/lib/opencode-go-migrate.js.map +1 -1
  19. package/lib/opencode-go-migration.d.ts +43 -0
  20. package/lib/opencode-go-migration.js +91 -2
  21. package/lib/opencode-go-migration.js.map +1 -1
  22. package/lib/opencode-go-one-shot.d.ts +6 -0
  23. package/lib/opencode-go-one-shot.js +41 -4
  24. package/lib/opencode-go-one-shot.js.map +1 -1
  25. package/lib/opencode-go-planner.d.ts +39 -24
  26. package/lib/opencode-go-planner.js +275 -207
  27. package/lib/opencode-go-planner.js.map +1 -1
  28. package/lib/opencode-go-sync.d.ts +16 -3
  29. package/lib/opencode-go-sync.js +24 -0
  30. package/lib/opencode-go-sync.js.map +1 -1
  31. package/lib/opencode-go-writer.d.ts +17 -1
  32. package/lib/opencode-go-writer.js +111 -16
  33. package/lib/opencode-go-writer.js.map +1 -1
  34. package/package.json +2 -2
  35. package/src/index.ts +100 -25
  36. package/src/opencode-go-diagnose.ts +124 -70
  37. package/src/opencode-go-grouping.ts +14 -85
  38. package/src/opencode-go-host-catalog.ts +125 -0
  39. package/src/opencode-go-journal.ts +5 -3
  40. package/src/opencode-go-migrate.ts +352 -95
  41. package/src/opencode-go-migration.ts +116 -2
  42. package/src/opencode-go-one-shot.ts +49 -4
  43. package/src/opencode-go-planner.ts +293 -216
  44. package/src/opencode-go-sync.ts +40 -2
  45. package/src/opencode-go-writer.ts +127 -15
@@ -21,7 +21,6 @@
21
21
  import { createHash } from 'node:crypto'
22
22
  import {
23
23
  GO_SLOT_ROUTES,
24
- groupGoModelsByProtocol,
25
24
  type GoRouteSlot,
26
25
  } from './opencode-go-grouping.ts'
27
26
  import {
@@ -29,16 +28,19 @@ import {
29
28
  mapGoModelToProfile,
30
29
  planGoRouteFields,
31
30
  profileHash,
31
+ GO_LEGACY_ROUTE_FIELDS,
32
32
  type GoManagedModel,
33
33
  type GoOwnershipEntry,
34
34
  type GoPlannedRouteFields,
35
35
  } from './opencode-go-planner.ts'
36
36
  import type { GoModelRecord } from './opencode-go-source.ts'
37
+ import { HOST_CATALOG_PROVIDER } from './opencode-go-host-catalog.ts'
37
38
  import type { SettingsModelProfile } from './translate.ts'
38
39
  import {
39
40
  appliedFingerprintOf,
40
41
  fingerprintGoIdentity,
41
42
  fingerprintSection,
43
+ migrationStateOf,
42
44
  readGoProviderSections,
43
45
  routeWriter,
44
46
  unclaimedRecordState,
@@ -53,7 +55,11 @@ import type { GoOwnershipStore } from './opencode-go-writer.ts'
53
55
  import type { GoJournalStore } from './opencode-go-journal.ts'
54
56
  import type { Logger, SettingsDescriptor, SettingsMutationOp, SettingsService } from './writer.ts'
55
57
 
56
- const OWNED_FIELDS = ['api', 'baseURL', 'displayName', 'apiKeyEnv'] as const
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
57
63
  const PLAN_VERSION = 1
58
64
 
59
65
  // ---------------------------------------------------------------------------
@@ -63,18 +69,6 @@ const PLAN_VERSION = 1
63
69
  /** What apply will do with one route. */
64
70
  export type MigrationAction = 'create' | 'update' | 'keep' | 'unset'
65
71
 
66
- /** Classification of one id that exists in the current route (design §14.2). */
67
- export type MigrationIdKind =
68
- | 'desired-chat'
69
- | 'desired-msg'
70
- | 'desired-resp'
71
- | 'desired-google'
72
- | 'legacy-other-protocol'
73
- | 'unknown-retired'
74
- | 'user-extra'
75
- /** Public catalog unavailable (offline/401/403) — fail-closed, never deleted (§14.2). */
76
- | 'unclassified'
77
-
78
72
  export interface MigrationIdClass {
79
73
  id: string
80
74
  kind: MigrationIdKind
@@ -126,6 +120,24 @@ export interface MigrationIdPlan {
126
120
  reason: string
127
121
  }
128
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
+
129
141
  export type RewriteRefMode = 'none' | 'default-model' | 'config'
130
142
 
131
143
  /** A reference candidate reported by plan. Only verified config keys may be rewritten. */
@@ -170,6 +182,16 @@ export interface MigrationPlanBody {
170
182
  /** True when apply cannot guarantee verbatim action-table execution: plan mode
171
183
  * is `adopt-disabled` and `--adopt` is rejected at the command layer (§14.2). */
172
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[]
173
195
  references: ReferenceCandidate[]
174
196
  pinnedSuggestions: string[]
175
197
  backupPath: string
@@ -212,6 +234,16 @@ export interface BuildPlanInput {
212
234
  * neither set are `user-extra` (user-written, never auto-deleted). `undefined`
213
235
  * means the catalog was unavailable → fail-closed `unclassified`. */
214
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
215
247
  /** Apply cannot execute the per-id table → plan mode `adopt-disabled` and
216
248
  * `--adopt` rejected at the command layer (design §14.2 fallback). */
217
249
  adoptDisabled?: boolean
@@ -327,6 +359,17 @@ export function verifyConsent(
327
359
  // Pure plan builder (V16: zero writes / zero external calls)
328
360
  // ---------------------------------------------------------------------------
329
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
+
330
373
  /** Per-route state, refined from the full-set state (§14.1). */
331
374
  function detectRouteStates(
332
375
  sections: Record<string, unknown> | undefined,
@@ -389,11 +432,18 @@ function defaultReferences(targets: readonly string[], rewriteRefs: RewriteRefMo
389
432
 
390
433
  /** Build the full change plan. Pure: identical inputs → identical plan/hash. */
391
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
+ }
392
442
  const routes = { ...GO_SLOT_ROUTES, ...input.routes }
393
443
  const routeIds = Object.values(routes)
394
444
  const sections = readGoProviderSections(input.descriptor, routeIds)
395
445
  const prior = input.record
396
- const state = migrationStateForPlan(sections, prior, routes.chat)
446
+ const state = migrationStateOf(sections, prior, routes.chat)
397
447
  const stateByRoute = detectRouteStates(sections, prior, routeIds, state)
398
448
  // Fail-closed capability gate (§14.2): when the executor cannot guarantee the
399
449
  // action table, adopt is reported as disabled and plan rows stay conservative.
@@ -401,25 +451,52 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
401
451
  const adopt = input.adopt === true && !adoptDisabled
402
452
  const rewriteRefs = input.rewriteRefs ?? 'none'
403
453
 
404
- const grouping = groupGoModelsByProtocol(input.entries)
405
- const entryById = new Map(input.entries.map((entry) => [entry.id, entry]))
406
-
407
- const desiredBySlot = new Map<GoRouteSlot, SettingsModelProfile[]>()
408
- for (const slot of ['chat', 'msg', 'resp', 'google'] as const) {
409
- desiredBySlot.set(slot, grouping.slots[slot]
410
- .map((id) => entryById.get(id))
411
- .filter((entry): entry is GoModelRecord => entry !== undefined)
412
- .map(mapGoModelToProfile)
413
- .sort((a, b) => a.id.localeCompare(b.id)))
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>)))
414
495
  }
415
- const desiredIds = new Set([...desiredBySlot.values()].flat().map((profile) => profile.id))
416
496
 
417
- // The two ids that move out of chat into dedicated protocol routes (§14.4).
418
- const targets = grouping.slots.msg.concat(grouping.slots.resp)
419
- const references = input.references ?? defaultReferences(targets, rewriteRefs)
420
-
421
- // Routes actually in scope for this plan (a conditional, empty google slot
422
- // with no pre-existing section is skipped — §9.4).
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).
423
500
  const scopedRoutes: {
424
501
  slot: GoRouteSlot
425
502
  route: string
@@ -427,27 +504,29 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
427
504
  fields: GoPlannedRouteFields
428
505
  desired: SettingsModelProfile[]
429
506
  currentModels: SettingsModelProfile[]
430
- }[] = []
431
- for (const slot of ['chat', 'msg', 'resp', 'google'] as const) {
432
- if (slot === 'google' && desiredBySlot.get(slot)!.length === 0 && sections?.[routes[slot]] === undefined) continue
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) {
433
516
  const route = routes[slot]
434
- const section = sections?.[route]
435
- const routeState = stateByRoute[route] ?? 'absent'
436
- const fields = planGoRouteFields(slot, input.entries.filter((entry) => grouping.slots[slot].includes(entry.id)), input.ref)
437
- const desired = desiredBySlot.get(slot) ?? []
438
- const currentModels: SettingsModelProfile[] = isRecord(section) && Array.isArray(section.models)
439
- ? section.models as SettingsModelProfile[]
440
- : []
441
- scopedRoutes.push({ slot, route, state: routeState, fields, desired, currentModels })
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
+ })
442
526
  }
443
527
 
444
- // desired id → its official target route + exact profile.
445
- const desiredTarget = new Map<string, { slot: GoRouteSlot; route: string; profile: SettingsModelProfile }>()
446
- for (const scope of scopedRoutes) {
447
- for (const profile of scope.desired) {
448
- desiredTarget.set(profile.id, { slot: scope.slot, route: scope.route, profile })
449
- }
450
- }
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 }]))
451
530
 
452
531
  // Every id currently in settings, with all the routes it occupies.
453
532
  const currentLocations = new Map<string, { route: string; profile: SettingsModelProfile }[]>()
@@ -459,6 +538,13 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
459
538
  }
460
539
  }
461
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
+
462
548
  const pinnedIds = new Set(input.pinnedModels ?? [])
463
549
  // `undefined` is materially different from an empty list: empty means the
464
550
  // catalog was fetched and truly has no such id (→ user-extra); undefined means
@@ -468,8 +554,9 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
468
554
  const pruneUserExtra = input.pruneUserExtra === true
469
555
 
470
556
  const kindOf = (id: string): MigrationIdKind => {
471
- const target = desiredTarget.get(id)
472
- if (target !== undefined) return `desired-${target.slot}` as 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'
473
560
  // Fail-closed (§14.2): no public catalog → never guess "user-written".
474
561
  if (!publicCatalogAvailable) return 'unclassified'
475
562
  // Ids in the official public catalog but not in the current key's authorized
@@ -553,11 +640,42 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
553
640
  continue
554
641
  }
555
642
 
556
- // Non-desired id: user-extra / unknown-retired / unclassified. Default keep.
557
- // Delete only when the classification's own flag is set AND the row is in
558
- // this plan. `unclassified` (no public catalog) is never deletable.
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.
559
653
  const mayDelete = kind === 'user-extra' ? pruneUserExtra : kind === 'unknown-retired' ? adopt : false
560
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
+ }
561
679
  if (mayDelete) {
562
680
  idActions.push({ id, op: 'delete', route: loc.route, kind, pinned: false, profile: loc.profile,
563
681
  reason: kind === 'user-extra'
@@ -590,7 +708,7 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
590
708
  reason: action.reason,
591
709
  }))
592
710
 
593
- const plannedRoutes: MigrationPlannedRoute[] = scopedRoutes.map((scope) => {
711
+ const plannedRoutesDraft: MigrationPlannedRoute[] = scopedRoutes.map((scope) => {
594
712
  const seen = new Set<string>()
595
713
  const existing: MigrationIdClass[] = []
596
714
  for (const profile of scope.currentModels) {
@@ -614,17 +732,35 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
614
732
  return { slot: scope.slot, route: scope.route, state: scope.state, action, fields: scope.fields, desired: scope.desired, existing }
615
733
  })
616
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
+
617
754
  const pinnedSuggestions = new Set<string>()
618
- const reversibleTargets = targets.filter((id) => !grouping.slots.chat.includes(id))
619
- for (const id of reversibleTargets) pinnedSuggestions.add(id)
755
+ // Reversible targets: desired ids still sitting on a legacy protocol route.
756
+ for (const id of targets) pinnedSuggestions.add(id)
620
757
  for (const id of pinnedIds) pinnedSuggestions.add(id)
621
758
 
622
759
  // B6 informed-consent text — part of the hashed body: any edit to this notice
623
760
  // changes planHash and invalidates the old confirmCode/ack. The id list comes
624
- // from `managedIdsAfterApply`, the SAME simulation apply uses for the ledger,
625
- // so a user-modified `update` row or a move onto a different-valued target is
626
- // never advertised as managed.
627
- const managedByRoute = managedIdsAfterApply({ routes: plannedRoutes, idActions }, input.descriptor)
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.
628
764
  // N2: no row may claim management on paper if the simulation shows apply
629
765
  // will not actually write/adopt that id. Normalise the per-id `managed`
630
766
  // flags to the simulated set so even the printed `[managed]` marker cannot
@@ -657,6 +793,8 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
657
793
  idActions,
658
794
  managedAfterMigration,
659
795
  publicCatalogAvailable,
796
+ hostCatalogAvailable,
797
+ hostCatalogLagIds,
660
798
  adoptDisabled,
661
799
  references,
662
800
  pinnedSuggestions: [...pinnedSuggestions].sort(),
@@ -673,39 +811,24 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
673
811
 
674
812
  function describeId(kind: MigrationIdKind, adopt: boolean): string {
675
813
  switch (kind) {
676
- case 'desired-chat': return 'official chat-completions target'
677
- case 'desired-msg': return 'official messages target (dedicated -msg route)'
678
- case 'desired-resp': return 'official responses target (dedicated -resp route)'
679
- case 'desired-google': return 'official google target'
814
+ case 'desired': return 'official desired id (single managed route)'
680
815
  case 'legacy-other-protocol': return adopt ? 'legacy id on the wrong protocol route' : 'legacy id kept in conservative mode'
681
816
  case 'unknown-retired': return adopt ? 'unknown/retired id, delete only if confirmed in plan' : 'unknown/retired id kept as user-owned'
682
817
  case 'user-extra': return 'user-written id, never auto-deleted'
683
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)'
684
820
  }
685
821
  }
686
822
 
687
- /** Local state detection mirroring `migrationStateOf` (kept here to stay import-light). */
688
- function migrationStateForPlan(
689
- sections: Record<string, unknown> | undefined,
690
- record: MigrationRecord | undefined,
691
- chatRoute: string,
692
- ): MigrationState {
693
- if (sections === undefined || Object.keys(sections).length === 0) return 'absent'
694
- const fingerprint = fingerprintSection(sections)
695
- if (record?.appliedIdentity !== undefined) {
696
- return fingerprintGoIdentity(sections, record.appliedIdentityRoutes) === record.appliedIdentity ? 'applied' : 'drifted'
697
- }
698
- if (record?.appliedFingerprint !== undefined && fingerprint === record.appliedFingerprint) return 'applied'
699
- if (record !== undefined && (record.appliedFingerprint !== undefined || record.legacyFingerprint !== undefined)) {
700
- if (record.legacyFingerprint !== undefined && fingerprint === record.legacyFingerprint) {
701
- const chat = sections[chatRoute]
702
- return isRecord(chat) && Array.isArray(chat.models) ? 'legacy-inline' : 'legacy-inherit'
703
- }
704
- return 'drifted'
705
- }
706
- const chat = sections[chatRoute]
707
- return isRecord(chat) && Array.isArray(chat.models) ? 'legacy-inline' : 'legacy-inherit'
708
- }
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`.
709
832
 
710
833
  // ---------------------------------------------------------------------------
711
834
  // Human-readable reports (V16 / V19)
@@ -725,13 +848,18 @@ export function formatMigrationPlan(plan: MigrationPlan): string {
725
848
  ` mode: ${mode} rewrite-refs: ${plan.rewriteRefs}`,
726
849
  ` sections fingerprint: ${plan.preFingerprint.slice(0, 16)}…`,
727
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 拒绝)']),
728
856
  '',
729
857
  'Routes:',
730
858
  ]
731
859
  for (const route of plan.routes) {
732
860
  const fields = route.fields
733
861
  lines.push(` ${route.route} [${route.slot}/${route.state}] ${route.action.toUpperCase()}`)
734
- lines.push(` api=${fields.api} baseURL=${fields.baseURL} displayName=${fields.displayName} apiKeyEnv=${fields.apiKeyEnv}`)
862
+ lines.push(` displayName=${fields.displayName} apiKeyEnv=${fields.apiKeyEnv}${route.action === 'unset' ? ' (whole-route unset; fields not written)' : ''}`)
735
863
  lines.push(` desired (${route.desired.length}): ${route.desired.map((profile) => profile.id).join(', ') || '(none)'}`)
736
864
  if (route.existing.length > 0) {
737
865
  lines.push(` existing: ${route.existing.map((entry) => `${entry.id}=${entry.kind}/${entry.action}`).join(', ')}`)
@@ -799,6 +927,11 @@ export interface MigrateDeps {
799
927
  /** Official public catalog ids, used to distinguish unknown-retired from user-extra.
800
928
  * `undefined` → fail-closed `unclassified` (never deleted). */
801
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
802
935
  /** Capability flag: `--adopt` is refused at the command layer when the per-id
803
936
  * action table cannot be executed verbatim (design §14.2 fallback). */
804
937
  adoptDisabled?: boolean
@@ -852,6 +985,7 @@ export function buildMigrationPlanFromDeps(deps: MigrateDeps, record: MigrationR
852
985
  pinnedModels: deps.pinnedModels,
853
986
  pruneUserExtra: deps.pruneUserExtra,
854
987
  publicCatalogIds: deps.publicCatalogIds,
988
+ hostCatalogIds: deps.hostCatalogIds,
855
989
  adoptDisabled: deps.adoptDisabled,
856
990
  now: deps.now,
857
991
  })
@@ -865,6 +999,20 @@ async function readRecord(deps: { migrationStore: MigrationStateStore }): Promis
865
999
  }
866
1000
  }
867
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
+
868
1016
  function llmDescriptor(settings: SettingsService | undefined): SettingsDescriptor | undefined {
869
1017
  return settings?.describe().find((desc) => desc.ns === 'llm-pi-ai')
870
1018
  }
@@ -900,12 +1048,36 @@ function routeOps(
900
1048
  route: string,
901
1049
  fields: GoPlannedRouteFields,
902
1050
  models: SettingsModelProfile[],
1051
+ mode: 'managed' | 'preserve' = 'managed',
903
1052
  ): SettingsMutationOp[] {
904
1053
  const data = rawRoute(desc, route)
905
1054
  const ops: SettingsMutationOp[] = []
906
- for (const field of OWNED_FIELDS) {
907
- if (data?.[field] !== fields[field]) {
908
- ops.push({ op: 'set', path: ['providers', route, field], value: fields[field] })
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] })
909
1081
  }
910
1082
  }
911
1083
  const sorted = [...models].sort((a, b) => a.id.localeCompare(b.id))
@@ -1076,6 +1248,8 @@ export type MigrateApplyReason =
1076
1248
  | 'unknown-action'
1077
1249
  | 'nothing-to-apply'
1078
1250
  | 'sync-in-flight'
1251
+ | 'host-catalog-unavailable'
1252
+ | 'host-catalog-unknown-models'
1079
1253
  | 'write-failed'
1080
1254
 
1081
1255
  /** Result of ONE row of the plan's action table — mirrors it one-to-one (V19). */
@@ -1114,7 +1288,19 @@ export async function applyMigration(
1114
1288
  args: { planHash?: string; confirmCode?: string; ackManaged?: boolean },
1115
1289
  deps: MigrateDeps,
1116
1290
  ): Promise<MigrateApplyResult> {
1117
- const prior = await readRecord(deps)
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
+ }
1118
1304
  const plan = buildMigrationPlanFromDeps(deps, prior)
1119
1305
 
1120
1306
  // 1. Consent — every rejection below is ZERO writes. `--ack-managed` is a
@@ -1172,6 +1358,41 @@ export async function applyMigration(
1172
1358
  { routes: plan.routes, idActions: actionsToRun }, desc,
1173
1359
  )
1174
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
+
1175
1396
  // 3. Capture the audit backup and persist `applying` BEFORE the first mutate.
1176
1397
  // If we crash mid-apply, the record still carries the restore snapshot.
1177
1398
  const backup = captureBackup(plan, desc, deps.now)
@@ -1214,9 +1435,45 @@ export async function applyMigration(
1214
1435
  continue
1215
1436
  }
1216
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
+ }
1217
1469
  // Write only ops that actually change fields/models. keep/update/delete-no
1218
1470
  // rows leave the section byte-identical, so no mutate happens for them.
1219
- const ops = routeOps(desc, planned.route, planned.fields, [...state.models.values()])
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')
1220
1477
  let wroteThisRoute = false
1221
1478
  if (ops.length > 0) {
1222
1479
  try {
@@ -1615,7 +1872,7 @@ export async function migrationStatusReport(
1615
1872
  const record = await readRecord(deps)
1616
1873
  const routeIds = Object.values({ ...GO_SLOT_ROUTES, ...deps.routes })
1617
1874
  const sections = readGoProviderSections(details, routeIds)
1618
- const sectionState = migrationStateForPlan(sections, record, routeIds[0])
1875
+ const sectionState = migrationStateOf(sections, record, routeIds[0])
1619
1876
  // D6: the store hides unreadable records from read() (B1). Ask it separately
1620
1877
  // for provenance so status can name the two unclaimable cases WITHOUT
1621
1878
  // changing the gate: both keep write authority `none`, claim nothing, and