@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
@@ -18,10 +18,15 @@
18
18
  // §14.5 (commands), §14.6 (order + single flight), §14.7 (write authority),
19
19
  // V16/V17/V19/V20/V22. No timer, no network, no real ~/.dsh lives here.
20
20
  import { createHash } from 'node:crypto';
21
- import { GO_SLOT_ROUTES, groupGoModelsByProtocol, } from "./opencode-go-grouping.js";
22
- import { goOwnershipKey, mapGoModelToProfile, planGoRouteFields, profileHash, } from "./opencode-go-planner.js";
23
- import { appliedFingerprintOf, fingerprintGoIdentity, fingerprintSection, readGoProviderSections, routeWriter, unclaimedRecordState, } from "./opencode-go-migration.js";
24
- const OWNED_FIELDS = ['api', 'baseURL', 'displayName', 'apiKeyEnv'];
21
+ import { GO_SLOT_ROUTES, } from "./opencode-go-grouping.js";
22
+ import { goOwnershipKey, mapGoModelToProfile, planGoRouteFields, profileHash, GO_LEGACY_ROUTE_FIELDS, } from "./opencode-go-planner.js";
23
+ import { HOST_CATALOG_PROVIDER } from "./opencode-go-host-catalog.js";
24
+ import { appliedFingerprintOf, fingerprintGoIdentity, fingerprintSection, migrationStateOf, readGoProviderSections, routeWriter, unclaimedRecordState, } from "./opencode-go-migration.js";
25
+ // 0.12.0 catalog-reuse: the only route field migrate writes is `apiKeyEnv`.
26
+ // `api`/`baseURL` are stripped (they make the host leave pi-ai's builtin
27
+ // catalog provider — and its x-opencode-session wrapping — behind), and
28
+ // `displayName` is never rewritten so a user rename survives the migration.
29
+ const OWNED_FIELDS = ['apiKeyEnv'];
25
30
  const PLAN_VERSION = 1;
26
31
  // ---------------------------------------------------------------------------
27
32
  // Pure helpers: canonical hash + confirmation code (V16 / V17)
@@ -108,6 +113,13 @@ export function verifyConsent(plan, planHash, confirmCode, ackManaged) {
108
113
  // ---------------------------------------------------------------------------
109
114
  // Pure plan builder (V16: zero writes / zero external calls)
110
115
  // ---------------------------------------------------------------------------
116
+ /** Raw models array of one section from a readGoProviderSections result. */
117
+ function routeModels(sections, route) {
118
+ const section = sections?.[route];
119
+ return isRecord(section) && Array.isArray(section.models)
120
+ ? section.models
121
+ : [];
122
+ }
111
123
  /** Per-route state, refined from the full-set state (§14.1). */
112
124
  function detectRouteStates(sections, record, routeIds, overall) {
113
125
  const identityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {});
@@ -166,54 +178,92 @@ function defaultReferences(targets, rewriteRefs) {
166
178
  }
167
179
  /** Build the full change plan. Pure: identical inputs → identical plan/hash. */
168
180
  export function buildMigrationPlan(input) {
181
+ // 0.12.1 fail-closed: without the host runtime catalog the desired write
182
+ // cannot be proven servable (the host rejects unknown ids wholesale), so no
183
+ // plan is built at all. The wiring and applyMigration refuse earlier with
184
+ // their own typed reasons; this is the last line of defence.
185
+ if (input.hostCatalogIds === null) {
186
+ throw new Error('host runtime catalog unavailable (host-catalog-unavailable): refusing to build a write plan (fail-closed)');
187
+ }
169
188
  const routes = { ...GO_SLOT_ROUTES, ...input.routes };
170
189
  const routeIds = Object.values(routes);
171
190
  const sections = readGoProviderSections(input.descriptor, routeIds);
172
191
  const prior = input.record;
173
- const state = migrationStateForPlan(sections, prior, routes.chat);
192
+ const state = migrationStateOf(sections, prior, routes.chat);
174
193
  const stateByRoute = detectRouteStates(sections, prior, routeIds, state);
175
194
  // Fail-closed capability gate (§14.2): when the executor cannot guarantee the
176
195
  // action table, adopt is reported as disabled and plan rows stay conservative.
177
196
  const adoptDisabled = input.adoptDisabled === true;
178
197
  const adopt = input.adopt === true && !adoptDisabled;
179
198
  const rewriteRefs = input.rewriteRefs ?? 'none';
180
- const grouping = groupGoModelsByProtocol(input.entries);
181
- const entryById = new Map(input.entries.map((entry) => [entry.id, entry]));
182
- const desiredBySlot = new Map();
183
- for (const slot of ['chat', 'msg', 'resp', 'google']) {
184
- desiredBySlot.set(slot, grouping.slots[slot]
185
- .map((id) => entryById.get(id))
186
- .filter((entry) => entry !== undefined)
187
- .map(mapGoModelToProfile)
188
- .sort((a, b) => a.id.localeCompare(b.id)));
189
- }
190
- const desiredIds = new Set([...desiredBySlot.values()].flat().map((profile) => profile.id));
191
- // The two ids that move out of chat into dedicated protocol routes (§14.4).
192
- const targets = grouping.slots.msg.concat(grouping.slots.resp);
193
- const references = input.references ?? defaultReferences(targets, rewriteRefs);
194
- // Routes actually in scope for this plan (a conditional, empty google slot
195
- // with no pre-existing section is skipped — §9.4).
196
- const scopedRoutes = [];
197
- for (const slot of ['chat', 'msg', 'resp', 'google']) {
198
- if (slot === 'google' && desiredBySlot.get(slot).length === 0 && sections?.[routes[slot]] === undefined)
199
+ // 0.12.0 desired collapse: EVERY official entry targets the single managed
200
+ // route (routes.chat). The three legacy protocol routes act only as move
201
+ // sources (adopt) / keep sources (conservative) for ids still sitting there.
202
+ const targetRoute = routes.chat;
203
+ const targetSlot = 'chat';
204
+ const fields = planGoRouteFields(input.entries, input.ref);
205
+ // 0.12.1 catalog-intersection: ids the host runtime catalog does not know
206
+ // are NOT desired — the host would reject the whole mutate. Lag ids keep
207
+ // their official record (publicCatalogIds) for reporting, and leftovers on
208
+ // routes get their own `host-catalog-lag` treatment below.
209
+ //
210
+ // P1-1 scope: the host validates ids against its runtime catalog ONLY for
211
+ // the route reusing the builtin catalog — the one NAMED after the catalog
212
+ // provider id (`go.routes.chat === 'opencode-go'`, the default). A custom
213
+ // chat route name keeps its own api/baseURL (no catalog reuse), so the
214
+ // intersection filter and the whole host-catalog-lag classification are off
215
+ // for it: every official entry is desired and nothing is filtered.
216
+ const catalogReuseTarget = targetRoute === HOST_CATALOG_PROVIDER;
217
+ const hostSet = input.hostCatalogIds === undefined || !catalogReuseTarget
218
+ ? undefined
219
+ : new Set(input.hostCatalogIds);
220
+ const hostCatalogAvailable = hostSet !== undefined;
221
+ const hostCatalogLagIds = hostSet === undefined
222
+ ? []
223
+ : input.entries.map((entry) => entry.id).filter((id) => !hostSet.has(id)).sort((a, b) => a.localeCompare(b));
224
+ const lagEntryById = new Map(hostSet === undefined ? [] : input.entries.filter((entry) => !hostSet.has(entry.id)).map((entry) => [entry.id, entry]));
225
+ const desired = input.entries
226
+ .filter((entry) => hostSet === undefined || hostSet.has(entry.id))
227
+ .map(mapGoModelToProfile)
228
+ .sort((a, b) => a.id.localeCompare(b.id));
229
+ const desiredIds = new Set(desired.map((profile) => profile.id));
230
+ // Per-route modelOverrides keys (M1-analog): a lag leftover under an
231
+ // override is USER content — never auto-removed.
232
+ const overrideIdsByRoute = new Map();
233
+ for (const [route, section] of Object.entries(sections ?? {})) {
234
+ if (section === null || typeof section !== 'object')
199
235
  continue;
200
- const route = routes[slot];
201
- const section = sections?.[route];
202
- const routeState = stateByRoute[route] ?? 'absent';
203
- const fields = planGoRouteFields(slot, input.entries.filter((entry) => grouping.slots[slot].includes(entry.id)), input.ref);
204
- const desired = desiredBySlot.get(slot) ?? [];
205
- const currentModels = isRecord(section) && Array.isArray(section.models)
206
- ? section.models
207
- : [];
208
- scopedRoutes.push({ slot, route, state: routeState, fields, desired, currentModels });
236
+ const overrides = section.modelOverrides;
237
+ if (overrides === null || typeof overrides !== 'object' || Array.isArray(overrides))
238
+ continue;
239
+ overrideIdsByRoute.set(route, new Set(Object.keys(overrides)));
209
240
  }
210
- // desired id → its official target route + exact profile.
211
- const desiredTarget = new Map();
212
- for (const scope of scopedRoutes) {
213
- for (const profile of scope.desired) {
214
- desiredTarget.set(profile.id, { slot: scope.slot, route: scope.route, profile });
215
- }
241
+ // Routes actually in scope for this plan: the managed route always; a legacy
242
+ // slot route only when its section exists (a never-created route has nothing
243
+ // to migrate).
244
+ const scopedRoutes = [{
245
+ slot: targetSlot,
246
+ route: targetRoute,
247
+ state: stateByRoute[targetRoute] ?? 'absent',
248
+ fields,
249
+ desired,
250
+ currentModels: routeModels(sections, targetRoute),
251
+ }];
252
+ for (const slot of ['msg', 'resp', 'google']) {
253
+ const route = routes[slot];
254
+ if (sections?.[route] === undefined)
255
+ continue;
256
+ scopedRoutes.push({
257
+ slot,
258
+ route,
259
+ state: stateByRoute[route] ?? 'absent',
260
+ fields,
261
+ desired: [],
262
+ currentModels: routeModels(sections, route),
263
+ });
216
264
  }
265
+ // desired id → its official target (always the single managed route).
266
+ const desiredTarget = new Map(desired.map((profile) => [profile.id, { slot: targetSlot, route: targetRoute, profile }]));
217
267
  // Every id currently in settings, with all the routes it occupies.
218
268
  const currentLocations = new Map();
219
269
  for (const scope of scopedRoutes) {
@@ -223,6 +273,12 @@ export function buildMigrationPlan(input) {
223
273
  currentLocations.set(profile.id, list);
224
274
  }
225
275
  }
276
+ // Ids whose references change under this plan: desired ids still sitting on
277
+ // a legacy protocol route (they end up on the managed route after apply).
278
+ const targets = desired
279
+ .filter((profile) => (currentLocations.get(profile.id) ?? []).some((loc) => loc.route !== targetRoute))
280
+ .map((profile) => profile.id);
281
+ const references = input.references ?? defaultReferences(targets, rewriteRefs);
226
282
  const pinnedIds = new Set(input.pinnedModels ?? []);
227
283
  // `undefined` is materially different from an empty list: empty means the
228
284
  // catalog was fetched and truly has no such id (→ user-extra); undefined means
@@ -231,9 +287,11 @@ export function buildMigrationPlan(input) {
231
287
  const publicIds = new Set(input.publicCatalogIds ?? []);
232
288
  const pruneUserExtra = input.pruneUserExtra === true;
233
289
  const kindOf = (id) => {
234
- const target = desiredTarget.get(id);
235
- if (target !== undefined)
236
- return `desired-${target.slot}`;
290
+ if (desiredTarget.has(id))
291
+ return 'desired';
292
+ // 0.12.1: an official id the host runtime catalog does not know.
293
+ if (lagEntryById.has(id))
294
+ return 'host-catalog-lag';
237
295
  // Fail-closed (§14.2): no public catalog → never guess "user-written".
238
296
  if (!publicCatalogAvailable)
239
297
  return 'unclassified';
@@ -324,11 +382,43 @@ export function buildMigrationPlan(input) {
324
382
  }
325
383
  continue;
326
384
  }
327
- // Non-desired id: user-extra / unknown-retired / unclassified. Default keep.
328
- // Delete only when the classification's own flag is set AND the row is in
329
- // this plan. `unclassified` (no public catalog) is never deletable.
385
+ // Non-desired id: user-extra / unknown-retired / unclassified / host-catalog-lag.
386
+ // Default keep. Delete only when the classification's own flag is set AND
387
+ // the row is in this plan. `unclassified` (no public catalog) is never
388
+ // deletable. `host-catalog-lag` (0.12.1): a PLUGIN-WRITTEN leftover the
389
+ // host catalog does not know is removed from the CATALOG-REUSE route —
390
+ // keeping it there would make the host reject every mutate of the route
391
+ // (and the id auto-returns after the host upgrades). P1-1 scope: only the
392
+ // builtin catalog route is validated against the runtime catalog, so the
393
+ // immediate removal fires only on it; a preserved legacy/custom route
394
+ // carries its own api/baseURL and keeps such ids as ordinary content.
330
395
  const mayDelete = kind === 'user-extra' ? pruneUserExtra : kind === 'unknown-retired' ? adopt : false;
331
396
  for (const loc of locations) {
397
+ if (kind === 'host-catalog-lag') {
398
+ const lagEntry = lagEntryById.get(id);
399
+ const officialProfile = lagEntry !== undefined ? mapGoModelToProfile(lagEntry) : undefined;
400
+ const pluginWritten = (prior?.appliedManagedIds?.[loc.route] ?? []).includes(id);
401
+ const hashMatches = officialProfile !== undefined && profileHash(loc.profile) === profileHash(officialProfile);
402
+ const overridden = (overrideIdsByRoute.get(loc.route) ?? new Set()).has(id);
403
+ const catalogReuseLocation = loc.route === targetRoute;
404
+ if (catalogReuseLocation && pluginWritten && hashMatches && !overridden) {
405
+ idActions.push({
406
+ id, op: 'delete', route: loc.route, kind, pinned: false, profile: loc.profile,
407
+ 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)',
408
+ });
409
+ }
410
+ else {
411
+ idActions.push({
412
+ id, op: 'keep', route: loc.route, kind, pinned: false, profile: loc.profile,
413
+ reason: !catalogReuseLocation
414
+ ? `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`
415
+ : pluginWritten && !hashMatches
416
+ ? 'host-catalog-lag: user-modified value kept as-is — 宿主目录不认识该 id,宿主可能拒绝本路由写入;请迁移到自定义路由或等待宿主升级'
417
+ : 'host-catalog-lag: user-owned/overridden value kept as-is — 宿主目录不认识该 id,宿主可能拒绝本路由写入;请迁移到自定义路由或等待宿主升级',
418
+ });
419
+ }
420
+ continue;
421
+ }
332
422
  if (mayDelete) {
333
423
  idActions.push({ id, op: 'delete', route: loc.route, kind, pinned: false, profile: loc.profile,
334
424
  reason: kind === 'user-extra'
@@ -360,7 +450,7 @@ export function buildMigrationPlan(input) {
360
450
  willDelete: true,
361
451
  reason: action.reason,
362
452
  }));
363
- const plannedRoutes = scopedRoutes.map((scope) => {
453
+ const plannedRoutesDraft = scopedRoutes.map((scope) => {
364
454
  const seen = new Set();
365
455
  const existing = [];
366
456
  for (const profile of scope.currentModels) {
@@ -387,18 +477,36 @@ export function buildMigrationPlan(input) {
387
477
  action = 'update';
388
478
  return { slot: scope.slot, route: scope.route, state: scope.state, action, fields: scope.fields, desired: scope.desired, existing };
389
479
  });
480
+ // ONE plan-time simulation — the SAME function apply executes — decides both
481
+ // the informed-consent id set and which legacy routes end up emptied. A
482
+ // legacy protocol route whose post-apply models map is empty carries no
483
+ // user content anymore: apply will whole-section unset it (never a
484
+ // `models: []` write) and delete its ledger key.
485
+ const simulation = buildRouteWriteStates({ routes: plannedRoutesDraft, idActions }, input.descriptor);
486
+ const managedByRoute = {};
487
+ for (const [route, state] of simulation.byRoute) {
488
+ managedByRoute[route] = Object.keys(state.managed).sort((a, b) => a.localeCompare(b));
489
+ }
490
+ const plannedRoutes = plannedRoutesDraft.map((planned) => {
491
+ if (planned.slot === 'chat' || planned.state === 'absent')
492
+ return planned;
493
+ const postModels = simulation.byRoute.get(planned.route)?.models;
494
+ if (postModels !== undefined && postModels.size === 0) {
495
+ return { ...planned, action: 'unset' };
496
+ }
497
+ return planned;
498
+ });
390
499
  const pinnedSuggestions = new Set();
391
- const reversibleTargets = targets.filter((id) => !grouping.slots.chat.includes(id));
392
- for (const id of reversibleTargets)
500
+ // Reversible targets: desired ids still sitting on a legacy protocol route.
501
+ for (const id of targets)
393
502
  pinnedSuggestions.add(id);
394
503
  for (const id of pinnedIds)
395
504
  pinnedSuggestions.add(id);
396
505
  // B6 informed-consent text — part of the hashed body: any edit to this notice
397
506
  // changes planHash and invalidates the old confirmCode/ack. The id list comes
398
- // from `managedIdsAfterApply`, the SAME simulation apply uses for the ledger,
399
- // so a user-modified `update` row or a move onto a different-valued target is
400
- // never advertised as managed.
401
- const managedByRoute = managedIdsAfterApply({ routes: plannedRoutes, idActions }, input.descriptor);
507
+ // from the single `buildRouteWriteStates` simulation above — the SAME engine
508
+ // apply uses for the ledger — so a user-modified `update` row or a move onto
509
+ // a different-valued target is never advertised as managed.
402
510
  // N2: no row may claim management on paper if the simulation shows apply
403
511
  // will not actually write/adopt that id. Normalise the per-id `managed`
404
512
  // flags to the simulated set so even the printed `[managed]` marker cannot
@@ -431,6 +539,8 @@ export function buildMigrationPlan(input) {
431
539
  idActions,
432
540
  managedAfterMigration,
433
541
  publicCatalogAvailable,
542
+ hostCatalogAvailable,
543
+ hostCatalogLagIds,
434
544
  adoptDisabled,
435
545
  references,
436
546
  pinnedSuggestions: [...pinnedSuggestions].sort(),
@@ -446,36 +556,23 @@ export function buildMigrationPlan(input) {
446
556
  }
447
557
  function describeId(kind, adopt) {
448
558
  switch (kind) {
449
- case 'desired-chat': return 'official chat-completions target';
450
- case 'desired-msg': return 'official messages target (dedicated -msg route)';
451
- case 'desired-resp': return 'official responses target (dedicated -resp route)';
452
- case 'desired-google': return 'official google target';
559
+ case 'desired': return 'official desired id (single managed route)';
453
560
  case 'legacy-other-protocol': return adopt ? 'legacy id on the wrong protocol route' : 'legacy id kept in conservative mode';
454
561
  case 'unknown-retired': return adopt ? 'unknown/retired id, delete only if confirmed in plan' : 'unknown/retired id kept as user-owned';
455
562
  case 'user-extra': return 'user-written id, never auto-deleted';
456
563
  case 'unclassified': return 'public catalog unavailable (unclassified): never deleted';
564
+ case 'host-catalog-lag': return 'official id the host runtime catalog does not know (host-side lag; not written)';
457
565
  }
458
566
  }
459
- /** Local state detection mirroring `migrationStateOf` (kept here to stay import-light). */
460
- function migrationStateForPlan(sections, record, chatRoute) {
461
- if (sections === undefined || Object.keys(sections).length === 0)
462
- return 'absent';
463
- const fingerprint = fingerprintSection(sections);
464
- if (record?.appliedIdentity !== undefined) {
465
- return fingerprintGoIdentity(sections, record.appliedIdentityRoutes) === record.appliedIdentity ? 'applied' : 'drifted';
466
- }
467
- if (record?.appliedFingerprint !== undefined && fingerprint === record.appliedFingerprint)
468
- return 'applied';
469
- if (record !== undefined && (record.appliedFingerprint !== undefined || record.legacyFingerprint !== undefined)) {
470
- if (record.legacyFingerprint !== undefined && fingerprint === record.legacyFingerprint) {
471
- const chat = sections[chatRoute];
472
- return isRecord(chat) && Array.isArray(chat.models) ? 'legacy-inline' : 'legacy-inherit';
473
- }
474
- return 'drifted';
475
- }
476
- const chat = sections[chatRoute];
477
- return isRecord(chat) && Array.isArray(chat.models) ? 'legacy-inline' : 'legacy-inherit';
478
- }
567
+ // agy final P2-②: the old local mirror `migrationStateForPlan` (a hand-rolled
568
+ // copy of `migrationStateOf` "kept to stay import-light" — moot, this module
569
+ // already imports from opencode-go-migration.ts) MISSED the empty
570
+ // `appliedIdentityRoutes` guard, so a degenerate historical record
571
+ // (`{appliedIdentity: sha256('{}'), appliedIdentityRoutes: []}`) read as
572
+ // `applied` in plan/status: `migrate status` claimed writeAuthority=go and
573
+ // apply refused with nothing-to-apply, blocking the very migrate that would
574
+ // repair it. Deleted — there is now exactly ONE state detector, the guarded
575
+ // `migrationStateOf`.
479
576
  // ---------------------------------------------------------------------------
480
577
  // Human-readable reports (V16 / V19)
481
578
  // ---------------------------------------------------------------------------
@@ -493,13 +590,18 @@ export function formatMigrationPlan(plan) {
493
590
  ` mode: ${mode} rewrite-refs: ${plan.rewriteRefs}`,
494
591
  ` sections fingerprint: ${plan.preFingerprint.slice(0, 16)}…`,
495
592
  ` public catalog: ${plan.publicCatalogAvailable ? 'available (ids classified)' : 'UNAVAILABLE — unclassified ids are never deleted (fail-closed)'}`,
593
+ ...(plan.hostCatalogAvailable
594
+ ? plan.hostCatalogLagIds.length > 0
595
+ ? [` host catalog: 官方有、宿主内置目录没有(未写入,宿主升级后自动纳入): ${plan.hostCatalogLagIds.join(', ')}`]
596
+ : [' host catalog: available (official listing fully covered)']
597
+ : [' host catalog: UNAVAILABLE — 宿主运行时目录未提供,desired 未做交集(0.12.0 行为;生产写路径已 fail-closed 拒绝)']),
496
598
  '',
497
599
  'Routes:',
498
600
  ];
499
601
  for (const route of plan.routes) {
500
602
  const fields = route.fields;
501
603
  lines.push(` ${route.route} [${route.slot}/${route.state}] ${route.action.toUpperCase()}`);
502
- lines.push(` api=${fields.api} baseURL=${fields.baseURL} displayName=${fields.displayName} apiKeyEnv=${fields.apiKeyEnv}`);
604
+ lines.push(` displayName=${fields.displayName} apiKeyEnv=${fields.apiKeyEnv}${route.action === 'unset' ? ' (whole-route unset; fields not written)' : ''}`);
503
605
  lines.push(` desired (${route.desired.length}): ${route.desired.map((profile) => profile.id).join(', ') || '(none)'}`);
504
606
  if (route.existing.length > 0) {
505
607
  lines.push(` existing: ${route.existing.map((entry) => `${entry.id}=${entry.kind}/${entry.action}`).join(', ')}`);
@@ -577,6 +679,7 @@ export function buildMigrationPlanFromDeps(deps, record) {
577
679
  pinnedModels: deps.pinnedModels,
578
680
  pruneUserExtra: deps.pruneUserExtra,
579
681
  publicCatalogIds: deps.publicCatalogIds,
682
+ hostCatalogIds: deps.hostCatalogIds,
580
683
  adoptDisabled: deps.adoptDisabled,
581
684
  now: deps.now,
582
685
  });
@@ -589,6 +692,20 @@ async function readRecord(deps) {
589
692
  return undefined;
590
693
  }
591
694
  }
695
+ /**
696
+ * P2-③: the WRITE path's record read. A store that offers `readStrict` gets
697
+ * its errors surfaced (H4: write paths must see store errors, never "no prior
698
+ * record"); legacy stores without the method keep the old swallowing `read`.
699
+ * applyMigration maps a surfaced error to a `write-failed` refusal — the
700
+ * consent gate would most likely catch the diverging planHash anyway, but
701
+ * refusing on the real cause is truthful and cheaper to diagnose.
702
+ */
703
+ async function readRecordForApply(deps) {
704
+ const store = deps.migrationStore;
705
+ if (typeof store.readStrict !== 'function')
706
+ return readRecord(deps);
707
+ return await store.readStrict();
708
+ }
592
709
  function llmDescriptor(settings) {
593
710
  return settings?.describe().find((desc) => desc.ns === 'llm-pi-ai');
594
711
  }
@@ -615,12 +732,36 @@ function errorText(err) {
615
732
  return typeof message === 'string' ? message : String(err);
616
733
  }
617
734
  /** Set ops that write exactly the target fields + models for one route. */
618
- function routeOps(desc, route, fields, models) {
735
+ function routeOps(desc, route, fields, models, mode = 'managed') {
619
736
  const data = rawRoute(desc, route);
620
737
  const ops = [];
621
- for (const field of OWNED_FIELDS) {
622
- if (data?.[field] !== fields[field]) {
623
- ops.push({ op: 'set', path: ['providers', route, field], value: fields[field] });
738
+ if (mode === 'managed') {
739
+ // H3 scope: field ownership (apiKeyEnv) applies ONLY in managed mode —
740
+ // the single managed route. A KEPT legacy route is a handwritten custom
741
+ // route that NEEDS api/baseURL (and its own displayName/apiKeyEnv) to be
742
+ // servable: stripping or rewriting fields would break it, so preserve
743
+ // mode touches models only.
744
+ for (const field of OWNED_FIELDS) {
745
+ if (data?.[field] !== fields[field]) {
746
+ ops.push({ op: 'set', path: ['providers', route, field], value: fields[field] });
747
+ }
748
+ }
749
+ }
750
+ // Catalog-reuse: strip legacy `api`/`baseURL` so the host reuses pi-ai's
751
+ // builtin catalog provider for this route. Only the BUILTIN catalog
752
+ // provider id ('opencode-go') reuses the catalog — a custom chat route
753
+ // name keeps its api/baseURL. agy final P2-② #3: the non-empty strip is
754
+ // MANAGED-mode only (preserve touches models verbatim, H3 — a preserved
755
+ // route needs its own api/baseURL to stay servable). P2-①: empty-string
756
+ // values are broken in BOTH modes (the host rejects `api: ""` outright,
757
+ // whatever the route), so the empty-string unset stays OUTSIDE this gate.
758
+ const stripCatalogReuse = mode === 'managed' && route === HOST_CATALOG_PROVIDER;
759
+ for (const field of GO_LEGACY_ROUTE_FIELDS) {
760
+ const value = data?.[field];
761
+ if (value === undefined)
762
+ continue;
763
+ if (value === '' || stripCatalogReuse) {
764
+ ops.push({ op: 'unset', path: ['providers', route, field] });
624
765
  }
625
766
  }
626
767
  const sorted = [...models].sort((a, b) => a.id.localeCompare(b.id));
@@ -778,7 +919,20 @@ function applyFailure(reason, planHash, confirmCode, detail, writesReverted = fa
778
919
  return { ok: false, reason, planHash, confirmCode, routes: [], actions: [], text: `migrate apply refused (${reason}): ${detail}; ${outcome}` };
779
920
  }
780
921
  export async function applyMigration(args, deps) {
781
- const prior = await readRecord(deps);
922
+ // 0.12.1 fail-closed: without the host runtime catalog the desired listing
923
+ // cannot be proven servable — refusing here means zero plan builds, zero
924
+ // writes. Never fail open onto the full official listing (incident
925
+ // migrate-go 20261129-114103: the host rejected exactly such a write).
926
+ if (deps.hostCatalogIds === null) {
927
+ return applyFailure('host-catalog-unavailable', '', '', 'host runtime catalog unavailable; refusing to write (fail-closed)');
928
+ }
929
+ let prior;
930
+ try {
931
+ prior = await readRecordForApply(deps);
932
+ }
933
+ catch (err) {
934
+ return applyFailure('write-failed', '', '', `migration record unreadable (strict): ${errorText(err)}`);
935
+ }
782
936
  const plan = buildMigrationPlanFromDeps(deps, prior);
783
937
  // 1. Consent — every rejection below is ZERO writes. `--ack-managed` is a
784
938
  // mandatory third token (B6); no bypass flag exists.
@@ -825,6 +979,44 @@ export async function applyMigration(args, deps) {
825
979
  // default throws on an unknown op — doing it here guarantees such a throw
826
980
  // cannot leave a persisted `applying` flag with no restore snapshot.
827
981
  const { byRoute, results: actionResults } = buildRouteWriteStates({ routes: plan.routes, idActions: actionsToRun }, desc);
982
+ // 0.12.1 H5 (fail-closed): the route reusing the builtin catalog must not
983
+ // carry post-apply ids the host runtime catalog does not know — the host
984
+ // rejects that mutate wholesale, so refuse the whole apply now, zero
985
+ // writes, instead of a raw host rejection mid-loop. Kept lag ids
986
+ // (user-owned/modified/override/pinned) are the only way to land here; the
987
+ // plan's delete rows already removed the plugin-written ones.
988
+ //
989
+ // P1-1 scope: ONLY the catalog-reuse route is checked (the chat slot route
990
+ // named after the builtin provider id — managed mode strips its
991
+ // api/baseURL, so it is catalog-reuse post-apply even when it currently
992
+ // carries legacy fields). Preserved legacy/custom routes keep their own
993
+ // api/baseURL and are never validated against the runtime catalog, so
994
+ // unknown ids there are NOT a rejection risk — refusing them was the
995
+ // self-contradictory over-reach (the message told users to move ids to a
996
+ // custom route while blocking a route that IS one). A route whose ops are
997
+ // empty writes nothing this apply, so it cannot trip the host either.
998
+ if (deps.hostCatalogIds !== undefined) {
999
+ const hostSet = new Set(deps.hostCatalogIds);
1000
+ const blocked = [];
1001
+ for (const planned of plan.routes) {
1002
+ if (planned.action === 'unset')
1003
+ continue;
1004
+ if (!(planned.slot === 'chat' && planned.route === HOST_CATALOG_PROVIDER))
1005
+ continue;
1006
+ const state = byRoute.get(planned.route);
1007
+ if (state === undefined)
1008
+ continue;
1009
+ const ops = routeOps(desc, planned.route, planned.fields, [...state.models.values()], 'managed');
1010
+ if (ops.length === 0)
1011
+ continue;
1012
+ const unknown = [...state.models.keys()].filter((id) => !hostSet.has(id));
1013
+ if (unknown.length > 0)
1014
+ blocked.push(`${planned.route}: ${unknown.join(', ')}`);
1015
+ }
1016
+ if (blocked.length > 0) {
1017
+ return applyFailure('host-catalog-unknown-models', plan.planHash, plan.confirmCode, `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`);
1018
+ }
1019
+ }
828
1020
  // 3. Capture the audit backup and persist `applying` BEFORE the first mutate.
829
1021
  // If we crash mid-apply, the record still carries the restore snapshot.
830
1022
  const backup = captureBackup(plan, desc, deps.now);
@@ -866,9 +1058,46 @@ export async function applyMigration(args, deps) {
866
1058
  continue;
867
1059
  }
868
1060
  const current = rawModels(desc, planned.route);
1061
+ // Emptied legacy protocol route (plan action `unset`): whole-section
1062
+ // unset + ledger key delete. Never a `models: []` write (§9.4), and no
1063
+ // ledger entry survives it (no managedByRoute entry → appliedManagedIds
1064
+ // mirrors only routes that still have a ledger, N3).
1065
+ if (planned.action === 'unset') {
1066
+ const section = rawRoute(desc, planned.route);
1067
+ if (section !== undefined) {
1068
+ try {
1069
+ await mutateWithRetry(deps, [{ op: 'unset', path: ['providers', planned.route] }]);
1070
+ writtenRoutes.push(planned.route);
1071
+ }
1072
+ catch (err) {
1073
+ failure = `${planned.route}: settings mutate failed (${errorText(err)})`;
1074
+ routesResult.push({ route: planned.route, status: 'failed', reason: errorText(err) });
1075
+ break;
1076
+ }
1077
+ }
1078
+ const legacyKey = goOwnershipKey(planned.route, deps.keyFingerprint);
1079
+ try {
1080
+ await deps.ownershipStore.delete(legacyKey);
1081
+ }
1082
+ catch (err) {
1083
+ failure = `${planned.route}: ledger delete failed (${errorText(err)})`;
1084
+ routesResult.push({ route: planned.route, status: 'failed', reason: errorText(err) });
1085
+ break;
1086
+ }
1087
+ routesResult.push({
1088
+ route: planned.route,
1089
+ status: section !== undefined ? 'wrote' : 'skipped',
1090
+ ...(section !== undefined ? {} : { reason: 'legacy route superseded; section already absent (no settings write)' }),
1091
+ });
1092
+ continue;
1093
+ }
869
1094
  // Write only ops that actually change fields/models. keep/update/delete-no
870
1095
  // rows leave the section byte-identical, so no mutate happens for them.
871
- const ops = routeOps(desc, planned.route, planned.fields, [...state.models.values()]);
1096
+ // H3: managed field-ownership semantics apply to the single managed
1097
+ // (chat-slot) route only. A kept legacy protocol route is a handwritten
1098
+ // custom route — preserve its api/baseURL/displayName/apiKeyEnv verbatim
1099
+ // and touch its models only.
1100
+ const ops = routeOps(desc, planned.route, planned.fields, [...state.models.values()], planned.slot === 'chat' ? 'managed' : 'preserve');
872
1101
  let wroteThisRoute = false;
873
1102
  if (ops.length > 0) {
874
1103
  try {
@@ -1218,7 +1447,7 @@ export async function migrationStatusReport(deps, config) {
1218
1447
  const record = await readRecord(deps);
1219
1448
  const routeIds = Object.values({ ...GO_SLOT_ROUTES, ...deps.routes });
1220
1449
  const sections = readGoProviderSections(details, routeIds);
1221
- const sectionState = migrationStateForPlan(sections, record, routeIds[0]);
1450
+ const sectionState = migrationStateOf(sections, record, routeIds[0]);
1222
1451
  // D6: the store hides unreadable records from read() (B1). Ask it separately
1223
1452
  // for provenance so status can name the two unclaimable cases WITHOUT
1224
1453
  // changing the gate: both keep write authority `none`, claim nothing, and