@aiwayds/dsh-model-sync 0.12.0 → 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 (41) hide show
  1. package/lib/index.d.ts +8 -0
  2. package/lib/index.js +90 -33
  3. package/lib/index.js.map +1 -1
  4. package/lib/opencode-go-diagnose.d.ts +22 -1
  5. package/lib/opencode-go-diagnose.js +36 -5
  6. package/lib/opencode-go-diagnose.js.map +1 -1
  7. package/lib/opencode-go-host-catalog.d.ts +42 -0
  8. package/lib/opencode-go-host-catalog.js +98 -0
  9. package/lib/opencode-go-host-catalog.js.map +1 -0
  10. package/lib/opencode-go-journal.d.ts +6 -2
  11. package/lib/opencode-go-journal.js +1 -1
  12. package/lib/opencode-go-journal.js.map +1 -1
  13. package/lib/opencode-go-migrate.d.ts +40 -7
  14. package/lib/opencode-go-migrate.js +192 -34
  15. package/lib/opencode-go-migrate.js.map +1 -1
  16. package/lib/opencode-go-migration.d.ts +43 -0
  17. package/lib/opencode-go-migration.js +91 -2
  18. package/lib/opencode-go-migration.js.map +1 -1
  19. package/lib/opencode-go-one-shot.d.ts +6 -0
  20. package/lib/opencode-go-one-shot.js +36 -1
  21. package/lib/opencode-go-one-shot.js.map +1 -1
  22. package/lib/opencode-go-planner.d.ts +14 -0
  23. package/lib/opencode-go-planner.js +112 -10
  24. package/lib/opencode-go-planner.js.map +1 -1
  25. package/lib/opencode-go-sync.d.ts +16 -3
  26. package/lib/opencode-go-sync.js +24 -0
  27. package/lib/opencode-go-sync.js.map +1 -1
  28. package/lib/opencode-go-writer.d.ts +17 -1
  29. package/lib/opencode-go-writer.js +94 -10
  30. package/lib/opencode-go-writer.js.map +1 -1
  31. package/package.json +2 -2
  32. package/src/index.ts +100 -34
  33. package/src/opencode-go-diagnose.ts +58 -5
  34. package/src/opencode-go-host-catalog.ts +125 -0
  35. package/src/opencode-go-journal.ts +5 -3
  36. package/src/opencode-go-migrate.ts +231 -44
  37. package/src/opencode-go-migration.ts +116 -2
  38. package/src/opencode-go-one-shot.ts +44 -1
  39. package/src/opencode-go-planner.ts +120 -10
  40. package/src/opencode-go-sync.ts +40 -2
  41. package/src/opencode-go-writer.ts +110 -10
@@ -0,0 +1,125 @@
1
+ // Host runtime catalog reader (0.12.1 catalog-intersection fix).
2
+ //
3
+ // 0.12.0 wrote the FULL official listing into the single managed route. The
4
+ // host validates every route model id against the pi-ai catalog snapshot its
5
+ // OWN process loaded (fail-closed: one unknown id rejects the whole mutate —
6
+ // incident migrate-go 20261129-114103: `beam-free` written from the official
7
+ // listing, rejected because the app's bundled pi-ai only knows 29 ids while
8
+ // the official listing carries it). The planner therefore needs the HOST's
9
+ // id universe, not a build-time snapshot and not a filesystem probe:
10
+ //
11
+ // - require.resolve('@earendil-works/pi-ai') is unusable here: this package
12
+ // is ESM (no bare require), pi-ai's exports map has no require condition
13
+ // (ERR_PACKAGE_PATH_NOT_EXPORTED), and even a resolvable path would walk
14
+ // up from the PROFILE node_modules to a DIFFERENT pi-ai copy than the one
15
+ // the running host loaded (measured 2026-11-29: profile closure pi-ai has
16
+ // 33 ids incl. beam-free, the running app asar has 29 without it — a
17
+ // false-positive intersection reintroduces the fault).
18
+ // - The correct source is the host llm adapter itself:
19
+ // `llm.discoverModels('llm-pi-ai', { provider })` answers from the
20
+ // adapter's in-memory installed catalog with no network, no apiKey and no
21
+ // baseURL (dsh-llm-pi-ai src/discovery.ts checks `catalogModels(provider)`
22
+ // first) — the exact whitelist the host's serviceability validation uses.
23
+ //
24
+ // Callers that WRITE treat `null` as fail-closed (abort, never write an
25
+ // unverified list); read-only callers (diagnose) may degrade to "catalog
26
+ // unknown". This module only resolves and normalizes ids — no settings write,
27
+ // no fetch of its own.
28
+ //
29
+ // @module dsh-model-sync/opencode-go-host-catalog
30
+
31
+ /** The pi-ai builtin catalog provider id backing the opencode-go route. */
32
+ export const HOST_CATALOG_PROVIDER = 'opencode-go'
33
+
34
+ /** The settings namespace whose registered discovery serves the request. */
35
+ export const HOST_CATALOG_SETTINGS_NS = 'llm-pi-ai'
36
+
37
+ /** One entry of the host llm adapter's discovery reply (structural subset). */
38
+ export interface HostDiscoveredModel {
39
+ id?: unknown
40
+ }
41
+
42
+ /** The `llm` service subset this module consumes (see dsh-llm types). */
43
+ export interface HostCatalogLlmSeam {
44
+ discoverModels?(
45
+ settingsNs: string,
46
+ request: { provider?: string; baseURL?: string; api?: string; apiKey?: string },
47
+ signal?: AbortSignal,
48
+ ): Promise<readonly HostDiscoveredModel[]>
49
+ }
50
+
51
+ /** Why the host catalog could not be read (carried verbatim in reports). */
52
+ export type HostCatalogUnavailable =
53
+ | 'llm-service-unavailable'
54
+ | 'discovery-failed'
55
+ | 'empty-catalog'
56
+
57
+ export type GoHostCatalogResult =
58
+ | { ok: true; ids: string[] }
59
+ | { ok: false; reason: HostCatalogUnavailable; message: string }
60
+
61
+ /**
62
+ * Normalize a discovery reply into a sorted unique id list. Non-string/empty
63
+ * ids are dropped; the result is deterministic for report/plan hashing.
64
+ */
65
+ export function parseGoHostCatalogModels(models: readonly HostDiscoveredModel[]): string[] {
66
+ // P1-2: the reply comes from a host seam whose shape we do not control — a
67
+ // non-array reply (a buggy adapter) must degrade to "no ids" here, never
68
+ // throw a TypeError out of the for-of. The caller maps [] to the structured
69
+ // `empty-catalog` result, keeping the never-throw contract.
70
+ if (!Array.isArray(models)) return []
71
+ const ids = new Set<string>()
72
+ for (const model of models) {
73
+ if (model === null || typeof model !== 'object') continue
74
+ const id = model.id
75
+ if (typeof id !== 'string' || id.length === 0) continue
76
+ ids.add(id)
77
+ }
78
+ return [...ids].sort((a, b) => a.localeCompare(b))
79
+ }
80
+
81
+ function errorText(err: unknown): string {
82
+ const message = (err as { message?: unknown } | null | undefined)?.message
83
+ return typeof message === 'string' ? message : String(err)
84
+ }
85
+
86
+ /**
87
+ * Read the host runtime catalog for opencode-go through the llm discovery
88
+ * seam. Never throws: every failure is a structured `{ ok: false }` result so
89
+ * callers decide between fail-closed (writes) and degrade (diagnostics).
90
+ */
91
+ export async function loadHostGoCatalogIds(
92
+ llm: HostCatalogLlmSeam | undefined,
93
+ options: { provider?: string; settingsNs?: string; signal?: AbortSignal } = {},
94
+ ): Promise<GoHostCatalogResult> {
95
+ const provider = options.provider ?? HOST_CATALOG_PROVIDER
96
+ const settingsNs = options.settingsNs ?? HOST_CATALOG_SETTINGS_NS
97
+ // P1-2: `== null` — an explicitly-injected null must take the structured
98
+ // unavailable path, not TypeError on member access.
99
+ if (llm == null || typeof llm.discoverModels !== 'function') {
100
+ return {
101
+ ok: false,
102
+ reason: 'llm-service-unavailable',
103
+ message: 'llm service has no discoverModels seam (host adapter missing or too old)',
104
+ }
105
+ }
106
+ let models: readonly HostDiscoveredModel[]
107
+ try {
108
+ models = await llm.discoverModels(settingsNs, { provider }, options.signal)
109
+ } catch (err) {
110
+ return {
111
+ ok: false,
112
+ reason: 'discovery-failed',
113
+ message: `discoverModels(${settingsNs}, { provider: ${provider} }) failed: ${errorText(err)}`,
114
+ }
115
+ }
116
+ const ids = parseGoHostCatalogModels(models)
117
+ if (ids.length === 0) {
118
+ return {
119
+ ok: false,
120
+ reason: 'empty-catalog',
121
+ message: `host runtime catalog lists no model ids for provider ${provider}`,
122
+ }
123
+ }
124
+ return { ok: true, ids }
125
+ }
@@ -304,8 +304,10 @@ export interface ReconcileDeps {
304
304
  keyFingerprint: string
305
305
  logger: Logger
306
306
  /** Same callback the writer uses after a healthy own-write: re-persist the
307
- * migration record. Store/record only — never touches settings. */
308
- onRecord?: (route: string, managedIds: string[]) => Promise<void> | void
307
+ * migration record. Store/record only — never touches settings. The third
308
+ * argument marks a whole-section unset (ledger key deleted) so the record
309
+ * update drops the route's appliedManagedIds key, mirroring the writer. */
310
+ onRecord?: (route: string, managedIds: string[], info?: { unset: boolean }) => Promise<void> | void
309
311
  }
310
312
 
311
313
  function rawModels(desc: SettingsDescriptor | undefined, route: string): SettingsModelProfile[] {
@@ -429,7 +431,7 @@ export async function reconcileJournals(deps: ReconcileDeps): Promise<ReconcileR
429
431
  await deps.ownershipStore.write(ledgerKey, journal.entry)
430
432
  }
431
433
  if (deps.onRecord !== undefined) {
432
- await deps.onRecord(journal.route, [...journal.modelIds].sort())
434
+ await deps.onRecord(journal.route, [...journal.modelIds].sort(), { unset: journal.unset === true })
433
435
  }
434
436
  await deps.journalStore.delete(key)
435
437
  result.reconciled.push(journal.route)
@@ -34,11 +34,13 @@ import {
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,
@@ -67,16 +69,6 @@ const PLAN_VERSION = 1
67
69
  /** What apply will do with one route. */
68
70
  export type MigrationAction = 'create' | 'update' | 'keep' | 'unset'
69
71
 
70
- /** Classification of one id that exists in the current route (design §14.2). */
71
- export type MigrationIdKind =
72
- /** Official desired id — always targets the single managed route (0.12.0). */
73
- | 'desired'
74
- | 'legacy-other-protocol'
75
- | 'unknown-retired'
76
- | 'user-extra'
77
- /** Public catalog unavailable (offline/401/403) — fail-closed, never deleted (§14.2). */
78
- | 'unclassified'
79
-
80
72
  export interface MigrationIdClass {
81
73
  id: string
82
74
  kind: MigrationIdKind
@@ -128,6 +120,24 @@ export interface MigrationIdPlan {
128
120
  reason: string
129
121
  }
130
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
+
131
141
  export type RewriteRefMode = 'none' | 'default-model' | 'config'
132
142
 
133
143
  /** A reference candidate reported by plan. Only verified config keys may be rewritten. */
@@ -172,6 +182,16 @@ export interface MigrationPlanBody {
172
182
  /** True when apply cannot guarantee verbatim action-table execution: plan mode
173
183
  * is `adopt-disabled` and `--adopt` is rejected at the command layer (§14.2). */
174
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[]
175
195
  references: ReferenceCandidate[]
176
196
  pinnedSuggestions: string[]
177
197
  backupPath: string
@@ -214,6 +234,16 @@ export interface BuildPlanInput {
214
234
  * neither set are `user-extra` (user-written, never auto-deleted). `undefined`
215
235
  * means the catalog was unavailable → fail-closed `unclassified`. */
216
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
217
247
  /** Apply cannot execute the per-id table → plan mode `adopt-disabled` and
218
248
  * `--adopt` rejected at the command layer (design §14.2 fallback). */
219
249
  adoptDisabled?: boolean
@@ -402,11 +432,18 @@ function defaultReferences(targets: readonly string[], rewriteRefs: RewriteRefMo
402
432
 
403
433
  /** Build the full change plan. Pure: identical inputs → identical plan/hash. */
404
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
+ }
405
442
  const routes = { ...GO_SLOT_ROUTES, ...input.routes }
406
443
  const routeIds = Object.values(routes)
407
444
  const sections = readGoProviderSections(input.descriptor, routeIds)
408
445
  const prior = input.record
409
- const state = migrationStateForPlan(sections, prior, routes.chat)
446
+ const state = migrationStateOf(sections, prior, routes.chat)
410
447
  const stateByRoute = detectRouteStates(sections, prior, routeIds, state)
411
448
  // Fail-closed capability gate (§14.2): when the executor cannot guarantee the
412
449
  // action table, adopt is reported as disabled and plan rows stay conservative.
@@ -420,10 +457,42 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
420
457
  const targetRoute = routes.chat
421
458
  const targetSlot: GoRouteSlot = 'chat'
422
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
+ )
423
482
  const desired = input.entries
483
+ .filter((entry) => hostSet === undefined || hostSet.has(entry.id))
424
484
  .map(mapGoModelToProfile)
425
485
  .sort((a, b) => a.id.localeCompare(b.id))
426
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
+ }
427
496
 
428
497
  // Routes actually in scope for this plan: the managed route always; a legacy
429
498
  // slot route only when its section exists (a never-created route has nothing
@@ -486,6 +555,8 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
486
555
 
487
556
  const kindOf = (id: string): MigrationIdKind => {
488
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'
489
560
  // Fail-closed (§14.2): no public catalog → never guess "user-written".
490
561
  if (!publicCatalogAvailable) return 'unclassified'
491
562
  // Ids in the official public catalog but not in the current key's authorized
@@ -569,11 +640,42 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
569
640
  continue
570
641
  }
571
642
 
572
- // Non-desired id: user-extra / unknown-retired / unclassified. Default keep.
573
- // Delete only when the classification's own flag is set AND the row is in
574
- // this plan. `unclassified` (no public catalog) is never deletable.
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.
575
653
  const mayDelete = kind === 'user-extra' ? pruneUserExtra : kind === 'unknown-retired' ? adopt : false
576
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
+ }
577
679
  if (mayDelete) {
578
680
  idActions.push({ id, op: 'delete', route: loc.route, kind, pinned: false, profile: loc.profile,
579
681
  reason: kind === 'user-extra'
@@ -691,6 +793,8 @@ export function buildMigrationPlan(input: BuildPlanInput): MigrationPlan {
691
793
  idActions,
692
794
  managedAfterMigration,
693
795
  publicCatalogAvailable,
796
+ hostCatalogAvailable,
797
+ hostCatalogLagIds,
694
798
  adoptDisabled,
695
799
  references,
696
800
  pinnedSuggestions: [...pinnedSuggestions].sort(),
@@ -712,31 +816,19 @@ function describeId(kind: MigrationIdKind, adopt: boolean): string {
712
816
  case 'unknown-retired': return adopt ? 'unknown/retired id, delete only if confirmed in plan' : 'unknown/retired id kept as user-owned'
713
817
  case 'user-extra': return 'user-written id, never auto-deleted'
714
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)'
715
820
  }
716
821
  }
717
822
 
718
- /** Local state detection mirroring `migrationStateOf` (kept here to stay import-light). */
719
- function migrationStateForPlan(
720
- sections: Record<string, unknown> | undefined,
721
- record: MigrationRecord | undefined,
722
- chatRoute: string,
723
- ): MigrationState {
724
- if (sections === undefined || Object.keys(sections).length === 0) return 'absent'
725
- const fingerprint = fingerprintSection(sections)
726
- if (record?.appliedIdentity !== undefined) {
727
- return fingerprintGoIdentity(sections, record.appliedIdentityRoutes) === record.appliedIdentity ? 'applied' : 'drifted'
728
- }
729
- if (record?.appliedFingerprint !== undefined && fingerprint === record.appliedFingerprint) return 'applied'
730
- if (record !== undefined && (record.appliedFingerprint !== undefined || record.legacyFingerprint !== undefined)) {
731
- if (record.legacyFingerprint !== undefined && fingerprint === record.legacyFingerprint) {
732
- const chat = sections[chatRoute]
733
- return isRecord(chat) && Array.isArray(chat.models) ? 'legacy-inline' : 'legacy-inherit'
734
- }
735
- return 'drifted'
736
- }
737
- const chat = sections[chatRoute]
738
- return isRecord(chat) && Array.isArray(chat.models) ? 'legacy-inline' : 'legacy-inherit'
739
- }
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`.
740
832
 
741
833
  // ---------------------------------------------------------------------------
742
834
  // Human-readable reports (V16 / V19)
@@ -756,6 +848,11 @@ export function formatMigrationPlan(plan: MigrationPlan): string {
756
848
  ` mode: ${mode} rewrite-refs: ${plan.rewriteRefs}`,
757
849
  ` sections fingerprint: ${plan.preFingerprint.slice(0, 16)}…`,
758
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 拒绝)']),
759
856
  '',
760
857
  'Routes:',
761
858
  ]
@@ -830,6 +927,11 @@ export interface MigrateDeps {
830
927
  /** Official public catalog ids, used to distinguish unknown-retired from user-extra.
831
928
  * `undefined` → fail-closed `unclassified` (never deleted). */
832
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
833
935
  /** Capability flag: `--adopt` is refused at the command layer when the per-id
834
936
  * action table cannot be executed verbatim (design §14.2 fallback). */
835
937
  adoptDisabled?: boolean
@@ -883,6 +985,7 @@ export function buildMigrationPlanFromDeps(deps: MigrateDeps, record: MigrationR
883
985
  pinnedModels: deps.pinnedModels,
884
986
  pruneUserExtra: deps.pruneUserExtra,
885
987
  publicCatalogIds: deps.publicCatalogIds,
988
+ hostCatalogIds: deps.hostCatalogIds,
886
989
  adoptDisabled: deps.adoptDisabled,
887
990
  now: deps.now,
888
991
  })
@@ -896,6 +999,20 @@ async function readRecord(deps: { migrationStore: MigrationStateStore }): Promis
896
999
  }
897
1000
  }
898
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
+
899
1016
  function llmDescriptor(settings: SettingsService | undefined): SettingsDescriptor | undefined {
900
1017
  return settings?.describe().find((desc) => desc.ns === 'llm-pi-ai')
901
1018
  }
@@ -931,19 +1048,35 @@ function routeOps(
931
1048
  route: string,
932
1049
  fields: GoPlannedRouteFields,
933
1050
  models: SettingsModelProfile[],
1051
+ mode: 'managed' | 'preserve' = 'managed',
934
1052
  ): SettingsMutationOp[] {
935
1053
  const data = rawRoute(desc, route)
936
1054
  const ops: SettingsMutationOp[] = []
937
- for (const field of OWNED_FIELDS) {
938
- if (data?.[field] !== fields[field]) {
939
- ops.push({ op: 'set', path: ['providers', route, field], value: fields[field] })
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
+ }
940
1065
  }
941
1066
  }
942
1067
  // Catalog-reuse: strip legacy `api`/`baseURL` so the host reuses pi-ai's
943
- // builtin catalog provider for this route.
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
944
1076
  for (const field of GO_LEGACY_ROUTE_FIELDS) {
945
1077
  const value = data?.[field]
946
- if (value !== undefined && value !== '') {
1078
+ if (value === undefined) continue
1079
+ if (value === '' || stripCatalogReuse) {
947
1080
  ops.push({ op: 'unset', path: ['providers', route, field] })
948
1081
  }
949
1082
  }
@@ -1115,6 +1248,8 @@ export type MigrateApplyReason =
1115
1248
  | 'unknown-action'
1116
1249
  | 'nothing-to-apply'
1117
1250
  | 'sync-in-flight'
1251
+ | 'host-catalog-unavailable'
1252
+ | 'host-catalog-unknown-models'
1118
1253
  | 'write-failed'
1119
1254
 
1120
1255
  /** Result of ONE row of the plan's action table — mirrors it one-to-one (V19). */
@@ -1153,7 +1288,19 @@ export async function applyMigration(
1153
1288
  args: { planHash?: string; confirmCode?: string; ackManaged?: boolean },
1154
1289
  deps: MigrateDeps,
1155
1290
  ): Promise<MigrateApplyResult> {
1156
- 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
+ }
1157
1304
  const plan = buildMigrationPlanFromDeps(deps, prior)
1158
1305
 
1159
1306
  // 1. Consent — every rejection below is ZERO writes. `--ack-managed` is a
@@ -1211,6 +1358,41 @@ export async function applyMigration(
1211
1358
  { routes: plan.routes, idActions: actionsToRun }, desc,
1212
1359
  )
1213
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
+
1214
1396
  // 3. Capture the audit backup and persist `applying` BEFORE the first mutate.
1215
1397
  // If we crash mid-apply, the record still carries the restore snapshot.
1216
1398
  const backup = captureBackup(plan, desc, deps.now)
@@ -1286,7 +1468,12 @@ export async function applyMigration(
1286
1468
  }
1287
1469
  // Write only ops that actually change fields/models. keep/update/delete-no
1288
1470
  // rows leave the section byte-identical, so no mutate happens for them.
1289
- 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')
1290
1477
  let wroteThisRoute = false
1291
1478
  if (ops.length > 0) {
1292
1479
  try {
@@ -1685,7 +1872,7 @@ export async function migrationStatusReport(
1685
1872
  const record = await readRecord(deps)
1686
1873
  const routeIds = Object.values({ ...GO_SLOT_ROUTES, ...deps.routes })
1687
1874
  const sections = readGoProviderSections(details, routeIds)
1688
- const sectionState = migrationStateForPlan(sections, record, routeIds[0])
1875
+ const sectionState = migrationStateOf(sections, record, routeIds[0])
1689
1876
  // D6: the store hides unreadable records from read() (B1). Ask it separately
1690
1877
  // for provenance so status can name the two unclaimable cases WITHOUT
1691
1878
  // changing the gate: both keep write authority `none`, claim nothing, and