@aiwayds/dsh-model-sync 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +20 -3
  2. package/README.zh-CN.md +20 -3
  3. package/lib/builtin-catalog-snapshot.js +6 -3
  4. package/lib/builtin-catalog-snapshot.js.map +1 -1
  5. package/lib/index.d.ts +379 -0
  6. package/lib/index.js +897 -13
  7. package/lib/index.js.map +1 -1
  8. package/lib/opencode-go-diagnose.d.ts +74 -0
  9. package/lib/opencode-go-diagnose.js +146 -0
  10. package/lib/opencode-go-diagnose.js.map +1 -0
  11. package/lib/opencode-go-grouping.d.ts +29 -0
  12. package/lib/opencode-go-grouping.js +77 -0
  13. package/lib/opencode-go-grouping.js.map +1 -0
  14. package/lib/opencode-go-journal.d.ts +110 -0
  15. package/lib/opencode-go-journal.js +406 -0
  16. package/lib/opencode-go-journal.js.map +1 -0
  17. package/lib/opencode-go-migrate.d.ts +343 -0
  18. package/lib/opencode-go-migrate.js +1300 -0
  19. package/lib/opencode-go-migrate.js.map +1 -0
  20. package/lib/opencode-go-migration.d.ts +227 -0
  21. package/lib/opencode-go-migration.js +384 -0
  22. package/lib/opencode-go-migration.js.map +1 -0
  23. package/lib/opencode-go-one-shot.d.ts +276 -0
  24. package/lib/opencode-go-one-shot.js +1094 -0
  25. package/lib/opencode-go-one-shot.js.map +1 -0
  26. package/lib/opencode-go-patch-file.d.ts +123 -0
  27. package/lib/opencode-go-patch-file.js +1185 -0
  28. package/lib/opencode-go-patch-file.js.map +1 -0
  29. package/lib/opencode-go-planner.d.ts +153 -0
  30. package/lib/opencode-go-planner.js +339 -0
  31. package/lib/opencode-go-planner.js.map +1 -0
  32. package/lib/opencode-go-profile.d.ts +57 -0
  33. package/lib/opencode-go-profile.js +103 -0
  34. package/lib/opencode-go-profile.js.map +1 -0
  35. package/lib/opencode-go-scheduler.d.ts +128 -0
  36. package/lib/opencode-go-scheduler.js +241 -0
  37. package/lib/opencode-go-scheduler.js.map +1 -0
  38. package/lib/opencode-go-source.d.ts +117 -0
  39. package/lib/opencode-go-source.js +331 -0
  40. package/lib/opencode-go-source.js.map +1 -0
  41. package/lib/opencode-go-store.d.ts +18 -0
  42. package/lib/opencode-go-store.js +68 -0
  43. package/lib/opencode-go-store.js.map +1 -0
  44. package/lib/opencode-go-sync.d.ts +94 -0
  45. package/lib/opencode-go-sync.js +364 -0
  46. package/lib/opencode-go-sync.js.map +1 -0
  47. package/lib/opencode-go-writer.d.ts +132 -0
  48. package/lib/opencode-go-writer.js +966 -0
  49. package/lib/opencode-go-writer.js.map +1 -0
  50. package/lib/provider-native.d.ts +3 -1
  51. package/lib/provider-native.js +4 -2
  52. package/lib/provider-native.js.map +1 -1
  53. package/lib/remote-catalog.d.ts +61 -0
  54. package/lib/remote-catalog.js +307 -3
  55. package/lib/remote-catalog.js.map +1 -1
  56. package/package.json +15 -15
  57. package/src/builtin-catalog-snapshot.ts +6 -3
  58. package/src/index.ts +1060 -12
  59. package/src/opencode-go-diagnose.ts +222 -0
  60. package/src/opencode-go-grouping.ts +97 -0
  61. package/src/opencode-go-journal.ts +458 -0
  62. package/src/opencode-go-migrate.ts +1694 -0
  63. package/src/opencode-go-migration.ts +552 -0
  64. package/src/opencode-go-one-shot.ts +1354 -0
  65. package/src/opencode-go-patch-file.ts +1168 -0
  66. package/src/opencode-go-planner.ts +505 -0
  67. package/src/opencode-go-profile.ts +114 -0
  68. package/src/opencode-go-scheduler.ts +315 -0
  69. package/src/opencode-go-source.ts +424 -0
  70. package/src/opencode-go-store.ts +73 -0
  71. package/src/opencode-go-sync.ts +503 -0
  72. package/src/opencode-go-writer.ts +1189 -0
  73. package/src/provider-native.ts +3 -1
  74. package/src/remote-catalog.ts +359 -3
package/lib/index.js CHANGED
@@ -22,12 +22,45 @@ import { translateEntries, } from "./translate.js";
22
22
  import { syncToSettings, } from "./writer.js";
23
23
  import { BUILTIN_CATALOG_SNAPSHOT } from "./builtin-catalog-snapshot.js";
24
24
  import { refreshLiveCatalog, getLiveBuiltinCatalogForRoute } from "./live-catalog.js";
25
- import { checkRouteCredential } from "./route-credential.js";
25
+ import { checkRouteCredential, deriveKeyRef } from "./route-credential.js";
26
+ import { OPENCODE_GO_MODELS_URL, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES, fetchGoOfficialModels, fetchGoPublicCatalogIds, fingerprintKey } from "./opencode-go-source.js";
27
+ import { GO_SLOT_ROUTES } from "./opencode-go-grouping.js";
28
+ import { createModelsStoreOwnershipStore } from "./opencode-go-store.js";
29
+ import { createModelsStoreJournalStore, } from "./opencode-go-journal.js";
30
+ import { GO_FETCH_SERVICE, GO_OWNERSHIP_STORE_SERVICE, GO_OVERRIDE_STORER_SERVICE, runGoSyncRound, } from "./opencode-go-sync.js";
31
+ import { GO_SCHEDULER_RANDOM_SERVICE, GO_SCHEDULER_TIMERS_SERVICE, GoScheduler, } from "./opencode-go-scheduler.js";
26
32
  import { PROVIDER_NATIVE_ENDPOINTS, fetchProviderNativeModels, mergeProviderNativeEntries, resolveRouteCredentialValue, } from "./provider-native.js";
27
33
  import { runLegacySettingsImport, resolveDshHome, } from "./legacy-import.js";
34
+ import { runGoDiagnostic, formatGoDiagnosticReport } from "./opencode-go-diagnose.js";
35
+ import { PROFILE_IDENTITY_REQUIRED_MESSAGE, PROFILE_IDENTITY_STATUS_HINT, resolveProfileKey, } from "./opencode-go-profile.js";
36
+ import { GO_MIGRATION_STORE_SERVICE, appliedFingerprintFieldsOf, createModelsStoreMigrationStateStore, goLedgerManagedIds, isGoRoute, MIGRATION_GATE_HINT, migrationStatusOf, readGoProviderSections, routeWriter, unclaimedRecordState, } from "./opencode-go-migration.js";
37
+ import { goOwnershipKey } from "./opencode-go-planner.js";
38
+ import { applyMigration, buildMigrationPlanFromDeps, formatMigrationPlan, migrationStatusReport, rollbackMigration, } from "./opencode-go-migrate.js";
39
+ import { runMigrateGoOneShot, parseMigrateGoFlags, } from "./opencode-go-one-shot.js";
40
+ import { MODELS_STORE_PATH } from "./remote-catalog.js";
41
+ import { mkdir, open, readFile, readdir, rename, stat as statFd, unlink, writeFile } from 'node:fs/promises';
42
+ import { readFileSync, statSync, writeFileSync } from 'node:fs';
28
43
  export const name = 'dsh-model-sync';
29
44
  /** The settings seam this plugin consumes (its own config namespace). */
30
45
  export const inject = ['settings'];
46
+ /** P1d-2 seams: injected official entries (plan/apply) and optional reference writer. */
47
+ export const GO_MIGRATION_ENTRIES_SERVICE = 'goMigrationEntries';
48
+ export const GO_MIGRATION_REF_WRITER_SERVICE = 'goMigrationRefWriter';
49
+ /** Public (unauthenticated) official catalog ids for id classification (design §14.2).
50
+ * `undefined` ⇒ fail-closed `unclassified`. Tests inject an array/function. */
51
+ export const GO_MIGRATION_PUBLIC_CATALOG_SERVICE = 'goMigrationPublicCatalog';
52
+ /** Capability flag: when true, `--adopt` is refused and plan mode is adopt-disabled. */
53
+ export const GO_MIGRATION_ADOPT_DISABLED_SERVICE = 'goMigrationAdoptDisabled';
54
+ /** Optional override for the single-flight check (tests inject an in-flight mutex). */
55
+ export const GO_MIGRATION_MUTEX_SERVICE = 'goMigrationMutex';
56
+ /** O1/C2 seam: injected write-ahead journal store (tests use a temp-dir store). */
57
+ export const GO_JOURNAL_STORE_SERVICE = 'goJournalStore';
58
+ /**
59
+ * One-shot migrate-go path overrides (tests point everything at a temp dir;
60
+ * a host may pin non-default locations). Plain `undefined` fields fall back
61
+ * to resolveDshHome() / MODELS_STORE_PATH / `<home>/profiles`.
62
+ */
63
+ export const GO_ONESHOT_PATHS_SERVICE = 'goOneShotPaths';
31
64
  // dsh-settings 0.1.7 rewrote the seam: the runtime register(ns, schema) call
32
65
  // is gone, and a plugin's settings form is projected from its exported
33
66
  // `Config` schema — the namespace IS the profile entry id. The bundle patch
@@ -86,6 +119,48 @@ export const Config = z.object({
86
119
  * a re-emitted retired id is a model the 0.1.7 host no longer resolves.
87
120
  */
88
121
  keepDeprecatedBuiltin: z.boolean().default(false).volatile(),
122
+ /**
123
+ * OpenCode Go / Zen configuration contract (design §6.2.6). Published in one
124
+ * Config schema in P1: read-only subset (go.enabled/ref/modelsUrl/
125
+ * intervalMinutes, zen.enabled/ref/mode/modelsUrl) plus the write-side subset
126
+ * (go.routes/adoptExisting/pinnedModels/confirmRemovals,
127
+ * zen.routes/seedFromBuiltin). Defaults are byte-for-byte the P0 constants —
128
+ * `modelsUrl` and `ref` are imported from the P0 modules so a P0→P1 drift is
129
+ * impossible. Zen stays login-only with no modelsUrl by default (design A5).
130
+ * Nested leaves are `.volatile()` (host settings can edit them); the parent
131
+ * objects are not, because schemastery forbids a volatile field under an
132
+ * enclosing volatile field.
133
+ */
134
+ opencode: z.object({
135
+ go: z.object({
136
+ enabled: z.boolean().default(false).volatile(),
137
+ ref: z.string().default(deriveKeyRef('opencode-go')).volatile(),
138
+ modelsUrl: z.string().default(OPENCODE_GO_MODELS_URL).volatile(),
139
+ intervalMinutes: z.number().step(1).min(15).default(OPENCODE_GO_DEFAULT_INTERVAL_MINUTES).volatile(),
140
+ adoptExisting: z.boolean().default(false).volatile(),
141
+ pinnedModels: z.array(z.string()).default([]).volatile(),
142
+ routes: z.object({
143
+ chat: z.string().default('opencode-go').volatile(),
144
+ msg: z.string().default('opencode-go-msg').volatile(),
145
+ resp: z.string().default('opencode-go-resp').volatile(),
146
+ google: z.string().default('opencode-go-google').volatile(),
147
+ }).default({}),
148
+ confirmRemovals: z.number().step(1).min(2).default(2).volatile(),
149
+ }).default({}),
150
+ zen: z.object({
151
+ enabled: z.boolean().default(true).volatile(),
152
+ ref: z.string().default('OPENCODE_API_KEY').volatile(),
153
+ mode: z.union(['login-only', 'routes']).default('login-only').volatile(),
154
+ /** No proven listing endpoint; without it routes mode is unsupported. */
155
+ modelsUrl: z.string().volatile(),
156
+ seedFromBuiltin: z.boolean().default(false).volatile(),
157
+ routes: z.object({
158
+ chat: z.string().default('opencode-zen').volatile(),
159
+ msg: z.string().default('opencode-zen-msg').volatile(),
160
+ resp: z.string().default('opencode-zen-resp').volatile(),
161
+ }).default({}),
162
+ }).default({}),
163
+ }).default({}),
89
164
  });
90
165
  /**
91
166
  * Default routes to manage when managedRoutes is empty.
@@ -106,12 +181,255 @@ const DEFAULT_ROUTES = [
106
181
  * the plugin syncs when `managedRoutes` is empty. Not part of the public
107
182
  * runtime surface; subject to change without notice. */
108
183
  export const DEFAULT_ROUTES_LIST = DEFAULT_ROUTES;
184
+ // ---------------------------------------------------------------------------
185
+ // P1c go config / dependency helpers (design §6.2.6)
186
+ // ---------------------------------------------------------------------------
187
+ /** Read a volatile Config leaf, tolerating hosts/tests that hand a plain value. */
188
+ function readVolatile(slot, fallback) {
189
+ if (slot === undefined)
190
+ return fallback;
191
+ if (typeof slot === 'object' && slot !== null && typeof slot.get === 'function') {
192
+ return slot.get();
193
+ }
194
+ return slot;
195
+ }
196
+ /**
197
+ * Project the go Config subset for one round. Reads the live volatile refs, so
198
+ * a settings edit takes effect on the next round without a remount. The
199
+ * defensive shape also keeps older/partial fake configs (no `opencode` block)
200
+ * on the default zero-behavior path instead of throwing during apply().
201
+ */
202
+ function readGoRuntimeConfig(config) {
203
+ const raw = config;
204
+ const opencode = raw.opencode;
205
+ const go = opencode?.go;
206
+ const rawRoutes = go?.routes;
207
+ const routes = Object.fromEntries(Object.keys(GO_SLOT_ROUTES).map((slot) => [
208
+ slot,
209
+ readVolatile(rawRoutes?.[slot], GO_SLOT_ROUTES[slot]),
210
+ ]));
211
+ return {
212
+ enabled: readVolatile(go?.enabled, false),
213
+ value: {
214
+ enabled: readVolatile(go?.enabled, false),
215
+ ref: readVolatile(go?.ref, deriveKeyRef('opencode-go')),
216
+ modelsUrl: readVolatile(go?.modelsUrl, OPENCODE_GO_MODELS_URL),
217
+ routes,
218
+ pinnedModels: readVolatile(go?.pinnedModels, []),
219
+ confirmRemovals: readVolatile(go?.confirmRemovals, 2),
220
+ adoptExisting: readVolatile(go?.adoptExisting, false),
221
+ },
222
+ };
223
+ }
224
+ /**
225
+ * Project the go scheduling subset (design §6.3). `intervalMinutes` is the go
226
+ * field (default 60, floor 15, enforced by the scheduler); the startup delay is
227
+ * the shared top-level field the design names for startup jitter.
228
+ *
229
+ * `enabled` defaults to false — the design §6.2.6 value, unchanged by P1d-1.
230
+ * Migration zero-write is now enforced independently by routeWriter (§14.6 /
231
+ * §14.7) on every write path, so this default is a product choice, not the
232
+ * only protection. All scheduler paths are still gated by this value.
233
+ */
234
+ function readGoSchedulerConfig(config) {
235
+ const raw = config;
236
+ const opencode = raw.opencode;
237
+ const go = opencode?.go;
238
+ return {
239
+ enabled: readVolatile(go?.enabled, false),
240
+ intervalMinutes: readVolatile(go?.intervalMinutes, OPENCODE_GO_DEFAULT_INTERVAL_MINUTES),
241
+ startupDelaySeconds: readVolatile(raw.startupDelaySeconds, 5),
242
+ };
243
+ }
244
+ /**
245
+ * Revision-keyed (not time-window-keyed) reentry marker. `readRevision` reads
246
+ * the live descriptor after a mutate, so the marker always holds the revision
247
+ * the host stamped on OUR write; a later event for the same ns+revision can
248
+ * only be that write's echo (§14.7.2 items 1/5). `now` is injected so tests
249
+ * never depend on a wall clock.
250
+ */
251
+ function createOwnWriteTracker(readRevision, now) {
252
+ let last;
253
+ const tracker = {
254
+ record(ns) {
255
+ const revision = readRevision(ns);
256
+ if (revision !== undefined)
257
+ last = { ns, revision, at: now() };
258
+ },
259
+ matches(ns, eventRevision) {
260
+ if (last === undefined || last.ns !== ns)
261
+ return false;
262
+ if (eventRevision !== undefined)
263
+ return eventRevision === last.revision;
264
+ const current = readRevision(ns);
265
+ return current !== undefined && current === last.revision;
266
+ },
267
+ };
268
+ return tracker;
269
+ }
270
+ function settingsRevision(settings, ns) {
271
+ return settings?.describe().find((desc) => desc.ns === ns)?.revision;
272
+ }
109
273
  export async function apply(ctx, config) {
110
274
  // On dsh 0.1.7 the resolved Config arrives as apply()'s second argument:
111
275
  // every volatile field is a stable reference (see VolatileRef), so the
112
276
  // reads below are live views — no scope.get() and no scope.watch() (both
113
277
  // removed from dsh-settings; the hot-reload notification moved to the
114
278
  // settings/document-updated event, subscribed at the bottom of apply()).
279
+ // P1d-1: one reentry marker shared by every write path. `rawSettings()` is
280
+ // resolved per call so a host that mounts the settings service after this
281
+ // plugin still works; the thin wrapper records the post-mutate revision for
282
+ // the document-updated reentry check (§14.7.2). Every settings-writing path
283
+ // below goes through `settingsForWrite*` — never a bare ctx.get('settings').
284
+ const rawSettings = () => ctx.get('settings');
285
+ const ownWrite = createOwnWriteTracker((ns) => settingsRevision(rawSettings(), ns), () => Date.now());
286
+ const settingsForWriteFrom = (context) => {
287
+ const raw = context.get('settings');
288
+ if (raw === undefined)
289
+ return undefined;
290
+ return {
291
+ describe: () => raw.describe(),
292
+ mutate: async (ns, ops, expectedRevision) => {
293
+ await raw.mutate(ns, ops, expectedRevision);
294
+ ownWrite.record(ns);
295
+ },
296
+ };
297
+ };
298
+ const settingsForWrite = () => settingsForWriteFrom(ctx);
299
+ // B1/H9: one stable profile identity per plugin instance, resolved from the
300
+ // host (profileContext / DSH_PROFILE). Both file-backed stores below scope
301
+ // every shared models-store key with it so two profiles cannot share a
302
+ // migration record or ownership ledger entry. When no identity can be
303
+ // resolved there is NO 'default' collapse: every file-backed ledger path
304
+ // fails closed with an actionable error instead of silently sharing a key.
305
+ const profileKey = resolveProfileKey(ctx);
306
+ const requireScopedProfileKey = () => {
307
+ if (profileKey === undefined)
308
+ throw new Error(PROFILE_IDENTITY_REQUIRED_MESSAGE);
309
+ return profileKey;
310
+ };
311
+ // The injection seam is an explicit opt-in (tests / hosts that supply their
312
+ // own scoped store); only the file-backed fallback requires host identity.
313
+ const migrationStore = () => ctx.get(GO_MIGRATION_STORE_SERVICE)
314
+ ?? createModelsStoreMigrationStateStore(undefined, requireScopedProfileKey());
315
+ const ownershipStoreForRound = () => ctx.get(GO_OWNERSHIP_STORE_SERVICE)
316
+ ?? createModelsStoreOwnershipStore(undefined, requireScopedProfileKey());
317
+ // O1/C2: the journal lives in the same models-store.json. An injected seam
318
+ // wins (tests use a temp-dir accessor); without a resolved profile identity
319
+ // there is NO journal — never fall back to the real default ~/.dsh from a
320
+ // host/test that supplied no identity (the ledger path fails closed too).
321
+ const journalStoreForRound = () => ctx.get(GO_JOURNAL_STORE_SERVICE)
322
+ ?? (profileKey === undefined ? undefined : createModelsStoreJournalStore());
323
+ /**
324
+ * Read current migration status from the persisted record + live settings +
325
+ * (when a key fingerprint is available) the live ownership ledger.
326
+ * `strict` rethrows a record read failure so the §14.7.5 second gate can fail
327
+ * closed with `canWrite-unavailable`; the normal path degrades to "no record"
328
+ * (conservative legacy detection) as before.
329
+ */
330
+ const loadMigrationStatus = async (opts = {}) => {
331
+ const desc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai');
332
+ // H9 fail-closed: with no resolvable profile identity the file-backed store
333
+ // factory throws. A non-strict READ degrades to "no record" (gate closed,
334
+ // zero writes) so boot-time status refreshes / isApplying cannot produce an
335
+ // unhandled rejection; strict reads (the per-mutate second gate) rethrow.
336
+ // Every WRITE path still fails closed when it builds its file-backed store.
337
+ // N2: remember an identity-refused file-backed store so the (non-strict)
338
+ // status read can surface it instead of looking like a normal legacy state.
339
+ // The check is on the thrown identity error, not on `profileKey === undefined`
340
+ // alone: an injected-store host has a usable ledger even with no host
341
+ // identity and must NOT get a false "identity unavailable" report.
342
+ let identityUnavailable = false;
343
+ let store;
344
+ try {
345
+ store = migrationStore();
346
+ }
347
+ catch (err) {
348
+ if (opts.strict === true)
349
+ throw err;
350
+ if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE)
351
+ identityUnavailable = true;
352
+ }
353
+ let record;
354
+ try {
355
+ record = await store?.read();
356
+ }
357
+ catch (err) {
358
+ if (opts.strict === true)
359
+ throw err;
360
+ record = undefined; // unreadable ⇒ conservative legacy detection
361
+ }
362
+ const goRoutes = Object.values(readGoRuntimeConfig(config).value.routes ?? {});
363
+ let managedIds;
364
+ const fp = opts.keyFingerprint;
365
+ if (fp !== undefined) {
366
+ let ownership;
367
+ try {
368
+ ownership = ownershipStoreForRound();
369
+ }
370
+ catch (err) {
371
+ if (opts.strict === true)
372
+ throw err;
373
+ if (err instanceof Error && err.message === PROFILE_IDENTITY_REQUIRED_MESSAGE)
374
+ identityUnavailable = true;
375
+ }
376
+ // Only routes with a REAL ledger entry join the fingerprint set. The old
377
+ // `<route>: []` filler for configured-but-absent routes disagreed with
378
+ // migrate/onOwnWrite and produced a phantom `fingerprint-healed` on the
379
+ // first healthy round after onboarding.
380
+ managedIds = await goLedgerManagedIds(goRoutes, (route) => ownership === undefined
381
+ ? Promise.resolve(undefined)
382
+ : ownership.read(goOwnershipKey(route, fp)));
383
+ }
384
+ const status = migrationStatusOf(desc, record, goRoutes, managedIds);
385
+ // W1/D6: the go report and `migrate status` must agree on the label for a
386
+ // record this profile cannot claim. Use the SAME helper as migrate status;
387
+ // only when our own scoped read() found no record (B1 isolation). This is
388
+ // label-only: both states already keep the gate closed / write authority
389
+ // none / zero writes, and nothing is claimed or deleted.
390
+ if (record === undefined && store?.unclaimedRecords !== undefined) {
391
+ let unclaimed;
392
+ try {
393
+ unclaimed = await store.unclaimedRecords();
394
+ }
395
+ catch (err) {
396
+ if (opts.strict === true)
397
+ throw err;
398
+ unclaimed = []; // advisory provenance scan never changes the gate
399
+ }
400
+ const recordState = unclaimedRecordState(unclaimed);
401
+ if (recordState !== undefined)
402
+ status.state = recordState;
403
+ }
404
+ // N2: a non-strict refresh that degraded because no identity was available
405
+ // must be VISIBLE — log the actionable error (covers boot / document-updated
406
+ // refresh where there is no report line) and tag the status so sync reports
407
+ // do not show the normal legacy hint. This changes NO write/fail-closed
408
+ // behavior: the gate is already closed and no store/settings write occurs.
409
+ if (identityUnavailable) {
410
+ status.identityUnavailable = true;
411
+ ctx.logger.warn('model-sync: non-strict status refresh degraded — %s', PROFILE_IDENTITY_REQUIRED_MESSAGE);
412
+ }
413
+ // §14.7.4 self-heal: identity matches but the stored full fingerprint is
414
+ // stale because the fingerprint persist failed after settings+ledger landed.
415
+ // Rewrite it in the same queue instead of closing the gate forever.
416
+ if (status.fingerprintHealed && typeof store?.write === 'function') {
417
+ try {
418
+ ctx.logger.info('model-sync: fingerprint-healed (identity matched; stale appliedFingerprint)');
419
+ await store.write({
420
+ ...(record ?? {}),
421
+ appliedManagedIds: managedIds ?? record?.appliedManagedIds,
422
+ appliedFingerprint: status.expectedFingerprint,
423
+ });
424
+ status.appliedFingerprint = status.expectedFingerprint;
425
+ status.fingerprintHealed = false;
426
+ }
427
+ catch (err) {
428
+ ctx.logger.warn('model-sync: fingerprint-healed write failed: %s', err instanceof Error ? err.message : String(err));
429
+ }
430
+ }
431
+ return status;
432
+ };
115
433
  // -----------------------------------------------------------------------
116
434
  // Overlay mode sync (existing behavior)
117
435
  // -----------------------------------------------------------------------
@@ -181,7 +499,7 @@ export async function apply(ctx, config) {
181
499
  // Settings mode sync (Plan C: fetch → translate → write)
182
500
  // -----------------------------------------------------------------------
183
501
  const syncSettings = async (config, force) => {
184
- const settings = ctx.get('settings');
502
+ const settings = settingsForWrite();
185
503
  const logger = ctx.logger;
186
504
  const store = loadModelsStore();
187
505
  const lines = [];
@@ -190,9 +508,35 @@ export async function apply(ctx, config) {
190
508
  const routes = managedRoutes.length > 0
191
509
  ? [...managedRoutes]
192
510
  : DEFAULT_ROUTES;
511
+ // P1d-1 single writer: while opencode.go.enabled=true the legacy pi.dev
512
+ // path must NEVER write an `opencode-go*` route — not even in `absent` /
513
+ // `applied` state (that belongs to go sync), and especially not when the
514
+ // migration gate is closed. Login-triggered/manual/auto all funnel through
515
+ // this one loop (design §14.7.1, ADR-008).
516
+ const { value: goCfg } = readGoRuntimeConfig(config);
517
+ const goRouteIds = Object.values(goCfg.routes ?? {});
518
+ const piDevAuthority = { caller: 'pi.dev', goEnabled: goCfg.enabled, goRoutes: goRouteIds };
519
+ let piDevMigration;
193
520
  const gateDesc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
194
521
  const gateCtx = ctx;
195
522
  for (const route of routes) {
523
+ // Single-writer gate before ANY fetch/translate/mutate for go routes.
524
+ // A skip always produces a report line (never silent, §14.7.1).
525
+ if (goCfg.enabled && isGoRoute(route, goRouteIds)) {
526
+ piDevMigration ??= await loadMigrationStatus();
527
+ const decision = routeWriter(route, piDevAuthority, piDevMigration);
528
+ if (decision.decision === 'skip') {
529
+ // N2: an identity-refused ledger is NOT a normal legacy state. Surface
530
+ // the actionable identity hint instead of the generic migration hint.
531
+ const hint = piDevMigration.identityUnavailable === true
532
+ ? `; ${PROFILE_IDENTITY_STATUS_HINT}`
533
+ : (piDevMigration.state === 'absent' || piDevMigration.state === 'applied'
534
+ ? ''
535
+ : `; ${MIGRATION_GATE_HINT}`);
536
+ lines.push(`${route}: skipped — ${decision.reason}${hint}`);
537
+ continue;
538
+ }
539
+ }
196
540
  // Layer 1 follows llm-pi-ai's resolveApiKey: prefer the credentials seam.
197
541
  // Layer 2 follows its authContextFrom(ctx).env(): launch environment,
198
542
  // or process.env when the service is absent. Both miss → skip fetch,
@@ -373,6 +717,421 @@ export async function apply(ctx, config) {
373
717
  }
374
718
  return syncOverlay(config, llm, force);
375
719
  };
720
+ // -----------------------------------------------------------------------
721
+ // P1c go round: source → planner → writer, all deps from cordis seams.
722
+ // P1c-2 wraps this in the scheduler below; the round itself still owns no
723
+ // timer and no command registration.
724
+ // -----------------------------------------------------------------------
725
+ const runGoRound = async (options = {}) => {
726
+ const { value } = readGoRuntimeConfig(config);
727
+ const settings = settingsForWrite();
728
+ const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
729
+ const apiKey = await resolveRouteCredentialValue(ctx, desc, 'opencode-go', value.ref);
730
+ // The ledger is keyed by the same credential fingerprint the source uses;
731
+ // deriving it here lets the status read include the live managed-id set.
732
+ const keyFingerprint = fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : '');
733
+ const migration = await loadMigrationStatus({ keyFingerprint });
734
+ const ownershipStore = ownershipStoreForRound();
735
+ // The existing models-store accessor already satisfies GoOverrideStorer
736
+ // (read(route).overrides + updateOverrides); the service seam lets tests
737
+ // point both stores at a temp dir instead of the real ~/.dsh.
738
+ const overrideStorer = ctx.get(GO_OVERRIDE_STORER_SERVICE)
739
+ ?? loadModelsStore();
740
+ return runGoSyncRound({
741
+ settings,
742
+ ownershipStore,
743
+ overrideStorer,
744
+ logger: ctx.logger,
745
+ // The explicit `adopt` command honours the master switch: disabled means
746
+ // zero writes (design §6.2.6). runGoSyncRound checks `enabled` first.
747
+ config: options.adopt === true ? { ...value, adoptExisting: true } : value,
748
+ apiKey,
749
+ fetchImpl: ctx.get(GO_FETCH_SERVICE),
750
+ signal: options.signal,
751
+ migration,
752
+ // O1/C2: journal + reconciliation use the same profile/fingerprint as the
753
+ // ledger. Reconciliation runs before the gate inside runGoSyncRound.
754
+ journalStore: journalStoreForRound(),
755
+ profileKey,
756
+ keyFingerprint,
757
+ // §14.7.5: the second gate re-reads the persisted record on each mutate
758
+ // (strict: a failed read skips the route with canWrite-unavailable).
759
+ reloadMigration: () => loadMigrationStatus({ keyFingerprint, strict: true }),
760
+ // §14.7.4: settings → ledger → fingerprint, all through the same
761
+ // models-store queue; only successful own writes reach this callback.
762
+ onOwnWrite: async (route, managedIds) => {
763
+ const store = migrationStore();
764
+ if (typeof store.write !== 'function')
765
+ return; // read-only injected store
766
+ let record;
767
+ try {
768
+ record = await store.read();
769
+ }
770
+ catch {
771
+ return; // cannot merge safely; the next round's self-heal covers it
772
+ }
773
+ const goRoutes = Object.values(value.routes ?? {});
774
+ const liveDesc = rawSettings()?.describe().find((d) => d.ns === 'llm-pi-ai');
775
+ const sections = readGoProviderSections(liveDesc, goRoutes);
776
+ const appliedIdentityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {});
777
+ const appliedManagedIds = { ...(record?.appliedManagedIds ?? {}), [route]: [...managedIds].sort() };
778
+ // Same helper + route-set convention as loadMigrationStatus: a normal
779
+ // onboarding/own write must not look like a fingerprint drift next round.
780
+ const { identity, appliedFingerprint } = appliedFingerprintFieldsOf(sections, record, appliedManagedIds);
781
+ await store.write({
782
+ ...(record ?? {}),
783
+ appliedIdentity: identity,
784
+ appliedIdentityRoutes,
785
+ appliedManagedIds,
786
+ appliedFingerprint,
787
+ });
788
+ },
789
+ });
790
+ };
791
+ // -----------------------------------------------------------------------
792
+ // P1c-2: async timer + scheduling for the go round (design §6.3 / §14.6).
793
+ // One GoScheduler instance serves BOTH the timer and the manual /model-sync
794
+ // go command, so they share the single-flight lock. Clock and jitter inputs
795
+ // are optional cordis services so tests never arm a real timer.
796
+ // -----------------------------------------------------------------------
797
+ const goTimers = ctx.get(GO_SCHEDULER_TIMERS_SERVICE) ?? {
798
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
799
+ clearTimeout: (handle) => clearTimeout(handle),
800
+ };
801
+ const goRandom = ctx.get(GO_SCHEDULER_RANDOM_SERVICE)
802
+ ?? { next: () => Math.random() };
803
+ const goScheduler = new GoScheduler({
804
+ config: () => readGoSchedulerConfig(config),
805
+ timers: goTimers,
806
+ random: goRandom,
807
+ runRound: async ({ adopt, signal }) => {
808
+ const round = await runGoRound({ adopt, signal });
809
+ return {
810
+ ok: round.ok,
811
+ reason: round.reason,
812
+ text: round.text,
813
+ failureKind: round.reason === 'source-failed' && round.source?.error !== undefined
814
+ ? round.source.error.kind
815
+ : undefined,
816
+ };
817
+ },
818
+ report: (text) => {
819
+ for (const line of text.split('\n'))
820
+ ctx.logger.info('model-sync: %s', line);
821
+ },
822
+ // M-5: drop (never queue) any round while a migration apply holds the routes.
823
+ isApplying: async () => (await loadMigrationStatus()).applying,
824
+ });
825
+ ctx.effect(() => () => goScheduler.dispose(), 'dsh-model-sync: go scheduler dispose');
826
+ // A changed credential invalidates any accumulated backoff: a fixed key must
827
+ // retry on the normal schedule instead of waiting out a capped 6h backoff
828
+ // (design §6.3). The effect scopes the listener to this plugin's lifetime —
829
+ // unload removes it together with the scheduler.
830
+ ctx.effect(() => ctx.on('credentials/reference-updated', (ref) => {
831
+ if (typeof ref !== 'string')
832
+ return;
833
+ const { value } = readGoRuntimeConfig(config);
834
+ if (ref !== value.ref)
835
+ return;
836
+ goScheduler.resetBackoff();
837
+ }), 'dsh-model-sync: credentials/reference-updated → go backoff reset');
838
+ goScheduler.start();
839
+ /** Resolve the official listing through an injectable seam (tests: a fixture array). */
840
+ const resolveMigrateEntries = async (value, apiKey) => {
841
+ const injected = ctx.get(GO_MIGRATION_ENTRIES_SERVICE);
842
+ if (Array.isArray(injected))
843
+ return injected;
844
+ if (typeof injected === 'function')
845
+ return await injected();
846
+ const source = await fetchGoOfficialModels({
847
+ url: value.modelsUrl,
848
+ apiKey,
849
+ fetchImpl: ctx.get(GO_FETCH_SERVICE),
850
+ timeoutMs: config.refreshTimeoutMs.get(),
851
+ });
852
+ if (!source.ok) {
853
+ throw new Error(`official opencode-go listing unavailable (${source.error?.kind ?? 'unknown'}); no plan generated`);
854
+ }
855
+ return source.entries;
856
+ };
857
+ /**
858
+ * Public-catalog producer for id classification (§14.2): ids the current key
859
+ * cannot serve but that are still official are `unknown-retired`, everything
860
+ * else is `user-extra`. When the public list cannot be fetched the result is
861
+ * `undefined`, which makes the plan mark such ids `unclassified` (never
862
+ * deleted) instead of defaulting them to deletable `user-extra`.
863
+ */
864
+ const resolvePublicCatalogIds = async (value, entries) => {
865
+ const injected = ctx.get(GO_MIGRATION_PUBLIC_CATALOG_SERVICE);
866
+ if (Array.isArray(injected))
867
+ return injected;
868
+ if (typeof injected === 'function')
869
+ return await injected();
870
+ // Offline fixture mode: the injected authorized entries are the only catalog
871
+ // available; deriving ids from them keeps `migrate plan` zero-fetch (V16).
872
+ if (ctx.get(GO_MIGRATION_ENTRIES_SERVICE) !== undefined)
873
+ return entries.map((entry) => entry.id);
874
+ const result = await fetchGoPublicCatalogIds({
875
+ url: value.modelsUrl,
876
+ fetchImpl: ctx.get(GO_FETCH_SERVICE),
877
+ timeoutMs: config.refreshTimeoutMs.get(),
878
+ });
879
+ return result.ok ? result.ids : undefined;
880
+ };
881
+ const migrateDeps = async (target, opts = {}, needsEntries = true) => {
882
+ const { value } = readGoRuntimeConfig(config);
883
+ const settings = settingsForWriteFrom(target);
884
+ const desc = settings?.describe().find((d) => d.ns === 'llm-pi-ai');
885
+ const apiKey = await resolveRouteCredentialValue(target, desc, 'opencode-go', value.ref);
886
+ const refWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE);
887
+ // Keep the pre-action-table evaluation order: the file-backed stores fail
888
+ // closed without a profile identity, and must do so BEFORE any source
889
+ // fetch (D4: no identity ⇒ zero outbound requests, zero writes).
890
+ const ownershipStore = target.get(GO_OWNERSHIP_STORE_SERVICE)
891
+ ?? ownershipStoreForRound();
892
+ const store = migrationStore();
893
+ // status/rollback never need the official listing: no fetch, no extra I/O.
894
+ const entries = needsEntries ? await resolveMigrateEntries(value, apiKey) : [];
895
+ const publicCatalogIds = needsEntries ? await resolvePublicCatalogIds(value, entries) : undefined;
896
+ const adoptDisabled = ctx.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
897
+ || settings === undefined || typeof settings.mutate !== 'function';
898
+ return {
899
+ settings,
900
+ ownershipStore,
901
+ migrationStore: store,
902
+ logger: target.logger,
903
+ entries,
904
+ publicCatalogIds,
905
+ routes: value.routes,
906
+ ref: value.ref,
907
+ keyFingerprint: fingerprintKey(typeof apiKey === 'string' ? apiKey.trim() : ''),
908
+ adopt: opts.adopt,
909
+ adoptDisabled,
910
+ rewriteRefs: opts.rewriteRefs,
911
+ // Config path: go.pinnedModels (readGoRuntimeConfig:361) now reaches plan.
912
+ pinnedModels: value.pinnedModels,
913
+ pruneUserExtra: opts.pruneUserExtra,
914
+ now: Date.now(),
915
+ isSyncInFlight: ctx.get(GO_MIGRATION_MUTEX_SERVICE)
916
+ ?? (() => goScheduler.isInFlight),
917
+ applyReferenceRewrite: refWriter,
918
+ // O1/C2: apply/rollback clear this profile's journals so a stale slot
919
+ // cannot re-account settings that the migration just rewrote or undid.
920
+ journalStore: journalStoreForRound(),
921
+ profileKey,
922
+ };
923
+ };
924
+ /** Shared by the slash command and the `modelSync` host service (§14.5). */
925
+ const runMigrate = async (args, target) => {
926
+ const usage = [
927
+ 'usage: /model-sync migrate plan [--adopt] [--prune-user-extra] [--rewrite-refs=default-model|config]',
928
+ ' /model-sync migrate apply --plan <planHash> --confirm <6-digit-code> --ack-managed',
929
+ ' /model-sync migrate rollback --plan <planHash>',
930
+ ' /model-sync migrate status',
931
+ ].join('\n');
932
+ const action = args[0] ?? 'plan';
933
+ const rest = args.slice(1);
934
+ if (!['plan', 'apply', 'rollback', 'status'].includes(action)) {
935
+ return { kind: 'error', text: `migrate: unknown action '${action}'\n${usage}` };
936
+ }
937
+ // Consent has no bypass: these flags are recognised and rejected explicitly.
938
+ if (rest.some((flag) => flag === '--yes' || flag === '--auto' || flag.startsWith('--yes=') || flag.startsWith('--auto='))) {
939
+ return { kind: 'error', text: 'migrate: --yes/--auto are not supported; apply requires --plan <hash> and --confirm <code>' };
940
+ }
941
+ const flagValue = (name) => {
942
+ const index = rest.indexOf(name);
943
+ if (index >= 0)
944
+ return rest[index + 1];
945
+ const inline = rest.find((token) => token.startsWith(`${name}=`));
946
+ return inline?.slice(name.length + 1);
947
+ };
948
+ const planHash = flagValue('--plan');
949
+ const confirmCode = flagValue('--confirm');
950
+ const adopt = rest.includes('--adopt');
951
+ const ackManaged = rest.includes('--ack-managed');
952
+ const pruneUserExtra = rest.includes('--prune-user-extra');
953
+ const rewriteRefsRaw = rest.find((token) => token.startsWith('--rewrite-refs='))?.slice('--rewrite-refs='.length);
954
+ const rewriteRefs = rewriteRefsRaw === 'default-model' || rewriteRefsRaw === 'config'
955
+ ? rewriteRefsRaw
956
+ : undefined;
957
+ try {
958
+ if (action === 'status') {
959
+ const deps = await migrateDeps(target, {}, false);
960
+ const report = await migrationStatusReport(deps, { caller: 'go', goEnabled: readGoRuntimeConfig(config).value.enabled });
961
+ return { kind: 'success', text: report.text };
962
+ }
963
+ if (action === 'plan') {
964
+ const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra });
965
+ const record = await deps.migrationStore.read().catch(() => undefined);
966
+ // Same pure builder apply uses — the printed table IS the consented one.
967
+ // When adopt is disabled the mode is reported as adopt-disabled and the
968
+ // rows stay conservative; no adopt action can be printed as executable.
969
+ const plan = buildMigrationPlanFromDeps(deps, record);
970
+ return { kind: 'success', text: formatMigrationPlan(plan) };
971
+ }
972
+ if (action === 'apply') {
973
+ const deps = await migrateDeps(target, { adopt, rewriteRefs, pruneUserExtra });
974
+ // Fail-closed fallback (§14.2): reject at the command layer before any
975
+ // write when the per-id action table cannot be executed verbatim.
976
+ if (adopt && deps.adoptDisabled === true) {
977
+ return {
978
+ kind: 'error',
979
+ text: 'migrate apply refused (adopt-disabled): --adopt cannot execute the per-id action table verbatim; use conservative mode; zero writes',
980
+ };
981
+ }
982
+ const result = await applyMigration({ planHash, confirmCode, ackManaged }, deps);
983
+ return { kind: result.ok ? 'success' : 'error', text: result.text };
984
+ }
985
+ // rollback
986
+ const deps = await migrateDeps(target, {}, false);
987
+ const result = await rollbackMigration({ planHash }, deps);
988
+ return { kind: result.ok ? 'success' : 'error', text: result.text };
989
+ }
990
+ catch (error) {
991
+ const message = error instanceof Error ? error.message : String(error);
992
+ return { kind: 'error', text: `migrate ${action} failed: ${message}` };
993
+ }
994
+ };
995
+ // -----------------------------------------------------------------------
996
+ // One-shot migrate-go deps (design: one command = plan + backup + confirm
997
+ // + apply). Assembled from the same seams migrateDeps reads; the fs subset
998
+ // and the clock are the only new external surfaces, both plain adapters
999
+ // over node:fs/promises and Date here so tests inject their own.
1000
+ // -----------------------------------------------------------------------
1001
+ const oneShotFs = {
1002
+ readFile: (path) => readFile(path, 'utf8'),
1003
+ writeFile: (path, data, mode) => (mode === undefined ? writeFile(path, data) : writeFile(path, data, { mode })),
1004
+ rename: (from, to) => rename(from, to),
1005
+ unlink: async (path) => { await unlink(path); },
1006
+ mkdir: async (path, options) => { await mkdir(path, options); },
1007
+ stat: async (path) => {
1008
+ const info = await statFd(path).catch(() => undefined);
1009
+ return info === undefined ? undefined : { mode: info.mode };
1010
+ },
1011
+ readdir: async (path) => readdir(path),
1012
+ // Backup creation: claim the final name exclusively (O_EXCL `wx` — false
1013
+ // when taken, so the caller retries the next sequence suffix), stamp the
1014
+ // claim with a recognizable placeholder line, then replace the claimed
1015
+ // file atomically via tmp + rename. A crash between claim and rename
1016
+ // leaves a self-describing placeholder (review M7) instead of a silent
1017
+ // 0-byte file that looks like a real backup; the tmp+rename guarantees the
1018
+ // backup content itself is never torn. A failure of the tmp write or the
1019
+ // rename releases the claim AND removes the tmp residue.
1020
+ writeFileExclusive: async (path, data, mode) => {
1021
+ let handle;
1022
+ try {
1023
+ handle = await open(path, 'wx', mode);
1024
+ }
1025
+ catch (err) {
1026
+ if (err.code === 'EEXIST')
1027
+ return false;
1028
+ throw err;
1029
+ }
1030
+ try {
1031
+ // The file was created with `mode` by open(wx); the placeholder write
1032
+ // keeps that mode — no explicit mode needed here.
1033
+ await handle.writeFile('dsh-model-sync: backup claim in progress — crash residue, NOT a backup (safe to delete)\n');
1034
+ }
1035
+ finally {
1036
+ await handle.close().catch(() => { });
1037
+ }
1038
+ const tmp = `${path}.tmp-${process.pid}-${exclusiveWriteSeq++}`;
1039
+ try {
1040
+ await writeFile(tmp, data, mode === undefined ? undefined : { mode });
1041
+ await rename(tmp, path);
1042
+ return true;
1043
+ }
1044
+ catch (err) {
1045
+ await unlink(tmp).catch(() => { }); // remove the tmp residue (review M7)
1046
+ await unlink(path).catch(() => { }); // release the claim; nothing was replaced
1047
+ throw err;
1048
+ }
1049
+ },
1050
+ };
1051
+ let exclusiveWriteSeq = 0;
1052
+ /** Sync-read + atomic-write io for one patch file (describe() is sync). */
1053
+ const patchIoFor = (path) => {
1054
+ let writeSeq = 0;
1055
+ return {
1056
+ readText: () => readFileSync(path, 'utf8'),
1057
+ writeAtomic: async (text) => {
1058
+ writeSeq += 1;
1059
+ const tmp = `${path}.tmp-${process.pid}-${writeSeq}`;
1060
+ const mode = statSync(path).mode;
1061
+ try {
1062
+ writeFileSync(tmp, text, mode !== undefined ? { mode } : undefined);
1063
+ await rename(tmp, path);
1064
+ }
1065
+ catch (err) {
1066
+ await unlink(tmp).catch(() => { }); // no tmp residue on a failed write (review M7)
1067
+ throw err;
1068
+ }
1069
+ },
1070
+ };
1071
+ };
1072
+ const buildOneShotDeps = (target) => {
1073
+ const { value } = readGoRuntimeConfig(config);
1074
+ const settings = settingsForWriteFrom(target);
1075
+ const desc = settings?.describe().find((item) => item.ns === 'llm-pi-ai');
1076
+ const ref = value.ref;
1077
+ const profile = target.get('profileContext');
1078
+ const launchEnv = target.get('launchEnvironment');
1079
+ const injectedMutex = target.get(GO_MIGRATION_MUTEX_SERVICE);
1080
+ const injectedRefWriter = target.get(GO_MIGRATION_REF_WRITER_SERVICE);
1081
+ const pathOverrides = target.get(GO_ONESHOT_PATHS_SERVICE);
1082
+ return {
1083
+ home: pathOverrides?.home ?? resolveDshHome(),
1084
+ modelsStorePath: pathOverrides?.modelsStorePath ?? MODELS_STORE_PATH,
1085
+ profilesDir: pathOverrides?.profilesDir,
1086
+ fs: oneShotFs,
1087
+ patchIoFor,
1088
+ currentProfile: {
1089
+ key: resolveProfileKey(target),
1090
+ dir: profile?.dir ?? launchEnv?.get('DSH_PROFILE_DIR')?.value,
1091
+ },
1092
+ currentSettings: settings,
1093
+ hostSettings: rawSettings(),
1094
+ goConfig: {
1095
+ routes: value.routes,
1096
+ ref,
1097
+ pinnedModels: value.pinnedModels,
1098
+ adoptDisabled: target.get(GO_MIGRATION_ADOPT_DISABLED_SERVICE) === true
1099
+ || settings === undefined || typeof settings.mutate !== 'function',
1100
+ },
1101
+ resolveCredential: async () => ({
1102
+ value: await resolveRouteCredentialValue(target, desc, 'opencode-go', ref),
1103
+ ref,
1104
+ }),
1105
+ resolveEntries: (apiKey) => resolveMigrateEntries(value, apiKey),
1106
+ resolvePublicCatalogIds: (_apiKey, entries) => resolvePublicCatalogIds(value, entries),
1107
+ resolveAsk: () => {
1108
+ try {
1109
+ return target.get('userQuestions');
1110
+ }
1111
+ catch {
1112
+ return undefined;
1113
+ }
1114
+ },
1115
+ // File-backed stores scoped per profile in the SAME models-store.json
1116
+ // the backup step snapshots. The GO_MIGRATION_STORE_SERVICE /
1117
+ // GO_OWNERSHIP_STORE_SERVICE seams are deliberately NOT consulted
1118
+ // here: the one-shot needs per-profile scoping, which the injected
1119
+ // single-store seams cannot express — the path override below is the
1120
+ // test seam instead (tests point it at a temp dir).
1121
+ storesFor: (profileKey) => ({
1122
+ ownership: createModelsStoreOwnershipStore(pathOverrides?.modelsStorePath, profileKey),
1123
+ migration: createModelsStoreMigrationStateStore(pathOverrides?.modelsStorePath, profileKey),
1124
+ }),
1125
+ journalStore: profileKey === undefined ? undefined : createModelsStoreJournalStore(pathOverrides?.modelsStorePath),
1126
+ isSyncInFlight: injectedMutex ?? (() => goScheduler.isInFlight),
1127
+ applyReferenceRewrite: injectedRefWriter,
1128
+ ...(pathOverrides?.testOnlyOwnershipWriteFaultPrefix !== undefined
1129
+ ? { faultOwnershipWriteOnKeyPrefix: pathOverrides.testOnlyOwnershipWriteFaultPrefix }
1130
+ : {}),
1131
+ logger: target.logger,
1132
+ now: Date.now,
1133
+ };
1134
+ };
376
1135
  /** Auto rounds log the same report the /model-sync command shows. */
377
1136
  const runAuto = () => {
378
1137
  // A rejected round (service lookups mid-dispose, a refused mutate) must
@@ -408,23 +1167,42 @@ export async function apply(ctx, config) {
408
1167
  // settings/document-updated event (the 0.1.7 replacement for scope.watch).
409
1168
  startupTimer = setTimeout(runAuto, Math.max(0, config.startupDelaySeconds.get() ?? 5) * 1000);
410
1169
  armInterval(config.intervalMinutes.get() ?? 240);
411
- ctx.effect(() => ctx.on('settings/document-updated', (ns) => {
412
- // Only this plugin's entry (the bundle-patch id) re-arms the timers; the
413
- // handler is idempotent — the refs already carry the new values, so the
414
- // next round reads them fresh. Never throws: an interval re-arm is two
415
- // timer calls, and a throwing settings listener is a host-side incident.
1170
+ ctx.effect(() => ctx.on('settings/document-updated', (ns, revision) => {
1171
+ // P1d-1 §14.7.2: if this event is the echo of a settings.mutate we just
1172
+ // performed, only refresh status — schedule NO round (the V23 race was a
1173
+ // go write echo triggering the legacy pi.dev auto round ~1s later).
1174
+ if (ownWrite.matches(ns, typeof revision === 'number' ? revision : undefined)) {
1175
+ ctx.logger.info('model-sync: reentry-ignored (ns=%s revision=%s); no round scheduled', ns, revision);
1176
+ void loadMigrationStatus(); // refresh state only; no timer, no runAuto
1177
+ return;
1178
+ }
1179
+ // Only this plugin's own config entry (the bundle-patch id) re-arms timers;
1180
+ // the handler is idempotent — the refs already carry the new values, so the
1181
+ // next round reads them fresh. A foreign ns (including llm-pi-ai writes by
1182
+ // other actors) never schedules a round here.
416
1183
  if (ns !== OWN_ENTRY_ID)
417
1184
  return;
418
1185
  armInterval(config.intervalMinutes.get() ?? 0);
419
- // Clear any pending startup timer before setting a new one
420
- if (startupTimer !== undefined)
421
- clearTimeout(startupTimer);
422
- startupTimer = setTimeout(runAuto, 1000);
1186
+ // §14.7.2 item 2: remove the old "immediate +1s runAuto". Config edits now
1187
+ // only re-arm the normal interval; an immediate round needs an explicit
1188
+ // /model-sync. (P1c-2 go scheduler still re-arms idempotently.)
1189
+ goScheduler.rearm();
1190
+ void loadMigrationStatus();
423
1191
  }), 'dsh-model-sync: settings/document-updated');
424
1192
  // The modelSync service stays exposed for UIs that want direct access. The
425
1193
  // /model-sync command itself is registered by this plugin (below) through
426
1194
  // the shared command registry, which interactive UIs discover on their own.
427
- ctx.provide('modelSync', { syncNow: () => syncNow(true) });
1195
+ ctx.provide('modelSync', {
1196
+ syncNow: () => syncNow(true),
1197
+ migratePlan: (options) => runMigrate(['plan', ...(options?.adopt === true ? ['--adopt'] : []),
1198
+ ...(options?.pruneUserExtra === true ? ['--prune-user-extra'] : []),
1199
+ ...(options?.rewriteRefs !== undefined ? [`--rewrite-refs=${options.rewriteRefs}`] : [])], ctx).then((result) => result.text),
1200
+ migrateApply: (args) => runMigrate(['apply', ...(args.planHash !== undefined ? ['--plan', args.planHash] : []),
1201
+ ...(args.confirmCode !== undefined ? ['--confirm', args.confirmCode] : []),
1202
+ ...(args.ackManaged === true ? ['--ack-managed'] : [])], ctx).then((result) => result.text),
1203
+ migrateRollback: (args) => runMigrate(['rollback', ...(args.planHash !== undefined ? ['--plan', args.planHash] : [])], ctx).then((result) => result.text),
1204
+ migrateStatus: () => runMigrate(['status'], ctx).then((result) => result.text),
1205
+ });
428
1206
  // Register the /model-sync slash command from the plugin itself. The
429
1207
  // registry is @deepseek-ai/dsh-commands' CommandRuntime ("Plugin-owned
430
1208
  // human-command registry shared by interactive UI adapters") — registration
@@ -440,8 +1218,85 @@ export async function apply(ctx, config) {
440
1218
  cmdCtx.effect(() => {
441
1219
  const definition = {
442
1220
  name: 'model-sync',
443
- description: 'Force one model-list sync round from the pi.dev gateway into settings (dsh-model-sync)',
1221
+ 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); migrate-go (one-shot full migration with file backups + one confirmation)',
444
1222
  handler: async (invocation) => {
1223
+ const args = invocation.rawInput.trim().split(/\s+/).filter((part) => part.length > 0);
1224
+ const [sub, scope] = args;
1225
+ // P1d-2: migration is the ONLY explicit-consent config writer. It is
1226
+ // never auto-triggered and never folded into the pi.dev sync path.
1227
+ if (sub === 'migrate') {
1228
+ return runMigrate(args.slice(1), cmdCtx);
1229
+ }
1230
+ // One-shot migrate-go: the full plan → backup → confirm → apply
1231
+ // pipeline for the current profile (or --all-profiles). Its consent
1232
+ // is the interactive confirmation; apply still passes through the
1233
+ // unchanged verifyConsent gate with the computed hash/code.
1234
+ if (sub === 'migrate-go') {
1235
+ const parsed = parseMigrateGoFlags(args.slice(1));
1236
+ if (!parsed.ok) {
1237
+ return { kind: 'error', text: parsed.error };
1238
+ }
1239
+ const flags = parsed.flags;
1240
+ try {
1241
+ return await runMigrateGoOneShot(buildOneShotDeps(cmdCtx), flags, { agent: invocation.agent, signal: invocation.signal });
1242
+ }
1243
+ catch (error) {
1244
+ const message = error instanceof Error ? error.message : String(error);
1245
+ return { kind: 'error', text: `migrate-go failed: ${message}` };
1246
+ }
1247
+ }
1248
+ // B3 (31 R-4): `eject` is retired — `migrate rollback` is the only
1249
+ // rollback entry. Reject the old invocation explicitly so it never
1250
+ // falls through to a bare sync (which would write to go routes under
1251
+ // a command name the user believed was read-only).
1252
+ if (sub === 'eject') {
1253
+ return { kind: 'error', text: 'model-sync eject go: retired; use /model-sync migrate rollback --plan <hash>' };
1254
+ }
1255
+ // Design §7.1 keeps bare `/model-sync` (pi.dev settings sync) exactly
1256
+ // as it was. The go subcommands are additive: `go`/`status` run one
1257
+ // full go round, `adopt go` runs it with adoption. Status stays the
1258
+ // read-only `/opencode-status` command — it is never a write trigger.
1259
+ if ((sub === 'go' || sub === 'status' || sub === 'adopt')
1260
+ && (scope === undefined || scope === 'go')) {
1261
+ try {
1262
+ // Route manual rounds through the scheduler so they share the
1263
+ // single-flight lock with timer-driven rounds. A second trigger
1264
+ // while a round is in flight is skipped and reported (design
1265
+ // §14.6), never queued. The report text is the round's own text,
1266
+ // unchanged, for real rounds.
1267
+ const outcome = await goScheduler.triggerManual({ adopt: sub === 'adopt' });
1268
+ // N1: a round that threw (e.g. the file-backed ledger refusing to
1269
+ // build without a profile identity) is reported as a scheduler
1270
+ // error. It is a real failure — the command must return
1271
+ // `kind:'error'` so callers that only read `kind` can detect it;
1272
+ // the actionable reason is carried in `text`. Skips (disabled,
1273
+ // already-in-flight, migration-applying, disposed) stay success,
1274
+ // byte-identical to before.
1275
+ const failed = outcome.reason === 'source-failed'
1276
+ // oldfox #3: a writer exception is a real failure at the
1277
+ // command surface, but a distinct reason from source failure.
1278
+ || outcome.reason === 'writer-error'
1279
+ || outcome.reason === 'scheduler-error'
1280
+ // B4: an abandoned round must be visible as a failure at the
1281
+ // command surface too (it is not a successful sync). The reason
1282
+ // text carries the actionable "settings changed, next round
1283
+ // retries" guidance; no backoff is scheduled for it.
1284
+ || outcome.reason === 'settings-changed-during-sync'
1285
+ // O1-minimal: failedRoutes (e.g. settings written but the ledger
1286
+ // failed) are a real failure even if other routes wrote. Callers
1287
+ // that only read `kind` must see `error`; the actionable reason
1288
+ // and the new report code are carried in `text`.
1289
+ || outcome.reason === 'write-failed';
1290
+ return {
1291
+ kind: failed ? 'error' : 'success',
1292
+ text: outcome.text,
1293
+ };
1294
+ }
1295
+ catch (error) {
1296
+ const message = error instanceof Error ? error.message : String(error);
1297
+ return { kind: 'error', text: `model-sync ${sub} failed: ${message}` };
1298
+ }
1299
+ }
445
1300
  const ignored = invocation.rawInput.trim().length > 0
446
1301
  ? 'The sync scope is decided by the model-sync managedRoutes config; the argument is ignored.\n'
447
1302
  : '';
@@ -457,6 +1312,35 @@ export async function apply(ctx, config) {
457
1312
  };
458
1313
  return commands.register(definition);
459
1314
  }, 'dsh-model-sync: /model-sync');
1315
+ // P0 read-only diagnostic. Parallel to /model-sync (whose behavior is
1316
+ // unchanged): fetch the official go listing, compare it with the current
1317
+ // profile's opencode-go routes, and print a structured report. This path
1318
+ // never calls settings.mutate, never writes credentials, and never edits
1319
+ // a profile file — it only reads describe()/credentials.resolve().
1320
+ cmdCtx.effect(() => {
1321
+ const definition = {
1322
+ name: 'opencode-status',
1323
+ description: 'Read-only diagnostic: compare opencode-go official /v1/models with the current profile routes (no writes)',
1324
+ handler: async (invocation) => {
1325
+ const token = invocation.rawInput.trim();
1326
+ const ignored = token !== '' && token !== 'go'
1327
+ ? 'opencode-status: P0 diagnoses opencode-go only; the argument is ignored.\n'
1328
+ : '';
1329
+ try {
1330
+ const desc = cmdCtx.get('settings')?.describe()
1331
+ .find((d) => d.ns === 'llm-pi-ai');
1332
+ const apiKey = await resolveRouteCredentialValue(cmdCtx, desc, 'opencode-go');
1333
+ const report = await runGoDiagnostic({ apiKey, descriptor: desc });
1334
+ return { kind: 'success', text: `${ignored}${formatGoDiagnosticReport(report)}` };
1335
+ }
1336
+ catch (error) {
1337
+ const message = error instanceof Error ? error.message : String(error);
1338
+ return { kind: 'error', text: `${ignored}opencode-status failed: ${message}` };
1339
+ }
1340
+ },
1341
+ };
1342
+ return commands.register(definition);
1343
+ }, 'dsh-model-sync: /opencode-status');
460
1344
  });
461
1345
  // One-time legacy settings import (0.1.5 → 0.1.7 upgrade path, see
462
1346
  // legacy-import.ts): recover the old `model-sync:` section for hosts where