@aiwayds/dsh-model-sync 0.9.0 → 0.11.0

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 (74) hide show
  1. package/README.md +20 -3
  2. package/README.zh-CN.md +20 -3
  3. package/lib/builtin-catalog-snapshot.js +6 -3
  4. package/lib/builtin-catalog-snapshot.js.map +1 -1
  5. package/lib/index.d.ts +379 -0
  6. package/lib/index.js +897 -13
  7. package/lib/index.js.map +1 -1
  8. package/lib/opencode-go-diagnose.d.ts +74 -0
  9. package/lib/opencode-go-diagnose.js +146 -0
  10. package/lib/opencode-go-diagnose.js.map +1 -0
  11. package/lib/opencode-go-grouping.d.ts +29 -0
  12. package/lib/opencode-go-grouping.js +77 -0
  13. package/lib/opencode-go-grouping.js.map +1 -0
  14. package/lib/opencode-go-journal.d.ts +110 -0
  15. package/lib/opencode-go-journal.js +406 -0
  16. package/lib/opencode-go-journal.js.map +1 -0
  17. package/lib/opencode-go-migrate.d.ts +343 -0
  18. package/lib/opencode-go-migrate.js +1300 -0
  19. package/lib/opencode-go-migrate.js.map +1 -0
  20. package/lib/opencode-go-migration.d.ts +227 -0
  21. package/lib/opencode-go-migration.js +384 -0
  22. package/lib/opencode-go-migration.js.map +1 -0
  23. package/lib/opencode-go-one-shot.d.ts +276 -0
  24. package/lib/opencode-go-one-shot.js +1094 -0
  25. package/lib/opencode-go-one-shot.js.map +1 -0
  26. package/lib/opencode-go-patch-file.d.ts +123 -0
  27. package/lib/opencode-go-patch-file.js +1185 -0
  28. package/lib/opencode-go-patch-file.js.map +1 -0
  29. package/lib/opencode-go-planner.d.ts +153 -0
  30. package/lib/opencode-go-planner.js +339 -0
  31. package/lib/opencode-go-planner.js.map +1 -0
  32. package/lib/opencode-go-profile.d.ts +57 -0
  33. package/lib/opencode-go-profile.js +103 -0
  34. package/lib/opencode-go-profile.js.map +1 -0
  35. package/lib/opencode-go-scheduler.d.ts +128 -0
  36. package/lib/opencode-go-scheduler.js +241 -0
  37. package/lib/opencode-go-scheduler.js.map +1 -0
  38. package/lib/opencode-go-source.d.ts +117 -0
  39. package/lib/opencode-go-source.js +331 -0
  40. package/lib/opencode-go-source.js.map +1 -0
  41. package/lib/opencode-go-store.d.ts +18 -0
  42. package/lib/opencode-go-store.js +68 -0
  43. package/lib/opencode-go-store.js.map +1 -0
  44. package/lib/opencode-go-sync.d.ts +94 -0
  45. package/lib/opencode-go-sync.js +364 -0
  46. package/lib/opencode-go-sync.js.map +1 -0
  47. package/lib/opencode-go-writer.d.ts +132 -0
  48. package/lib/opencode-go-writer.js +966 -0
  49. package/lib/opencode-go-writer.js.map +1 -0
  50. package/lib/provider-native.d.ts +3 -1
  51. package/lib/provider-native.js +4 -2
  52. package/lib/provider-native.js.map +1 -1
  53. package/lib/remote-catalog.d.ts +61 -0
  54. package/lib/remote-catalog.js +307 -3
  55. package/lib/remote-catalog.js.map +1 -1
  56. package/package.json +15 -15
  57. package/src/builtin-catalog-snapshot.ts +6 -3
  58. package/src/index.ts +1060 -12
  59. package/src/opencode-go-diagnose.ts +222 -0
  60. package/src/opencode-go-grouping.ts +97 -0
  61. package/src/opencode-go-journal.ts +458 -0
  62. package/src/opencode-go-migrate.ts +1694 -0
  63. package/src/opencode-go-migration.ts +552 -0
  64. package/src/opencode-go-one-shot.ts +1354 -0
  65. package/src/opencode-go-patch-file.ts +1168 -0
  66. package/src/opencode-go-planner.ts +505 -0
  67. package/src/opencode-go-profile.ts +114 -0
  68. package/src/opencode-go-scheduler.ts +315 -0
  69. package/src/opencode-go-source.ts +424 -0
  70. package/src/opencode-go-store.ts +73 -0
  71. package/src/opencode-go-sync.ts +503 -0
  72. package/src/opencode-go-writer.ts +1189 -0
  73. package/src/provider-native.ts +3 -1
  74. package/src/remote-catalog.ts +359 -3
@@ -0,0 +1,1094 @@
1
+ // One-shot migrate-go: `/model-sync migrate-go` — one command that runs the
2
+ // FULL opencode-go migration flow (plan → backup → confirm → apply) for one
3
+ // or every profile, reusing the existing plan builder and apply engine
4
+ // unchanged (design §14.2 consent gate stays authoritative; this module only
5
+ // COMPUTES planHash/confirmCode on the caller side and passes them in, never
6
+ // touching verifyConsent).
7
+ //
8
+ // Fixed pipeline (per user-approved behavior):
9
+ // a. targets: the current profile, or --all-profiles = every profile whose
10
+ // patch still carries a legacy opencode-go stub (models-only, no
11
+ // api/baseURL). Profile keys reuse the repo's resolveProfileKey source.
12
+ // b. credential: resolveRouteCredentialValue over go.ref; missing →
13
+ // fail-closed (zero outbound calls, zero writes) with guidance.
14
+ // c. plan per target: buildMigrationPlanFromDeps — never re-implemented.
15
+ // d. backups BEFORE any write: `<profileDir>/cordis.patch.yml` and the
16
+ // shared models-store.json (once per run), named `.bak.<stamp>` with a
17
+ // sequence suffix inside one second; 3 newest kept per category.
18
+ // e. ONE user-questions confirmation for the whole run; no channel or any
19
+ // ask error → fail closed with the manual migrate plan/apply path.
20
+ // Cancel → zero writes. After the ask returns, invocation.signal.aborted
21
+ // is re-checked (abort ⇒ cancel) and an answer carrying BOTH option
22
+ // labels is an ambiguous cancel + rerun — proceed never wins a contested
23
+ // answer.
24
+ // f. apply via applyMigration with the computed consent triple and
25
+ // ackManaged: true. --yes/--auto do not exist on this command.
26
+ // g. slots come from the resolved opencode.go.routes config (the top-level
27
+ // patch's dsh-model-sync section as resolved by the host); apply writes
28
+ // exactly the plan's routes — no google slot unless configured, and no
29
+ // other provider is ever touched.
30
+ // h. on success, opencode.go.enabled flips to true in the CURRENT profile
31
+ // through the host settings seam; if that key cannot be written, the
32
+ // report says so with the manual step instead of failing the migration.
33
+ //
34
+ // Atomicity: any apply failure stops the loop and byte-restores every file
35
+ // this run changed (per-profile patches + models-store.json) — patches through
36
+ // the same atomic tmp+rename io the apply writes with, the models-store as a
37
+ // whole-document byte replacement through the remote-catalog lock accessor
38
+ // (exact backup bytes, tmp+rename under the lock — never a raw overwrite and
39
+ // never a key-order-changing per-key rebuild). Every restore first re-hashes
40
+ // the on-disk content and refuses to touch a file a concurrent process has
41
+ // modified since this run's last write. Backups are created under an O_EXCL
42
+ // exclusive claim (same-second collisions retry the next sequence suffix; no
43
+ // readdir snapshot can hand out one name twice), and each target's staleness
44
+ // is re-verified (sha256) right before apply, so a file edited between backup
45
+ // and apply aborts that target with zero writes. `--rewrite-refs` writes ride
46
+ // the same change tracker as settings writes (registered + sha-baselined, so
47
+ // a later failure restores them too). All external effects (fs, settings,
48
+ // userQuestions, fetch, clock, homedir) arrive through OneShotDeps.
49
+ import { createHash } from 'node:crypto';
50
+ import { join } from 'node:path';
51
+ import { fingerprintKey } from "./opencode-go-source.js";
52
+ import { GO_SLOT_ROUTES } from "./opencode-go-grouping.js";
53
+ import { PROFILE_IDENTITY_REQUIRED_MESSAGE } from "./opencode-go-profile.js";
54
+ import { applyMigration, buildMigrationPlanFromDeps, } from "./opencode-go-migrate.js";
55
+ import { loadModelsStore, STORE_RESTORE_SHA_MISMATCH } from "./remote-catalog.js";
56
+ import { createFilePatchSettingsService, parsePatchDocument, patchLlmPiAiProviders, } from "./opencode-go-patch-file.js";
57
+ export const MIGRATE_GO_USAGE = [
58
+ 'usage: /model-sync migrate-go [--all-profiles] [--adopt] [--prune-user-extra] [--rewrite-refs=default-model|config]',
59
+ ' one command = plan + file backups + ONE confirmation + apply, then opencode.go.enabled=true in the current profile',
60
+ ' --all-profiles process every profile whose patch still has a legacy opencode-go stub',
61
+ ' --adopt adopt existing copies (plan may move ids / delete unknown-retired ids)',
62
+ ' --prune-user-extra allow deleting plan-listed user-extra ids',
63
+ ' --rewrite-refs=default-model|config opt into verified reference rewrites (default: report-only)',
64
+ ' defaults: current profile only, conservative plan (no adopt, no prune, report-only refs)',
65
+ ' rollback: /model-sync migrate rollback --plan <planHash>',
66
+ ].join('\n');
67
+ const REWRITE_REF_VALUES = ['default-model', 'config'];
68
+ /**
69
+ * Strict flag parsing: unknown flags (including --yes/--auto — there is no
70
+ * bypass semantics on this command) and stray positional words are errors
71
+ * carrying the usage text.
72
+ */
73
+ export function parseMigrateGoFlags(args) {
74
+ const flags = { allProfiles: false, adopt: false, pruneUserExtra: false, rewriteRefs: 'none' };
75
+ for (let i = 0; i < args.length; i++) {
76
+ const token = args[i];
77
+ if (token === '--all-profiles') {
78
+ flags.allProfiles = true;
79
+ continue;
80
+ }
81
+ if (token === '--adopt') {
82
+ flags.adopt = true;
83
+ continue;
84
+ }
85
+ if (token === '--prune-user-extra') {
86
+ flags.pruneUserExtra = true;
87
+ continue;
88
+ }
89
+ if (token === '--rewrite-refs') {
90
+ const value = args[i + 1];
91
+ if (value === undefined || value.startsWith('--')) {
92
+ return { ok: false, error: `migrate-go: --rewrite-refs needs a value (${REWRITE_REF_VALUES.join('|')})\n${MIGRATE_GO_USAGE}` };
93
+ }
94
+ if (!REWRITE_REF_VALUES.includes(value)) {
95
+ return { ok: false, error: `migrate-go: unsupported --rewrite-refs value '${value}' (${REWRITE_REF_VALUES.join('|')})\n${MIGRATE_GO_USAGE}` };
96
+ }
97
+ flags.rewriteRefs = value;
98
+ i += 1;
99
+ continue;
100
+ }
101
+ if (token.startsWith('--rewrite-refs=')) {
102
+ const value = token.slice('--rewrite-refs='.length);
103
+ if (!REWRITE_REF_VALUES.includes(value)) {
104
+ return { ok: false, error: `migrate-go: unsupported --rewrite-refs value '${value}' (${REWRITE_REF_VALUES.join('|')})\n${MIGRATE_GO_USAGE}` };
105
+ }
106
+ flags.rewriteRefs = value;
107
+ continue;
108
+ }
109
+ if (token.startsWith('--')) {
110
+ return { ok: false, error: `migrate-go: unknown flag '${token}' (note: --yes/--auto do not exist here; consent comes from the interactive confirmation)\n${MIGRATE_GO_USAGE}` };
111
+ }
112
+ return { ok: false, error: `migrate-go: unexpected argument '${token}'\n${MIGRATE_GO_USAGE}` };
113
+ }
114
+ return { ok: true, flags };
115
+ }
116
+ // ---------------------------------------------------------------------------
117
+ // Small pure helpers (exported for tests)
118
+ // ---------------------------------------------------------------------------
119
+ /** Local-time `YYYYMMDD-HHMMSS` stamp — the backup/log naming convention. */
120
+ export function formatStamp(date) {
121
+ const p = (value) => String(value).padStart(2, '0');
122
+ return `${date.getFullYear()}${p(date.getMonth() + 1)}${p(date.getDate())}-${p(date.getHours())}${p(date.getMinutes())}${p(date.getSeconds())}`;
123
+ }
124
+ const PATCH_BACKUP_PATTERN = /^cordis\.patch\.yml\.bak\.(\d{8}-\d{6})(?:\.(\d+))?$/;
125
+ const STORE_BACKUP_PATTERN = /^models-store\.json\.bak\.(\d{8}-\d{6})(?:\.(\d+))?$/;
126
+ /** sha256 hex digest of a text — the staleness / concurrent-modification detector. */
127
+ export function sha256Of(text) {
128
+ return createHash('sha256').update(text).digest('hex');
129
+ }
130
+ /**
131
+ * Create `<base>` / `<base>.<seq>` exclusively: `writeFileExclusive` returns
132
+ * false when the name is taken (O_EXCL), and only then does the loop advance
133
+ * the sequence suffix. No readdir snapshot is consulted, so two processes
134
+ * racing inside the same second can never both "win" the same backup name —
135
+ * the loser retries onto `.<seq+1>` and both files survive.
136
+ */
137
+ export async function writeExclusiveBackup(fs, base, text, mode) {
138
+ let candidate = base;
139
+ for (let seq = 2;; seq += 1) {
140
+ if (await fs.writeFileExclusive(candidate, text, mode))
141
+ return candidate;
142
+ candidate = `${base}.${seq}`;
143
+ }
144
+ }
145
+ function backupSortKey(name, pattern) {
146
+ const match = pattern.exec(name);
147
+ if (match === null)
148
+ return undefined;
149
+ return { ts: match[1], seq: Number(match[2] ?? 0) };
150
+ }
151
+ /**
152
+ * Retention: keep the `keep` newest backups matching `pattern` in `dirPath`
153
+ * (sorted by filename timestamp, then sequence) and unlink the rest. Returns
154
+ * the removed names. Best-effort per file: unlink errors are reported, not
155
+ * thrown — retention must never fail a migration that already backed up.
156
+ */
157
+ export async function pruneBackups(fs, dirPath, pattern, keep = 3) {
158
+ let names;
159
+ try {
160
+ names = await fs.readdir(dirPath);
161
+ }
162
+ catch {
163
+ return []; // no directory yet → nothing to prune
164
+ }
165
+ const backups = names
166
+ .map((name) => ({ name, key: backupSortKey(name, pattern) }))
167
+ .filter((item) => item.key !== undefined)
168
+ .sort((a, b) => a.key.ts.localeCompare(b.key.ts) || a.key.seq - b.key.seq);
169
+ const excess = backups.slice(0, Math.max(0, backups.length - keep));
170
+ const removed = [];
171
+ for (const item of excess) {
172
+ try {
173
+ await fs.unlink(join(dirPath, item.name));
174
+ removed.push(item.name);
175
+ }
176
+ catch {
177
+ // Advisory: a stuck file only means 4 backups instead of 3.
178
+ }
179
+ }
180
+ return removed;
181
+ }
182
+ /**
183
+ * The legacy stub definition from the approved behavior: an `opencode-go*`
184
+ * section that carries a models array but NO api/baseURL — the handwritten
185
+ * pre-migration entry. Any other provider section is ignored here.
186
+ */
187
+ export function legacyStubsOf(providers, goRouteIds) {
188
+ const stubs = [];
189
+ if (typeof providers !== 'object' || providers === null)
190
+ return stubs;
191
+ const record = providers;
192
+ for (const route of [...new Set(goRouteIds)]) {
193
+ const section = record[route];
194
+ if (section === null || typeof section !== 'object' || Array.isArray(section))
195
+ continue;
196
+ const data = section;
197
+ if (data.api !== undefined || data.baseURL !== undefined)
198
+ continue;
199
+ if (!Array.isArray(data.models))
200
+ continue;
201
+ const ids = data.models
202
+ .map((model) => (model !== null && typeof model === 'object' ? model.id : undefined))
203
+ .filter((id) => typeof id === 'string' && id.length > 0);
204
+ stubs.push({ route, ids });
205
+ }
206
+ return stubs;
207
+ }
208
+ /** Read + parse a patch file and return its llm-pi-ai providers plain tree. */
209
+ async function readPatchProviders(fs, patchPath) {
210
+ let text;
211
+ try {
212
+ text = await fs.readFile(patchPath);
213
+ }
214
+ catch (err) {
215
+ return { ok: false, reason: `cannot read ${patchPath}: ${err instanceof Error ? err.message : String(err)}` };
216
+ }
217
+ const parsed = parsePatchDocument(text);
218
+ if (!parsed.ok)
219
+ return { ok: false, reason: parsed.reason };
220
+ const providers = patchLlmPiAiProviders(parsed.root);
221
+ if (!providers.ok)
222
+ return { ok: false, reason: providers.reason };
223
+ return { ok: true, providers: providers.providers };
224
+ }
225
+ function resolveProfileDir(deps) {
226
+ const dir = deps.currentProfile?.dir;
227
+ if (dir !== undefined && dir.trim() !== '')
228
+ return dir;
229
+ const key = deps.currentProfile?.key;
230
+ if (key === undefined || key.trim() === '')
231
+ return undefined;
232
+ // The host derives name = basename(dir), so a NAME key maps back into the
233
+ // standard profiles layout; a dir-shaped key already is the directory.
234
+ if (key.includes('/'))
235
+ return key;
236
+ return join(deps.profilesDir ?? join(deps.home, 'profiles'), key);
237
+ }
238
+ async function discoverTargets(deps, flags) {
239
+ const goRouteIds = [...new Set(Object.values({ ...GO_SLOT_ROUTES, ...deps.goConfig.routes }))];
240
+ const currentKey = deps.currentProfile?.key;
241
+ if (currentKey === undefined || currentKey.trim() === '') {
242
+ throw new Error(PROFILE_IDENTITY_REQUIRED_MESSAGE);
243
+ }
244
+ const skipped = [];
245
+ if (!flags.allProfiles) {
246
+ const dir = resolveProfileDir(deps);
247
+ if (dir === undefined) {
248
+ throw new Error(`${PROFILE_IDENTITY_REQUIRED_MESSAGE} (also: no profile directory available to back up)`);
249
+ }
250
+ const patchPath = join(dir, 'cordis.patch.yml');
251
+ let stubs = [];
252
+ if (deps.currentSettings !== undefined) {
253
+ const desc = deps.currentSettings.describe().find((item) => item.ns === 'llm-pi-ai');
254
+ stubs = legacyStubsOf(desc?.user?.providers, goRouteIds);
255
+ }
256
+ else {
257
+ const providers = await readPatchProviders(deps.fs, patchPath);
258
+ if (!providers.ok)
259
+ skipped.push(`current profile: ${providers.reason}`);
260
+ else
261
+ stubs = legacyStubsOf(providers.providers, goRouteIds);
262
+ }
263
+ return { targets: [{ key: currentKey, dir, patchPath, isCurrent: true, stubs }], skipped };
264
+ }
265
+ const profilesDir = deps.profilesDir ?? join(deps.home, 'profiles');
266
+ let names;
267
+ try {
268
+ names = await deps.fs.readdir(profilesDir);
269
+ }
270
+ catch (err) {
271
+ throw new Error(`cannot list ${profilesDir}: ${err instanceof Error ? err.message : String(err)}`);
272
+ }
273
+ const targets = [];
274
+ for (const name of names.sort()) {
275
+ if (name === 'node_modules' || name.startsWith('.'))
276
+ continue;
277
+ const dir = join(profilesDir, name);
278
+ const patchPath = join(dir, 'cordis.patch.yml');
279
+ const providers = await readPatchProviders(deps.fs, patchPath);
280
+ if (!providers.ok) {
281
+ // Files the reader cannot handle (missing patch, unsupported YAML) are
282
+ // reported and skipped — fail closed, never edited.
283
+ skipped.push(`${name}: ${providers.reason}`);
284
+ continue;
285
+ }
286
+ const stubs = legacyStubsOf(providers.providers, goRouteIds);
287
+ if (stubs.length === 0)
288
+ continue;
289
+ const isCurrent = name === currentKey || currentKey === dir;
290
+ targets.push({ key: name, dir, patchPath, isCurrent, stubs });
291
+ }
292
+ return { targets, skipped };
293
+ }
294
+ function wrapOwnershipStore(store, tracker, faultPrefix, profileKey) {
295
+ return {
296
+ read: (key) => store.read(key),
297
+ write: async (key, entry) => {
298
+ // The underlying store scopes keys as `<profileKey>#<key>`; the fault
299
+ // prefix targets the SCOPED form (per profile), mirroring the raw form
300
+ // for unscoped callers.
301
+ const scopedKey = profileKey === undefined ? key : `${profileKey}#${key}`;
302
+ if (faultPrefix !== undefined && (scopedKey.startsWith(faultPrefix) || key.startsWith(faultPrefix))) {
303
+ throw new Error(`fault-injected ledger write failure for ${scopedKey}`);
304
+ }
305
+ tracker.storeChanged = true;
306
+ await store.write(key, entry);
307
+ },
308
+ delete: (key) => store.delete(key),
309
+ };
310
+ }
311
+ function wrapMigrationStore(store, tracker) {
312
+ const write = store.write;
313
+ const legacyKeys = store.legacyKeys;
314
+ const unclaimedRecords = store.unclaimedRecords;
315
+ return {
316
+ read: () => store.read(),
317
+ ...(write === undefined ? {} : {
318
+ write: async (record) => {
319
+ tracker.storeChanged = true;
320
+ await write(record);
321
+ },
322
+ }),
323
+ ...(legacyKeys === undefined ? {} : { legacyKeys: () => legacyKeys() }),
324
+ ...(unclaimedRecords === undefined ? {} : { unclaimedRecords: () => unclaimedRecords() }),
325
+ };
326
+ }
327
+ function wrapSettings(settings, tracker, recordPostWrite) {
328
+ return {
329
+ describe: () => settings.describe(),
330
+ mutate: async (ns, ops, expectedRevision) => {
331
+ await settings.mutate(ns, ops, expectedRevision);
332
+ tracker.patchChanged = true;
333
+ // Baseline the post-write bytes while nothing else has had a chance to
334
+ // touch the file — this hash is what the restore path verifies against.
335
+ await recordPostWrite();
336
+ },
337
+ };
338
+ }
339
+ /**
340
+ * Review M4: `--rewrite-refs` writes land in the SAME document the settings
341
+ * seam writes, but they used to bypass the change tracker entirely — a later
342
+ * target's failure then left the rewritten references unrestored, and the
343
+ * stale post-write sha made the restore guard misreport the very file this
344
+ * run had just written as "concurrent modification detected". The wrapped
345
+ * seam registers the write on the tracker (restorable) and refreshes the sha
346
+ * baseline immediately after the rewrite lands.
347
+ */
348
+ function wrapReferenceRewrite(rewrite, tracker, recordPostWrite) {
349
+ return async (request) => {
350
+ await rewrite(request);
351
+ tracker.patchChanged = true;
352
+ await recordPostWrite();
353
+ };
354
+ }
355
+ function buildTargetDeps(deps, target, shared, flags) {
356
+ const tracker = { patchChanged: false, storeChanged: false, patchPostWriteSha: undefined };
357
+ // Baseline the patch file's bytes right after every settings write so the
358
+ // restore path can prove the file was not touched by anyone else in between
359
+ // (review Major 2: restore only ever replaces content this run wrote).
360
+ const recordPatchPostWrite = async () => {
361
+ try {
362
+ tracker.patchPostWriteSha = sha256Of(await deps.fs.readFile(target.patchPath));
363
+ }
364
+ catch {
365
+ tracker.patchPostWriteSha = undefined; // unreadable ⇒ restore must refuse
366
+ }
367
+ };
368
+ const rawSettings = target.isCurrent && deps.currentSettings !== undefined
369
+ ? deps.currentSettings
370
+ : createFilePatchSettingsService(deps.patchIoFor(target.patchPath));
371
+ const stores = deps.storesFor(target.key);
372
+ const migrateDeps = {
373
+ settings: wrapSettings(rawSettings, tracker, recordPatchPostWrite),
374
+ ownershipStore: wrapOwnershipStore(stores.ownership, tracker, deps.faultOwnershipWriteOnKeyPrefix, target.key),
375
+ migrationStore: wrapMigrationStore(stores.migration, tracker),
376
+ logger: deps.logger,
377
+ entries: shared.entries,
378
+ publicCatalogIds: shared.publicCatalogIds,
379
+ routes: deps.goConfig.routes,
380
+ ref: deps.goConfig.ref,
381
+ keyFingerprint: shared.keyFingerprint,
382
+ adopt: flags.adopt,
383
+ adoptDisabled: deps.goConfig.adoptDisabled,
384
+ rewriteRefs: flags.rewriteRefs,
385
+ pinnedModels: deps.goConfig.pinnedModels,
386
+ pruneUserExtra: flags.pruneUserExtra,
387
+ now: deps.now(),
388
+ isSyncInFlight: deps.isSyncInFlight,
389
+ // Reference rewrites ride the host ctx seam and only ever touch the
390
+ // current profile's own document — never a sibling profile's files. They
391
+ // go through the change tracker (review M4) so a later failure restores
392
+ // them and the post-write sha stays truthful.
393
+ applyReferenceRewrite: target.isCurrent && deps.applyReferenceRewrite !== undefined
394
+ ? wrapReferenceRewrite(deps.applyReferenceRewrite, tracker, recordPatchPostWrite)
395
+ : undefined,
396
+ journalStore: deps.journalStore,
397
+ profileKey: target.key,
398
+ };
399
+ return { migrateDeps, tracker };
400
+ }
401
+ /**
402
+ * Snapshot `source` into `<source>.bak.<stamp>[.<seq>]`. The write is an
403
+ * exclusive O_EXCL claim followed by an atomic tmp+rename (mode preserved from
404
+ * the source), so a crash leaves either no backup or a complete one, and two
405
+ * same-second racers get distinct sequence suffixes instead of one clobbering
406
+ * the other. Returns the record with the source hash for the staleness check.
407
+ */
408
+ async function backupFile(deps, source, stamp, dirPath, pattern) {
409
+ let text;
410
+ let mode;
411
+ try {
412
+ text = await deps.fs.readFile(source);
413
+ mode = (await deps.fs.stat(source))?.mode;
414
+ }
415
+ catch (err) {
416
+ throw new Error(`backup failed for ${source}: ${err instanceof Error ? err.message : String(err)}`);
417
+ }
418
+ const base = `${source}.bak.${stamp}`;
419
+ const backupPath = await writeExclusiveBackup(deps.fs, base, text, mode);
420
+ await pruneBackups(deps.fs, dirPath, pattern);
421
+ return { source, backup: backupPath, sourceSha: sha256Of(text) };
422
+ }
423
+ // ---------------------------------------------------------------------------
424
+ // Confirmation
425
+ // ---------------------------------------------------------------------------
426
+ const CONFIRM_QUESTION_ID = 'migrate-go-confirm';
427
+ const CONFIRM_PROCEED = '执行迁移';
428
+ const CONFIRM_CANCEL = '取消';
429
+ /**
430
+ * Slot summary INCLUDING the route field values (api/baseURL, review M8) —
431
+ * the user approves the exact endpoints, not just route names.
432
+ */
433
+ function slotSummary(plan) {
434
+ const slots = ['chat', 'msg', 'resp', 'google']
435
+ .map((slot) => ({ slot, route: plan.routes.find((candidate) => candidate.slot === slot) }))
436
+ .filter((item) => item.route !== undefined)
437
+ .map((item) => `${item.slot}→${item.route.route} (${item.route.fields.api}, ${item.route.fields.baseURL})`);
438
+ return slots.length > 0 ? slots.join('、') : '(no route changes)';
439
+ }
440
+ /**
441
+ * Compact before→after for one `update` row (review M8): only the fields
442
+ * that actually differ, JSON-encoded values, capped so the dialog stays
443
+ * readable. Empty string when the profiles cannot be compared.
444
+ */
445
+ function compactProfileDiff(before, after) {
446
+ if (before === null || typeof before !== 'object' || after === null || typeof after !== 'object')
447
+ return '';
448
+ const b = before;
449
+ const a = after;
450
+ const parts = [];
451
+ for (const key of [...new Set([...Object.keys(b), ...Object.keys(a)])].sort((x, y) => x.localeCompare(y))) {
452
+ const bv = JSON.stringify(b[key] ?? null);
453
+ const av = JSON.stringify(a[key] ?? null);
454
+ if (bv !== av)
455
+ parts.push(`${key}: ${bv} → ${av}`);
456
+ }
457
+ const joined = parts.join('; ');
458
+ return joined.length > 240 ? `${joined.slice(0, 240)}…` : joined;
459
+ }
460
+ /**
461
+ * The per-id action rows for the confirmation question (review Major 3: the
462
+ * dialog must not stop at +n/-n counts — every add/move/update/delete id is
463
+ * listed, and ids deleted as user-written or unknown/retired carry their kind
464
+ * so the user sees exactly which handwritten models `--adopt`/
465
+ * `--prune-user-extra` will remove). Review M8: every row carries its plan
466
+ * reason and `update` rows show the before→after diff. Compact: adds and
467
+ * deletes group onto one line per route (distinct reasons joined); moves and
468
+ * updates are one line each.
469
+ */
470
+ function perIdActionLines(plan) {
471
+ const groupByRoute = (op) => {
472
+ const grouped = new Map();
473
+ for (const action of plan.idActions) {
474
+ if (action.op !== op)
475
+ continue;
476
+ const label = op === 'delete' && (action.kind === 'user-extra' || action.kind === 'unknown-retired')
477
+ ? `${action.id}(${action.kind === 'user-extra' ? '用户手写' : '未知/已下架'})`
478
+ : action.id;
479
+ const bucket = grouped.get(action.route) ?? { labels: [], reasons: [] };
480
+ bucket.labels.push(label);
481
+ if (!bucket.reasons.includes(action.reason))
482
+ bucket.reasons.push(action.reason);
483
+ grouped.set(action.route, bucket);
484
+ }
485
+ return grouped;
486
+ };
487
+ const lines = [];
488
+ for (const [route, group] of groupByRoute('add')) {
489
+ lines.push(` + 新增 → ${route}: ${group.labels.join(', ')}(${group.reasons.join(' / ')})`);
490
+ }
491
+ for (const action of plan.idActions) {
492
+ if (action.op === 'move') {
493
+ lines.push(` ~ 移动 ${action.id}: ${action.route} → ${action.to ?? action.route}(${action.reason})`);
494
+ }
495
+ }
496
+ for (const action of plan.idActions) {
497
+ if (action.op !== 'update')
498
+ continue;
499
+ // `update` rows are report-only drift (apply never overwrites a
500
+ // user-modified profile) — the dialog shows the drift it promises to show.
501
+ const diff = compactProfileDiff(action.before, action.profile);
502
+ lines.push(` ~ 更新 → ${action.route}: ${action.id}${diff !== '' ? ` ${diff}` : ''}(${action.reason})`);
503
+ }
504
+ for (const [route, group] of groupByRoute('delete')) {
505
+ lines.push(` - 删除 → ${route}: ${group.labels.join(', ')}(${group.reasons.join(' / ')})`);
506
+ }
507
+ return lines;
508
+ }
509
+ function buildConfirmQuestion(stamp, prepared, modelsStoreBackup, rewriteRefs) {
510
+ const lines = [];
511
+ lines.push('即将执行 opencode-go 一键迁移(写入前最后确认)。');
512
+ lines.push('');
513
+ lines.push('【旧条目删除/重写(legacy 残桩 → 托管槽位)】');
514
+ for (const item of prepared) {
515
+ for (const stub of item.stubs) {
516
+ lines.push(` - [${item.target.key}] ${stub.route}(手写模型 ${stub.ids.length} 个: ${stub.ids.join(', ') || '无'})`);
517
+ }
518
+ }
519
+ lines.push('');
520
+ lines.push('【逐 id 动作(保留项从略;每行附 plan 原因)】');
521
+ for (const item of prepared) {
522
+ const add = item.plan.idActions.filter((action) => action.op === 'add' || action.op === 'move').length;
523
+ const del = item.plan.idActions.filter((action) => action.op === 'delete').length;
524
+ const upd = item.plan.idActions.filter((action) => action.op === 'update').length;
525
+ const keep = item.plan.idActions.filter((action) => action.op === 'keep').length;
526
+ lines.push(` [${item.target.key}] +${add} 新增/移动、${upd} 更新(不改写)、${del} 删除、${keep} 保留;planHash ${item.plan.planHash.slice(0, 12)}…`);
527
+ const rows = perIdActionLines(item.plan);
528
+ lines.push(...(rows.length > 0 ? rows : [' (无新增/移动/更新/删除)']));
529
+ }
530
+ lines.push('');
531
+ // The B6 managed-after notice, VERBATIM from the plan it belongs to (it is
532
+ // hashed into planHash, so this text and the applied plan cannot drift
533
+ // apart): `ackManaged: true` is the user's own informed answer to exactly
534
+ // this text, never a code-signed claim.
535
+ lines.push('【托管后告知(逐 profile,取自该 profile 的迁移计划)】');
536
+ for (const item of prepared) {
537
+ lines.push(` [${item.target.key}]`);
538
+ for (const line of item.plan.managedAfterMigration.split('\n'))
539
+ lines.push(` ${line}`);
540
+ }
541
+ lines.push('');
542
+ lines.push(`【槽位】${slotSummary(prepared[0].plan)}(按 opencode.go.routes 配置;未配置的槽不创建,google 缺省不建)`);
543
+ lines.push('');
544
+ // Review M8 (the most important item): with --rewrite-refs in effect, the
545
+ // user must SEE the exact references apply is about to rewrite, before →
546
+ // after. Sessions are always report-only and never appear as rewrite rows.
547
+ if (rewriteRefs !== 'none') {
548
+ lines.push(`【引用改写(--rewrite-refs=${rewriteRefs} 生效;apply 成功后执行)】`);
549
+ const seen = new Set();
550
+ let shown = 0;
551
+ for (const item of prepared) {
552
+ for (const ref of item.plan.references) {
553
+ if (!ref.verified || !ref.rewritable || ref.reportOnly)
554
+ continue;
555
+ const dedupe = `${ref.surface}|${ref.before}|${ref.after}`;
556
+ if (seen.has(dedupe))
557
+ continue;
558
+ seen.add(dedupe);
559
+ lines.push(` - ${ref.surface}: ${ref.before} → ${ref.after}`);
560
+ shown += 1;
561
+ }
562
+ }
563
+ if (shown === 0)
564
+ lines.push(' (没有已验证、可改写的引用)');
565
+ lines.push(' 会话内历史引用只报告,永不改写。');
566
+ lines.push('');
567
+ }
568
+ lines.push('【备份文件(失败即字节恢复)】');
569
+ for (const item of prepared)
570
+ lines.push(` - ${item.patchBackup.backup}`);
571
+ if (modelsStoreBackup !== undefined)
572
+ lines.push(` - ${modelsStoreBackup}`);
573
+ lines.push(`迁移成功后: 当前 profile 的 opencode.go.enabled → true(时间戳 ${stamp})。`);
574
+ return {
575
+ id: CONFIRM_QUESTION_ID,
576
+ header: 'model-sync migrate-go',
577
+ question: lines.join('\n'),
578
+ detail: lines.join('\n'),
579
+ options: [
580
+ { label: CONFIRM_PROCEED, description: '按以上计划执行迁移;任一步失败会用本轮备份自动恢复' },
581
+ { label: CONFIRM_CANCEL, description: '不做任何写入(本轮备份保留,可手动删除)' },
582
+ ],
583
+ };
584
+ }
585
+ function failClosedConfirmMessage(reason, prepared) {
586
+ const lines = [
587
+ `migrate-go: 确认通道不可用(${reason})——零写入。`,
588
+ '按要求不跳过确认:请改用手动流程逐个 profile 执行:',
589
+ ' 1. /model-sync migrate plan [--adopt] [--prune-user-extra]',
590
+ ' 2. /model-sync migrate apply --plan <planHash> --confirm <confirmCode> --ack-managed',
591
+ ];
592
+ for (const item of prepared) {
593
+ lines.push(` [${item.target.key}] planHash: ${item.plan.planHash}`);
594
+ lines.push(` [${item.target.key}] confirmCode: ${item.plan.confirmCode}`);
595
+ }
596
+ return lines.join('\n');
597
+ }
598
+ /**
599
+ * Restore one changed patch file from its backup, but ONLY while the on-disk
600
+ * content still hashes to the post-write baseline this run recorded right
601
+ * after its last write. Anything else means another process touched the file
602
+ * after us: never overwrite it — report "concurrent modification detected,
603
+ * not restored" with the backup path so a human can decide. The write itself
604
+ * goes through the SAME atomic io (tmp + rename, mode preserved) the apply
605
+ * used — never a raw writeFile.
606
+ */
607
+ export async function restorePatchIfUnchanged(deps, record, postWriteSha) {
608
+ let currentSha;
609
+ try {
610
+ currentSha = sha256Of(await deps.fs.readFile(record.source));
611
+ }
612
+ catch {
613
+ currentSha = undefined;
614
+ }
615
+ if (postWriteSha === undefined || currentSha === undefined || currentSha !== postWriteSha) {
616
+ return {
617
+ restored: false,
618
+ line: `concurrent modification detected, not restored: ${record.source} (backup: ${record.backup}) — 人工核对后处理`,
619
+ };
620
+ }
621
+ const backupText = await deps.fs.readFile(record.backup);
622
+ await deps.patchIoFor(record.source).writeAtomic(backupText);
623
+ return { restored: true, line: `restored ${record.source} ← ${record.backup}` };
624
+ }
625
+ /**
626
+ * Remove a models-store this run CREATED, but only while its content still
627
+ * matches this run's post-write baseline; a store another process has touched
628
+ * since is left in place and reported for manual handling.
629
+ */
630
+ export async function removeStoreIfUnchanged(deps, postWriteSha) {
631
+ let currentSha;
632
+ try {
633
+ currentSha = sha256Of(await deps.fs.readFile(deps.modelsStorePath));
634
+ }
635
+ catch {
636
+ currentSha = undefined;
637
+ }
638
+ if (postWriteSha === undefined || currentSha === undefined || currentSha !== postWriteSha) {
639
+ return {
640
+ restored: false,
641
+ line: `concurrent modification detected, not restored: ${deps.modelsStorePath} (created by this run, changed since) — 人工核对后处理`,
642
+ };
643
+ }
644
+ await deps.fs.unlink(deps.modelsStorePath);
645
+ return { restored: true, line: `removed ${deps.modelsStorePath} (created by this run)` };
646
+ }
647
+ /**
648
+ * Restore the models-store from its backup through the remote-catalog store
649
+ * accessor — the SAME promise queue + cross-process lock every other
650
+ * models-store writer uses — instead of overwriting the file behind its back.
651
+ * Review M5: the restore is a whole-document BYTE replacement
652
+ * (`restoreRawDocument`: exact backup bytes staged via tmp + rename under the
653
+ * lock), not a per-key rebuild — the backup's key order survives verbatim and
654
+ * the restore is transactional. The same post-write-baseline check as the
655
+ * patch restore applies first, and a backup that is not valid JSON refuses
656
+ * loudly before anything is touched. Round 3: the baseline is ALSO
657
+ * re-verified INSIDE the store's queue + cross-process lock (the accessor's
658
+ * `expectedCurrentSha`), so a writer that landed between the pre-lock check
659
+ * and the restore is refused at the write site and reported as concurrent
660
+ * modification instead of clobbering the foreign bytes.
661
+ */
662
+ export async function restoreModelsStoreIfUnchanged(deps, backupPath, postWriteSha) {
663
+ let currentSha;
664
+ try {
665
+ currentSha = sha256Of(await deps.fs.readFile(deps.modelsStorePath));
666
+ }
667
+ catch {
668
+ currentSha = undefined;
669
+ }
670
+ if (postWriteSha === undefined || currentSha === undefined || currentSha !== postWriteSha) {
671
+ return {
672
+ restored: false,
673
+ line: `concurrent modification detected, not restored: ${deps.modelsStorePath} (backup: ${backupPath}) — 人工核对后处理`,
674
+ };
675
+ }
676
+ const backupText = await deps.fs.readFile(backupPath);
677
+ try {
678
+ JSON.parse(backupText);
679
+ }
680
+ catch (err) {
681
+ throw new Error(`backup is not valid JSON (${err instanceof Error ? err.message : String(err)})`);
682
+ }
683
+ const accessor = loadModelsStore(deps.modelsStorePath);
684
+ try {
685
+ // The pre-lock check above is advisory (it can only narrow the window);
686
+ // the authoritative re-verify runs inside the lock via expectedCurrentSha.
687
+ await accessor.restoreRawDocument(backupText, postWriteSha);
688
+ }
689
+ catch (err) {
690
+ if (err.code === STORE_RESTORE_SHA_MISMATCH) {
691
+ return {
692
+ restored: false,
693
+ line: `concurrent modification detected, not restored: ${deps.modelsStorePath} (backup: ${backupPath}) — 人工核对后处理`,
694
+ };
695
+ }
696
+ throw err;
697
+ }
698
+ return { restored: true, line: `restored ${deps.modelsStorePath} ← ${backupPath} (byte-exact via models-store lock accessor)` };
699
+ }
700
+ /**
701
+ * Re-hash every target's patch file and drop the ones whose content changed
702
+ * after their backup was taken (the backup → apply window, review Major 2
703
+ * item 3): a plan computed from stale bytes is never applied, and a dropped
704
+ * target writes nothing.
705
+ */
706
+ export async function dropStaleTargets(deps, prepared) {
707
+ const ready = [];
708
+ const stale = [];
709
+ for (const item of prepared) {
710
+ let currentSha;
711
+ try {
712
+ currentSha = sha256Of(await deps.fs.readFile(item.target.patchPath));
713
+ }
714
+ catch {
715
+ currentSha = undefined;
716
+ }
717
+ if (currentSha !== item.patchBackup.sourceSha)
718
+ stale.push({ key: item.target.key, patchPath: item.target.patchPath });
719
+ else
720
+ ready.push(item);
721
+ }
722
+ return { ready, stale };
723
+ }
724
+ /**
725
+ * Verify the shared models-store has not drifted inside the backup → apply
726
+ * window: with a backup, its content must still hash to the backup-time
727
+ * value; without one (the file did not exist at backup time), it must still
728
+ * not exist — a store another process created meanwhile must never end up
729
+ * deleted by this run's rollback path.
730
+ */
731
+ export async function verifyStoreFreshness(deps, modelsStoreBackup, storeSourceSha, storeExistedBefore) {
732
+ const rerunHint = '请重跑 /model-sync migrate-go 以基于最新内容重新规划。';
733
+ if (modelsStoreBackup !== undefined) {
734
+ let shaNow;
735
+ try {
736
+ shaNow = sha256Of(await deps.fs.readFile(deps.modelsStorePath));
737
+ }
738
+ catch {
739
+ shaNow = undefined;
740
+ }
741
+ if (shaNow !== storeSourceSha) {
742
+ return {
743
+ ok: false,
744
+ reason: `${deps.modelsStorePath} changed after its backup was taken; aborted with zero writes.\n备份仍在(人工核对可用): ${modelsStoreBackup}\n${rerunHint}`,
745
+ };
746
+ }
747
+ return { ok: true };
748
+ }
749
+ if (!storeExistedBefore) {
750
+ let existsNow = false;
751
+ try {
752
+ await deps.fs.readFile(deps.modelsStorePath);
753
+ existsNow = true;
754
+ }
755
+ catch {
756
+ existsNow = false;
757
+ }
758
+ if (existsNow) {
759
+ return { ok: false, reason: `${deps.modelsStorePath} was created by another process after this run started; aborted with zero writes.\n${rerunHint}` };
760
+ }
761
+ }
762
+ return { ok: true };
763
+ }
764
+ export async function runMigrateGoOneShot(deps, flags, invocation) {
765
+ const log = [];
766
+ const stamp = formatStamp(new Date(deps.now()));
767
+ const note = (line) => { log.push(line); };
768
+ try {
769
+ // ---- a. targets -------------------------------------------------------
770
+ const { targets, skipped } = await discoverTargets(deps, flags);
771
+ for (const line of skipped)
772
+ note(`skipped: ${line}`);
773
+ if (targets.length === 0) {
774
+ const text = ['migrate-go: nothing to migrate (no target profile).', ...skipped.map((line) => ` skipped: ${line}`)].join('\n');
775
+ return { kind: 'success', text };
776
+ }
777
+ // ---- b. credential (fail closed before any fetch or write) ------------
778
+ const credential = await deps.resolveCredential();
779
+ if (credential.value === undefined || credential.value.trim() === '') {
780
+ return {
781
+ kind: 'error',
782
+ text: [
783
+ `migrate-go: credential '${credential.ref}' 未配置——零外呼、零写入。`,
784
+ `请先配置该凭证(dsh credentials 或环境变量 ${credential.ref}),再运行 /model-sync migrate-go;`,
785
+ '或走手动流程:/model-sync migrate plan → apply。',
786
+ ].join('\n'),
787
+ };
788
+ }
789
+ const apiKey = credential.value;
790
+ // ---- c. plans (shared listing, per-target plan via the existing builder)
791
+ let entries;
792
+ try {
793
+ entries = await deps.resolveEntries(apiKey);
794
+ }
795
+ catch (err) {
796
+ return { kind: 'error', text: `migrate-go: official listing unavailable (${err instanceof Error ? err.message : String(err)}); zero writes` };
797
+ }
798
+ const publicCatalogIds = await deps.resolvePublicCatalogIds(apiKey, entries);
799
+ const shared = { entries, publicCatalogIds, keyFingerprint: fingerprintKey(apiKey.trim()) };
800
+ const prepared = [];
801
+ const notMigratable = [];
802
+ for (const target of targets) {
803
+ const { migrateDeps, tracker } = buildTargetDeps(deps, target, shared, flags);
804
+ const record = await migrateDeps.migrationStore.read().catch(() => undefined);
805
+ const plan = buildMigrationPlanFromDeps(migrateDeps, record);
806
+ if (plan.state !== 'legacy-inherit' && plan.state !== 'legacy-inline' && plan.state !== 'drifted') {
807
+ notMigratable.push(`${target.key}: state=${plan.state} (nothing to migrate)`);
808
+ continue;
809
+ }
810
+ prepared.push({ target, plan, migrateDeps, tracker, stubs: target.stubs, patchBackup: { source: '', backup: '', sourceSha: '' } });
811
+ }
812
+ for (const line of notMigratable)
813
+ note(`not migratable: ${line}`);
814
+ if (prepared.length === 0) {
815
+ const text = [
816
+ 'migrate-go: nothing to apply — no target profile is in a migratable state.',
817
+ ...notMigratable.map((line) => ` ${line}`),
818
+ ...skipped.map((line) => ` skipped: ${line}`),
819
+ ].join('\n');
820
+ return { kind: 'success', text };
821
+ }
822
+ // ---- d. backups BEFORE any write --------------------------------------
823
+ const patchBackups = [];
824
+ let modelsStoreBackup;
825
+ let storeSourceSha;
826
+ let storeExistedBefore = false;
827
+ try {
828
+ for (const item of prepared) {
829
+ const record = await backupFile(deps, item.target.patchPath, stamp, item.target.dir, PATCH_BACKUP_PATTERN);
830
+ patchBackups.push(record);
831
+ item.patchBackup = record;
832
+ note(`backup: ${record.source} → ${record.backup}`);
833
+ }
834
+ let storeText;
835
+ try {
836
+ storeText = await deps.fs.readFile(deps.modelsStorePath);
837
+ }
838
+ catch (err) {
839
+ if (!isEnoent(err))
840
+ throw err;
841
+ }
842
+ storeExistedBefore = storeText !== undefined;
843
+ if (storeText !== undefined) {
844
+ const base = `${deps.modelsStorePath}.bak.${stamp}`;
845
+ const homeDir = deps.home;
846
+ const storeMode = (await deps.fs.stat(deps.modelsStorePath))?.mode;
847
+ const backupPath = await writeExclusiveBackup(deps.fs, base, storeText, storeMode);
848
+ modelsStoreBackup = backupPath;
849
+ storeSourceSha = sha256Of(storeText);
850
+ note(`backup: ${deps.modelsStorePath} → ${backupPath}`);
851
+ await pruneBackups(deps.fs, homeDir, STORE_BACKUP_PATTERN);
852
+ }
853
+ }
854
+ catch (err) {
855
+ return { kind: 'error', text: `migrate-go: ${err instanceof Error ? err.message : String(err)}; zero writes` };
856
+ }
857
+ // ---- d2. staleness re-verify (the backup → apply window) --------------
858
+ const { ready, stale } = await dropStaleTargets(deps, prepared);
859
+ for (const item of stale) {
860
+ note(`stale: [${item.key}] ${item.patchPath} changed after its backup was taken; target aborted (zero writes)`);
861
+ }
862
+ if (ready.length === 0) {
863
+ return {
864
+ kind: 'success',
865
+ text: [
866
+ 'migrate-go: nothing to apply — every target changed after its backup was taken; zero writes.',
867
+ '请重跑 /model-sync migrate-go 以基于最新内容重新规划。',
868
+ ...patchBackups.map((record) => ` backup kept: ${record.backup}`),
869
+ ].join('\n'),
870
+ };
871
+ }
872
+ const storeFresh = await verifyStoreFreshness(deps, modelsStoreBackup, storeSourceSha, storeExistedBefore);
873
+ if (!storeFresh.ok) {
874
+ note(`stale: ${storeFresh.reason.split('\n')[0]}`);
875
+ return { kind: 'error', text: `migrate-go: ${storeFresh.reason}` };
876
+ }
877
+ // ---- e. ONE confirmation (fail closed without the channel) ------------
878
+ const ask = deps.resolveAsk();
879
+ if (ask === undefined || typeof ask.ask !== 'function') {
880
+ return { kind: 'error', text: failClosedConfirmMessage('userQuestions 服务缺失(NO_PROVIDER / 未注册)', ready) };
881
+ }
882
+ let answers;
883
+ try {
884
+ answers = await ask.ask({
885
+ questions: [buildConfirmQuestion(stamp, ready, modelsStoreBackup, flags.rewriteRefs)],
886
+ ...(invocation.agent === undefined ? {} : { agent: invocation.agent }),
887
+ ...(invocation.signal === undefined ? {} : { signal: invocation.signal }),
888
+ });
889
+ }
890
+ catch (err) {
891
+ const code = typeof err.code === 'string' ? err.code : undefined;
892
+ const reason = err instanceof Error ? `${err.message}${code !== undefined ? ` [${code}]` : ''}` : String(err);
893
+ note(`confirm failed: ${reason}`);
894
+ return { kind: 'error', text: failClosedConfirmMessage(reason, ready) };
895
+ }
896
+ const backupListLines = () => [...patchBackups.map((record) => record.backup), ...(modelsStoreBackup !== undefined ? [modelsStoreBackup] : [])]
897
+ .map((path) => ` ${path}`);
898
+ const answer = (answers.answers ?? []).find((item) => item.id === CONFIRM_QUESTION_ID);
899
+ const selected = answer?.selected ?? [];
900
+ // Abort defense in depth (review Minor 5): the ask seam can return after
901
+ // the invocation was already aborted — re-check here and treat it as a
902
+ // cancel, zero writes.
903
+ if (invocation.signal?.aborted === true) {
904
+ note('confirm: aborted (signal aborted when ask returned)');
905
+ return {
906
+ kind: 'success',
907
+ text: ['migrate-go: 确认请求已中止(signal aborted)——按取消处理,零写入。', '本轮备份已生成(保留,可手动删除):', ...backupListLines()].join('\n'),
908
+ };
909
+ }
910
+ const choseProceed = selected.includes(CONFIRM_PROCEED);
911
+ const choseCancel = selected.includes(CONFIRM_CANCEL);
912
+ if (!choseProceed || choseCancel) {
913
+ // Blank/skip and an answer carrying BOTH labels are ambiguous: cancel
914
+ // and ask the user to rerun — proceed never wins a contested answer.
915
+ const ambiguous = choseProceed && choseCancel;
916
+ note(ambiguous ? 'confirm: ambiguous (both labels selected)' : 'confirm: cancelled / blank');
917
+ return {
918
+ kind: 'success',
919
+ text: [
920
+ ambiguous
921
+ ? 'migrate-go: 两个选项同时被选中,答案有歧义——按取消处理,零写入。请重跑后再确认。'
922
+ : 'migrate-go: 已取消——零写入。',
923
+ '本轮备份已生成(保留,可手动删除):',
924
+ ...backupListLines(),
925
+ ].join('\n'),
926
+ };
927
+ }
928
+ note('confirm: approved');
929
+ // ---- f. apply (existing engine; consent triple computed HERE) ---------
930
+ const applied = [];
931
+ const changedPatches = [];
932
+ let modelsStoreChanged = false;
933
+ let modelsStoreCreated = false;
934
+ let storePostWriteSha;
935
+ let failure;
936
+ for (const item of ready) {
937
+ let resultText;
938
+ let resultOk = false;
939
+ try {
940
+ const result = await applyMigration({ planHash: item.plan.planHash, confirmCode: item.plan.confirmCode, ackManaged: true }, item.migrateDeps);
941
+ resultText = result.text;
942
+ resultOk = result.ok;
943
+ }
944
+ catch (err) {
945
+ resultText = err instanceof Error ? err.message : String(err);
946
+ }
947
+ // Track changes BEFORE judging the outcome: applyMigration may have
948
+ // mutated settings/stores and then failed (its internal logical restore
949
+ // mutates too) — those files must be byte-restored regardless.
950
+ if (item.tracker.patchChanged === true) {
951
+ changedPatches.push({ backup: item.patchBackup, isCurrent: item.target.isCurrent, tracker: item.tracker });
952
+ }
953
+ if (item.tracker.storeChanged === true) {
954
+ modelsStoreChanged = true;
955
+ // The store backup only exists when the file pre-dated the run; a
956
+ // store created by this run is restored by removing it again.
957
+ modelsStoreCreated ||= modelsStoreBackup === undefined;
958
+ // Baseline the store's post-write bytes (read right after the write
959
+ // through the lock accessor) for the restore path's content check.
960
+ try {
961
+ storePostWriteSha = sha256Of(await deps.fs.readFile(deps.modelsStorePath));
962
+ }
963
+ catch {
964
+ storePostWriteSha = undefined;
965
+ }
966
+ }
967
+ for (const line of (resultText ?? '').split('\n'))
968
+ note(`[${item.target.key}] apply: ${line}`);
969
+ if (!resultOk) {
970
+ failure = { target: item.target, detail: resultText ?? 'unknown apply failure' };
971
+ break;
972
+ }
973
+ applied.push(item);
974
+ }
975
+ // ---- atomicity: restore everything this run changed -------------------
976
+ if (failure !== undefined) {
977
+ const restore = [];
978
+ let restoredHostSeamProfile = false;
979
+ for (const changed of [...changedPatches].reverse()) {
980
+ try {
981
+ const outcome = await restorePatchIfUnchanged(deps, changed.backup, changed.tracker.patchPostWriteSha);
982
+ restore.push(outcome.line);
983
+ restoredHostSeamProfile ||= outcome.restored && changed.isCurrent;
984
+ }
985
+ catch (err) {
986
+ restore.push(`RESTORE FAILED for ${changed.backup.source}: ${err instanceof Error ? err.message : String(err)} (backup: ${changed.backup.backup})`);
987
+ }
988
+ }
989
+ if (modelsStoreCreated) {
990
+ try {
991
+ const outcome = await removeStoreIfUnchanged(deps, storePostWriteSha);
992
+ restore.push(outcome.line);
993
+ }
994
+ catch (err) {
995
+ restore.push(`RESTORE FAILED for ${deps.modelsStorePath}: ${err instanceof Error ? err.message : String(err)}`);
996
+ }
997
+ }
998
+ else if (modelsStoreChanged && modelsStoreBackup !== undefined) {
999
+ try {
1000
+ const outcome = await restoreModelsStoreIfUnchanged(deps, modelsStoreBackup, storePostWriteSha);
1001
+ restore.push(outcome.line);
1002
+ }
1003
+ catch (err) {
1004
+ restore.push(`RESTORE FAILED for ${deps.modelsStorePath}: ${err instanceof Error ? err.message : String(err)} (backup: ${modelsStoreBackup})`);
1005
+ }
1006
+ }
1007
+ const text = [
1008
+ `migrate-go: FAILED at apply for [${failure.target.key}] — 已停止,改动文件按本轮备份恢复(逐文件核对结果见下)。`,
1009
+ `失败步骤: apply;原始错误: ${failure.detail}`,
1010
+ '恢复结果:',
1011
+ ...(restore.length > 0 ? restore.map((line) => ` ${line}`) : [' (no file had been written)']),
1012
+ ...(restoredHostSeamProfile
1013
+ ? ['注意: 当前 profile 的写入经宿主 settings 服务落地,恢复后宿主内存态可能与磁盘文件短暂不一致;如需核对请重启该 profile 或运行 /model-sync migrate status。']
1014
+ : []),
1015
+ `日志: ${logPathOf(deps, stamp)}`,
1016
+ ].join('\n');
1017
+ await writeRunLog(deps, stamp, log, text);
1018
+ return { kind: 'error', text };
1019
+ }
1020
+ // ---- h. flip opencode.go.enabled in the CURRENT profile ---------------
1021
+ let enabledLine;
1022
+ if (deps.hostSettings === undefined) {
1023
+ enabledLine = 'opencode.go.enabled 未写入(宿主 settings 服务不可用)— 请手动在该 profile 的 dsh-model-sync 配置里设 opencode.go.enabled: true';
1024
+ }
1025
+ else {
1026
+ enabledLine = await flipGoEnabled(deps);
1027
+ }
1028
+ // ---- report + log ------------------------------------------------------
1029
+ const lines = [];
1030
+ lines.push(`migrate-go: ${applied.length} profile(s) migrated.`);
1031
+ for (const item of applied) {
1032
+ const postPlan = buildMigrationPlanFromDeps(item.migrateDeps, await item.migrateDeps.migrationStore.read().catch(() => undefined));
1033
+ const desiredCount = postPlan.routes.reduce((sum, route) => sum + route.desired.length, 0);
1034
+ const add = item.plan.idActions.filter((action) => action.op === 'add' || action.op === 'move').length;
1035
+ const del = item.plan.idActions.filter((action) => action.op === 'delete').length;
1036
+ lines.push(` [${item.target.key}] slots: ${slotSummary(item.plan)}; +${add}/-${del}; ${desiredCount} managed models; state after: ${postPlan.state}`);
1037
+ lines.push(` backup: ${item.patchBackup.backup}`);
1038
+ lines.push(` rollback: /model-sync migrate rollback --plan ${item.plan.planHash}`);
1039
+ }
1040
+ if (modelsStoreBackup !== undefined)
1041
+ lines.push(` models-store backup: ${modelsStoreBackup}`);
1042
+ lines.push(` ${enabledLine}`);
1043
+ for (const line of skipped)
1044
+ lines.push(` skipped: ${line}`);
1045
+ const logPath = await writeRunLog(deps, stamp, log, undefined);
1046
+ if (logPath !== undefined)
1047
+ lines.push(` log: ${logPath}`);
1048
+ return { kind: 'success', text: lines.join('\n') };
1049
+ }
1050
+ catch (err) {
1051
+ const message = err instanceof Error ? err.message : String(err);
1052
+ await writeRunLog(deps, stamp, [...log, `unhandled error: ${message}`], undefined);
1053
+ return { kind: 'error', text: `migrate-go failed: ${message}` };
1054
+ }
1055
+ }
1056
+ // ---------------------------------------------------------------------------
1057
+ // Enabled flip + log
1058
+ // ---------------------------------------------------------------------------
1059
+ async function flipGoEnabled(deps) {
1060
+ const settings = deps.hostSettings;
1061
+ try {
1062
+ if (typeof settings.update === 'function') {
1063
+ await settings.update('dsh-model-sync', { opencode: { go: { enabled: true } } });
1064
+ return 'opencode.go.enabled → true (written through settings.update).';
1065
+ }
1066
+ await settings.mutate('dsh-model-sync', [{ op: 'set', path: ['opencode', 'go', 'enabled'], value: true }]);
1067
+ return 'opencode.go.enabled → true (written through settings.mutate).';
1068
+ }
1069
+ catch (err) {
1070
+ const message = err instanceof Error ? err.message : String(err);
1071
+ return `opencode.go.enabled 不可写(${message})— 请手动在该 profile 的 dsh-model-sync 配置里设 opencode.go.enabled: true`;
1072
+ }
1073
+ }
1074
+ function logPathOf(deps, stamp) {
1075
+ return join(deps.home, 'storages', 'dsh-model-sync', `migrate-go-${stamp}.log`);
1076
+ }
1077
+ /** Full-detail run log. A failed log write only warns — never fails the run. */
1078
+ async function writeRunLog(deps, stamp, log, extra) {
1079
+ const path = logPathOf(deps, stamp);
1080
+ try {
1081
+ await deps.fs.mkdir(join(path, '..'), { recursive: true });
1082
+ const body = [...log, ...(extra !== undefined ? ['', ...extra.split('\n')] : [])].join('\n');
1083
+ await deps.fs.writeFile(path, `${body}\n`);
1084
+ return path;
1085
+ }
1086
+ catch (err) {
1087
+ deps.logger.warn('migrate-go: log write failed (%s): %s', path, err instanceof Error ? err.message : String(err));
1088
+ return undefined;
1089
+ }
1090
+ }
1091
+ function isEnoent(err) {
1092
+ return typeof err === 'object' && err !== null && err.code === 'ENOENT';
1093
+ }
1094
+ //# sourceMappingURL=opencode-go-one-shot.js.map