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