@aiwayds/dsh-model-sync 0.12.1 → 0.13.1

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