@aiwayds/dsh-model-sync 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +9 -4
  3. package/README.zh-CN.md +9 -4
  4. package/lib/builtin-catalog-snapshot.d.ts +5 -1
  5. package/lib/builtin-catalog-snapshot.js +13 -10
  6. package/lib/builtin-catalog-snapshot.js.map +1 -1
  7. package/lib/index.d.ts +366 -0
  8. package/lib/index.js +729 -13
  9. package/lib/index.js.map +1 -1
  10. package/lib/opencode-go-diagnose.d.ts +74 -0
  11. package/lib/opencode-go-diagnose.js +146 -0
  12. package/lib/opencode-go-diagnose.js.map +1 -0
  13. package/lib/opencode-go-grouping.d.ts +29 -0
  14. package/lib/opencode-go-grouping.js +77 -0
  15. package/lib/opencode-go-grouping.js.map +1 -0
  16. package/lib/opencode-go-journal.d.ts +110 -0
  17. package/lib/opencode-go-journal.js +406 -0
  18. package/lib/opencode-go-journal.js.map +1 -0
  19. package/lib/opencode-go-migrate.d.ts +343 -0
  20. package/lib/opencode-go-migrate.js +1300 -0
  21. package/lib/opencode-go-migrate.js.map +1 -0
  22. package/lib/opencode-go-migration.d.ts +227 -0
  23. package/lib/opencode-go-migration.js +384 -0
  24. package/lib/opencode-go-migration.js.map +1 -0
  25. package/lib/opencode-go-planner.d.ts +153 -0
  26. package/lib/opencode-go-planner.js +339 -0
  27. package/lib/opencode-go-planner.js.map +1 -0
  28. package/lib/opencode-go-profile.d.ts +57 -0
  29. package/lib/opencode-go-profile.js +103 -0
  30. package/lib/opencode-go-profile.js.map +1 -0
  31. package/lib/opencode-go-scheduler.d.ts +128 -0
  32. package/lib/opencode-go-scheduler.js +241 -0
  33. package/lib/opencode-go-scheduler.js.map +1 -0
  34. package/lib/opencode-go-source.d.ts +117 -0
  35. package/lib/opencode-go-source.js +331 -0
  36. package/lib/opencode-go-source.js.map +1 -0
  37. package/lib/opencode-go-store.d.ts +18 -0
  38. package/lib/opencode-go-store.js +68 -0
  39. package/lib/opencode-go-store.js.map +1 -0
  40. package/lib/opencode-go-sync.d.ts +94 -0
  41. package/lib/opencode-go-sync.js +364 -0
  42. package/lib/opencode-go-sync.js.map +1 -0
  43. package/lib/opencode-go-writer.d.ts +132 -0
  44. package/lib/opencode-go-writer.js +966 -0
  45. package/lib/opencode-go-writer.js.map +1 -0
  46. package/lib/provider-native.d.ts +3 -1
  47. package/lib/provider-native.js +4 -2
  48. package/lib/provider-native.js.map +1 -1
  49. package/lib/remote-catalog.d.ts +37 -0
  50. package/lib/remote-catalog.js +261 -3
  51. package/lib/remote-catalog.js.map +1 -1
  52. package/package.json +18 -18
  53. package/src/builtin-catalog-snapshot.ts +18 -11
  54. package/src/index.ts +873 -12
  55. package/src/opencode-go-diagnose.ts +222 -0
  56. package/src/opencode-go-grouping.ts +97 -0
  57. package/src/opencode-go-journal.ts +458 -0
  58. package/src/opencode-go-migrate.ts +1694 -0
  59. package/src/opencode-go-migration.ts +552 -0
  60. package/src/opencode-go-planner.ts +505 -0
  61. package/src/opencode-go-profile.ts +114 -0
  62. package/src/opencode-go-scheduler.ts +315 -0
  63. package/src/opencode-go-source.ts +424 -0
  64. package/src/opencode-go-store.ts +73 -0
  65. package/src/opencode-go-sync.ts +503 -0
  66. package/src/opencode-go-writer.ts +1189 -0
  67. package/src/provider-native.ts +3 -1
  68. package/src/remote-catalog.ts +293 -3
package/src/index.ts CHANGED
@@ -25,6 +25,11 @@ import type { Context } from '@deepseek-ai/cordis'
25
25
  // settings service; alpha.3 removed the settingsNamespace() helper this file
26
26
  // used to import.
27
27
  import type {} from '@deepseek-ai/dsh-settings'
28
+ // Type-only side-effect import: loads dsh-credentials' `declare module
29
+ // '@deepseek-ai/cordis'` Events augmentation, which types the
30
+ // `credentials/reference-updated` listener used for backoff reset. Erased at
31
+ // emit — the host provides the service at runtime.
32
+ import type {} from '@deepseek-ai/dsh-credentials/types'
28
33
  // Types only (erased at emit); dsh-commands is an optional peer, so hosts
29
34
  // without it still load this plugin — see the guarded registration below.
30
35
  import type { CommandDefinition, CommandResult } from '@deepseek-ai/dsh-commands'
@@ -49,7 +54,31 @@ import {
49
54
  } from './writer.ts'
50
55
  import { BUILTIN_CATALOG_SNAPSHOT } from './builtin-catalog-snapshot.ts'
51
56
  import { refreshLiveCatalog, getLiveBuiltinCatalogForRoute } from './live-catalog.ts'
52
- import { checkRouteCredential, type RouteCredentialContext } from './route-credential.ts'
57
+ import { checkRouteCredential, deriveKeyRef, type RouteCredentialContext } from './route-credential.ts'
58
+ import { OPENCODE_GO_MODELS_URL, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES, fetchGoOfficialModels, fetchGoPublicCatalogIds, fingerprintKey, type GoFetchLike, type GoModelRecord } from './opencode-go-source.ts'
59
+ import { GO_SLOT_ROUTES, type GoRouteSlot } from './opencode-go-grouping.ts'
60
+ import { createModelsStoreOwnershipStore } from './opencode-go-store.ts'
61
+ import {
62
+ createModelsStoreJournalStore,
63
+ type GoJournalStore,
64
+ } from './opencode-go-journal.ts'
65
+ import {
66
+ GO_FETCH_SERVICE,
67
+ GO_OWNERSHIP_STORE_SERVICE,
68
+ GO_OVERRIDE_STORER_SERVICE,
69
+ runGoSyncRound,
70
+ type GoSyncRoundResult,
71
+ type GoSyncRuntimeConfig,
72
+ } from './opencode-go-sync.ts'
73
+ import type { GoOverrideStorer, GoOwnershipStore } from './opencode-go-writer.ts'
74
+ import {
75
+ GO_SCHEDULER_RANDOM_SERVICE,
76
+ GO_SCHEDULER_TIMERS_SERVICE,
77
+ GoScheduler,
78
+ type GoSchedulerConfig,
79
+ type GoSchedulerRandom,
80
+ type GoSchedulerTimers,
81
+ } from './opencode-go-scheduler.ts'
53
82
  import {
54
83
  PROVIDER_NATIVE_ENDPOINTS,
55
84
  fetchProviderNativeModels,
@@ -63,12 +92,58 @@ import {
63
92
  type LegacyImportLogger,
64
93
  type SettingsUpdateSeam,
65
94
  } from './legacy-import.ts'
95
+ import { runGoDiagnostic, formatGoDiagnosticReport } from './opencode-go-diagnose.ts'
96
+ import {
97
+ PROFILE_IDENTITY_REQUIRED_MESSAGE,
98
+ PROFILE_IDENTITY_STATUS_HINT,
99
+ resolveProfileKey,
100
+ } from './opencode-go-profile.ts'
101
+ import {
102
+ GO_MIGRATION_STORE_SERVICE,
103
+ appliedFingerprintFieldsOf,
104
+ createModelsStoreMigrationStateStore,
105
+ goLedgerManagedIds,
106
+ isGoRoute,
107
+ MIGRATION_GATE_HINT,
108
+ migrationStatusOf,
109
+ readGoProviderSections,
110
+ routeWriter,
111
+ unclaimedRecordState,
112
+ type MigrationRecord,
113
+ type MigrationStatus,
114
+ type MigrationStateStore,
115
+ type UnclaimedMigrationRecord,
116
+ } from './opencode-go-migration.ts'
117
+ import { goOwnershipKey } from './opencode-go-planner.ts'
118
+ import {
119
+ applyMigration,
120
+ buildMigrationPlanFromDeps,
121
+ formatMigrationPlan,
122
+ migrationStatusReport,
123
+ rollbackMigration,
124
+ type MigrateDeps,
125
+ type ReferenceRewrite,
126
+ type RewriteRefMode,
127
+ } from './opencode-go-migrate.ts'
66
128
 
67
129
  export const name = 'dsh-model-sync'
68
130
 
69
131
  /** The settings seam this plugin consumes (its own config namespace). */
70
132
  export const inject = ['settings']
71
133
 
134
+ /** P1d-2 seams: injected official entries (plan/apply) and optional reference writer. */
135
+ export const GO_MIGRATION_ENTRIES_SERVICE = 'goMigrationEntries'
136
+ export const GO_MIGRATION_REF_WRITER_SERVICE = 'goMigrationRefWriter'
137
+ /** Public (unauthenticated) official catalog ids for id classification (design §14.2).
138
+ * `undefined` ⇒ fail-closed `unclassified`. Tests inject an array/function. */
139
+ export const GO_MIGRATION_PUBLIC_CATALOG_SERVICE = 'goMigrationPublicCatalog'
140
+ /** Capability flag: when true, `--adopt` is refused and plan mode is adopt-disabled. */
141
+ export const GO_MIGRATION_ADOPT_DISABLED_SERVICE = 'goMigrationAdoptDisabled'
142
+ /** Optional override for the single-flight check (tests inject an in-flight mutex). */
143
+ export const GO_MIGRATION_MUTEX_SERVICE = 'goMigrationMutex'
144
+ /** O1/C2 seam: injected write-ahead journal store (tests use a temp-dir store). */
145
+ export const GO_JOURNAL_STORE_SERVICE = 'goJournalStore'
146
+
72
147
  // dsh-settings 0.1.7 rewrote the seam: the runtime register(ns, schema) call
73
148
  // is gone, and a plugin's settings form is projected from its exported
74
149
  // `Config` schema — the namespace IS the profile entry id. The bundle patch
@@ -128,6 +203,49 @@ export const Config = z.object({
128
203
  * a re-emitted retired id is a model the 0.1.7 host no longer resolves.
129
204
  */
130
205
  keepDeprecatedBuiltin: z.boolean().default(false).volatile(),
206
+
207
+ /**
208
+ * OpenCode Go / Zen configuration contract (design §6.2.6). Published in one
209
+ * Config schema in P1: read-only subset (go.enabled/ref/modelsUrl/
210
+ * intervalMinutes, zen.enabled/ref/mode/modelsUrl) plus the write-side subset
211
+ * (go.routes/adoptExisting/pinnedModels/confirmRemovals,
212
+ * zen.routes/seedFromBuiltin). Defaults are byte-for-byte the P0 constants —
213
+ * `modelsUrl` and `ref` are imported from the P0 modules so a P0→P1 drift is
214
+ * impossible. Zen stays login-only with no modelsUrl by default (design A5).
215
+ * Nested leaves are `.volatile()` (host settings can edit them); the parent
216
+ * objects are not, because schemastery forbids a volatile field under an
217
+ * enclosing volatile field.
218
+ */
219
+ opencode: z.object({
220
+ go: z.object({
221
+ enabled: z.boolean().default(false).volatile(),
222
+ ref: z.string().default(deriveKeyRef('opencode-go')).volatile(),
223
+ modelsUrl: z.string().default(OPENCODE_GO_MODELS_URL).volatile(),
224
+ intervalMinutes: z.number().step(1).min(15).default(OPENCODE_GO_DEFAULT_INTERVAL_MINUTES).volatile(),
225
+ adoptExisting: z.boolean().default(false).volatile(),
226
+ pinnedModels: z.array(z.string()).default([]).volatile(),
227
+ routes: z.object({
228
+ chat: z.string().default('opencode-go').volatile(),
229
+ msg: z.string().default('opencode-go-msg').volatile(),
230
+ resp: z.string().default('opencode-go-resp').volatile(),
231
+ google: z.string().default('opencode-go-google').volatile(),
232
+ }).default({}),
233
+ confirmRemovals: z.number().step(1).min(2).default(2).volatile(),
234
+ }).default({}),
235
+ zen: z.object({
236
+ enabled: z.boolean().default(true).volatile(),
237
+ ref: z.string().default('OPENCODE_API_KEY').volatile(),
238
+ mode: z.union(['login-only', 'routes']).default('login-only').volatile(),
239
+ /** No proven listing endpoint; without it routes mode is unsupported. */
240
+ modelsUrl: z.string().volatile(),
241
+ seedFromBuiltin: z.boolean().default(false).volatile(),
242
+ routes: z.object({
243
+ chat: z.string().default('opencode-zen').volatile(),
244
+ msg: z.string().default('opencode-zen-msg').volatile(),
245
+ resp: z.string().default('opencode-zen-resp').volatile(),
246
+ }).default({}),
247
+ }).default({}),
248
+ }).default({}),
131
249
  })
132
250
 
133
251
  /**
@@ -154,6 +272,26 @@ interface ModelSyncConfigValue {
154
272
  forceMaxReasoningEffort: VolatileRef<boolean>
155
273
  providerNativeFetch: VolatileRef<boolean>
156
274
  keepDeprecatedBuiltin: VolatileRef<boolean>
275
+ opencode: {
276
+ go: {
277
+ enabled: VolatileRef<boolean>
278
+ ref: VolatileRef<string>
279
+ modelsUrl: VolatileRef<string>
280
+ intervalMinutes: VolatileRef<number>
281
+ adoptExisting: VolatileRef<boolean>
282
+ pinnedModels: VolatileRef<readonly string[]>
283
+ routes: Record<'chat' | 'msg' | 'resp' | 'google', VolatileRef<string>>
284
+ confirmRemovals: VolatileRef<number>
285
+ }
286
+ zen: {
287
+ enabled: VolatileRef<boolean>
288
+ ref: VolatileRef<string>
289
+ mode: VolatileRef<'login-only' | 'routes'>
290
+ modelsUrl: VolatileRef<string | undefined>
291
+ seedFromBuiltin: VolatileRef<boolean>
292
+ routes: Record<'chat' | 'msg' | 'resp', VolatileRef<string>>
293
+ }
294
+ }
157
295
  }
158
296
 
159
297
  /** The llm seam as this plugin needs it (overlay mode). */
@@ -170,6 +308,11 @@ interface CatalogSeam {
170
308
  /** The `modelSync` service surfaced to UIs: run one refresh round and get the report. */
171
309
  export interface ModelSyncService {
172
310
  syncNow(): Promise<string>
311
+ /** P1d-2: host-service mirrors of the migrate commands (design §14.5). */
312
+ migratePlan?(options?: { adopt?: boolean; rewriteRefs?: RewriteRefMode; pruneUserExtra?: boolean }): Promise<string>
313
+ migrateApply?(args: { planHash?: string; confirmCode?: string; ackManaged?: boolean }): Promise<string>
314
+ migrateRollback?(args: { planHash?: string }): Promise<string>
315
+ migrateStatus?(): Promise<string>
173
316
  }
174
317
 
175
318
  /**
@@ -193,6 +336,120 @@ const DEFAULT_ROUTES = [
193
336
  * runtime surface; subject to change without notice. */
194
337
  export const DEFAULT_ROUTES_LIST = DEFAULT_ROUTES
195
338
 
339
+ // ---------------------------------------------------------------------------
340
+ // P1c go config / dependency helpers (design §6.2.6)
341
+ // ---------------------------------------------------------------------------
342
+
343
+ /** Read a volatile Config leaf, tolerating hosts/tests that hand a plain value. */
344
+ function readVolatile<T>(slot: unknown, fallback: T): T {
345
+ if (slot === undefined) return fallback
346
+ if (typeof slot === 'object' && slot !== null && typeof (slot as { get?: unknown }).get === 'function') {
347
+ return (slot as { get(): T }).get()
348
+ }
349
+ return slot as T
350
+ }
351
+
352
+ /**
353
+ * Project the go Config subset for one round. Reads the live volatile refs, so
354
+ * a settings edit takes effect on the next round without a remount. The
355
+ * defensive shape also keeps older/partial fake configs (no `opencode` block)
356
+ * on the default zero-behavior path instead of throwing during apply().
357
+ */
358
+ function readGoRuntimeConfig(config: ModelSyncConfigValue): { enabled: boolean; value: GoSyncRuntimeConfig } {
359
+ const raw = config as unknown as Record<string, unknown>
360
+ const opencode = raw.opencode as Record<string, unknown> | undefined
361
+ const go = opencode?.go as Record<string, unknown> | undefined
362
+ const rawRoutes = go?.routes as Record<string, unknown> | undefined
363
+ const routes = Object.fromEntries(
364
+ (Object.keys(GO_SLOT_ROUTES) as GoRouteSlot[]).map((slot) => [
365
+ slot,
366
+ readVolatile(rawRoutes?.[slot], GO_SLOT_ROUTES[slot]),
367
+ ]),
368
+ ) as GoSyncRuntimeConfig['routes']
369
+ return {
370
+ enabled: readVolatile(go?.enabled, false),
371
+ value: {
372
+ enabled: readVolatile(go?.enabled, false),
373
+ ref: readVolatile(go?.ref, deriveKeyRef('opencode-go')),
374
+ modelsUrl: readVolatile(go?.modelsUrl, OPENCODE_GO_MODELS_URL),
375
+ routes,
376
+ pinnedModels: readVolatile(go?.pinnedModels, [] as readonly string[]),
377
+ confirmRemovals: readVolatile(go?.confirmRemovals, 2),
378
+ adoptExisting: readVolatile(go?.adoptExisting, false),
379
+ },
380
+ }
381
+ }
382
+
383
+ /**
384
+ * Project the go scheduling subset (design §6.3). `intervalMinutes` is the go
385
+ * field (default 60, floor 15, enforced by the scheduler); the startup delay is
386
+ * the shared top-level field the design names for startup jitter.
387
+ *
388
+ * `enabled` defaults to false — the design §6.2.6 value, unchanged by P1d-1.
389
+ * Migration zero-write is now enforced independently by routeWriter (§14.6 /
390
+ * §14.7) on every write path, so this default is a product choice, not the
391
+ * only protection. All scheduler paths are still gated by this value.
392
+ */
393
+ function readGoSchedulerConfig(config: ModelSyncConfigValue): GoSchedulerConfig {
394
+ const raw = config as unknown as Record<string, unknown>
395
+ const opencode = raw.opencode as Record<string, unknown> | undefined
396
+ const go = opencode?.go as Record<string, unknown> | undefined
397
+ return {
398
+ enabled: readVolatile(go?.enabled, false),
399
+ intervalMinutes: readVolatile(go?.intervalMinutes, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES),
400
+ startupDelaySeconds: readVolatile(raw.startupDelaySeconds, 5),
401
+ }
402
+ }
403
+
404
+ // ---------------------------------------------------------------------------
405
+ // P1d-1: own-write reentry marker + migration status reads (design §14.7.2)
406
+ // ---------------------------------------------------------------------------
407
+
408
+ /** Revision-stamped marker of the last settings write this plugin performed. */
409
+ interface OwnWriteMarker {
410
+ ns: string
411
+ revision: number
412
+ at: number
413
+ }
414
+
415
+ interface OwnWriteTracker {
416
+ /** Called after a successful settings.mutate, with the post-write revision. */
417
+ record(ns: string): void
418
+ /** True when a document-updated event is the echo of our own write. */
419
+ matches(ns: string, eventRevision?: number): boolean
420
+ }
421
+
422
+ /**
423
+ * Revision-keyed (not time-window-keyed) reentry marker. `readRevision` reads
424
+ * the live descriptor after a mutate, so the marker always holds the revision
425
+ * the host stamped on OUR write; a later event for the same ns+revision can
426
+ * only be that write's echo (§14.7.2 items 1/5). `now` is injected so tests
427
+ * never depend on a wall clock.
428
+ */
429
+ function createOwnWriteTracker(
430
+ readRevision: (ns: string) => number | undefined,
431
+ now: () => number,
432
+ ): OwnWriteTracker {
433
+ let last: OwnWriteMarker | undefined
434
+ const tracker: OwnWriteTracker = {
435
+ record(ns) {
436
+ const revision = readRevision(ns)
437
+ if (revision !== undefined) last = { ns, revision, at: now() }
438
+ },
439
+ matches(ns, eventRevision) {
440
+ if (last === undefined || last.ns !== ns) return false
441
+ if (eventRevision !== undefined) return eventRevision === last.revision
442
+ const current = readRevision(ns)
443
+ return current !== undefined && current === last.revision
444
+ },
445
+ }
446
+ return tracker
447
+ }
448
+
449
+ function settingsRevision(settings: SettingsService | undefined, ns: string): number | undefined {
450
+ return settings?.describe().find((desc) => desc.ns === ns)?.revision
451
+ }
452
+
196
453
  export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise<void> {
197
454
  // On dsh 0.1.7 the resolved Config arrives as apply()'s second argument:
198
455
  // every volatile field is a stable reference (see VolatileRef), so the
@@ -200,6 +457,158 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
200
457
  // removed from dsh-settings; the hot-reload notification moved to the
201
458
  // settings/document-updated event, subscribed at the bottom of apply()).
202
459
 
460
+ // P1d-1: one reentry marker shared by every write path. `rawSettings()` is
461
+ // resolved per call so a host that mounts the settings service after this
462
+ // plugin still works; the thin wrapper records the post-mutate revision for
463
+ // the document-updated reentry check (§14.7.2). Every settings-writing path
464
+ // below goes through `settingsForWrite*` — never a bare ctx.get('settings').
465
+ const rawSettings = (): SettingsService | undefined => ctx.get('settings') as SettingsService | undefined
466
+ const ownWrite = createOwnWriteTracker(
467
+ (ns) => settingsRevision(rawSettings(), ns),
468
+ () => Date.now(),
469
+ )
470
+ const settingsForWriteFrom = (context: Context): SettingsService | undefined => {
471
+ const raw = context.get('settings') as SettingsService | undefined
472
+ if (raw === undefined) return undefined
473
+ return {
474
+ describe: () => raw.describe(),
475
+ mutate: async (ns, ops, expectedRevision) => {
476
+ await raw.mutate(ns, ops, expectedRevision)
477
+ ownWrite.record(ns)
478
+ },
479
+ }
480
+ }
481
+ const settingsForWrite = (): SettingsService | undefined => settingsForWriteFrom(ctx)
482
+
483
+ // B1/H9: one stable profile identity per plugin instance, resolved from the
484
+ // host (profileContext / DSH_PROFILE). Both file-backed stores below scope
485
+ // every shared models-store key with it so two profiles cannot share a
486
+ // migration record or ownership ledger entry. When no identity can be
487
+ // resolved there is NO 'default' collapse: every file-backed ledger path
488
+ // fails closed with an actionable error instead of silently sharing a key.
489
+ const profileKey = resolveProfileKey(ctx)
490
+ const requireScopedProfileKey = (): string => {
491
+ if (profileKey === undefined) throw new Error(PROFILE_IDENTITY_REQUIRED_MESSAGE)
492
+ return profileKey
493
+ }
494
+ // The injection seam is an explicit opt-in (tests / hosts that supply their
495
+ // own scoped store); only the file-backed fallback requires host identity.
496
+ const migrationStore = (): MigrationStateStore =>
497
+ (ctx.get(GO_MIGRATION_STORE_SERVICE) as MigrationStateStore | undefined)
498
+ ?? createModelsStoreMigrationStateStore(undefined, requireScopedProfileKey())
499
+ const ownershipStoreForRound = (): GoOwnershipStore =>
500
+ (ctx.get(GO_OWNERSHIP_STORE_SERVICE) as GoOwnershipStore | undefined)
501
+ ?? createModelsStoreOwnershipStore(undefined, requireScopedProfileKey())
502
+ // O1/C2: the journal lives in the same models-store.json. An injected seam
503
+ // wins (tests use a temp-dir accessor); without a resolved profile identity
504
+ // there is NO journal — never fall back to the real default ~/.dsh from a
505
+ // host/test that supplied no identity (the ledger path fails closed too).
506
+ const journalStoreForRound = (): GoJournalStore | undefined =>
507
+ (ctx.get(GO_JOURNAL_STORE_SERVICE) as GoJournalStore | undefined)
508
+ ?? (profileKey === undefined ? undefined : createModelsStoreJournalStore())
509
+
510
+ /**
511
+ * Read current migration status from the persisted record + live settings +
512
+ * (when a key fingerprint is available) the live ownership ledger.
513
+ * `strict` rethrows a record read failure so the §14.7.5 second gate can fail
514
+ * closed with `canWrite-unavailable`; the normal path degrades to "no record"
515
+ * (conservative legacy detection) as before.
516
+ */
517
+ const loadMigrationStatus = async (
518
+ opts: { keyFingerprint?: string; strict?: boolean } = {},
519
+ ): Promise<MigrationStatus> => {
520
+ const desc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai')
521
+ // H9 fail-closed: with no resolvable profile identity the file-backed store
522
+ // factory throws. A non-strict READ degrades to "no record" (gate closed,
523
+ // zero writes) so boot-time status refreshes / isApplying cannot produce an
524
+ // unhandled rejection; strict reads (the per-mutate second gate) rethrow.
525
+ // Every WRITE path still fails closed when it builds its file-backed store.
526
+ // N2: remember an identity-refused file-backed store so the (non-strict)
527
+ // status read can surface it instead of looking like a normal legacy state.
528
+ // The check is on the thrown identity error, not on `profileKey === undefined`
529
+ // alone: an injected-store host has a usable ledger even with no host
530
+ // identity and must NOT get a false "identity unavailable" report.
531
+ let identityUnavailable = false
532
+ let store: MigrationStateStore | undefined
533
+ try {
534
+ store = migrationStore()
535
+ } catch (err) {
536
+ if (opts.strict === true) throw err
537
+ if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE) identityUnavailable = true
538
+ }
539
+ let record: MigrationRecord | undefined
540
+ try {
541
+ record = await store?.read()
542
+ } catch (err) {
543
+ if (opts.strict === true) throw err
544
+ record = undefined // unreadable ⇒ conservative legacy detection
545
+ }
546
+ const goRoutes = Object.values(readGoRuntimeConfig(config).value.routes ?? {})
547
+ let managedIds: Record<string, string[]> | undefined
548
+ const fp = opts.keyFingerprint
549
+ if (fp !== undefined) {
550
+ let ownership: GoOwnershipStore | undefined
551
+ try {
552
+ ownership = ownershipStoreForRound()
553
+ } catch (err) {
554
+ if (opts.strict === true) throw err
555
+ if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE) identityUnavailable = true
556
+ }
557
+ // Only routes with a REAL ledger entry join the fingerprint set. The old
558
+ // `<route>: []` filler for configured-but-absent routes disagreed with
559
+ // migrate/onOwnWrite and produced a phantom `fingerprint-healed` on the
560
+ // first healthy round after onboarding.
561
+ managedIds = await goLedgerManagedIds(goRoutes, (route) =>
562
+ ownership === undefined
563
+ ? Promise.resolve(undefined)
564
+ : ownership.read(goOwnershipKey(route, fp)))
565
+ }
566
+ const status = migrationStatusOf(desc, record, goRoutes, managedIds)
567
+ // W1/D6: the go report and `migrate status` must agree on the label for a
568
+ // record this profile cannot claim. Use the SAME helper as migrate status;
569
+ // only when our own scoped read() found no record (B1 isolation). This is
570
+ // label-only: both states already keep the gate closed / write authority
571
+ // none / zero writes, and nothing is claimed or deleted.
572
+ if (record === undefined && store?.unclaimedRecords !== undefined) {
573
+ let unclaimed: UnclaimedMigrationRecord[]
574
+ try {
575
+ unclaimed = await store.unclaimedRecords()
576
+ } catch (err) {
577
+ if (opts.strict === true) throw err
578
+ unclaimed = [] // advisory provenance scan never changes the gate
579
+ }
580
+ const recordState = unclaimedRecordState(unclaimed)
581
+ if (recordState !== undefined) status.state = recordState
582
+ }
583
+ // N2: a non-strict refresh that degraded because no identity was available
584
+ // must be VISIBLE — log the actionable error (covers boot / document-updated
585
+ // refresh where there is no report line) and tag the status so sync reports
586
+ // do not show the normal legacy hint. This changes NO write/fail-closed
587
+ // behavior: the gate is already closed and no store/settings write occurs.
588
+ if (identityUnavailable) {
589
+ status.identityUnavailable = true
590
+ ctx.logger.warn('model-sync: non-strict status refresh degraded — %s', PROFILE_IDENTITY_REQUIRED_MESSAGE)
591
+ }
592
+ // §14.7.4 self-heal: identity matches but the stored full fingerprint is
593
+ // stale because the fingerprint persist failed after settings+ledger landed.
594
+ // Rewrite it in the same queue instead of closing the gate forever.
595
+ if (status.fingerprintHealed && typeof store?.write === 'function') {
596
+ try {
597
+ ctx.logger.info('model-sync: fingerprint-healed (identity matched; stale appliedFingerprint)')
598
+ await store.write({
599
+ ...(record ?? {}),
600
+ appliedManagedIds: managedIds ?? record?.appliedManagedIds,
601
+ appliedFingerprint: status.expectedFingerprint,
602
+ })
603
+ status.appliedFingerprint = status.expectedFingerprint
604
+ status.fingerprintHealed = false
605
+ } catch (err) {
606
+ ctx.logger.warn('model-sync: fingerprint-healed write failed: %s', err instanceof Error ? err.message : String(err))
607
+ }
608
+ }
609
+ return status
610
+ }
611
+
203
612
  // -----------------------------------------------------------------------
204
613
  // Overlay mode sync (existing behavior)
205
614
  // -----------------------------------------------------------------------
@@ -274,7 +683,7 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
274
683
  config: ModelSyncConfigValue,
275
684
  force: boolean,
276
685
  ): Promise<string> => {
277
- const settings = ctx.get('settings') as SettingsService | undefined
686
+ const settings = settingsForWrite()
278
687
  const logger = ctx.logger as unknown as Logger
279
688
  const store = loadModelsStore()
280
689
  const lines: string[] = []
@@ -285,9 +694,37 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
285
694
  ? [...managedRoutes]
286
695
  : DEFAULT_ROUTES
287
696
 
697
+ // P1d-1 single writer: while opencode.go.enabled=true the legacy pi.dev
698
+ // path must NEVER write an `opencode-go*` route — not even in `absent` /
699
+ // `applied` state (that belongs to go sync), and especially not when the
700
+ // migration gate is closed. Login-triggered/manual/auto all funnel through
701
+ // this one loop (design §14.7.1, ADR-008).
702
+ const { value: goCfg } = readGoRuntimeConfig(config)
703
+ const goRouteIds = Object.values(goCfg.routes ?? {})
704
+ const piDevAuthority = { caller: 'pi.dev' as const, goEnabled: goCfg.enabled, goRoutes: goRouteIds }
705
+ let piDevMigration: MigrationStatus | undefined
706
+
288
707
  const gateDesc = settings?.describe().find((d) => d.ns === 'llm-pi-ai')
289
708
  const gateCtx = ctx as RouteCredentialContext
290
709
  for (const route of routes) {
710
+ // Single-writer gate before ANY fetch/translate/mutate for go routes.
711
+ // A skip always produces a report line (never silent, §14.7.1).
712
+ if (goCfg.enabled && isGoRoute(route, goRouteIds)) {
713
+ piDevMigration ??= await loadMigrationStatus()
714
+ const decision = routeWriter(route, piDevAuthority, piDevMigration)
715
+ if (decision.decision === 'skip') {
716
+ // N2: an identity-refused ledger is NOT a normal legacy state. Surface
717
+ // the actionable identity hint instead of the generic migration hint.
718
+ const hint = piDevMigration.identityUnavailable === true
719
+ ? `; ${PROFILE_IDENTITY_STATUS_HINT}`
720
+ : (piDevMigration.state === 'absent' || piDevMigration.state === 'applied'
721
+ ? ''
722
+ : `; ${MIGRATION_GATE_HINT}`)
723
+ lines.push(`${route}: skipped — ${decision.reason}${hint}`)
724
+ continue
725
+ }
726
+ }
727
+
291
728
  // Layer 1 follows llm-pi-ai's resolveApiKey: prefer the credentials seam.
292
729
  // Layer 2 follows its authContextFrom(ctx).env(): launch environment,
293
730
  // or process.env when the service is absent. Both miss → skip fetch,
@@ -503,6 +940,310 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
503
940
  return syncOverlay(config, llm, force)
504
941
  }
505
942
 
943
+ // -----------------------------------------------------------------------
944
+ // P1c go round: source → planner → writer, all deps from cordis seams.
945
+ // P1c-2 wraps this in the scheduler below; the round itself still owns no
946
+ // timer and no command registration.
947
+ // -----------------------------------------------------------------------
948
+ const runGoRound = async (options: { adopt?: boolean; signal?: AbortSignal } = {}): Promise<GoSyncRoundResult> => {
949
+ const { value } = readGoRuntimeConfig(config)
950
+ const settings = settingsForWrite()
951
+ const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai')
952
+ const apiKey = await resolveRouteCredentialValue(
953
+ ctx as unknown as NativeCredentialContext,
954
+ desc,
955
+ 'opencode-go',
956
+ value.ref,
957
+ )
958
+ // The ledger is keyed by the same credential fingerprint the source uses;
959
+ // deriving it here lets the status read include the live managed-id set.
960
+ const keyFingerprint = fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : '')
961
+ const migration = await loadMigrationStatus({ keyFingerprint })
962
+ const ownershipStore = ownershipStoreForRound()
963
+ // The existing models-store accessor already satisfies GoOverrideStorer
964
+ // (read(route).overrides + updateOverrides); the service seam lets tests
965
+ // point both stores at a temp dir instead of the real ~/.dsh.
966
+ const overrideStorer = (ctx.get(GO_OVERRIDE_STORER_SERVICE) as GoOverrideStorer | undefined)
967
+ ?? loadModelsStore()
968
+ return runGoSyncRound({
969
+ settings,
970
+ ownershipStore,
971
+ overrideStorer,
972
+ logger: ctx.logger as unknown as Logger,
973
+ // The explicit `adopt` command honours the master switch: disabled means
974
+ // zero writes (design §6.2.6). runGoSyncRound checks `enabled` first.
975
+ config: options.adopt === true ? { ...value, adoptExisting: true } : value,
976
+ apiKey,
977
+ fetchImpl: ctx.get(GO_FETCH_SERVICE) as GoFetchLike | undefined,
978
+ signal: options.signal,
979
+ migration,
980
+ // O1/C2: journal + reconciliation use the same profile/fingerprint as the
981
+ // ledger. Reconciliation runs before the gate inside runGoSyncRound.
982
+ journalStore: journalStoreForRound(),
983
+ profileKey,
984
+ keyFingerprint,
985
+ // §14.7.5: the second gate re-reads the persisted record on each mutate
986
+ // (strict: a failed read skips the route with canWrite-unavailable).
987
+ reloadMigration: () => loadMigrationStatus({ keyFingerprint, strict: true }),
988
+ // §14.7.4: settings → ledger → fingerprint, all through the same
989
+ // models-store queue; only successful own writes reach this callback.
990
+ onOwnWrite: async (route, managedIds) => {
991
+ const store = migrationStore()
992
+ if (typeof store.write !== 'function') return // read-only injected store
993
+ let record: MigrationRecord | undefined
994
+ try {
995
+ record = await store.read()
996
+ } catch {
997
+ return // cannot merge safely; the next round's self-heal covers it
998
+ }
999
+ const goRoutes = Object.values(value.routes ?? {})
1000
+ const liveDesc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai')
1001
+ const sections = readGoProviderSections(liveDesc, goRoutes)
1002
+ const appliedIdentityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {})
1003
+ const appliedManagedIds = { ...(record?.appliedManagedIds ?? {}), [route]: [...managedIds].sort() }
1004
+ // Same helper + route-set convention as loadMigrationStatus: a normal
1005
+ // onboarding/own write must not look like a fingerprint drift next round.
1006
+ const { identity, appliedFingerprint } = appliedFingerprintFieldsOf(
1007
+ sections, record, appliedManagedIds,
1008
+ )
1009
+ await store.write({
1010
+ ...(record ?? {}),
1011
+ appliedIdentity: identity,
1012
+ appliedIdentityRoutes,
1013
+ appliedManagedIds,
1014
+ appliedFingerprint,
1015
+ })
1016
+ },
1017
+ })
1018
+ }
1019
+
1020
+ // -----------------------------------------------------------------------
1021
+ // P1c-2: async timer + scheduling for the go round (design §6.3 / §14.6).
1022
+ // One GoScheduler instance serves BOTH the timer and the manual /model-sync
1023
+ // go command, so they share the single-flight lock. Clock and jitter inputs
1024
+ // are optional cordis services so tests never arm a real timer.
1025
+ // -----------------------------------------------------------------------
1026
+ const goTimers: GoSchedulerTimers = (ctx.get(GO_SCHEDULER_TIMERS_SERVICE) as GoSchedulerTimers | undefined) ?? {
1027
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
1028
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
1029
+ }
1030
+ const goRandom: GoSchedulerRandom = (ctx.get(GO_SCHEDULER_RANDOM_SERVICE) as GoSchedulerRandom | undefined)
1031
+ ?? { next: () => Math.random() }
1032
+ const goScheduler = new GoScheduler({
1033
+ config: () => readGoSchedulerConfig(config),
1034
+ timers: goTimers,
1035
+ random: goRandom,
1036
+ runRound: async ({ adopt, signal }) => {
1037
+ const round = await runGoRound({ adopt, signal })
1038
+ return {
1039
+ ok: round.ok,
1040
+ reason: round.reason,
1041
+ text: round.text,
1042
+ failureKind: round.reason === 'source-failed' && round.source?.error !== undefined
1043
+ ? round.source.error.kind
1044
+ : undefined,
1045
+ }
1046
+ },
1047
+ report: (text) => {
1048
+ for (const line of text.split('\n')) ctx.logger.info('model-sync: %s', line)
1049
+ },
1050
+ // M-5: drop (never queue) any round while a migration apply holds the routes.
1051
+ isApplying: async () => (await loadMigrationStatus()).applying,
1052
+ })
1053
+ ctx.effect(() => () => goScheduler.dispose(), 'dsh-model-sync: go scheduler dispose')
1054
+ // A changed credential invalidates any accumulated backoff: a fixed key must
1055
+ // retry on the normal schedule instead of waiting out a capped 6h backoff
1056
+ // (design §6.3). The effect scopes the listener to this plugin's lifetime —
1057
+ // unload removes it together with the scheduler.
1058
+ ctx.effect(() => ctx.on('credentials/reference-updated', (ref: unknown) => {
1059
+ if (typeof ref !== 'string') return
1060
+ const { value } = readGoRuntimeConfig(config)
1061
+ if (ref !== value.ref) return
1062
+ goScheduler.resetBackoff()
1063
+ }), 'dsh-model-sync: credentials/reference-updated → go backoff reset')
1064
+ goScheduler.start()
1065
+
1066
+ // -----------------------------------------------------------------------
1067
+ // P1d-2: `/model-sync migrate plan|apply|rollback|status` (design §14.5).
1068
+ // plan is pure/read-only; apply carries the consent gate and the single-flight
1069
+ // mutex against goScheduler. No auto/startup path reaches any of these.
1070
+ // -----------------------------------------------------------------------
1071
+ type MigrateEntries = readonly GoModelRecord[] | (() => Promise<readonly GoModelRecord[]> | readonly GoModelRecord[])
1072
+ type PublicCatalog = readonly string[] | (() => Promise<readonly string[]> | readonly string[])
1073
+
1074
+ /** Resolve the official listing through an injectable seam (tests: a fixture array). */
1075
+ const resolveMigrateEntries = async (
1076
+ value: GoSyncRuntimeConfig,
1077
+ apiKey: string | undefined,
1078
+ ): Promise<readonly GoModelRecord[]> => {
1079
+ const injected = ctx.get(GO_MIGRATION_ENTRIES_SERVICE) as MigrateEntries | undefined
1080
+ if (Array.isArray(injected)) return injected
1081
+ if (typeof injected === 'function') return await injected()
1082
+ const source = await fetchGoOfficialModels({
1083
+ url: value.modelsUrl,
1084
+ apiKey,
1085
+ fetchImpl: ctx.get(GO_FETCH_SERVICE) as GoFetchLike | undefined,
1086
+ timeoutMs: config.refreshTimeoutMs.get(),
1087
+ })
1088
+ if (!source.ok) {
1089
+ throw new Error(`official opencode-go listing unavailable (${source.error?.kind ?? 'unknown'}); no plan generated`)
1090
+ }
1091
+ return source.entries
1092
+ }
1093
+
1094
+ /**
1095
+ * Public-catalog producer for id classification (§14.2): ids the current key
1096
+ * cannot serve but that are still official are `unknown-retired`, everything
1097
+ * else is `user-extra`. When the public list cannot be fetched the result is
1098
+ * `undefined`, which makes the plan mark such ids `unclassified` (never
1099
+ * deleted) instead of defaulting them to deletable `user-extra`.
1100
+ */
1101
+ const resolvePublicCatalogIds = async (
1102
+ value: GoSyncRuntimeConfig,
1103
+ entries: readonly GoModelRecord[],
1104
+ ): Promise<readonly string[] | undefined> => {
1105
+ const injected = ctx.get(GO_MIGRATION_PUBLIC_CATALOG_SERVICE) as PublicCatalog | undefined
1106
+ if (Array.isArray(injected)) return injected
1107
+ if (typeof injected === 'function') return await injected()
1108
+ // Offline fixture mode: the injected authorized entries are the only catalog
1109
+ // available; deriving ids from them keeps `migrate plan` zero-fetch (V16).
1110
+ if (ctx.get(GO_MIGRATION_ENTRIES_SERVICE) !== undefined) return entries.map((entry) => entry.id)
1111
+ const result = await fetchGoPublicCatalogIds({
1112
+ url: value.modelsUrl,
1113
+ fetchImpl: ctx.get(GO_FETCH_SERVICE) as GoFetchLike | undefined,
1114
+ timeoutMs: config.refreshTimeoutMs.get(),
1115
+ })
1116
+ return result.ok ? result.ids : undefined
1117
+ }
1118
+
1119
+ const migrateDeps = async (
1120
+ target: Context,
1121
+ opts: { adopt?: boolean; rewriteRefs?: RewriteRefMode; pruneUserExtra?: boolean } = {},
1122
+ needsEntries = true,
1123
+ ): Promise<MigrateDeps> => {
1124
+ const { value } = readGoRuntimeConfig(config)
1125
+ const settings = settingsForWriteFrom(target)
1126
+ const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai')
1127
+ const apiKey = await resolveRouteCredentialValue(
1128
+ target as unknown as NativeCredentialContext,
1129
+ desc,
1130
+ 'opencode-go',
1131
+ value.ref,
1132
+ )
1133
+ const refWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE) as
1134
+ | ((rewrite: ReferenceRewrite) => Promise<void>) | undefined
1135
+ // Keep the pre-action-table evaluation order: the file-backed stores fail
1136
+ // closed without a profile identity, and must do so BEFORE any source
1137
+ // fetch (D4: no identity ⇒ zero outbound requests, zero writes).
1138
+ const ownershipStore = (target.get(GO_OWNERSHIP_STORE_SERVICE) as GoOwnershipStore | undefined)
1139
+ ?? ownershipStoreForRound()
1140
+ const store = migrationStore()
1141
+ // status/rollback never need the official listing: no fetch, no extra I/O.
1142
+ const entries = needsEntries ? await resolveMigrateEntries(value, apiKey) : []
1143
+ const publicCatalogIds = needsEntries ? await resolvePublicCatalogIds(value, entries) : undefined
1144
+ const adoptDisabled = ctx.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
1145
+ || settings === undefined || typeof settings.mutate !== 'function'
1146
+ return {
1147
+ settings,
1148
+ ownershipStore,
1149
+ migrationStore: store,
1150
+ logger: target.logger as unknown as Logger,
1151
+ entries,
1152
+ publicCatalogIds,
1153
+ routes: value.routes,
1154
+ ref: value.ref,
1155
+ keyFingerprint: fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : ''),
1156
+ adopt: opts.adopt,
1157
+ adoptDisabled,
1158
+ rewriteRefs: opts.rewriteRefs,
1159
+ // Config path: go.pinnedModels (readGoRuntimeConfig:361) now reaches plan.
1160
+ pinnedModels: value.pinnedModels,
1161
+ pruneUserExtra: opts.pruneUserExtra,
1162
+ now: Date.now(),
1163
+ isSyncInFlight: (ctx.get(GO_MIGRATION_MUTEX_SERVICE) as (() => boolean) | undefined)
1164
+ ?? (() => goScheduler.isInFlight),
1165
+ applyReferenceRewrite: refWriter,
1166
+ // O1/C2: apply/rollback clear this profile's journals so a stale slot
1167
+ // cannot re-account settings that the migration just rewrote or undid.
1168
+ journalStore: journalStoreForRound(),
1169
+ profileKey,
1170
+ }
1171
+ }
1172
+
1173
+ /** Shared by the slash command and the `modelSync` host service (§14.5). */
1174
+ const runMigrate = async (
1175
+ args: string[],
1176
+ target: Context,
1177
+ ): Promise<{ kind: 'success' | 'error'; text: string }> => {
1178
+ const usage = [
1179
+ 'usage: /model-sync migrate plan [--adopt] [--prune-user-extra] [--rewrite-refs=default-model|config]',
1180
+ ' /model-sync migrate apply --plan <planHash> --confirm <6-digit-code> --ack-managed',
1181
+ ' /model-sync migrate rollback --plan <planHash>',
1182
+ ' /model-sync migrate status',
1183
+ ].join('\n')
1184
+ const action = args[0] ?? 'plan'
1185
+ const rest = args.slice(1)
1186
+ if (!['plan', 'apply', 'rollback', 'status'].includes(action)) {
1187
+ return { kind: 'error', text: `migrate: unknown action '${action}'\n${usage}` }
1188
+ }
1189
+ // Consent has no bypass: these flags are recognised and rejected explicitly.
1190
+ if (rest.some((flag) => flag === '--yes' || flag === '--auto' || flag.startsWith('--yes=') || flag.startsWith('--auto='))) {
1191
+ return { kind: 'error', text: 'migrate: --yes/--auto are not supported; apply requires --plan <hash> and --confirm <code>' }
1192
+ }
1193
+ const flagValue = (name: string): string | undefined => {
1194
+ const index = rest.indexOf(name)
1195
+ if (index >= 0) return rest[index + 1]
1196
+ const inline = rest.find((token) => token.startsWith(`${name}=`))
1197
+ return inline?.slice(name.length + 1)
1198
+ }
1199
+ const planHash = flagValue('--plan')
1200
+ const confirmCode = flagValue('--confirm')
1201
+ const adopt = rest.includes('--adopt')
1202
+ const ackManaged = rest.includes('--ack-managed')
1203
+ const pruneUserExtra = rest.includes('--prune-user-extra')
1204
+ const rewriteRefsRaw = rest.find((token) => token.startsWith('--rewrite-refs='))?.slice('--rewrite-refs='.length)
1205
+ const rewriteRefs = rewriteRefsRaw === 'default-model' || rewriteRefsRaw === 'config'
1206
+ ? rewriteRefsRaw as RewriteRefMode
1207
+ : undefined
1208
+
1209
+ try {
1210
+ if (action === 'status') {
1211
+ const deps = await migrateDeps(target, {}, false)
1212
+ const report = await migrationStatusReport(deps, { caller: 'go', goEnabled: readGoRuntimeConfig(config).value.enabled })
1213
+ return { kind: 'success', text: report.text }
1214
+ }
1215
+ if (action === 'plan') {
1216
+ const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra })
1217
+ const record = await deps.migrationStore.read().catch(() => undefined)
1218
+ // Same pure builder apply uses — the printed table IS the consented one.
1219
+ // When adopt is disabled the mode is reported as adopt-disabled and the
1220
+ // rows stay conservative; no adopt action can be printed as executable.
1221
+ const plan = buildMigrationPlanFromDeps(deps, record)
1222
+ return { kind: 'success', text: formatMigrationPlan(plan) }
1223
+ }
1224
+ if (action === 'apply') {
1225
+ const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra })
1226
+ // Fail-closed fallback (§14.2): reject at the command layer before any
1227
+ // write when the per-id action table cannot be executed verbatim.
1228
+ if (adopt && deps.adoptDisabled === true) {
1229
+ return {
1230
+ kind: 'error',
1231
+ text: 'migrate apply refused (adopt-disabled): --adopt cannot execute the per-id action table verbatim; use conservative mode; zero writes',
1232
+ }
1233
+ }
1234
+ const result = await applyMigration({ planHash, confirmCode, ackManaged }, deps)
1235
+ return { kind: result.ok ? 'success' : 'error', text: result.text }
1236
+ }
1237
+ // rollback
1238
+ const deps = await migrateDeps(target, {}, false)
1239
+ const result = await rollbackMigration({ planHash }, deps)
1240
+ return { kind: result.ok ? 'success' : 'error', text: result.text }
1241
+ } catch (error) {
1242
+ const message = error instanceof Error ? error.message : String(error)
1243
+ return { kind: 'error', text: `migrate ${action} failed: ${message}` }
1244
+ }
1245
+ }
1246
+
506
1247
  /** Auto rounds log the same report the /model-sync command shows. */
507
1248
  const runAuto = (): void => {
508
1249
  // A rejected round (service lookups mid-dispose, a refused mutate) must
@@ -538,22 +1279,51 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
538
1279
  // settings/document-updated event (the 0.1.7 replacement for scope.watch).
539
1280
  startupTimer = setTimeout(runAuto, Math.max(0, config.startupDelaySeconds.get() ?? 5) * 1000)
540
1281
  armInterval(config.intervalMinutes.get() ?? 240)
541
- ctx.effect(() => ctx.on('settings/document-updated', (ns) => {
542
- // Only this plugin's entry (the bundle-patch id) re-arms the timers; the
543
- // handler is idempotent — the refs already carry the new values, so the
544
- // next round reads them fresh. Never throws: an interval re-arm is two
545
- // timer calls, and a throwing settings listener is a host-side incident.
1282
+ ctx.effect(() => ctx.on('settings/document-updated', (ns, revision) => {
1283
+ // P1d-1 §14.7.2: if this event is the echo of a settings.mutate we just
1284
+ // performed, only refresh status — schedule NO round (the V23 race was a
1285
+ // go write echo triggering the legacy pi.dev auto round ~1s later).
1286
+ if (ownWrite.matches(ns, typeof revision === 'number' ? revision : undefined)) {
1287
+ ctx.logger.info('model-sync: reentry-ignored (ns=%s revision=%s); no round scheduled', ns, revision)
1288
+ void loadMigrationStatus() // refresh state only; no timer, no runAuto
1289
+ return
1290
+ }
1291
+ // Only this plugin's own config entry (the bundle-patch id) re-arms timers;
1292
+ // the handler is idempotent — the refs already carry the new values, so the
1293
+ // next round reads them fresh. A foreign ns (including llm-pi-ai writes by
1294
+ // other actors) never schedules a round here.
546
1295
  if (ns !== OWN_ENTRY_ID) return
547
1296
  armInterval(config.intervalMinutes.get() ?? 0)
548
- // Clear any pending startup timer before setting a new one
549
- if (startupTimer !== undefined) clearTimeout(startupTimer)
550
- startupTimer = setTimeout(runAuto, 1000)
1297
+ // §14.7.2 item 2: remove the old "immediate +1s runAuto". Config edits now
1298
+ // only re-arm the normal interval; an immediate round needs an explicit
1299
+ // /model-sync. (P1c-2 go scheduler still re-arms idempotently.)
1300
+ goScheduler.rearm()
1301
+ void loadMigrationStatus()
551
1302
  }), 'dsh-model-sync: settings/document-updated')
552
1303
 
553
1304
  // The modelSync service stays exposed for UIs that want direct access. The
554
1305
  // /model-sync command itself is registered by this plugin (below) through
555
1306
  // the shared command registry, which interactive UIs discover on their own.
556
- ctx.provide('modelSync', { syncNow: () => syncNow(true) } satisfies ModelSyncService)
1307
+ ctx.provide('modelSync', {
1308
+ syncNow: () => syncNow(true),
1309
+ migratePlan: (options) => runMigrate(
1310
+ ['plan', ...(options?.adopt === true ? ['--adopt'] : []),
1311
+ ...(options?.pruneUserExtra === true ? ['--prune-user-extra'] : []),
1312
+ ...(options?.rewriteRefs !== undefined ? [`--rewrite-refs=${options.rewriteRefs}`] : [])],
1313
+ ctx,
1314
+ ).then((result) => result.text),
1315
+ migrateApply: (args) => runMigrate(
1316
+ ['apply', ...(args.planHash !== undefined ? ['--plan', args.planHash] : []),
1317
+ ...(args.confirmCode !== undefined ? ['--confirm', args.confirmCode] : []),
1318
+ ...(args.ackManaged === true ? ['--ack-managed'] : [])],
1319
+ ctx,
1320
+ ).then((result) => result.text),
1321
+ migrateRollback: (args) => runMigrate(
1322
+ ['rollback', ...(args.planHash !== undefined ? ['--plan', args.planHash] : [])],
1323
+ ctx,
1324
+ ).then((result) => result.text),
1325
+ migrateStatus: () => runMigrate(['status'], ctx).then((result) => result.text),
1326
+ } satisfies ModelSyncService)
557
1327
 
558
1328
  // Register the /model-sync slash command from the plugin itself. The
559
1329
  // registry is @deepseek-ai/dsh-commands' CommandRuntime ("Plugin-owned
@@ -571,8 +1341,66 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
571
1341
  cmdCtx.effect(() => {
572
1342
  const definition: CommandDefinition = {
573
1343
  name: 'model-sync',
574
- description: 'Force one model-list sync round from the pi.dev gateway into settings (dsh-model-sync)',
1344
+ description: 'Force one model-list sync round from the pi.dev gateway into settings; go subcommands: go|status (one full opencode-go round), adopt go; migrate plan|apply|rollback|status (explicit consent only)',
575
1345
  handler: async (invocation) => {
1346
+ const args = invocation.rawInput.trim().split(/\s+/).filter((part) => part.length > 0)
1347
+ const [sub, scope] = args
1348
+ // P1d-2: migration is the ONLY explicit-consent config writer. It is
1349
+ // never auto-triggered and never folded into the pi.dev sync path.
1350
+ if (sub === 'migrate') {
1351
+ return runMigrate(args.slice(1), cmdCtx)
1352
+ }
1353
+ // B3 (31 R-4): `eject` is retired — `migrate rollback` is the only
1354
+ // rollback entry. Reject the old invocation explicitly so it never
1355
+ // falls through to a bare sync (which would write to go routes under
1356
+ // a command name the user believed was read-only).
1357
+ if (sub === 'eject') {
1358
+ return { kind: 'error', text: 'model-sync eject go: retired; use /model-sync migrate rollback --plan <hash>' } satisfies CommandResult
1359
+ }
1360
+ // Design §7.1 keeps bare `/model-sync` (pi.dev settings sync) exactly
1361
+ // as it was. The go subcommands are additive: `go`/`status` run one
1362
+ // full go round, `adopt go` runs it with adoption. Status stays the
1363
+ // read-only `/opencode-status` command — it is never a write trigger.
1364
+ if ((sub === 'go' || sub === 'status' || sub === 'adopt')
1365
+ && (scope === undefined || scope === 'go')) {
1366
+ try {
1367
+ // Route manual rounds through the scheduler so they share the
1368
+ // single-flight lock with timer-driven rounds. A second trigger
1369
+ // while a round is in flight is skipped and reported (design
1370
+ // §14.6), never queued. The report text is the round's own text,
1371
+ // unchanged, for real rounds.
1372
+ const outcome = await goScheduler.triggerManual({ adopt: sub === 'adopt' })
1373
+ // N1: a round that threw (e.g. the file-backed ledger refusing to
1374
+ // build without a profile identity) is reported as a scheduler
1375
+ // error. It is a real failure — the command must return
1376
+ // `kind:'error'` so callers that only read `kind` can detect it;
1377
+ // the actionable reason is carried in `text`. Skips (disabled,
1378
+ // already-in-flight, migration-applying, disposed) stay success,
1379
+ // byte-identical to before.
1380
+ const failed = outcome.reason === 'source-failed'
1381
+ // oldfox #3: a writer exception is a real failure at the
1382
+ // command surface, but a distinct reason from source failure.
1383
+ || outcome.reason === 'writer-error'
1384
+ || outcome.reason === 'scheduler-error'
1385
+ // B4: an abandoned round must be visible as a failure at the
1386
+ // command surface too (it is not a successful sync). The reason
1387
+ // text carries the actionable "settings changed, next round
1388
+ // retries" guidance; no backoff is scheduled for it.
1389
+ || outcome.reason === 'settings-changed-during-sync'
1390
+ // O1-minimal: failedRoutes (e.g. settings written but the ledger
1391
+ // failed) are a real failure even if other routes wrote. Callers
1392
+ // that only read `kind` must see `error`; the actionable reason
1393
+ // and the new report code are carried in `text`.
1394
+ || outcome.reason === 'write-failed'
1395
+ return {
1396
+ kind: failed ? 'error' : 'success',
1397
+ text: outcome.text,
1398
+ } satisfies CommandResult
1399
+ } catch (error) {
1400
+ const message = error instanceof Error ? error.message : String(error)
1401
+ return { kind: 'error', text: `model-sync ${sub} failed: ${message}` } satisfies CommandResult
1402
+ }
1403
+ }
576
1404
  const ignored = invocation.rawInput.trim().length > 0
577
1405
  ? 'The sync scope is decided by the model-sync managedRoutes config; the argument is ignored.\n'
578
1406
  : ''
@@ -587,6 +1415,39 @@ export async function apply(ctx: Context, config: ModelSyncConfigValue): Promise
587
1415
  }
588
1416
  return commands.register(definition)
589
1417
  }, 'dsh-model-sync: /model-sync')
1418
+
1419
+ // P0 read-only diagnostic. Parallel to /model-sync (whose behavior is
1420
+ // unchanged): fetch the official go listing, compare it with the current
1421
+ // profile's opencode-go routes, and print a structured report. This path
1422
+ // never calls settings.mutate, never writes credentials, and never edits
1423
+ // a profile file — it only reads describe()/credentials.resolve().
1424
+ cmdCtx.effect(() => {
1425
+ const definition: CommandDefinition = {
1426
+ name: 'opencode-status',
1427
+ description: 'Read-only diagnostic: compare opencode-go official /v1/models with the current profile routes (no writes)',
1428
+ handler: async (invocation) => {
1429
+ const token = invocation.rawInput.trim()
1430
+ const ignored = token !== '' && token !== 'go'
1431
+ ? 'opencode-status: P0 diagnoses opencode-go only; the argument is ignored.\n'
1432
+ : ''
1433
+ try {
1434
+ const desc = (cmdCtx.get('settings') as SettingsService | undefined)?.describe()
1435
+ .find((d) => d.ns === 'llm-pi-ai')
1436
+ const apiKey = await resolveRouteCredentialValue(
1437
+ cmdCtx as unknown as NativeCredentialContext,
1438
+ desc,
1439
+ 'opencode-go',
1440
+ )
1441
+ const report = await runGoDiagnostic({ apiKey, descriptor: desc })
1442
+ return { kind: 'success', text: `${ignored}${formatGoDiagnosticReport(report)}` } satisfies CommandResult
1443
+ } catch (error) {
1444
+ const message = error instanceof Error ? error.message : String(error)
1445
+ return { kind: 'error', text: `${ignored}opencode-status failed: ${message}` } satisfies CommandResult
1446
+ }
1447
+ },
1448
+ }
1449
+ return commands.register(definition)
1450
+ }, 'dsh-model-sync: /opencode-status')
590
1451
  })
591
1452
 
592
1453
  // One-time legacy settings import (0.1.5 → 0.1.7 upgrade path, see