@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
@@ -133,6 +133,15 @@ export function unclaimedRecordState(
133
133
  /** Migration record seam. `write` / `legacyKeys` are optional so read-only test stores keep working. */
134
134
  export interface MigrationStateStore {
135
135
  read(): Promise<MigrationRecord | undefined>
136
+ /**
137
+ * H4: strict read for write paths — `undefined` ONLY when the slot does not
138
+ * exist; a store error is THROWN so the caller (onOwnWrite /
139
+ * loadMigrationStatus({strict:true})) can fail closed instead of mistaking
140
+ * an unreadable record for "no prior record" and overwriting a live
141
+ * MigrationRecord (backup/planHash/movedIds would be lost). The plain
142
+ * `read()` keeps its tolerant read-only semantics for status/plan paths.
143
+ */
144
+ readStrict?(): Promise<MigrationRecord | undefined>
136
145
  /** Queue-serialized atomic slot replacement (same models-store queue as the ledger). */
137
146
  write?(record: MigrationRecord): Promise<void>
138
147
  /** Advisory: unscoped legacy keys found in the shared store (reported, never claimed). */
@@ -294,6 +303,86 @@ export function appliedFingerprintFieldsOf(
294
303
  return { identity, appliedFingerprint: appliedFingerprintOf(identity, managedIds) }
295
304
  }
296
305
 
306
+ /** Inputs to `ownWriteRecordUpdate` — everything the go writer knows post-write. */
307
+ export interface OwnWriteRecordInput {
308
+ /** The migration record read BEFORE this update (strict read; may be undefined). */
309
+ record: MigrationRecord | undefined
310
+ /** Live llm-pi-ai descriptor (or raw providers map) read AFTER the settings write. */
311
+ source: SettingsDescriptor | Record<string, unknown> | undefined
312
+ /** Configured go route ids (the identity comparison universe). */
313
+ routes: readonly string[]
314
+ /** The route this write landed on. */
315
+ route: string
316
+ /** Ledger-managed ids just committed for this route (sorted by the writer). */
317
+ managedIds: readonly string[]
318
+ /** True when this write was a whole-section unset (the ledger key was deleted). */
319
+ unset?: boolean
320
+ }
321
+
322
+ /**
323
+ * The ONE post-own-write migration record update — extracted from index.ts so
324
+ * tests (H2: the 0.11.x four-route convergence) drive the exact code the
325
+ * plugin runs. Semantics:
326
+ * - `appliedIdentityRoutes` shrinks to the routes still PRESENT in settings
327
+ * (0.12.0 catalog-reuse unsets the legacy protocol routes; keeping them in
328
+ * the identity set would make every later read look like drift) — with the
329
+ * just-written route always included (M2: prevents the degenerate
330
+ * constant `sha256('{}')` identity when every section is gone).
331
+ * - `appliedManagedIds[route]` is SET for a normal write and DELETED for an
332
+ * unset (M2: the ledger key was deleted — a persisted `[]` entry no ledger
333
+ * backs makes the stored fingerprint disagree with every status read and
334
+ * costs a fingerprint-healed round).
335
+ * - `appliedIdentity` / `appliedFingerprint` are recomputed from the live
336
+ * sections + the updated managed-id map, so the persisted record always
337
+ * matches what `migrationStatusOf` recomputes (no phantom heal).
338
+ * Pure: returns the next record; the caller persists it.
339
+ */
340
+ export function ownWriteRecordUpdate(input: OwnWriteRecordInput): MigrationRecord {
341
+ const sections = readGoProviderSections(input.source, input.routes) ?? {}
342
+ const presentRoutes = Object.keys(sections)
343
+ const prior = input.record ?? {}
344
+ // The just-written route joins the identity set ONLY on a real write. An
345
+ // unset drops it together with its section: identity and fingerprint are
346
+ // always recomputed from the SAME list the status read will use, so the
347
+ // degenerate empty-set hash (`sha256('{}')`) can only ever arise on BOTH
348
+ // sides simultaneously — never as a one-sided drift.
349
+ const includeRoute = input.unset !== true
350
+ const identityRoutes = [...new Set([
351
+ ...(prior.appliedIdentityRoutes ?? presentRoutes).filter((candidate) =>
352
+ presentRoutes.includes(candidate) || (includeRoute && candidate === input.route)),
353
+ ...(includeRoute ? [input.route] : []),
354
+ ])]
355
+ const appliedManagedIds: Record<string, string[]> = { ...(prior.appliedManagedIds ?? {}) }
356
+ if (input.unset === true) delete appliedManagedIds[input.route]
357
+ else appliedManagedIds[input.route] = [...input.managedIds].sort((a, b) => a.localeCompare(b))
358
+ // P2-②: an EMPTY identity route set means "no verifiable applied identity".
359
+ // Persisting `appliedIdentityRoutes: []` (+ the constant `sha256('{}')`
360
+ // identity it hashes to) would make ANY later config — including an
361
+ // unmigrated legacy-inline one — constant-match and read as `applied`
362
+ // (migration-gate penetration). Drop the applied-state fields instead: the
363
+ // record keeps everything else and state detection falls back to the
364
+ // closed-gate legacy path. `migrationStateOf` carries the matching
365
+ // read-side guard, so an old record that already carries `[]` cannot
366
+ // penetrate either.
367
+ if (identityRoutes.length === 0) {
368
+ const rest = { ...prior, appliedManagedIds }
369
+ delete rest.appliedIdentity
370
+ delete rest.appliedIdentityRoutes
371
+ delete rest.appliedFingerprint
372
+ return rest
373
+ }
374
+ const { identity, appliedFingerprint } = appliedFingerprintFieldsOf(
375
+ sections, { appliedIdentityRoutes: identityRoutes }, appliedManagedIds,
376
+ )
377
+ return {
378
+ ...prior,
379
+ appliedIdentity: identity,
380
+ appliedIdentityRoutes: identityRoutes,
381
+ appliedManagedIds,
382
+ appliedFingerprint,
383
+ }
384
+ }
385
+
297
386
  /**
298
387
  * Ledger ids for exactly the routes that HAVE a ledger entry. This is the
299
388
  * managed-id half of the shared fingerprint convention above: no entry means
@@ -339,8 +428,15 @@ export function migrationStateOf(
339
428
  if (sections === undefined || Object.keys(sections).length === 0) return 'absent'
340
429
  const fingerprint = fingerprintSection(sections)
341
430
  if (record?.appliedIdentity !== undefined) {
342
- return fingerprintGoIdentity(sections, record.appliedIdentityRoutes) === record.appliedIdentity
343
- ? 'applied' : 'drifted'
431
+ // P2-②: an explicit EMPTY appliedIdentityRoutes hashes every config to the
432
+ // same constant (`sha256('{}')`), so it must never count as a valid
433
+ // applied identity — treat it as absent and fall through to the legacy
434
+ // fingerprint comparison (which can only match the truly applied bytes).
435
+ const identityRoutes = record.appliedIdentityRoutes
436
+ if (identityRoutes === undefined || identityRoutes.length > 0) {
437
+ return fingerprintGoIdentity(sections, identityRoutes) === record.appliedIdentity
438
+ ? 'applied' : 'drifted'
439
+ }
344
440
  }
345
441
  // Backward compatibility with the pre-§14.7.4 full-section fingerprint.
346
442
  if (record?.appliedFingerprint !== undefined && fingerprint === record.appliedFingerprint) return 'applied'
@@ -383,7 +479,16 @@ export function migrationStatusOf(
383
479
  appliedFingerprint: record?.appliedFingerprint,
384
480
  legacyFingerprint: record?.legacyFingerprint,
385
481
  applying: record?.applying === true,
482
+ // P2-② (agy final): a degenerate record (`appliedIdentityRoutes: []`,
483
+ // constant `sha256('{}')` identity) constant-matches ANY config, so the
484
+ // raw identity equality below is trivially true — gating `fingerprintHealed`
485
+ // on the same valid-identity condition `migrationStateOf` uses keeps the
486
+ // §14.7.4 self-heal write-back (index.ts persists `expectedFingerprint`
487
+ // when this flag fires) away from records no state detector reads as
488
+ // applied. `undefined` routes stay valid (pre-identity-list records fall
489
+ // back to the routes present in settings).
386
490
  fingerprintHealed: record?.appliedIdentity !== undefined
491
+ && (record.appliedIdentityRoutes === undefined || record.appliedIdentityRoutes.length > 0)
387
492
  && identity === record.appliedIdentity
388
493
  && record.appliedFingerprint !== expectedFingerprint,
389
494
  expectedFingerprint,
@@ -508,6 +613,15 @@ export function createFileMigrationStateStore(
508
613
  if (profileKey !== undefined && raw.profileKey !== profileKey) return undefined
509
614
  return raw as unknown as MigrationRecord
510
615
  },
616
+ // H4: write paths must see store errors, never "no prior record". Only a
617
+ // genuinely absent slot (or a foreign stamp, which is an ownership
618
+ // verdict — not an error) reads as undefined here.
619
+ async readStrict(): Promise<MigrationRecord | undefined> {
620
+ const raw = await accessor.readRaw(slot)
621
+ if (!isRecord(raw)) return undefined
622
+ if (profileKey !== undefined && raw.profileKey !== profileKey) return undefined
623
+ return raw as unknown as MigrationRecord
624
+ },
511
625
  async write(record: MigrationRecord): Promise<void> {
512
626
  // writeRaw is queue-serialized atomic temp+rename, i.e. the SAME queue
513
627
  // that persists the ownership ledger (§14.7.4: settings → ledger → fingerprint).
@@ -225,6 +225,12 @@ export interface OneShotDeps {
225
225
  resolveEntries(apiKey: string): Promise<readonly GoModelRecord[]>
226
226
  /** Public catalog ids for id classification; undefined = fail-closed. */
227
227
  resolvePublicCatalogIds(apiKey: string, entries: readonly GoModelRecord[]): Promise<readonly string[] | undefined>
228
+ /**
229
+ * 0.12.1: host runtime catalog ids for opencode-go. `null` FAILS THE RUN
230
+ * CLOSED (zero writes) — without it the desired listing cannot be proven
231
+ * servable and the host would reject the whole mutate anyway.
232
+ */
233
+ resolveHostCatalogIds(): Promise<readonly string[] | null>
228
234
  /** ask-user seam, resolved lazily at invocation time. */
229
235
  resolveAsk(): AskServiceShape | undefined
230
236
  /**
@@ -547,6 +553,8 @@ function wrapReferenceRewrite(
547
553
  interface SharedPlanInputs {
548
554
  entries: readonly GoModelRecord[]
549
555
  publicCatalogIds: readonly string[] | undefined
556
+ /** Host runtime catalog ids (0.12.1); the run aborts before planning on null. */
557
+ hostCatalogIds: readonly string[]
550
558
  keyFingerprint: string
551
559
  }
552
560
 
@@ -578,6 +586,7 @@ function buildTargetDeps(
578
586
  logger: deps.logger,
579
587
  entries: shared.entries,
580
588
  publicCatalogIds: shared.publicCatalogIds,
589
+ hostCatalogIds: shared.hostCatalogIds,
581
590
  routes: deps.goConfig.routes,
582
591
  ref: deps.goConfig.ref,
583
592
  keyFingerprint: shared.keyFingerprint,
@@ -729,6 +738,11 @@ function perIdActionLines(plan: MigrationPlan): string[] {
729
738
  return lines
730
739
  }
731
740
 
741
+ /** Host-catalog lag ids of a plan (official ids excluded from the desired write). */
742
+ function hostCatalogLagOf(plan: MigrationPlan): string[] {
743
+ return plan.hostCatalogLagIds ?? []
744
+ }
745
+
732
746
  function buildConfirmQuestion(stamp: string, prepared: PreparedTarget[], modelsStoreBackup: string | undefined, rewriteRefs: RewriteRefMode): AskItemShape {
733
747
  const lines: string[] = []
734
748
  lines.push('即将执行 opencode-go 一键迁移(写入前最后确认)。')
@@ -761,6 +775,17 @@ function buildConfirmQuestion(stamp: string, prepared: PreparedTarget[], modelsS
761
775
  for (const line of item.plan.managedAfterMigration.split('\n')) lines.push(` ${line}`)
762
776
  }
763
777
  lines.push('')
778
+ // 0.12.1: host-catalog lag ids — the section the user most needs to see,
779
+ // because these OFFICIAL ids are deliberately not written.
780
+ const lagIds = hostCatalogLagOf(prepared[0]!.plan)
781
+ lines.push('【宿主目录滞后(官方有、宿主内置目录没有 —— 本轮不写入)】')
782
+ if (lagIds.length > 0) {
783
+ lines.push(` ${lagIds.join(', ')}`)
784
+ lines.push(' 宿主侧滞后,非本插件问题;宿主升级后 sync 自动纳入。')
785
+ } else {
786
+ lines.push(' (无 —— 官方 listing 全部被宿主目录覆盖)')
787
+ }
788
+ lines.push('')
764
789
  lines.push(`【槽位】${slotSummary(prepared[0]!.plan)}(按 opencode.go.routes 配置;未配置的槽不创建,google 缺省不建)`)
765
790
  lines.push('')
766
791
  // Review M8 (the most important item): with --rewrite-refs in effect, the
@@ -1061,7 +1086,21 @@ export async function runMigrateGoOneShot(
1061
1086
  return { kind: 'error', text: `migrate-go: official listing unavailable (${err instanceof Error ? err.message : String(err)}); zero writes` }
1062
1087
  }
1063
1088
  const publicCatalogIds = await deps.resolvePublicCatalogIds(apiKey, entries)
1064
- const shared: SharedPlanInputs = { entries, publicCatalogIds, keyFingerprint: fingerprintKey(apiKey.trim()) }
1089
+ // 0.12.1 fail-closed: no host runtime catalog → the run aborts before any
1090
+ // plan/write. Never fail open onto the unverified full listing.
1091
+ const hostCatalogIds = await deps.resolveHostCatalogIds()
1092
+ if (hostCatalogIds === null) {
1093
+ return {
1094
+ kind: 'error',
1095
+ text: [
1096
+ 'migrate-go: host runtime catalog unavailable(host-catalog-unavailable)—— 已中止:零写入。',
1097
+ ' 宿主 llm 服务未能返回 opencode-go 的内置目录(discoverModels 失败/未注册)。',
1098
+ ' 继续迁移会写入宿主目录不认识的模型 id(宿主对整条 mutate fail-closed 拒绝,0.12.0 故障根因);',
1099
+ ' 待宿主目录可读后重跑 /model-sync migrate-go。',
1100
+ ].join('\n'),
1101
+ }
1102
+ }
1103
+ const shared: SharedPlanInputs = { entries, publicCatalogIds, hostCatalogIds, keyFingerprint: fingerprintKey(apiKey.trim()) }
1065
1104
 
1066
1105
  const prepared: PreparedTarget[] = []
1067
1106
  const notMigratable: string[] = []
@@ -1298,6 +1337,10 @@ export async function runMigrateGoOneShot(
1298
1337
  const add = item.plan.idActions.filter((action) => action.op === 'add' || action.op === 'move').length
1299
1338
  const del = item.plan.idActions.filter((action) => action.op === 'delete').length
1300
1339
  lines.push(` [${item.target.key}] slots: ${slotSummary(item.plan)}; +${add}/-${del}; ${desiredCount} managed models; state after: ${postPlan.state}`)
1340
+ const lagIds = hostCatalogLagOf(item.plan)
1341
+ if (lagIds.length > 0) {
1342
+ lines.push(` host-catalog lag (未写入,宿主升级后自动纳入): ${lagIds.join(', ')}`)
1343
+ }
1301
1344
  lines.push(` backup: ${item.patchBackup.backup}`)
1302
1345
  lines.push(` rollback: /model-sync migrate rollback --plan ${item.plan.planHash}`)
1303
1346
  }
@@ -20,6 +20,7 @@ import { createHash } from 'node:crypto'
20
20
  import type { SettingsModelProfile } from './translate.ts'
21
21
  import type { GoModelRecord } from './opencode-go-source.ts'
22
22
  import { deriveKeyRef } from './route-credential.ts'
23
+ import { HOST_CATALOG_PROVIDER } from './opencode-go-host-catalog.ts'
23
24
  import {
24
25
  GO_SLOT_ROUTES,
25
26
  type GoRouteSlot,
@@ -152,6 +153,12 @@ export interface GoRouteState {
152
153
  models: readonly SettingsModelProfile[]
153
154
  /** Ids covered by a non-empty modelOverrides key on this route. */
154
155
  overrideIds?: readonly string[]
156
+ /**
157
+ * M1: section keys outside the plugin's known field set (headers, custom
158
+ * user fields, …). A legacy route carrying any of these holds user content
159
+ * the whole-route unset would destroy, so it is never "fully managed".
160
+ */
161
+ unknownKeys?: readonly string[]
155
162
  }
156
163
 
157
164
  // ---------------------------------------------------------------------------
@@ -213,6 +220,14 @@ export interface GoPlannerOptions {
213
220
  /** sha256(key) first 16 hex from the source result; '-' when no key. */
214
221
  keyFingerprint: string
215
222
  entries: readonly GoModelRecord[]
223
+ /**
224
+ * Host runtime catalog ids for opencode-go (0.12.1). `undefined` keeps the
225
+ * 0.12.0 behavior (every official entry is desired); an array intersects the
226
+ * desired set with it — ids the host catalog does not know are NOT written
227
+ * (they would make the host reject the whole mutate, fail-closed) and are
228
+ * reported as a single `needs-host-catalog` info line instead.
229
+ */
230
+ hostCatalogIds?: readonly string[]
216
231
  /** Current state of the go routes, keyed by route id. */
217
232
  currentRoutes: Readonly<Record<string, GoRouteState>>
218
233
  ownership: GoOwnershipLedger
@@ -302,8 +317,39 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
302
317
  const desiredByRoute: Record<string, SettingsModelProfile[]> = {}
303
318
 
304
319
  const entryById = new Map(options.entries.map((entry) => [entry.id, entry]))
305
- // Single-route desired set: every official entry, in stable id order.
306
- const desiredIds = [...entryById.keys()].sort((a, b) => a.localeCompare(b))
320
+ // 0.12.1 catalog-intersection: ids the host runtime catalog does not know
321
+ // are NEVER desired — the host validates every route model id against its
322
+ // in-memory pi-ai catalog and rejects the whole mutate on one unknown id
323
+ // (fail-closed; incident migrate-go 20261129-114103: beam-free). The full
324
+ // official entry set stays in `entryById` for mapping/reports; the filtered
325
+ // ids are surfaced as one `needs-host-catalog` info line.
326
+ //
327
+ // P1-1 scope: that validation exists ONLY for the route that reuses the
328
+ // builtin catalog — the one NAMED after the catalog provider id
329
+ // (`go.routes.chat === 'opencode-go'`, the default). A custom go.routes.chat
330
+ // name keeps its own api/baseURL (it does not reuse any catalog), so the
331
+ // host never validates its ids against the runtime catalog: the whole
332
+ // restriction (filter, lag report, kept-host-unknown warnings) is off for it.
333
+ const hostSet = options.hostCatalogIds === undefined || routes.chat !== HOST_CATALOG_PROVIDER
334
+ ? undefined
335
+ : new Set(options.hostCatalogIds)
336
+ const lagIds = hostSet === undefined
337
+ ? []
338
+ : options.entries.map((entry) => entry.id).filter((id) => !hostSet.has(id)).sort((a, b) => a.localeCompare(b))
339
+ if (lagIds.length > 0) {
340
+ report.push({
341
+ level: 'info',
342
+ code: 'needs-host-catalog',
343
+ route: routes.chat,
344
+ slot: 'chat',
345
+ message: `host catalog lag: ${lagIds.join(', ')} not written — 官方 listing 有、宿主内置目录没有(宿主侧滞后,非本插件问题);宿主升级后 sync 自动纳入`,
346
+ })
347
+ }
348
+ // Single-route desired set: every official entry the host catalog knows, in
349
+ // stable id order (0.12.0 behavior when no host catalog was supplied).
350
+ const desiredIds = [...entryById.keys()]
351
+ .filter((id) => hostSet === undefined || hostSet.has(id))
352
+ .sort((a, b) => a.localeCompare(b))
307
353
 
308
354
  // --- The single managed route (chat slot) --------------------------------
309
355
  const managedSlot: GoRouteSlot = 'chat'
@@ -313,6 +359,9 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
313
359
  const owned = options.ownership[ledgerKey]
314
360
  const fields = planGoRouteFields(options.entries, ref)
315
361
  desiredByRoute[managedRoute] = []
362
+ // H2: the main route's field conflict, hoisted so the legacy cleanup below
363
+ // can defer while the managed route is not writable.
364
+ let conflictOnMainRoute: GoRouteConflict | undefined
316
365
 
317
366
  if (desiredIds.length === 0) {
318
367
  const currentModels = current?.models ?? []
@@ -326,6 +375,7 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
326
375
  const conflict = detectConflict(managedSlot, managedRoute, fields, current)
327
376
  if (conflict !== undefined) {
328
377
  conflicts.push(conflict)
378
+ conflictOnMainRoute = conflict
329
379
  report.push({
330
380
  level: 'error',
331
381
  code: 'route-conflict',
@@ -343,9 +393,14 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
343
393
 
344
394
  // Catalog-reuse strip notice: a route still carrying the old 0.11.x
345
395
  // `api`/`baseURL` fields gets them unset this round (the writer emits
346
- // the ops; this line explains why in the report).
347
- if (current !== undefined && current.exists
348
- && GO_LEGACY_ROUTE_FIELDS.some((field) => current[field] !== undefined && current[field] !== '')) {
396
+ // the ops; this line explains why in the report). H3 scope: only the
397
+ // builtin catalog provider route may lose api/baseURL — catalog-reuse
398
+ // only exists for it. A custom go.routes.chat name (or a kept legacy
399
+ // custom route) NEEDS api/baseURL to be servable, so it is never
400
+ // stripped (empty-string fields are still garbage the host rejects and
401
+ // are stripped unconditionally by the writer).
402
+ if (managedRoute === HOST_CATALOG_PROVIDER && current !== undefined && current.exists
403
+ && GO_LEGACY_ROUTE_FIELDS.some((field) => current[field] !== undefined)) {
349
404
  report.push({
350
405
  level: 'info',
351
406
  code: 'legacy-fields-strip',
@@ -359,6 +414,22 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
359
414
  const managed = owned?.managed ?? {}
360
415
  const nextManaged: Record<string, GoManagedModel> = {}
361
416
  const kept: SettingsModelProfile[] = []
417
+ // H5: a KEPT id the host catalog does not know poisons every future
418
+ // mutate of this route (the host rejects the whole models array). The
419
+ // plan never removes user content on its own, so it warns instead — the
420
+ // actionable exits are a custom route (with api/baseURL) or the host
421
+ // upgrade.
422
+ const warnKeptHostUnknown = (id: string): void => {
423
+ if (hostSet === undefined || hostSet.has(id)) return
424
+ report.push({
425
+ level: 'warn',
426
+ code: 'kept-host-unknown',
427
+ route: managedRoute,
428
+ slot: managedSlot,
429
+ id,
430
+ message: `model ${id} kept but not in the host runtime catalog — 宿主可能拒绝本路由的全部写入;请迁移到带 api/baseURL 的自定义路由或等待宿主升级`,
431
+ })
432
+ }
362
433
 
363
434
  for (const model of currentModels) {
364
435
  const id = model.id
@@ -387,6 +458,7 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
387
458
  id,
388
459
  message: record !== undefined ? `model ${id} was modified; kept user value` : `model ${id} is user-owned; kept`,
389
460
  })
461
+ warnKeptHostUnknown(id)
390
462
  }
391
463
  continue
392
464
  }
@@ -406,6 +478,7 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
406
478
  ? 'kept-override'
407
479
  : 'kept-pinned'
408
480
  report.push({ level: 'info', code, route: managedRoute, slot: managedSlot, id, message: `model ${id} kept (${code}); not removed` })
481
+ warnKeptHostUnknown(id)
409
482
  }
410
483
 
411
484
  // New desired ids (absent from settings) are added and claimed.
@@ -434,7 +507,22 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
434
507
  // --- Legacy protocol routes: cleanup plan ---------------------------------
435
508
  // Only on a healthy payload: an anomalous empty listing must not trigger
436
509
  // route teardown on top of the upstream anomaly.
437
- if (desiredIds.length > 0) {
510
+ // H2: also NOT while the main route has a field conflict — the writer
511
+ // executes routes independently, and a failed/skipped main-route write must
512
+ // never be followed by legacy unsets (the host validates route REMOVAL
513
+ // against no catalog, so the unsets would succeed and the user's
514
+ // non-chat-protocol models would be gone with the main route unwritten).
515
+ const conflictDeferred = conflictOnMainRoute !== undefined && desiredIds.length > 0
516
+ if (conflictDeferred) {
517
+ report.push({
518
+ level: 'warn',
519
+ code: 'legacy-cleanup-deferred',
520
+ route: managedRoute,
521
+ slot: managedSlot,
522
+ message: `main route ${managedRoute} has a field conflict; legacy route cleanup is deferred to the round that fixes it (H2: never unset legacy routes while the managed route write is not healthy)`,
523
+ })
524
+ }
525
+ if (desiredIds.length > 0 && conflictOnMainRoute === undefined) {
438
526
  for (const slot of ['msg', 'resp', 'google'] as const) {
439
527
  const route = routes[slot]
440
528
  const routeCurrent = options.currentRoutes[route]
@@ -446,13 +534,25 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
446
534
  const currentModels = routeCurrent?.models ?? []
447
535
  const managed = legacyOwned?.managed ?? {}
448
536
  // Fully managed = the plugin owns every model present (an empty route
449
- // with a ledger entry counts: it was emptied by a previous round) and
450
- // the recorded ownership fields match this plan.
537
+ // with a ledger entry counts: it was emptied by a previous round), the
538
+ // recorded ownership fields match this plan, AND the section carries no
539
+ // user content the whole-route unset would destroy (M1): no
540
+ // modelOverrides, no pinned ids, no renamed-away apiKeyEnv, no unknown
541
+ // fields (headers, custom keys).
542
+ const overrideIds = routeCurrent?.overrideIds ?? []
543
+ const unknownKeys = routeCurrent?.unknownKeys ?? []
544
+ const liveApiKeyEnv = routeCurrent?.apiKeyEnv
545
+ const apiKeyEnvUserTouched = liveApiKeyEnv !== undefined
546
+ && liveApiKeyEnv !== '' && liveApiKeyEnv !== legacyFields.apiKeyEnv
451
547
  const fullyManaged = legacyOwned !== undefined
452
548
  && currentModels.every((model) => {
453
549
  const record = managed[model.id]
454
550
  return record !== undefined && record.hash === profileHash(model)
455
551
  })
552
+ && currentModels.every((model) => !pinned.has(model.id))
553
+ && overrideIds.length === 0
554
+ && unknownKeys.length === 0
555
+ && !apiKeyEnvUserTouched
456
556
  && ownedFieldsMatch(legacyOwned, legacyFields)
457
557
  if (fullyManaged) {
458
558
  plannedRoutes.push({ slot, route, fields: legacyFields, models: [], unset: true, skip: false })
@@ -461,8 +561,18 @@ export function planGoRoutes(options: GoPlannerOptions): GoPlanResult {
461
561
  delete nextOwnership[legacyLedgerKey]
462
562
  } else {
463
563
  plannedRoutes.push({ slot, route, fields: legacyFields, models: [...currentModels], unset: false, skip: true })
464
- if (currentModels.length > 0) {
465
- report.push({ level: 'warn', code: 'legacy-route-kept', route, slot, message: `legacy route ${route} holds user content; kept as-is (superseded by the single managed route)` })
564
+ const userContent: string[] = []
565
+ if (currentModels.length > 0) userContent.push(`${currentModels.length} model(s)`)
566
+ if (overrideIds.length > 0) userContent.push(`modelOverrides: ${overrideIds.join(', ')}`)
567
+ if (unknownKeys.length > 0) userContent.push(`custom fields: ${unknownKeys.join(', ')}`)
568
+ if (apiKeyEnvUserTouched) userContent.push(`apiKeyEnv: ${liveApiKeyEnv}`)
569
+ // P3: when pinned ids are the ONLY reason the route stays, say so —
570
+ // otherwise the keep looks unexplained (the fully-managed unset gates
571
+ // would have passed without them).
572
+ const pinnedKept = currentModels.filter((model) => pinned.has(model.id)).map((model) => model.id)
573
+ if (pinnedKept.length > 0) userContent.push(`pinned: ${pinnedKept.join(', ')}`)
574
+ if (userContent.length > 0) {
575
+ report.push({ level: 'warn', code: 'legacy-route-kept', route, slot, message: `legacy route ${route} holds user content (${userContent.join('; ')}); kept as-is (superseded by the single managed route)` })
466
576
  }
467
577
  }
468
578
  }
@@ -59,6 +59,16 @@ export interface GoRoundDeps {
59
59
  overrideStorer?: GoOverrideStorer
60
60
  logger: Logger
61
61
  config: GoSyncRuntimeConfig
62
+ /**
63
+ * Host runtime catalog ids for opencode-go (0.12.1). An ARRAY intersects the
64
+ * desired set with it (ids the host catalog does not know are reported as
65
+ * `needs-host-catalog`, never written). `null` FAILS THE ROUND CLOSED —
66
+ * zero writes — because writing the unverified full listing is exactly how
67
+ * 0.12.0 got the whole mutate rejected by the host. `undefined` (pure unit
68
+ * callers only; production always supplies one of the two) keeps the 0.12.0
69
+ * behavior.
70
+ */
71
+ hostCatalogIds?: readonly string[] | null
62
72
  /** Resolved credential VALUE; undefined/empty means no request and no write (V4). */
63
73
  apiKey?: string
64
74
  /** Injectable network; production falls back to the global fetch in the source. */
@@ -81,8 +91,9 @@ export interface GoRoundDeps {
81
91
  * `canWrite-unavailable` and skips the route (fail closed).
82
92
  */
83
93
  reloadMigration?: () => Promise<MigrationStatus>
84
- /** §14.7.4: forward the post-own-write managed ids to the record persister. */
85
- onOwnWrite?: (route: string, managedIds: string[]) => Promise<void>
94
+ /** §14.7.4: forward the post-own-write managed ids to the record persister.
95
+ * The third argument marks a whole-section unset (ledger key deleted). */
96
+ onOwnWrite?: (route: string, managedIds: string[], info?: { unset: boolean }) => Promise<void>
86
97
  /**
87
98
  * O1/C2: file-backed write-ahead journal store. With `profileKey` and
88
99
  * `keyFingerprint`, the round reconciles surviving journals BEFORE the
@@ -110,6 +121,9 @@ export type GoRoundReason =
110
121
  | 'aborted'
111
122
  | 'migration-gate'
112
123
  | 'settings-changed-during-sync'
124
+ // 0.12.1: the host runtime catalog could not be read — fail closed, zero
125
+ // writes (never write an unverified listing the host may reject wholesale).
126
+ | 'host-catalog-unavailable'
113
127
  // O1-minimal: one or more routes had failedRoutes (including the truthful
114
128
  // "settings written but not recorded" case). The command surface reports
115
129
  // kind:'error' for it, not a clean success.
@@ -154,6 +168,12 @@ function readRouteState(desc: SettingsDescriptor | undefined, route: string): Go
154
168
  const value = data[field]
155
169
  if (typeof value === 'string') state[field] = value
156
170
  }
171
+ // M1: keys outside the plugin's known field set are user content (headers,
172
+ // custom config) — a whole-route unset would destroy them, so the planner's
173
+ // fully-managed verdict never fires while any exist.
174
+ const knownFields = new Set(['api', 'baseURL', 'displayName', 'apiKeyEnv', 'models', 'modelOverrides'])
175
+ const unknownKeys = Object.keys(data).filter((key) => !knownFields.has(key))
176
+ if (unknownKeys.length > 0) state.unknownKeys = unknownKeys
157
177
  return state
158
178
  }
159
179
 
@@ -327,6 +347,22 @@ export async function runGoSyncRound(deps: GoRoundDeps): Promise<GoSyncRoundResu
327
347
  })
328
348
  }
329
349
 
350
+ // 0.12.1: fail-closed BEFORE the source fetch (zero side effects, same spirit
351
+ // as the migration gate short-circuit above). Without the host runtime
352
+ // catalog there is no servable write: the 0.12.0 full-listing write is what
353
+ // got rejected by the host in the first place.
354
+ if (deps.hostCatalogIds === null) {
355
+ return withJournal({
356
+ ok: false,
357
+ reason: 'host-catalog-unavailable',
358
+ text: [
359
+ 'opencode-go: host runtime catalog unavailable — 本轮 fail-closed 中止,零写入、零请求。',
360
+ ' 宿主 llm 服务的 discoverModels 未返回目录(服务缺失/未注册/无 opencode-go catalog)。',
361
+ ' 为避免再次写入宿主不认识的模型 id(宿主对整条 mutate fail-closed 拒绝),未做任何写入;目录可用后自动恢复。',
362
+ ].join('\n'),
363
+ })
364
+ }
365
+
330
366
  // B4 (31, design §14.7.5): snapshot the host settings document revision
331
367
  // BEFORE the network wait. This is only a baseline for the post-fetch
332
368
  // freshness check below — never a source for the write plan itself.
@@ -389,6 +425,7 @@ export async function runGoSyncRound(deps: GoRoundDeps): Promise<GoSyncRoundResu
389
425
  const plan = planGoRoutes({
390
426
  keyFingerprint: source.keyFingerprint,
391
427
  entries: source.entries,
428
+ hostCatalogIds: deps.hostCatalogIds,
392
429
  currentRoutes,
393
430
  ownership,
394
431
  ref: config.ref,
@@ -431,6 +468,7 @@ export async function runGoSyncRound(deps: GoRoundDeps): Promise<GoSyncRoundResu
431
468
  overrideStorer: deps.overrideStorer,
432
469
  logger,
433
470
  keyFingerprint: source.keyFingerprint,
471
+ hostCatalogIds: deps.hostCatalogIds,
434
472
  confirmRemovals: config.confirmRemovals,
435
473
  adoptExisting: config.adoptExisting,
436
474
  // B4/N1: the revision this round validated (post-fetch == pre-fetch).