@aiwayds/dsh-model-sync 0.12.1 → 0.13.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 (88) hide show
  1. package/README.md +18 -17
  2. package/README.zh-CN.md +18 -17
  3. package/lib/index.d.ts +54 -384
  4. package/lib/index.js +306 -1107
  5. package/lib/index.js.map +1 -1
  6. package/lib/official-adapter.d.ts +80 -0
  7. package/lib/official-adapter.js +34 -0
  8. package/lib/official-adapter.js.map +1 -0
  9. package/lib/official-migrate.d.ts +122 -0
  10. package/lib/official-migrate.js +653 -0
  11. package/lib/official-migrate.js.map +1 -0
  12. package/lib/official-scheduler.d.ts +72 -0
  13. package/lib/official-scheduler.js +195 -0
  14. package/lib/official-scheduler.js.map +1 -0
  15. package/lib/official-store.d.ts +41 -0
  16. package/lib/official-store.js +84 -0
  17. package/lib/official-store.js.map +1 -0
  18. package/lib/official-sync.d.ts +68 -0
  19. package/lib/official-sync.js +274 -0
  20. package/lib/official-sync.js.map +1 -0
  21. package/lib/opencode-go-adapter.d.ts +56 -0
  22. package/lib/opencode-go-adapter.js +455 -0
  23. package/lib/opencode-go-adapter.js.map +1 -0
  24. package/lib/opencode-go-patch-file.d.ts +11 -0
  25. package/lib/opencode-go-patch-file.js +175 -11
  26. package/lib/opencode-go-patch-file.js.map +1 -1
  27. package/lib/opencode-go-source.d.ts +1 -1
  28. package/lib/opencode-go-source.js +1 -1
  29. package/locale/en.json +1 -1
  30. package/locale/zh.json +1 -1
  31. package/package.json +3 -3
  32. package/src/index.ts +352 -1281
  33. package/src/official-adapter.ts +111 -0
  34. package/src/official-migrate.ts +863 -0
  35. package/src/official-scheduler.ts +235 -0
  36. package/src/official-store.ts +122 -0
  37. package/src/official-sync.ts +371 -0
  38. package/src/opencode-go-adapter.ts +494 -0
  39. package/src/opencode-go-patch-file.ts +175 -9
  40. package/src/opencode-go-source.ts +1 -1
  41. package/lib/opencode-go-diagnose.d.ts +0 -96
  42. package/lib/opencode-go-diagnose.js +0 -177
  43. package/lib/opencode-go-diagnose.js.map +0 -1
  44. package/lib/opencode-go-grouping.d.ts +0 -7
  45. package/lib/opencode-go-grouping.js +0 -21
  46. package/lib/opencode-go-grouping.js.map +0 -1
  47. package/lib/opencode-go-host-catalog.d.ts +0 -42
  48. package/lib/opencode-go-host-catalog.js +0 -98
  49. package/lib/opencode-go-host-catalog.js.map +0 -1
  50. package/lib/opencode-go-journal.d.ts +0 -114
  51. package/lib/opencode-go-journal.js +0 -406
  52. package/lib/opencode-go-journal.js.map +0 -1
  53. package/lib/opencode-go-migrate.d.ts +0 -378
  54. package/lib/opencode-go-migrate.js +0 -1529
  55. package/lib/opencode-go-migrate.js.map +0 -1
  56. package/lib/opencode-go-migration.d.ts +0 -270
  57. package/lib/opencode-go-migration.js +0 -473
  58. package/lib/opencode-go-migration.js.map +0 -1
  59. package/lib/opencode-go-one-shot.d.ts +0 -282
  60. package/lib/opencode-go-one-shot.js +0 -1131
  61. package/lib/opencode-go-one-shot.js.map +0 -1
  62. package/lib/opencode-go-planner.d.ts +0 -168
  63. package/lib/opencode-go-planner.js +0 -407
  64. package/lib/opencode-go-planner.js.map +0 -1
  65. package/lib/opencode-go-scheduler.d.ts +0 -128
  66. package/lib/opencode-go-scheduler.js +0 -241
  67. package/lib/opencode-go-scheduler.js.map +0 -1
  68. package/lib/opencode-go-store.d.ts +0 -18
  69. package/lib/opencode-go-store.js +0 -68
  70. package/lib/opencode-go-store.js.map +0 -1
  71. package/lib/opencode-go-sync.d.ts +0 -107
  72. package/lib/opencode-go-sync.js +0 -388
  73. package/lib/opencode-go-sync.js.map +0 -1
  74. package/lib/opencode-go-writer.d.ts +0 -148
  75. package/lib/opencode-go-writer.js +0 -1061
  76. package/lib/opencode-go-writer.js.map +0 -1
  77. package/src/opencode-go-diagnose.ts +0 -276
  78. package/src/opencode-go-grouping.ts +0 -26
  79. package/src/opencode-go-host-catalog.ts +0 -125
  80. package/src/opencode-go-journal.ts +0 -460
  81. package/src/opencode-go-migrate.ts +0 -1951
  82. package/src/opencode-go-migration.ts +0 -666
  83. package/src/opencode-go-one-shot.ts +0 -1399
  84. package/src/opencode-go-planner.ts +0 -582
  85. package/src/opencode-go-scheduler.ts +0 -315
  86. package/src/opencode-go-store.ts +0 -73
  87. package/src/opencode-go-sync.ts +0 -541
  88. package/src/opencode-go-writer.ts +0 -1301
@@ -1,1529 +0,0 @@
1
- // P1d-2: the two-stage `/model-sync migrate plan|apply|rollback|status` surface.
2
- //
3
- // This is the ONLY entry point that is allowed to touch the go routes' config
4
- // after explicit user consent (design §14.0 M-1/M-2/M-3). Hard rules baked into
5
- // this module:
6
- // - `buildMigrationPlan` is PURE: no settings write, no store write, no fetch.
7
- // Its inputs are injected, so a plan can be produced entirely offline.
8
- // - `applyMigration` refuses unless BOTH the planHash AND the 6-digit confirm
9
- // code match a freshly rebuilt plan of the CURRENT settings. There is no
10
- // `--yes` / `--auto` / env bypass anywhere in this file.
11
- // - write order is settings → ledger → appliedFingerprint (§14.7.4), and the
12
- // applied flag is persisted BEFORE the first mutate so the go scheduler
13
- // drops any round that races the apply (M-5 single writer).
14
- // - `rollbackMigration` refuses on a missing backup or a post-apply hash edit,
15
- // and never overwrites ids the user added after apply.
16
- //
17
- // Design refs: §14.1 (states), §14.2 (three input shapes), §14.4 (references),
18
- // §14.5 (commands), §14.6 (order + single flight), §14.7 (write authority),
19
- // V16/V17/V19/V20/V22. No timer, no network, no real ~/.dsh lives here.
20
- import { createHash } from 'node:crypto';
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'];
30
- const PLAN_VERSION = 1;
31
- // ---------------------------------------------------------------------------
32
- // Pure helpers: canonical hash + confirmation code (V16 / V17)
33
- // ---------------------------------------------------------------------------
34
- function isRecord(value) {
35
- return typeof value === 'object' && value !== null && !Array.isArray(value);
36
- }
37
- function canonicalize(value) {
38
- if (Array.isArray(value))
39
- return value.map(canonicalize);
40
- if (!isRecord(value))
41
- return value;
42
- const out = {};
43
- for (const key of Object.keys(value).sort())
44
- out[key] = canonicalize(value[key]);
45
- return out;
46
- }
47
- /** sha256 of canonical JSON — the planHash algorithm (V17: changes with the plan). */
48
- export function hashCanonical(value) {
49
- return createHash('sha256').update(JSON.stringify(canonicalize(value))).digest('hex');
50
- }
51
- /** Deterministic 6-digit confirmation code derived from a planHash. */
52
- export function confirmCodeOf(planHash) {
53
- return String(Number.parseInt(planHash.slice(0, 12), 16) % 1_000_000).padStart(6, '0');
54
- }
55
- export function planHashOf(body) {
56
- return hashCanonical(body);
57
- }
58
- /**
59
- * THE single source of truth for the per-route "managed after apply" id set.
60
- *
61
- * It simulates the action table against the SAME settings descriptor apply
62
- * will use, so the ids the plan advertises are exactly the ids apply actually
63
- * writes or adopts into the ownership ledger. An id already sitting on its
64
- * target with a user-edited value (an `update` row, or a `move` onto a
65
- * different-valued target) is NEVER claimed: it is not written, so it must not
66
- * be advertised as managed anywhere (B6 + user ruling: update never overwrites
67
- * and never manages).
68
- *
69
- * `buildMigrationPlan` derives the informed-consent text from this function,
70
- * and `applyMigration` derives the ledger `managed` / `appliedManagedIds` from
71
- * the very same `buildRouteWriteStates` computation, so the four surfaces
72
- * cannot disagree.
73
- */
74
- export function managedIdsAfterApply(table, desc) {
75
- const { byRoute } = buildRouteWriteStates(table, desc);
76
- return Object.fromEntries([...byRoute].map(([route, state]) => [
77
- route,
78
- Object.keys(state.managed).sort((a, b) => a.localeCompare(b)),
79
- ]));
80
- }
81
- const KNOWN_ACTION_OPS = new Set(['keep', 'add', 'update', 'move', 'delete']);
82
- /**
83
- * Fail-closed guard: any op outside the closed `MigrationIdActionOp` union is
84
- * rejected before a single write. Returns the first offending row, if any.
85
- */
86
- export function findUnknownAction(actions) {
87
- for (const action of actions) {
88
- if (!KNOWN_ACTION_OPS.has(String(action.op)))
89
- return { id: action.id, op: String(action.op) };
90
- }
91
- return undefined;
92
- }
93
- /**
94
- * The consent gate (V17 + 31 B6). THREE values are mandatory: the matching
95
- * planHash, the 6-digit confirmCode and `--ack-managed` (acknowledgement of the
96
- * `[managed-after-migration]` notice). A missing/incorrect value never reaches
97
- * a write. Deliberately there is no accept-anything branch — `--yes`/`--auto`
98
- * cannot be expressed.
99
- */
100
- export function verifyConsent(plan, planHash, confirmCode, ackManaged) {
101
- if (typeof planHash !== 'string' || planHash === ''
102
- || typeof confirmCode !== 'string' || confirmCode === '') {
103
- return { ok: false, reason: 'consent-required' };
104
- }
105
- if (planHash !== plan.planHash)
106
- return { ok: false, reason: 'plan-hash-mismatch' };
107
- if (confirmCode !== plan.confirmCode)
108
- return { ok: false, reason: 'confirm-code-mismatch' };
109
- if (ackManaged !== true)
110
- return { ok: false, reason: 'ack-required' };
111
- return { ok: true };
112
- }
113
- // ---------------------------------------------------------------------------
114
- // Pure plan builder (V16: zero writes / zero external calls)
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
- }
123
- /** Per-route state, refined from the full-set state (§14.1). */
124
- function detectRouteStates(sections, record, routeIds, overall) {
125
- const identityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {});
126
- const out = {};
127
- for (const route of routeIds) {
128
- const present = sections?.[route];
129
- if (!isRecord(present)) {
130
- out[route] = 'absent';
131
- }
132
- else if (overall === 'drifted') {
133
- // A drift anywhere closes the gate for the whole route set; report it per route too.
134
- out[route] = identityRoutes.includes(route) ? 'drifted' : 'legacy-inline';
135
- }
136
- else if (overall === 'applied' || (record?.appliedIdentity !== undefined && identityRoutes.includes(route))) {
137
- out[route] = 'applied';
138
- }
139
- else {
140
- out[route] = Array.isArray(present.models) ? 'legacy-inline' : 'legacy-inherit';
141
- }
142
- }
143
- return out;
144
- }
145
- /** Default reference report when the caller has no offline scan result to inject. */
146
- function defaultReferences(targets, rewriteRefs) {
147
- const refs = targets.length > 0 ? targets.join(' / ') : 'qwen4-max / grok-4.7';
148
- const candidates = [
149
- {
150
- surface: 'agent-default-model (profile patch)',
151
- location: '~/.dsh/profiles/<profile>/cordis.patch.yml',
152
- before: `opencode-go/${refs}`,
153
- after: 'see pinnedModels / new route',
154
- verified: true,
155
- rewritable: rewriteRefs === 'default-model' || rewriteRefs === 'config',
156
- reportOnly: rewriteRefs === 'none',
157
- },
158
- {
159
- surface: 'favoriteModels / hiddenModels (profile patch)',
160
- location: '~/.dsh/profiles/<profile>/cordis.patch.yml',
161
- before: `opencode-go/${refs}`,
162
- after: 'see pinnedModels / new route',
163
- verified: true,
164
- rewritable: rewriteRefs === 'config',
165
- reportOnly: rewriteRefs === 'none',
166
- },
167
- {
168
- surface: 'session/conversation {provider,model}',
169
- location: '~/.dsh/sessions/**/session.v4.jsonl.zstd',
170
- before: `opencode-go/${refs}`,
171
- after: 'manual / new session',
172
- verified: false,
173
- rewritable: false,
174
- reportOnly: true,
175
- },
176
- ];
177
- return candidates;
178
- }
179
- /** Build the full change plan. Pure: identical inputs → identical plan/hash. */
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
- }
188
- const routes = { ...GO_SLOT_ROUTES, ...input.routes };
189
- const routeIds = Object.values(routes);
190
- const sections = readGoProviderSections(input.descriptor, routeIds);
191
- const prior = input.record;
192
- const state = migrationStateOf(sections, prior, routes.chat);
193
- const stateByRoute = detectRouteStates(sections, prior, routeIds, state);
194
- // Fail-closed capability gate (§14.2): when the executor cannot guarantee the
195
- // action table, adopt is reported as disabled and plan rows stay conservative.
196
- const adoptDisabled = input.adoptDisabled === true;
197
- const adopt = input.adopt === true && !adoptDisabled;
198
- const rewriteRefs = input.rewriteRefs ?? 'none';
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')
235
- continue;
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)));
240
- }
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
- });
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 }]));
267
- // Every id currently in settings, with all the routes it occupies.
268
- const currentLocations = new Map();
269
- for (const scope of scopedRoutes) {
270
- for (const profile of scope.currentModels) {
271
- const list = currentLocations.get(profile.id) ?? [];
272
- list.push({ route: scope.route, profile });
273
- currentLocations.set(profile.id, list);
274
- }
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);
282
- const pinnedIds = new Set(input.pinnedModels ?? []);
283
- // `undefined` is materially different from an empty list: empty means the
284
- // catalog was fetched and truly has no such id (→ user-extra); undefined means
285
- // it could not be fetched at all (→ unclassified, never deleted).
286
- const publicCatalogAvailable = input.publicCatalogIds !== undefined;
287
- const publicIds = new Set(input.publicCatalogIds ?? []);
288
- const pruneUserExtra = input.pruneUserExtra === true;
289
- const kindOf = (id) => {
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';
295
- // Fail-closed (§14.2): no public catalog → never guess "user-written".
296
- if (!publicCatalogAvailable)
297
- return 'unclassified';
298
- // Ids in the official public catalog but not in the current key's authorized
299
- // list are unknown-retired; ids in neither set are user-written extras.
300
- return publicIds.has(id) ? 'unknown-retired' : 'user-extra';
301
- };
302
- // ---- The per-id action table: the SINGLE source of truth for apply (31 B2) ----
303
- const idActions = [];
304
- const idsInScope = new Set([...currentLocations.keys(), ...desiredTarget.keys()]);
305
- for (const id of [...idsInScope].sort((a, b) => a.localeCompare(b))) {
306
- const kind = kindOf(id);
307
- const target = desiredTarget.get(id);
308
- const locations = currentLocations.get(id) ?? [];
309
- const isPinned = pinnedIds.has(id);
310
- if (isPinned) {
311
- // User ruling "pinned = 两边都放": every existing copy is kept in place AND
312
- // a copy is added to the official target route (duplicate display allowed).
313
- // A pinned desired id is never moved/deleted, even in adopt mode.
314
- if (locations.length === 0) {
315
- if (target !== undefined)
316
- idActions.push({
317
- id, op: 'add', route: target.route, kind, pinned: true, profile: target.profile, managed: true,
318
- reason: 'pinnedModels: added to its official route (never moved/deleted)',
319
- });
320
- }
321
- else {
322
- for (const loc of locations)
323
- idActions.push({
324
- id, op: 'keep', route: loc.route, kind, pinned: true, profile: loc.profile,
325
- reason: 'pinnedModels: forced keep (not moved, not deleted)',
326
- });
327
- if (target !== undefined && !locations.some((loc) => loc.route === target.route)) {
328
- idActions.push({
329
- id, op: 'add', route: target.route, kind, pinned: true, profile: target.profile, managed: true,
330
- reason: 'pinnedModels: old copy kept; also added to its official route (duplicate display allowed)',
331
- });
332
- }
333
- }
334
- continue;
335
- }
336
- if (target !== undefined) {
337
- // Official desired id: make sure it ends up on its target route.
338
- const targetLoc = locations.find((loc) => loc.route === target.route);
339
- if (targetLoc === undefined) {
340
- if (locations.length === 0) {
341
- idActions.push({ id, op: 'add', route: target.route, kind, pinned: false, profile: target.profile, managed: true,
342
- reason: 'desired id missing from its official route' });
343
- }
344
- else if (adopt) {
345
- for (const loc of locations)
346
- idActions.push({
347
- id, op: 'move', route: loc.route, to: target.route, kind, pinned: false, profile: target.profile, managed: true,
348
- reason: 'adopt: move desired id from its legacy route (old copy removed)',
349
- });
350
- }
351
- else {
352
- idActions.push({ id, op: 'add', route: target.route, kind, pinned: false, profile: target.profile, managed: true,
353
- reason: 'conservative: keep existing copy, add desired id to its official route' });
354
- for (const loc of locations)
355
- idActions.push({
356
- id, op: 'keep', route: loc.route, kind, pinned: false, profile: loc.profile,
357
- reason: 'conservative: existing copy kept as user-owned',
358
- });
359
- }
360
- }
361
- else {
362
- // Already on the target route. A user-edited profile is reported as an
363
- // UPDATE/drift row with before→after, but apply NEVER overwrites it and
364
- // NEVER claims it as managed (user ruling).
365
- if (profileHash(targetLoc.profile) !== profileHash(target.profile)) {
366
- idActions.push({ id, op: 'update', route: target.route, kind, pinned: false,
367
- profile: target.profile, before: targetLoc.profile,
368
- reason: 'user-modified desired value: plan shows before→after; apply leaves it untouched and unmanaged' });
369
- }
370
- else {
371
- idActions.push({ id, op: 'keep', route: target.route, kind, pinned: false, profile: target.profile, managed: true,
372
- reason: 'desired id already matches the official value (adopted into ledger)' });
373
- }
374
- if (adopt) {
375
- for (const loc of locations) {
376
- if (loc.route === target.route)
377
- continue;
378
- idActions.push({ id, op: 'move', route: loc.route, to: target.route, kind, pinned: false, profile: target.profile, managed: true,
379
- reason: 'adopt: remove duplicate desired id from the wrong route' });
380
- }
381
- }
382
- }
383
- continue;
384
- }
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.
395
- const mayDelete = kind === 'user-extra' ? pruneUserExtra : kind === 'unknown-retired' ? adopt : false;
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
- }
422
- if (mayDelete) {
423
- idActions.push({ id, op: 'delete', route: loc.route, kind, pinned: false, profile: loc.profile,
424
- reason: kind === 'user-extra'
425
- ? '--prune-user-extra: explicitly listed for deletion in this plan'
426
- : 'adopt: unknown-retired id explicitly listed for deletion in this plan' });
427
- }
428
- else {
429
- idActions.push({ id, op: 'keep', route: loc.route, kind, pinned: false, profile: loc.profile,
430
- reason: kind === 'unclassified'
431
- ? 'public catalog unavailable (unclassified): never deleted (fail-closed)'
432
- : describeId(kind, adopt) });
433
- }
434
- }
435
- }
436
- // Deletions are reported with the three-gate explanation, driven from the
437
- // SAME action table (so the report cannot disagree with apply). `move` rows
438
- // are NOT deletions — they are listed in the per-id table with a destination.
439
- const deletions = idActions
440
- .filter((action) => action.op === 'delete')
441
- .map((action) => ({
442
- route: action.route,
443
- id: action.id,
444
- kind: action.kind,
445
- gates: {
446
- managedHash: 'plan-confirmed: id removed by this migration',
447
- override: 'no modelOverrides on legacy section',
448
- pinned: action.pinned ? 'pinned — never removed' : 'not pinned',
449
- },
450
- willDelete: true,
451
- reason: action.reason,
452
- }));
453
- const plannedRoutesDraft = scopedRoutes.map((scope) => {
454
- const seen = new Set();
455
- const existing = [];
456
- for (const profile of scope.currentModels) {
457
- if (seen.has(profile.id))
458
- continue;
459
- seen.add(profile.id);
460
- const row = idActions.find((action) => action.route === scope.route && action.id === profile.id);
461
- const legacyAction = row?.op === 'move' ? 'move'
462
- : row?.op === 'delete' ? 'delete'
463
- : row?.op === 'keep' ? 'keep' : 'adopt';
464
- existing.push({
465
- id: profile.id,
466
- kind: row?.kind ?? 'user-extra',
467
- action: legacyAction,
468
- reason: row?.reason ?? describeId('user-extra', adopt),
469
- });
470
- }
471
- let action;
472
- if (scope.state === 'absent')
473
- action = 'create';
474
- else if (scope.state === 'applied')
475
- action = 'keep';
476
- else
477
- action = 'update';
478
- return { slot: scope.slot, route: scope.route, state: scope.state, action, fields: scope.fields, desired: scope.desired, existing };
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
- });
499
- const pinnedSuggestions = new Set();
500
- // Reversible targets: desired ids still sitting on a legacy protocol route.
501
- for (const id of targets)
502
- pinnedSuggestions.add(id);
503
- for (const id of pinnedIds)
504
- pinnedSuggestions.add(id);
505
- // B6 informed-consent text — part of the hashed body: any edit to this notice
506
- // changes planHash and invalidates the old confirmCode/ack. The id list comes
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.
510
- // N2: no row may claim management on paper if the simulation shows apply
511
- // will not actually write/adopt that id. Normalise the per-id `managed`
512
- // flags to the simulated set so even the printed `[managed]` marker cannot
513
- // disagree with the ledger. (Turning a flag OFF cannot change the simulation
514
- // that produced `managedByRoute`, so plan ↔ apply stay deterministic.)
515
- for (const action of idActions) {
516
- if (action.managed !== true)
517
- continue;
518
- const targetRoute = action.op === 'move' ? action.to : action.route;
519
- if (targetRoute === undefined || !(managedByRoute[targetRoute] ?? []).includes(action.id)) {
520
- action.managed = false;
521
- }
522
- }
523
- const managedAfterMigration = [
524
- '[managed-after-migration] 以下模型将交由插件管理:',
525
- ` ${scopedRoutes.map((s) => `${s.route}: ${managedByRoute[s.route]?.join(', ') || '(none)'}`).join(';')}`,
526
- '官方下架时,这些模型会在满足「归属账本 + 现值哈希 + 无 override/pin」三闸门且连续 2 轮确认后自动从列表移除。',
527
- ].join('\n');
528
- const preFingerprint = fingerprintSection(sections ?? {});
529
- const body = {
530
- version: PLAN_VERSION,
531
- keyFingerprint: input.keyFingerprint,
532
- adopt,
533
- rewriteRefs,
534
- preFingerprint,
535
- state,
536
- stateByRoute,
537
- routes: plannedRoutes,
538
- deletions,
539
- idActions,
540
- managedAfterMigration,
541
- publicCatalogAvailable,
542
- hostCatalogAvailable,
543
- hostCatalogLagIds,
544
- adoptDisabled,
545
- references,
546
- pinnedSuggestions: [...pinnedSuggestions].sort(),
547
- backupPath: `models-store:migration:backup:${input.keyFingerprint}`,
548
- rollbackCommand: `/model-sync migrate rollback --plan <planHash>`,
549
- unverified: [
550
- 'session/conversation storage: report-only (checksummed zstd, append-only, revision drift, FTS invalidation)',
551
- 'external scripts / third-party config: report-only',
552
- ],
553
- };
554
- const planHash = planHashOf(body);
555
- return { ...body, planHash, confirmCode: confirmCodeOf(planHash) };
556
- }
557
- function describeId(kind, adopt) {
558
- switch (kind) {
559
- case 'desired': return 'official desired id (single managed route)';
560
- case 'legacy-other-protocol': return adopt ? 'legacy id on the wrong protocol route' : 'legacy id kept in conservative mode';
561
- case 'unknown-retired': return adopt ? 'unknown/retired id, delete only if confirmed in plan' : 'unknown/retired id kept as user-owned';
562
- case 'user-extra': return 'user-written id, never auto-deleted';
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)';
565
- }
566
- }
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`.
576
- // ---------------------------------------------------------------------------
577
- // Human-readable reports (V16 / V19)
578
- // ---------------------------------------------------------------------------
579
- function profileLabel(profile) {
580
- if (profile === undefined)
581
- return '(none)';
582
- return `${profile.name ?? profile.id} [${profileHash(profile).slice(0, 8)}]`;
583
- }
584
- export function formatMigrationPlan(plan) {
585
- const mode = plan.adoptDisabled
586
- ? 'adopt-disabled (--adopt rejected: apply cannot guarantee the action table)'
587
- : plan.adopt ? 'adopt' : 'conservative';
588
- const lines = [
589
- `model-sync migrate plan (v${plan.version}) — ${plan.state} (read-only, nothing written)`,
590
- ` mode: ${mode} rewrite-refs: ${plan.rewriteRefs}`,
591
- ` sections fingerprint: ${plan.preFingerprint.slice(0, 16)}…`,
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 拒绝)']),
598
- '',
599
- 'Routes:',
600
- ];
601
- for (const route of plan.routes) {
602
- const fields = route.fields;
603
- lines.push(` ${route.route} [${route.slot}/${route.state}] ${route.action.toUpperCase()}`);
604
- lines.push(` displayName=${fields.displayName} apiKeyEnv=${fields.apiKeyEnv}${route.action === 'unset' ? ' (whole-route unset; fields not written)' : ''}`);
605
- lines.push(` desired (${route.desired.length}): ${route.desired.map((profile) => profile.id).join(', ') || '(none)'}`);
606
- if (route.existing.length > 0) {
607
- lines.push(` existing: ${route.existing.map((entry) => `${entry.id}=${entry.kind}/${entry.action}`).join(', ')}`);
608
- }
609
- }
610
- lines.push('', 'Deletions (three-gate explanation):');
611
- if (plan.deletions.length === 0)
612
- lines.push(' (none)');
613
- for (const del of plan.deletions) {
614
- lines.push(` ${del.route}/${del.id} [${del.kind}] willDelete=${del.willDelete}`);
615
- lines.push(` gates: managedHash=${del.gates.managedHash}; override=${del.gates.override}; pinned=${del.gates.pinned}`);
616
- lines.push(` why: ${del.reason}`);
617
- }
618
- lines.push('', 'Per-id actions (apply consumes this table verbatim; keep/update/pin are non-destructive):');
619
- if (plan.idActions.length === 0)
620
- lines.push(' (none)');
621
- for (const action of plan.idActions) {
622
- const dest = action.to !== undefined ? ` → ${action.to}` : '';
623
- const beforeAfter = action.op === 'update'
624
- ? ` before=${profileLabel(action.before)} → official=${profileLabel(action.profile)} (apply keeps current value, not managed)`
625
- : '';
626
- lines.push(` ${action.op.toUpperCase().padEnd(6)} ${action.route}/${action.id}${dest} [${action.kind}]${action.pinned ? ' [pinned]' : ''}${action.managed === true ? ' [managed]' : ''}${beforeAfter}`);
627
- lines.push(` why: ${action.reason}`);
628
- }
629
- lines.push('', plan.managedAfterMigration);
630
- lines.push('', 'Reference rewrites (report-only by default; sessions are NEVER rewritten):');
631
- for (const ref of plan.references) {
632
- lines.push(` ${ref.verified ? 'verified' : 'unverified'}/${ref.reportOnly ? 'report-only' : 'rewritable'} ${ref.surface} @ ${ref.location}`);
633
- lines.push(` ${ref.before} → ${ref.after}`);
634
- }
635
- if (plan.pinnedSuggestions.length > 0) {
636
- lines.push('', `pinnedModels suggestion: ${plan.pinnedSuggestions.join(', ')}`);
637
- }
638
- lines.push('', `Backup: ${plan.backupPath}`);
639
- lines.push(`Rollback: ${plan.rollbackCommand}`);
640
- if (plan.unverified.length > 0) {
641
- lines.push('', 'Unverified (report-only):');
642
- for (const item of plan.unverified)
643
- lines.push(` - ${item}`);
644
- }
645
- lines.push('', `planHash: ${plan.planHash}`);
646
- lines.push(`confirmCode: ${plan.confirmCode}`);
647
- lines.push('apply: /model-sync migrate apply --plan <planHash> --confirm <confirmCode> --ack-managed');
648
- return lines.join('\n');
649
- }
650
- /** Best-effort: drop every write-ahead journal of this profile. */
651
- async function clearProfileJournals(deps) {
652
- if (deps.journalStore === undefined || deps.profileKey === undefined)
653
- return;
654
- try {
655
- await deps.journalStore.clearProfile(deps.profileKey);
656
- }
657
- catch (err) {
658
- // Advisory only: a surviving slot is re-validated (and discarded) by the
659
- // next reconciliation, never replayed blindly. Never fail a migration for it.
660
- deps.logger.warn('journal cleanup after migration failed: %s', errorText(err));
661
- }
662
- }
663
- /**
664
- * The ONE plan-construction path used by both `/migrate plan` and `apply`.
665
- * Sharing it is what makes the printed plan and the plan apply re-builds
666
- * byte-identical — a prerequisite for the consent gate (V17) and V19.
667
- */
668
- export function buildMigrationPlanFromDeps(deps, record) {
669
- return buildMigrationPlan({
670
- descriptor: deps.settings?.describe().find((desc) => desc.ns === 'llm-pi-ai'),
671
- entries: deps.entries,
672
- routes: deps.routes,
673
- ref: deps.ref,
674
- keyFingerprint: deps.keyFingerprint,
675
- adopt: deps.adopt,
676
- rewriteRefs: deps.rewriteRefs,
677
- record,
678
- references: deps.references,
679
- pinnedModels: deps.pinnedModels,
680
- pruneUserExtra: deps.pruneUserExtra,
681
- publicCatalogIds: deps.publicCatalogIds,
682
- hostCatalogIds: deps.hostCatalogIds,
683
- adoptDisabled: deps.adoptDisabled,
684
- now: deps.now,
685
- });
686
- }
687
- async function readRecord(deps) {
688
- try {
689
- return await deps.migrationStore.read();
690
- }
691
- catch {
692
- return undefined;
693
- }
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
- }
709
- function llmDescriptor(settings) {
710
- return settings?.describe().find((desc) => desc.ns === 'llm-pi-ai');
711
- }
712
- function rawRoute(desc, route) {
713
- const providers = desc?.user?.providers;
714
- if (!isRecord(providers))
715
- return undefined;
716
- const data = providers[route];
717
- return isRecord(data) ? data : undefined;
718
- }
719
- function rawModels(desc, route) {
720
- const models = rawRoute(desc, route)?.models;
721
- return Array.isArray(models) ? models : [];
722
- }
723
- function isConflictError(err) {
724
- return err?.code === 'SETTINGS_CONFLICT';
725
- }
726
- function errorText(err) {
727
- // Prefer a structured `message` so re-wrapped plain-object errors still carry
728
- // the actionable text (lock path / retry advice) instead of "[object Object]".
729
- // Error instances already expose `message`; everything else falls back to
730
- // String(err) exactly as before.
731
- const message = err?.message;
732
- return typeof message === 'string' ? message : String(err);
733
- }
734
- /** Set ops that write exactly the target fields + models for one route. */
735
- function routeOps(desc, route, fields, models, mode = 'managed') {
736
- const data = rawRoute(desc, route);
737
- const ops = [];
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] });
765
- }
766
- }
767
- const sorted = [...models].sort((a, b) => a.id.localeCompare(b.id));
768
- const current = [...rawModels(desc, route)].sort((a, b) => a.id.localeCompare(b.id));
769
- if (current.length !== sorted.length || current.some((profile, index) => profileHash(profile) !== profileHash(sorted[index]))) {
770
- ops.push({ op: 'set', path: ['providers', route, 'models'], value: sorted });
771
- }
772
- return ops;
773
- }
774
- /**
775
- * Translate the plan's per-id action table into per-route desired states. This
776
- * is the ONLY place that decides what apply writes: there is no
777
- * `merged = [...desired]` re-derivation anywhere (31 B2). Every row yields
778
- * exactly one result, in table order, so plan ↔ apply is checkable row by row.
779
- *
780
- * This same function powers plan-time simulation (`managedIdsAfterApply`) and
781
- * apply-time execution, so "will be managed" and "was managed" use ONE source.
782
- *
783
- * Semantics (user rulings + §14.2/§14.3):
784
- * keep → untouched; adopted only when the row is flagged `managed` AND the
785
- * id is actually present on the route.
786
- * add → write the official profile unless the id is already present; an
787
- * already-present id is only adopted (managed) if its value matches.
788
- * update → NOTHING written, never managed (user-edited value is preserved).
789
- * move → remove from source route; on the destination, write/adopt the
790
- * official profile ONLY if the target is empty or already holds the
791
- * same value. A different-valued target is a user edit: never
792
- * overwritten, never claimed, and reported as `skipped`.
793
- * delete → remove from the route (only rows explicitly listed in the plan).
794
- * pinned → expressed by keep (+ add on the target) rows; never moved/deleted.
795
- * default → FAIL-CLOSED: an unknown op throws, it is never silently skipped.
796
- */
797
- export function buildRouteWriteStates(table, desc) {
798
- const byRoute = new Map();
799
- for (const planned of table.routes) {
800
- byRoute.set(planned.route, {
801
- models: new Map(rawModels(desc, planned.route).map((profile) => [profile.id, structuredClone(profile)])),
802
- managed: {},
803
- addedIds: new Set(),
804
- });
805
- }
806
- const results = [];
807
- const claim = (state, action) => {
808
- if (action.managed !== true || state === undefined || action.profile === undefined)
809
- return;
810
- // Never claim an id that is not actually on the route after this action.
811
- if (!state.models.has(action.id))
812
- return;
813
- state.managed[action.id] = { hash: profileHash(action.profile) };
814
- };
815
- for (const action of table.idActions) {
816
- const source = byRoute.get(action.route);
817
- const result = (status, reason) => {
818
- results.push({ id: action.id, op: action.op, route: action.route, ...(action.to !== undefined ? { to: action.to } : {}), status, reason });
819
- };
820
- switch (action.op) {
821
- case 'keep':
822
- claim(source, action);
823
- result('kept', action.reason);
824
- break;
825
- case 'add': {
826
- if (source === undefined || action.profile === undefined) {
827
- result('skipped', 'route or profile unavailable; nothing written');
828
- break;
829
- }
830
- if (source.models.has(action.id)) {
831
- // Idempotent: never overwrite an existing value (C4 / update ruling).
832
- const existing = source.models.get(action.id);
833
- if (action.managed === true && profileHash(existing) === profileHash(action.profile))
834
- claim(source, action);
835
- result('kept', `already present on ${action.route}; not overwritten`);
836
- }
837
- else {
838
- source.models.set(action.id, structuredClone(action.profile));
839
- source.addedIds.add(action.id);
840
- claim(source, action);
841
- result('applied', action.reason);
842
- }
843
- break;
844
- }
845
- case 'update':
846
- // User ruling: report before→after, but write nothing and claim nothing.
847
- result('skipped', `${action.reason} (before=${profileLabel(action.before)}; official=${profileLabel(action.profile)})`);
848
- break;
849
- case 'move': {
850
- source?.models.delete(action.id);
851
- const dest = action.to !== undefined ? byRoute.get(action.to) : undefined;
852
- const suffix = action.to !== undefined ? ` → ${action.to}` : '';
853
- if (dest === undefined || action.profile === undefined) {
854
- result('skipped', `${action.reason}${suffix}: destination/profile unavailable; source copy removed, nothing written to target`);
855
- break;
856
- }
857
- if (dest.models.has(action.id)) {
858
- const existing = dest.models.get(action.id);
859
- if (action.managed === true && profileHash(existing) === profileHash(action.profile)) {
860
- claim(dest, action);
861
- result('kept', `${action.reason}${suffix}: target already holds the official value; adopted into ledger`);
862
- }
863
- else {
864
- // Different value = user edit on the target. Do not overwrite and
865
- // do NOT claim as managed — truthful result + ledger + notice.
866
- result('skipped', `${action.reason}${suffix}: target holds a user-modified value; not overwritten, not managed`);
867
- }
868
- }
869
- else {
870
- dest.models.set(action.id, structuredClone(action.profile));
871
- dest.addedIds.add(action.id);
872
- claim(dest, action);
873
- result('applied', `${action.reason}${suffix}`);
874
- }
875
- break;
876
- }
877
- case 'delete':
878
- source?.models.delete(action.id);
879
- result('applied', action.reason);
880
- break;
881
- default: {
882
- // Fail-closed (N4): an unknown op must never silently disappear. Throwing
883
- // here means neither plan simulation nor apply can report success on a
884
- // table it did not fully execute. `applyMigration` rejects earlier with a
885
- // typed reason; this is the last line of defence.
886
- const bad = action;
887
- throw new Error(`unknown migration action op '${String(bad.op)}' on id ${bad.id}; refusing (adopt-disabled: action table not executable)`);
888
- }
889
- }
890
- }
891
- return { byRoute, results };
892
- }
893
- async function mutateWithRetry(deps, ops) {
894
- const settings = deps.settings;
895
- if (settings === undefined)
896
- throw new Error('settings service unavailable');
897
- const desc = llmDescriptor(settings);
898
- if (desc === undefined)
899
- throw new Error('llm-pi-ai namespace unavailable');
900
- try {
901
- await settings.mutate('llm-pi-ai', ops, desc.revision);
902
- }
903
- catch (err) {
904
- if (!isConflictError(err))
905
- throw err;
906
- const fresh = llmDescriptor(settings);
907
- if (fresh === undefined)
908
- throw new Error('llm-pi-ai namespace disappeared on retry');
909
- await settings.mutate('llm-pi-ai', ops, fresh.revision);
910
- }
911
- }
912
- function applyFailure(reason, planHash, confirmCode, detail, writesReverted = false) {
913
- // O1-minimal: "zero writes" is only true for a refusal BEFORE the first
914
- // mutate. When settings were written and then byte-restored, say so instead
915
- // of misreporting a clean zero-write no-op.
916
- const outcome = writesReverted
917
- ? 'settings writes were rolled back to the pre-apply snapshot (bytes restored; no net change)'
918
- : 'zero writes';
919
- return { ok: false, reason, planHash, confirmCode, routes: [], actions: [], text: `migrate apply refused (${reason}): ${detail}; ${outcome}` };
920
- }
921
- export async function applyMigration(args, 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
- }
936
- const plan = buildMigrationPlanFromDeps(deps, prior);
937
- // 1. Consent — every rejection below is ZERO writes. `--ack-managed` is a
938
- // mandatory third token (B6); no bypass flag exists.
939
- const consent = verifyConsent(plan, args.planHash, args.confirmCode, args.ackManaged);
940
- if (!consent.ok)
941
- return applyFailure(consent.reason, plan.planHash, plan.confirmCode, `${consent.reason}`);
942
- // N4 fail-closed: an op outside the closed union can never be executed
943
- // verbatim. Reject BEFORE the applying flag, any settings write, or any
944
- // ledger write. `faultInjectOp` is a test-only seam; production uses only
945
- // plan.idActions (which the builder always keeps inside the union).
946
- const actionsToRun = deps.faultInjectOp === undefined
947
- ? [...plan.idActions]
948
- : [...plan.idActions, {
949
- id: '__fault-injected__', op: deps.faultInjectOp,
950
- route: plan.routes[0]?.route ?? 'opencode-go', kind: 'user-extra', pinned: false,
951
- reason: 'fault-injected unknown action op',
952
- }];
953
- const unknown = findUnknownAction(actionsToRun);
954
- if (unknown !== undefined) {
955
- return applyFailure('unknown-action', plan.planHash, plan.confirmCode, `unknown action op '${unknown.op}' on id '${unknown.id}'; refusing (adopt-disabled: action table not executable)`);
956
- }
957
- // Fail-closed fallback (§14.2): if the executor cannot guarantee verbatim
958
- // table execution, adopt is refused here as well as at the command layer.
959
- if (deps.adopt === true && (deps.adoptDisabled === true || plan.adoptDisabled)) {
960
- return applyFailure('adopt-disabled', plan.planHash, plan.confirmCode, '--adopt disabled: apply cannot execute the per-id action table; use conservative mode');
961
- }
962
- if (plan.state !== 'legacy-inherit' && plan.state !== 'legacy-inline' && plan.state !== 'drifted') {
963
- return applyFailure('nothing-to-apply', plan.planHash, plan.confirmCode, `state=${plan.state} (nothing needs migration)`);
964
- }
965
- // 2. Single flight against the go sync round (V22). The scheduler drops its
966
- // own rounds once `applying` is persisted (step 3); this check rejects apply
967
- // while a round already holds the lock.
968
- if (deps.isSyncInFlight?.() === true) {
969
- return applyFailure('sync-in-flight', plan.planHash, plan.confirmCode, 'a go sync round is in flight; retry when it finishes');
970
- }
971
- if (typeof deps.migrationStore.write !== 'function') {
972
- return applyFailure('write-failed', plan.planHash, plan.confirmCode, 'migration store is read-only');
973
- }
974
- const desc = llmDescriptor(deps.settings);
975
- if (desc === undefined || deps.settings === undefined) {
976
- return applyFailure('write-failed', plan.planHash, plan.confirmCode, 'settings/llm-pi-ai unavailable');
977
- }
978
- // Simulate the action table BEFORE any write. It is pure, and its fail-closed
979
- // default throws on an unknown op — doing it here guarantees such a throw
980
- // cannot leave a persisted `applying` flag with no restore snapshot.
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
- }
1020
- // 3. Capture the audit backup and persist `applying` BEFORE the first mutate.
1021
- // If we crash mid-apply, the record still carries the restore snapshot.
1022
- const backup = captureBackup(plan, desc, deps.now);
1023
- const applyingRecord = {
1024
- ...(prior ?? {}),
1025
- applying: true,
1026
- backup,
1027
- planHash: plan.planHash,
1028
- legacyFingerprint: plan.preFingerprint,
1029
- };
1030
- try {
1031
- await deps.migrationStore.write(applyingRecord);
1032
- }
1033
- catch (err) {
1034
- return applyFailure('write-failed', plan.planHash, plan.confirmCode, `could not persist applying flag: ${errorText(err)}`);
1035
- }
1036
- const routesResult = [];
1037
- const committedLedgerKeys = [];
1038
- const writtenRoutes = [];
1039
- const managedByRoute = {};
1040
- let failure;
1041
- // The action table is the ONLY write source (31 B2): apply writes exactly the
1042
- // simulated states above, never re-deriving from `planned.desired`. The SAME
1043
- // simulation drives the plan's informed text (`managedIdsAfterApply`), so
1044
- // "will manage" and "did manage" are one computation.
1045
- try {
1046
- for (const planned of plan.routes) {
1047
- const state = byRoute.get(planned.route);
1048
- if (state === undefined) {
1049
- routesResult.push({ route: planned.route, status: 'skipped', reason: 'no write state' });
1050
- continue;
1051
- }
1052
- const touched = actionsToRun.some((action) => action.route === planned.route || action.to === planned.route);
1053
- if (planned.action === 'keep' && !touched) {
1054
- // No row touches this route: do not write settings, do not write a
1055
- // ledger entry, and do not list it in appliedManagedIds. Listing it
1056
- // here used to fabricate a "+route: []" entry never backed by a ledger.
1057
- routesResult.push({ route: planned.route, status: 'skipped', reason: 'already-applied (no rows touched this route)' });
1058
- continue;
1059
- }
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
- }
1094
- // Write only ops that actually change fields/models. keep/update/delete-no
1095
- // rows leave the section byte-identical, so no mutate happens for them.
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');
1101
- let wroteThisRoute = false;
1102
- if (ops.length > 0) {
1103
- try {
1104
- await mutateWithRetry(deps, ops);
1105
- writtenRoutes.push(planned.route);
1106
- wroteThisRoute = true;
1107
- }
1108
- catch (err) {
1109
- failure = `${planned.route}: settings mutate failed (${errorText(err)})`;
1110
- routesResult.push({ route: planned.route, status: 'failed', reason: errorText(err) });
1111
- break;
1112
- }
1113
- }
1114
- // B6: ledger `managed` is EXACTLY the set of ids this simulation claimed
1115
- // on this route — the same set the plan advertised. Ids not written or
1116
- // adopted (user-edited `update`, different-valued `move` target) are
1117
- // absent. `managedByRoute` is the sole source for `appliedManagedIds`.
1118
- const managed = state.managed;
1119
- managedByRoute[planned.route] = Object.keys(managed).sort((a, b) => a.localeCompare(b));
1120
- const ledgerKey = goOwnershipKey(planned.route, deps.keyFingerprint);
1121
- const preManagedSection = backup.routes[planned.route]?.section;
1122
- const entry = {
1123
- routeFields: planned.fields,
1124
- managed,
1125
- // Audit-only pre-managed ids; rollback uses preManagedSection below.
1126
- preManagedSnapshot: current.map((profile) => ({ ...profile })),
1127
- // §14.3 whole-section snapshot: the exact pre-apply section (null when
1128
- // the route did not exist) plus the ids this apply introduced.
1129
- preManagedSection: preManagedSection === undefined ? null : structuredClone(preManagedSection),
1130
- appliedAddedIds: [...state.addedIds].sort((a, b) => a.localeCompare(b)),
1131
- };
1132
- try {
1133
- await deps.ownershipStore.write(ledgerKey, entry);
1134
- committedLedgerKeys.push(ledgerKey);
1135
- }
1136
- catch (err) {
1137
- failure = `${planned.route}: ledger write failed (${errorText(err)})`;
1138
- routesResult.push({ route: planned.route, status: 'failed', reason: errorText(err) });
1139
- break;
1140
- }
1141
- // N1: a route is "wrote" only when settings actually changed. A pure
1142
- // ledger adoption (keep row, zero ops) is a no-op on settings and must
1143
- // not inflate the success count.
1144
- routesResult.push({
1145
- route: planned.route,
1146
- status: wroteThisRoute ? 'wrote' : 'skipped',
1147
- ...(wroteThisRoute ? {} : { reason: 'no-op: route already matches the plan (no settings write)' }),
1148
- });
1149
- }
1150
- }
1151
- catch (err) {
1152
- failure = errorText(err);
1153
- }
1154
- if (failure === undefined) {
1155
- // 4. Fingerprint LAST (§14.7.4): only after settings + ledger both landed.
1156
- const identityRoutes = Object.keys(readGoProviderSections(llmDescriptor(deps.settings), Object.values(routesOf(deps))) ?? {});
1157
- const liveSections = readGoProviderSections(llmDescriptor(deps.settings), Object.values(routesOf(deps)));
1158
- const identity = fingerprintGoIdentity(liveSections, identityRoutes);
1159
- // N3: `appliedManagedIds` mirrors ONLY the ledger entries actually written
1160
- // above. No fallback to `managedIdsForRoute` for routes skipped by the plan
1161
- // (e.g. an empty google slot): that used to fabricate a route -> [] entry
1162
- // with no backing ledger record.
1163
- const managedIds = { ...managedByRoute };
1164
- const applied = {
1165
- ...(prior ?? {}),
1166
- applying: false,
1167
- // Keep the captured whole-section backup: it is the audit copy and the
1168
- // crash-window fallback for rollback. The authoritative copy also lives
1169
- // on each ledger entry (preManagedSection), so neither is discarded.
1170
- backup,
1171
- planHash: plan.planHash,
1172
- backupPath: plan.backupPath,
1173
- appliedAt: deps.now,
1174
- appliedIdentity: identity,
1175
- appliedIdentityRoutes: identityRoutes,
1176
- appliedManagedIds: managedIds,
1177
- appliedFingerprint: appliedFingerprintOf(identity, managedIds),
1178
- // Moves are relocations, not deletions: report them separately from the
1179
- // delete rows so rollback/audit can tell the two apart (V19).
1180
- movedIds: [...new Set(plan.idActions.filter((action) => action.op === 'move').map((action) => action.id))],
1181
- legacyFingerprint: undefined,
1182
- };
1183
- try {
1184
- await deps.migrationStore.write(applied);
1185
- }
1186
- catch (err) {
1187
- failure = `appliedFingerprint persist failed (${errorText(err)})`;
1188
- }
1189
- // 5. Opt-in reference rewrite — only verified config keys, never sessions.
1190
- if (failure === undefined && plan.rewriteRefs !== 'none' && deps.applyReferenceRewrite !== undefined) {
1191
- for (const ref of plan.references) {
1192
- if (!ref.verified || !ref.rewritable || ref.reportOnly)
1193
- continue;
1194
- try {
1195
- await deps.applyReferenceRewrite({ surface: ref.surface, location: ref.location, before: ref.before, after: ref.after });
1196
- }
1197
- catch (err) {
1198
- deps.logger.warn('reference rewrite failed for %s: %s', ref.surface, errorText(err));
1199
- }
1200
- }
1201
- }
1202
- }
1203
- if (failure !== undefined) {
1204
- // Best-effort restore from the captured snapshot; re-lock and keep no fingerprint.
1205
- await restoreOnApplyFailure(deps, backup, writtenRoutes, committedLedgerKeys, prior);
1206
- // O1/C2: settings were restored to the pre-apply snapshot; any journal from
1207
- // the pre-migration writer is now stale. Drop it so a later round cannot
1208
- // re-account settings the apply just rolled back.
1209
- await clearProfileJournals(deps);
1210
- deps.logger.warn('migrate apply rolled back after failure: %s', failure);
1211
- return applyFailure('write-failed', plan.planHash, plan.confirmCode, failure, writtenRoutes.length > 0);
1212
- }
1213
- // O1/C2: apply succeeded — its settings writes are fully accounted by the
1214
- // migration record + ledger. Any pre-migration journal is stale now.
1215
- await clearProfileJournals(deps);
1216
- // N1: count the settings writes that actually happened (`writtenRoutes`),
1217
- // not the per-route result rows (which now include truthful no-op `skipped`
1218
- // routes). Zero writes must say so explicitly instead of "N routes written".
1219
- const writtenCount = writtenRoutes.length;
1220
- const headline = writtenCount === 0
1221
- ? 'migrate apply: 0 routes written (no settings writes; all routes already match / ledger-only adoptions), fingerprint persisted'
1222
- : `migrate apply: ${writtenCount} routes written, fingerprint persisted`;
1223
- const text = [
1224
- headline,
1225
- ...routesResult.map((r) => ` ${r.route}: ${r.status}${r.reason !== undefined ? ` (${r.reason})` : ''}`),
1226
- 'Per-id results (one per plan action row):',
1227
- ...actionResults.map((a) => ` ${a.status.toUpperCase().padEnd(7)} ${a.op.toUpperCase().padEnd(6)} ${a.route}/${a.id}${a.to !== undefined ? ` → ${a.to}` : ''} — ${a.reason}`),
1228
- ` backup: ${plan.backupPath}`,
1229
- ` rollback: /model-sync migrate rollback --plan ${plan.planHash}`,
1230
- ].join('\n');
1231
- return {
1232
- ok: true,
1233
- reason: 'applied',
1234
- planHash: plan.planHash,
1235
- confirmCode: plan.confirmCode,
1236
- routes: routesResult,
1237
- actions: actionResults,
1238
- backupPath: plan.backupPath,
1239
- text,
1240
- };
1241
- }
1242
- function routesOf(deps) {
1243
- return { ...GO_SLOT_ROUTES, ...deps.routes };
1244
- }
1245
- function captureBackup(plan, desc, now) {
1246
- const backup = { planHash: plan.planHash, capturedAt: now, routes: {} };
1247
- for (const planned of plan.routes) {
1248
- const section = rawRoute(desc, planned.route);
1249
- backup.routes[planned.route] = {
1250
- ...(section === undefined ? {} : { section: structuredClone(section) }),
1251
- };
1252
- }
1253
- return backup;
1254
- }
1255
- /** Best-effort undo of a partial apply: restore route sections, drop new ledger entries, clear applying. */
1256
- async function restoreOnApplyFailure(deps, backup, writtenRoutes, ledgerKeys, prior) {
1257
- const desc = llmDescriptor(deps.settings);
1258
- for (const route of writtenRoutes) {
1259
- if (desc === undefined)
1260
- continue;
1261
- const original = backup.routes[route]?.section;
1262
- const ops = [];
1263
- if (original === undefined) {
1264
- ops.push({ op: 'unset', path: ['providers', route] });
1265
- }
1266
- else {
1267
- // Restore via field-level ops (never replace the whole section): unset the
1268
- // route first so plugin-created sections disappear, then reapply the
1269
- // original fields/models. This keeps the operation compatible with the
1270
- // writer's path-based mutate contract (§14.3: no whole-section write-back).
1271
- ops.push({ op: 'unset', path: ['providers', route] });
1272
- for (const [field, value] of Object.entries(original)) {
1273
- if (field === 'models' && !Array.isArray(value))
1274
- continue;
1275
- ops.push({ op: 'set', path: ['providers', route, field], value: structuredClone(value) });
1276
- }
1277
- }
1278
- try {
1279
- await mutateWithRetry(deps, ops);
1280
- }
1281
- catch (err) {
1282
- deps.logger.warn('apply-failure restore failed for %s: %s', route, errorText(err));
1283
- }
1284
- }
1285
- for (const key of ledgerKeys) {
1286
- try {
1287
- const original = backup.routes[key.split('#')[0]]?.ledger;
1288
- if (original === undefined)
1289
- await deps.ownershipStore.delete(key);
1290
- else
1291
- await deps.ownershipStore.write(key, original);
1292
- }
1293
- catch (err) {
1294
- deps.logger.warn('apply-failure ledger restore failed for %s: %s', key, errorText(err));
1295
- }
1296
- }
1297
- if (typeof deps.migrationStore.write === 'function') {
1298
- try {
1299
- await deps.migrationStore.write({ ...(prior ?? {}), applying: false });
1300
- }
1301
- catch (err) {
1302
- deps.logger.warn('apply-failure applying flag clear failed: %s', errorText(err));
1303
- }
1304
- }
1305
- }
1306
- export async function rollbackMigration(args, deps) {
1307
- const refuse = (reason, detail) => ({
1308
- ok: false, reason, routes: [], text: `migrate rollback refused (${reason}): ${detail}; zero writes`,
1309
- });
1310
- const record = await readRecord(deps);
1311
- if (record === undefined)
1312
- return refuse('no-record', 'no migration record to roll back');
1313
- if (typeof args.planHash !== 'string' || args.planHash === '')
1314
- return refuse('consent-required', 'a --plan <hash> is required');
1315
- if (record.planHash !== args.planHash)
1316
- return refuse('plan-hash-mismatch', `record hash != ${args.planHash}`);
1317
- // A crashed apply leaves `applying:true` + the captured backup but no
1318
- // fingerprint; rollback must still be able to restore from that backup.
1319
- if (record.appliedFingerprint === undefined && record.backup === undefined) {
1320
- return refuse('no-record', 'record has neither appliedFingerprint nor a captured backup');
1321
- }
1322
- const desc = llmDescriptor(deps.settings);
1323
- if (desc === undefined || deps.settings === undefined)
1324
- return refuse('snapshot-missing', 'settings/llm-pi-ai unavailable');
1325
- const routeIds = Object.values(routesOf(deps));
1326
- // Hash check: every plugin-managed id still present in settings must match the
1327
- // hash we wrote. An external edit → refuse (never clobber user changes).
1328
- for (const route of routeIds) {
1329
- const entry = await deps.ownershipStore.read(goOwnershipKey(route, deps.keyFingerprint)).catch(() => undefined);
1330
- if (entry === undefined)
1331
- continue;
1332
- const currentById = new Map(rawModels(desc, route).map((profile) => [profile.id, profile]));
1333
- for (const [id, managed] of Object.entries(entry.managed ?? {})) {
1334
- const model = currentById.get(id);
1335
- if (model !== undefined && profileHash(model) !== managed.hash) {
1336
- return refuse('hash-mismatch', `${route}/${id} changed after apply (managed hash mismatch)`);
1337
- }
1338
- }
1339
- }
1340
- // Reconstruct each route from the WHOLE pre-apply section (§14.3), not from a
1341
- // models-only list. Restore its exact fields/values/order, remove ids this
1342
- // migration introduced, and keep ids the user added after apply.
1343
- const rollbackOps = [];
1344
- for (const route of routeIds) {
1345
- const entry = await deps.ownershipStore.read(goOwnershipKey(route, deps.keyFingerprint)).catch(() => undefined);
1346
- const backupRoute = record.backup?.routes[route];
1347
- if (entry === undefined && backupRoute === undefined)
1348
- continue;
1349
- // Authoritative snapshot: the ledger copy written by apply, or the captured
1350
- // backup for a crash before the ledger commit. `null`/`undefined` section
1351
- // means the route did not exist before the migration; a written-but-missing
1352
- // field is the snapshot-missing refusal below.
1353
- const hasSectionSnapshot = entry !== undefined
1354
- ? entry.preManagedSection !== undefined
1355
- : backupRoute !== undefined;
1356
- if (!hasSectionSnapshot)
1357
- return refuse('snapshot-missing', `${route} has no preManagedSection`);
1358
- const originalSection = entry !== undefined ? entry.preManagedSection : backupRoute?.section;
1359
- const originalModels = Array.isArray(originalSection?.models)
1360
- ? originalSection.models
1361
- : [];
1362
- const originalIds = new Set(originalModels.map((profile) => profile.id));
1363
- const current = rawModels(desc, route);
1364
- // Ids introduced by the migration itself: recorded at apply time when a
1365
- // ledger exists. For a crash-window rollback every current id absent from
1366
- // the captured snapshot was written by the half-finished apply.
1367
- const addedIds = entry !== undefined
1368
- ? new Set(entry.appliedAddedIds ?? [])
1369
- : new Set(current.filter((profile) => !originalIds.has(profile.id)).map((profile) => profile.id));
1370
- // A post-apply id is neither in the original section nor one of ours — keep
1371
- // it (never clobber user edits, even if it sits on a plugin-created route).
1372
- const userAdded = current.filter((profile) => !originalIds.has(profile.id) && !addedIds.has(profile.id));
1373
- const finalModels = [...originalModels, ...userAdded];
1374
- const ops = [];
1375
- if (originalSection === null || originalSection === undefined) {
1376
- // Route did not exist before apply: drop everything the plugin created,
1377
- // keeping only models the user added afterwards.
1378
- ops.push({ op: 'unset', path: ['providers', route] });
1379
- if (finalModels.length > 0)
1380
- ops.push({ op: 'set', path: ['providers', route, 'models'], value: finalModels });
1381
- }
1382
- else {
1383
- // Rebuild field-by-field in the ORIGINAL key order with the ORIGINAL values
1384
- // so the restored bytes match the pre-apply section exactly: fields that
1385
- // existed before are restored (never unset), fields apply wrote that were
1386
- // absent before disappear with the whole-section reset, and the models
1387
- // array keeps its original order with user-added ids appended.
1388
- ops.push({ op: 'unset', path: ['providers', route] });
1389
- const hasModelsKey = Object.prototype.hasOwnProperty.call(originalSection, 'models');
1390
- for (const [field, value] of Object.entries(originalSection)) {
1391
- if (field === 'models') {
1392
- if (hasModelsKey)
1393
- ops.push({ op: 'set', path: ['providers', route, 'models'], value: finalModels });
1394
- }
1395
- else {
1396
- ops.push({ op: 'set', path: ['providers', route, field], value: structuredClone(value) });
1397
- }
1398
- }
1399
- if (!hasModelsKey && finalModels.length > 0) {
1400
- ops.push({ op: 'set', path: ['providers', route, 'models'], value: finalModels });
1401
- }
1402
- }
1403
- if (ops.length > 0)
1404
- rollbackOps.push({ route, ops });
1405
- }
1406
- for (const item of rollbackOps) {
1407
- try {
1408
- await mutateWithRetry(deps, item.ops);
1409
- }
1410
- catch (err) {
1411
- // Some rollback ops may already have landed. Drop this profile's journals
1412
- // so a later round cannot re-commit ledger/record for settings rollback
1413
- // is in the middle of undoing.
1414
- await clearProfileJournals(deps);
1415
- return refuse('hash-mismatch', `${item.route}: settings mutate failed (${errorText(err)})`);
1416
- }
1417
- }
1418
- for (const route of routeIds) {
1419
- try {
1420
- await deps.ownershipStore.delete(goOwnershipKey(route, deps.keyFingerprint));
1421
- }
1422
- catch (err) {
1423
- deps.logger.warn('rollback ledger cleanup failed for %s: %s', route, errorText(err));
1424
- }
1425
- }
1426
- if (typeof deps.migrationStore.write === 'function') {
1427
- // Clear the applied marker + fingerprint; the state falls back to legacy-*
1428
- // from the restored sections, so go sync write authority is re-locked.
1429
- await deps.migrationStore.write({
1430
- ...(record.legacyFingerprint !== undefined ? { legacyFingerprint: record.legacyFingerprint } : {}),
1431
- applying: false,
1432
- });
1433
- }
1434
- // O1/C2: rollback rewrote settings back to the pre-migration snapshot; every
1435
- // journal of this profile describes a now-obsolete write. Clear them (this
1436
- // also removes key-rotation orphans) so no later round re-accounts them.
1437
- await clearProfileJournals(deps);
1438
- return {
1439
- ok: true,
1440
- reason: 'rolled-back',
1441
- routes: rollbackOps.map((item) => item.route),
1442
- text: `migrate rollback: restored ${rollbackOps.length} routes, cleared ledger + fingerprint, write authority re-locked`,
1443
- };
1444
- }
1445
- export async function migrationStatusReport(deps, config) {
1446
- const details = deps.settings?.describe().find((desc) => desc.ns === 'llm-pi-ai');
1447
- const record = await readRecord(deps);
1448
- const routeIds = Object.values({ ...GO_SLOT_ROUTES, ...deps.routes });
1449
- const sections = readGoProviderSections(details, routeIds);
1450
- const sectionState = migrationStateOf(sections, record, routeIds[0]);
1451
- // D6: the store hides unreadable records from read() (B1). Ask it separately
1452
- // for provenance so status can name the two unclaimable cases WITHOUT
1453
- // changing the gate: both keep write authority `none`, claim nothing, and
1454
- // never authorize rollback deletion. Detection is advisory and read-only.
1455
- //
1456
- // Only when read() found NO record for this profile: another profile's own
1457
- // valid record is normal multi-profile coexistence and must not relabel a
1458
- // profile that already has its own applied/drifted record (B1 isolation).
1459
- let unclaimed = [];
1460
- if (record === undefined) {
1461
- try {
1462
- unclaimed = await deps.migrationStore.unclaimedRecords?.() ?? [];
1463
- }
1464
- catch {
1465
- // An unreadable store never changes status (same rule as legacyKeys).
1466
- }
1467
- }
1468
- const recordState = unclaimedRecordState(unclaimed);
1469
- const overall = recordState ?? sectionState;
1470
- const states = detectRouteStates(sections, record, routeIds, sectionState);
1471
- const authority = {
1472
- caller: config?.caller ?? 'go',
1473
- goEnabled: config?.goEnabled ?? true,
1474
- goRoutes: routeIds,
1475
- zenMode: config?.zenMode,
1476
- zenRoutes: config?.zenRoutes,
1477
- };
1478
- const stub = {
1479
- state: overall,
1480
- fingerprint: fingerprintSection(sections ?? {}),
1481
- identity: fingerprintGoIdentity(sections, record?.appliedIdentityRoutes),
1482
- appliedIdentity: record?.appliedIdentity,
1483
- appliedFingerprint: record?.appliedFingerprint,
1484
- applying: record?.applying === true,
1485
- fingerprintHealed: false,
1486
- expectedFingerprint: '',
1487
- };
1488
- const routes = routeIds.map((route) => {
1489
- const decision = routeWriter(route, authority, stub);
1490
- return {
1491
- route,
1492
- // An unclaimed record closes the gate for the whole route set; surface
1493
- // that label on every go route instead of the misleading legacy-inline.
1494
- state: recordState ?? states[route] ?? 'absent',
1495
- owner: decision.owner,
1496
- decision: decision.decision,
1497
- reason: decision.reason,
1498
- };
1499
- });
1500
- const writeAuthority = unclaimed.length > 0
1501
- ? 'none'
1502
- : routes.some((r) => r.owner === 'go' && r.decision === 'write') ? 'go' : 'none';
1503
- const lines = [
1504
- `model-sync migrate status: ${overall}${stub.applying ? ' (applying)' : ''}`,
1505
- ...routes.map((r) => ` ${r.route}: state=${r.state} owner=${r.owner} ${r.decision}${r.reason !== undefined ? ` (${r.reason})` : ''}`),
1506
- ];
1507
- if (recordState !== undefined) {
1508
- lines.push(` unclaimed: ${recordState} writeAuthority=none (不认领 / 不开门 / 不可回滚删除;请在归属 profile 重新运行 /model-sync migrate plan/apply)`);
1509
- for (const item of unclaimed) {
1510
- lines.push(` ${item.kind}: ${item.key}${item.profileKey !== undefined ? ` (profileKey=${item.profileKey})` : ''}`);
1511
- }
1512
- }
1513
- // B1 compatibility: unscoped legacy keys are reported but NEVER claimed.
1514
- // A pre-fix record has no profile stamp, so its owner is unknown; adopting
1515
- // it could open the gate for a profile that never consented. Tell the user
1516
- // to re-migrate in the owning profile instead of silently using the record.
1517
- let legacy = [];
1518
- try {
1519
- legacy = await deps.migrationStore.legacyKeys?.() ?? [];
1520
- }
1521
- catch {
1522
- // Detection is advisory — an unreadable store never changes status.
1523
- }
1524
- if (legacy.length > 0) {
1525
- lines.push(` 警告: 检测到 ${legacy.length} 个无 profile 前缀的旧键(归属未知,未认领): ${legacy.join(', ')};请在归属 profile 重新运行 /model-sync migrate plan/apply`);
1526
- }
1527
- return { overall, writeAuthority, unclaimed, applying: stub.applying, routes, text: lines.join('\n') };
1528
- }
1529
- //# sourceMappingURL=opencode-go-migrate.js.map