@aiwayds/dsh-model-sync 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,112 @@
1
+ // Live builtin-catalog loader — prefer the host's own pi-ai data over the
2
+ // frozen build-time snapshot.
3
+ //
4
+ // Why this exists: the snapshot (builtin-catalog-snapshot.ts) is generated at
5
+ // dev time and goes stale the moment the host's bundled pi-ai drops, renames,
6
+ // or adds models. A stale snapshot made keepBuiltinOnly emit a grok-4.5 entry
7
+ // the host no longer knew (pi-ai 0.84.4 removed it), and the alpha line's
8
+ // strict llm-pi-ai registration rejected the whole namespace because of it —
9
+ // every provider route vanished from the TUI (2026-09-02). Reading the live
10
+ // data keeps emitted ids serviceable by construction. The snapshot remains
11
+ // only as a per-route fallback when the host install cannot be located (e.g.
12
+ // `npm test` on a machine without dsh).
13
+ //
14
+ // Discovery order for the host closure's @earendil-works/pi-ai:
15
+ // 1. DSH_CLOSURE_DIR — points at the @deepseek-ai closure dir (same
16
+ // convention as scripts/link-dsh-closure.mjs); @earendil-works/pi-ai is
17
+ // a sibling scope of the same node_modules.
18
+ // 2. `which dsh` realpath — the installed CLI's own node_modules.
19
+ // 3. `npm root -g` — dsh's nested node_modules, then the flat layout.
20
+
21
+ import { execFileSync } from 'node:child_process'
22
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
23
+ import { dirname, join } from 'node:path'
24
+ import type { BuiltinModelData } from './translate.ts'
25
+
26
+ const DATA_REL = join('dist', 'providers', 'data')
27
+
28
+ interface CatalogCache {
29
+ dir: string
30
+ byRoute: Map<string, BuiltinModelData[]>
31
+ }
32
+
33
+ let cache: CatalogCache | undefined
34
+
35
+ function findPiAiPackageDir(): string | undefined {
36
+ const candidates: string[] = []
37
+ const override = process.env.DSH_CLOSURE_DIR
38
+ if (override !== undefined && override !== '') {
39
+ try {
40
+ candidates.push(join(dirname(realpathSync(override)), '@earendil-works', 'pi-ai'))
41
+ } catch { /* bad override path — fall through to auto-discovery */ }
42
+ }
43
+ try {
44
+ const bin = execFileSync('which', ['dsh'], { encoding: 'utf8' }).trim()
45
+ if (bin !== '') {
46
+ const real = realpathSync(bin)
47
+ candidates.push(join(dirname(dirname(real)), 'node_modules', '@earendil-works', 'pi-ai'))
48
+ }
49
+ } catch { /* dsh not on PATH */ }
50
+ try {
51
+ const root = execFileSync('npm', ['root', '-g'], { encoding: 'utf8' }).trim()
52
+ if (root !== '') {
53
+ candidates.push(join(root, '@deepseek-ai', 'dsh', 'node_modules', '@earendil-works', 'pi-ai'))
54
+ candidates.push(join(root, '@earendil-works', 'pi-ai'))
55
+ }
56
+ } catch { /* npm unavailable */ }
57
+ for (const candidate of candidates) {
58
+ try {
59
+ const dir = realpathSync(candidate)
60
+ if (existsSync(join(dir, DATA_REL))) return dir
61
+ } catch { /* candidate missing — try next */ }
62
+ }
63
+ return undefined
64
+ }
65
+
66
+ /** Flatten one route's pi-ai data file (`{api: {modelId: model}}`) into the snapshot shape. */
67
+ function loadRoute(dir: string, route: string): BuiltinModelData[] {
68
+ const raw = JSON.parse(readFileSync(join(dir, DATA_REL, `${route}.json`), 'utf8')) as Record<
69
+ string,
70
+ Record<string, { id?: string; api?: string; maxTokens?: number } | null>
71
+ >
72
+ const models: BuiltinModelData[] = []
73
+ for (const [api, apiModels] of Object.entries(raw)) {
74
+ if (typeof apiModels !== 'object' || apiModels === null) continue
75
+ for (const modelData of Object.values(apiModels)) {
76
+ if (typeof modelData !== 'object' || modelData === null || typeof modelData.id !== 'string') continue
77
+ models.push({ id: modelData.id, api: modelData.api ?? api, maxTokens: modelData.maxTokens })
78
+ }
79
+ }
80
+ return models.sort((a, b) => a.id.localeCompare(b.id))
81
+ }
82
+
83
+ /**
84
+ * Refresh the live-catalog cache from the host's pi-ai install. Call once per
85
+ * sync round, before any translate/builtin matching runs. Routes whose data
86
+ * file is unreadable are simply absent from the cache — callers fall back to
87
+ * the frozen snapshot for those. When no host install is found at all the
88
+ * cache is cleared and every route falls back.
89
+ */
90
+ export function refreshLiveCatalog(routes: readonly string[]): void {
91
+ const dir = findPiAiPackageDir()
92
+ if (dir === undefined) {
93
+ cache = undefined
94
+ return
95
+ }
96
+ const byRoute = new Map<string, BuiltinModelData[]>()
97
+ for (const route of routes) {
98
+ try {
99
+ byRoute.set(route, loadRoute(dir, route))
100
+ } catch { /* unreadable route file — fall back to snapshot for this route */ }
101
+ }
102
+ cache = { dir, byRoute }
103
+ }
104
+
105
+ /**
106
+ * The live builtin data for a route, or undefined when the host install could
107
+ * not be located or the route file is unreadable — callers fall back to the
108
+ * frozen snapshot.
109
+ */
110
+ export function getLiveBuiltinCatalogForRoute(route: string): BuiltinModelData[] | undefined {
111
+ return cache?.byRoute.get(route)
112
+ }
@@ -13,7 +13,7 @@
13
13
 
14
14
  import { homedir } from 'node:os'
15
15
  import { dirname, join } from 'node:path'
16
- import { mkdir, readFile, writeFile } from 'node:fs/promises'
16
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
17
17
 
18
18
  // ---------------------------------------------------------------------------
19
19
  // Constants (ported from docs-dsh-llm-pi-ai.patch:35-36)
@@ -65,6 +65,14 @@ export interface ModelsStoreEntry {
65
65
  checkedAt: number
66
66
  lastModified: number
67
67
  etag?: string
68
+ /**
69
+ * User `modelOverrides` folded out of settings and unset there (the dsh
70
+ * llm-pi-ai validation refuses a models list beside non-empty
71
+ * modelOverrides). Replayed into the translated target on every later
72
+ * round so the user's values survive — the catalog refresh must carry this
73
+ * field through untouched, exactly like the ETag.
74
+ */
75
+ overrides?: Record<string, Record<string, unknown>>
68
76
  }
69
77
 
70
78
  /** Top-level shape of ~/.dsh/models-store.json. */
@@ -147,14 +155,37 @@ export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
147
155
  const readDoc = async (): Promise<ModelsStore> => {
148
156
  try {
149
157
  return JSON.parse(await readFile(effectivePath, 'utf8')) as ModelsStore
150
- } catch {
151
- return {}
158
+ } catch (err: unknown) {
159
+ // ENOENT is a normal first run — the store has never been written.
160
+ // Anything else (SyntaxError on a corrupted file, EACCES on a
161
+ // permission-denied read, EIO on storage failure) bubbles up so the
162
+ // writer fails closed: treating an unreadable store as empty would
163
+ // let a later replay write the raw pi.dev target into settings and
164
+ // clobber user-folded values (the v0.1.5 data-loss shape). The
165
+ // failure propagates to the writer which skips the round and keeps
166
+ // settings.models — the authoritative, already-landed source —
167
+ // untouched.
168
+ if (err instanceof Error && (err as NodeJS.ErrnoException).code === 'ENOENT') {
169
+ return {}
170
+ }
171
+ throw err
152
172
  }
153
173
  }
154
174
 
155
175
  const writeDoc = async (doc: ModelsStore): Promise<void> => {
156
176
  await mkdir(dirname(effectivePath), { recursive: true })
157
- await writeFile(effectivePath, JSON.stringify(doc))
177
+ // Atomic write: stage to a sibling temp file then rename(2) into place.
178
+ // rename(2) is atomic on POSIX, so a concurrent reader either sees the
179
+ // pre-rename doc or the post-rename doc — never a half-written file.
180
+ // JSON.stringify without spaces keeps the existing wire format (the
181
+ // reader is strict on the parse side; legacy stores carry no
182
+ // whitespace). A fresh write also *heals* a previously-corrupt store:
183
+ // the first successful write after corruption replaces the bad file
184
+ // atomically with a well-formed doc, so subsequent reads see the
185
+ // expected shape.
186
+ const tmpPath = `${effectivePath}.${process.pid}.tmp`
187
+ await writeFile(tmpPath, JSON.stringify(doc))
188
+ await rename(tmpPath, effectivePath)
158
189
  }
159
190
 
160
191
  let queue: Promise<void> = Promise.resolve()
@@ -171,13 +202,31 @@ export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
171
202
  },
172
203
  write: (providerId: string, entry: ModelsStoreEntry): Promise<void> =>
173
204
  enqueue(async () => {
174
- const doc = await readDoc()
205
+ // The read-modify-write pattern preserves concurrent routes'
206
+ // entries; if the file is corrupt or unreadable, treat the doc as
207
+ // empty and overwrite — the atomic writeDoc below replaces the
208
+ // bad file with a fresh, well-formed doc carrying this route's
209
+ // entry (and any other routes the caller writes later will
210
+ // re-stamp theirs). The store reads path stays strict (readDoc
211
+ // still throws) so the writer's fail-closed logic can react to
212
+ // the actual error instead of seeing a fake empty doc.
213
+ let doc: ModelsStore
214
+ try {
215
+ doc = await readDoc()
216
+ } catch {
217
+ doc = {}
218
+ }
175
219
  doc[providerId] = entry
176
220
  await writeDoc(doc)
177
221
  }),
178
222
  delete: (providerId: string): Promise<void> =>
179
223
  enqueue(async () => {
180
- const doc = await readDoc()
224
+ let doc: ModelsStore
225
+ try {
226
+ doc = await readDoc()
227
+ } catch {
228
+ doc = {}
229
+ }
181
230
  delete doc[providerId]
182
231
  await writeDoc(doc)
183
232
  }),
@@ -264,6 +313,7 @@ export async function fetchRemoteCatalog(
264
313
  checkedAt,
265
314
  lastModified: 0,
266
315
  etag: undefined,
316
+ overrides: stored?.overrides,
267
317
  }
268
318
  await effectiveStore.write(route, entry)
269
319
  return { entries: [], fromCache: false }
@@ -276,6 +326,7 @@ export async function fetchRemoteCatalog(
276
326
  checkedAt,
277
327
  lastModified: stored?.lastModified ?? 0,
278
328
  etag: stored?.etag,
329
+ overrides: stored?.overrides,
279
330
  }
280
331
  await effectiveStore.write(route, entry)
281
332
  return {
@@ -295,6 +346,7 @@ export async function fetchRemoteCatalog(
295
346
  checkedAt,
296
347
  lastModified: Number.isNaN(lastModified) ? 0 : lastModified,
297
348
  etag,
349
+ overrides: stored?.overrides,
298
350
  }
299
351
  await effectiveStore.write(route, storeEntry)
300
352
 
package/src/writer.ts CHANGED
@@ -3,24 +3,48 @@
3
3
  /**
4
4
  * Write translated model profiles to dsh settings via the settings.mutate API.
5
5
  *
6
- * Key behaviors (design doc §4):
6
+ * Key behaviors (design doc §4, revised for the modelOverrides mutual
7
+ * exclusion, 2026-09-03):
7
8
  * - Change-only writes: compare the merged target (target ⊕ modelOverrides)
8
9
  * against the raw user segment (desc.user), not resolved values (which have
9
10
  * schema defaults applied)
10
11
  * - modelOverrides are the user's own per-model channel (think levels,
11
- * narrowed context windows). They are preserved forever: the synced models
12
- * list is written with override fields folded in, and the overrides key is
13
- * never unset or edited. (Earlier versions unset the key to "migrate" the
14
- * values into models, which silently wiped them on the next round once the
15
- * target was regenerated from pi.dev.)
12
+ * narrowed context windows). The dsh llm-pi-ai validation refuses a route
13
+ * whose settings carry a models list beside non-empty modelOverrides, so a
14
+ * models write must clear the key in the same mutate: the overrides are
15
+ * folded into the written models, an `unset` op removes the key (set+unset
16
+ * apply atomically), and the raw overrides are staged in the models-store
17
+ * BEFORE the mutate (store-first). Store-first is the data-safety
18
+ * invariant: settings is the authoritative, lossless source in every
19
+ * failure window — a failed/rejected mutate leaves the key in place and
20
+ * the settings-wins rule (see Replay below) suppresses the staged copy,
21
+ * while a failed store write skips the mutate entirely ('store-unavailable',
22
+ * settings untouched), so the key is never unset without a stored copy.
23
+ * Earlier behaviors both failed:
24
+ * v0.1.5 unset without persisting (the next round clobbered the folded
25
+ * fields), v0.1.6 preserved the key forever (every mutate was rejected by
26
+ * the mutual-exclusion validation and nothing landed).
27
+ * - Replay: when settings carries no overrides but the models-store does, the
28
+ * stored values fold into the target with no unset op — the merged view is
29
+ * re-derived identically every round, so change-only detection stays
30
+ * stable and the customizations survive. Settings overrides win over
31
+ * stored ones (a re-added key is the user's latest intent).
16
32
  * - Revision conflict retry: catch SETTINGS_CONFLICT, re-read, re-translate,
17
33
  * re-write once
18
34
  * - Never touches ~/.dsh/settings.yaml directly — only through settings.mutate
35
+ * - Store read failure: when the models-store read fails (corrupt JSON,
36
+ * EACCES, …) AND settings carries no overrides key, skip the round with
37
+ * reason 'store-unavailable' and leave settings.models untouched — the
38
+ * already-landed folded values are the authoritative fallback. A write
39
+ * triggered from a settings-side key is unaffected: settings-wins, and the
40
+ * atomic writeDoc replaces it on disk (heals the corruption as a side
41
+ * effect).
19
42
  *
20
43
  * @module dsh-model-sync/writer
21
44
  */
22
45
 
23
46
  import type { SettingsModelProfile } from './translate.ts'
47
+ import type { ModelsStoreAccessor, ModelsStoreEntry } from './remote-catalog.ts'
24
48
 
25
49
  // ---------------------------------------------------------------------------
26
50
  // Types
@@ -58,7 +82,29 @@ export interface Logger {
58
82
 
59
83
  export interface SyncResult {
60
84
  wrote: boolean
61
- reason: 'no-change' | 'wrote' | 'conflict-retry-ok' | 'conflict-retry-failed' | 'mutate-rejected' | 'skipped'
85
+ reason:
86
+ | 'no-change'
87
+ | 'wrote'
88
+ | 'conflict-retry-ok'
89
+ | 'conflict-retry-failed'
90
+ | 'mutate-rejected'
91
+ | 'store-unavailable'
92
+ | 'skipped'
93
+ /**
94
+ * Where the folded overrides came from: 'settings' = the key was present
95
+ * (folded + unset in the same mutate, staged in the models-store before
96
+ * the mutate — store-first); 'store' = replayed from the models-store (no
97
+ * unset). Absent when no overrides were involved at all.
98
+ */
99
+ overridesSource?: 'settings' | 'store'
100
+ /**
101
+ * Override ids with no matching entry in the written target. 'settings'
102
+ * source: they were dropped from settings by the unset but are kept in the
103
+ * models-store verbatim (and apply again if the id shows up in a later
104
+ * target). 'store' source: they simply stay stored. Undefined when no
105
+ * overrides were involved.
106
+ */
107
+ droppedOverrideIds?: string[]
62
108
  }
63
109
 
64
110
  // ---------------------------------------------------------------------------
@@ -164,7 +210,105 @@ function mergeOverrides(
164
210
  return target.map((entry) => {
165
211
  const override = overrides[entry.id]
166
212
  if (override === undefined) return entry
167
- return { ...entry, ...override } as SettingsModelProfile
213
+ // Force the entry's own id back on: an override object that happens to
214
+ // carry an `id` field must not silently re-key the entry in the written
215
+ // models list.
216
+ return { ...entry, ...override, id: entry.id } as SettingsModelProfile
217
+ })
218
+ }
219
+
220
+ /**
221
+ * Override ids that cannot fold into the target (no entry carries the id).
222
+ * Sorted so the report line is deterministic.
223
+ */
224
+ function droppedOverrideIds(
225
+ overrides: Record<string, Record<string, unknown>> | undefined,
226
+ mergedTarget: SettingsModelProfile[],
227
+ ): string[] | undefined {
228
+ if (overrides === undefined) return undefined
229
+ const targetIds = new Set(mergedTarget.map((entry) => entry.id))
230
+ return Object.keys(overrides).filter((id) => !targetIds.has(id)).sort()
231
+ }
232
+
233
+ /**
234
+ * Resolve the overrides to fold for one route: a non-empty settings key wins
235
+ * (a re-added key is the user's latest intent); otherwise the models-store
236
+ * replay applies. An empty `{}` key counts as absent — the dsh validation
237
+ * only refuses non-empty overrides beside a models list, and there is nothing
238
+ * in it to preserve.
239
+ */
240
+ async function resolveOverrides(
241
+ desc: SettingsDescriptor,
242
+ route: string,
243
+ store: ModelsStoreAccessor | undefined,
244
+ ): Promise<{
245
+ overrides: Record<string, Record<string, unknown>> | undefined
246
+ source: 'settings' | 'store' | undefined
247
+ }> {
248
+ const raw = getRawUserModelOverrides(desc, route)
249
+ if (raw !== undefined && Object.keys(raw).length > 0) {
250
+ return { overrides: raw, source: 'settings' }
251
+ }
252
+ if (store !== undefined) {
253
+ // The store read may now throw on corruption / permission failures
254
+ // (remote-catalog readDoc propagates anything other than ENOENT). We
255
+ // bubble it up: with no settings overrides to fall back on, the caller
256
+ // must skip the round rather than fold an unreplayed target into
257
+ // settings and clobber the folded values. With a settings key in play
258
+ // (the earlier branch above) this code path is never reached, so a
259
+ // settings-side write always proceeds and the atomic writeDoc heals the
260
+ // corruption on its next write.
261
+ const stored = await store.read(route)
262
+ if (stored?.overrides !== undefined && Object.keys(stored.overrides).length > 0) {
263
+ return { overrides: stored.overrides, source: 'store' }
264
+ }
265
+ }
266
+ return { overrides: undefined, source: undefined }
267
+ }
268
+
269
+ /**
270
+ * Stage overrides in the models-store BEFORE the mutate that unsets them
271
+ * from settings (store-first). The read runs outside the store's serialized
272
+ * write queue — only the merged entry write goes through the queue — so the
273
+ * route's models/checkedAt/etag, written by the fetch earlier in this round,
274
+ * stay intact. While the settings key is present it always wins over the
275
+ * store (resolveOverrides order); the stored copy is only ever replayed
276
+ * once the key is gone. Callers must treat a throw from here as "skip the
277
+ * mutate": unsetting without a staged copy is the v0.1.5 data loss.
278
+ *
279
+ * The store read may now fail on corruption / permission errors (readDoc
280
+ * propagates everything except ENOENT). Swallowing it here is intentional:
281
+ * the settings key carries the only authoritative copy of the overrides, the
282
+ * atomic writeDoc below replaces the (possibly corrupt) file with a fresh
283
+ * entry that carries the overrides — which is what heals the store. The
284
+ * fetch side will re-populate models/checkedAt/etag on its next round.
285
+ * (A storeless call — store undefined — cannot stage anything and keeps the
286
+ * legacy unset-without-copy behavior; production wiring in index.ts always
287
+ * passes a store.)
288
+ */
289
+ async function persistOverridesToStore(
290
+ store: ModelsStoreAccessor | undefined,
291
+ route: string,
292
+ overrides: Record<string, Record<string, unknown>>,
293
+ ): Promise<void> {
294
+ if (store === undefined) return
295
+ let stored: ModelsStoreEntry | undefined
296
+ try {
297
+ stored = await store.read(route)
298
+ } catch (readErr: unknown) {
299
+ // Cache lost — fall through with no cached metadata. The atomic
300
+ // writeDoc below replaces the bad file with a fresh entry carrying
301
+ // only the overrides. The fetch side re-populates the rest on its
302
+ // next round. The settings key remains the authoritative source of
303
+ // truth in the meantime.
304
+ void readErr
305
+ }
306
+ await store.write(route, {
307
+ models: stored?.models ?? [],
308
+ checkedAt: stored?.checkedAt ?? Date.now(),
309
+ lastModified: stored?.lastModified ?? 0,
310
+ etag: stored?.etag,
311
+ overrides,
168
312
  })
169
313
  }
170
314
 
@@ -175,20 +319,32 @@ function mergeOverrides(
175
319
  /**
176
320
  * Write translated model profiles to settings for a given route.
177
321
  *
178
- * Implements the full §4 protocol:
322
+ * Implements the full §4 protocol (revised for the modelOverrides mutual
323
+ * exclusion):
179
324
  * 1. Get revision from describe()
180
- * 2. Merge modelOverrides into the target (override wins per field); the
181
- * overrides key itself is never written or deleted
325
+ * 2. Resolve the overrides to fold: the settings key when non-empty, the
326
+ * models-store replay otherwise; merge into the target (override wins per
327
+ * field)
182
328
  * 3. Change-only write: skip when the raw user-segment models already equal
183
- * the merged target
184
- * 4. Call mutate with expectedRevision (single set op on the models path)
185
- * 5. On SETTINGS_CONFLICT: re-read, re-translate (caller's job), re-write once
329
+ * the merged target — except when the settings key is present, because the
330
+ * models+overrides combo is refused by the llm-pi-ai validation (the
331
+ * set+unset must run to move the document out of the refused shape)
332
+ * 4. Store-first: when the settings key is present, stage the raw overrides
333
+ * in the models-store BEFORE the mutate; a store write failure skips the
334
+ * mutate entirely and reports 'store-unavailable' (settings untouched —
335
+ * the key is never unset without a stored copy). Then call mutate with
336
+ * expectedRevision: one `set` on the models path, plus an `unset` on the
337
+ * modelOverrides path (atomic in a single mutate).
338
+ * 5. On SETTINGS_CONFLICT: re-read, re-translate (caller's job), re-resolve
339
+ * the overrides from the fresh descriptor, stage again (store-first),
340
+ * re-write once
186
341
  *
187
342
  * @param settings The settings service (injected, not imported)
188
343
  * @param route The provider route id
189
344
  * @param target Translated settings-writable entries (sorted by id)
190
345
  * @param logger Logger for warnings/errors
191
346
  * @param retranslate Callback to re-translate on conflict (receives new revision)
347
+ * @param store The models-store accessor for the overrides replay/persist
192
348
  */
193
349
  export async function syncToSettings(
194
350
  settings: SettingsService | undefined,
@@ -196,6 +352,7 @@ export async function syncToSettings(
196
352
  target: SettingsModelProfile[],
197
353
  logger: Logger,
198
354
  retranslate?: (newRevision: number) => Promise<SettingsModelProfile[]>,
355
+ store?: ModelsStoreAccessor,
199
356
  ): Promise<SyncResult> {
200
357
  if (settings === undefined) {
201
358
  logger.debug('settings service unavailable; skip write for route %s', route)
@@ -210,26 +367,72 @@ export async function syncToSettings(
210
367
  }
211
368
 
212
369
  const rawModels = getRawUserModels(desc, route)
213
- const rawOverrides = getRawUserModelOverrides(desc, route)
370
+ let effectiveOverrides: Record<string, Record<string, unknown>> | undefined
371
+ let overridesSource: 'settings' | 'store' | undefined
372
+ try {
373
+ ({ overrides: effectiveOverrides, source: overridesSource } =
374
+ await resolveOverrides(desc, route, store))
375
+ } catch (readErr: unknown) {
376
+ // The store is unreadable (corrupted JSON, EACCES, …) and settings
377
+ // carries no overrides key — there is no authoritative source for the
378
+ // user's folded values other than the existing settings.models. Skip
379
+ // the round with reason 'store-unavailable': writing the raw pi.dev
380
+ // target now would overwrite settings.models with unreplayed values
381
+ // and silently clobber the user's fold (the same data-loss shape
382
+ // v0.1.5 hit, just via a different path). The next refresh attempts
383
+ // the same round again; a manual re-add of the key (or a fresh
384
+ // successful settings-side write that heals the file) unblocks it.
385
+ logger.warn(
386
+ 'models-store read failed for route %s: %s',
387
+ route,
388
+ readErr instanceof Error ? readErr.message : String(readErr),
389
+ )
390
+ return { wrote: false, reason: 'store-unavailable' }
391
+ }
392
+ const hasSettingsOverrides = overridesSource === 'settings'
214
393
 
215
- const mergedTarget = mergeOverrides(target, rawOverrides)
394
+ const mergedTarget = mergeOverrides(target, effectiveOverrides)
216
395
 
217
396
  // Change-only write (§4.4): skip when the stored models already reflect
218
- // target ⊕ overrides. Because the overrides key is preserved, this stays
219
- // stable across rounds: once written, the merged view is re-derived
220
- // identically every round until pi.dev actually changes.
221
- if (rawModels !== undefined && profilesEqual(rawModels, mergedTarget)) {
397
+ // target ⊕ overrides. Skipped when the settings key is present — the unset
398
+ // must run in this mutate to clear the refused models+overrides combo, and
399
+ // after it lands the replay keeps later rounds change-only.
400
+ if (!hasSettingsOverrides && rawModels !== undefined && profilesEqual(rawModels, mergedTarget)) {
222
401
  logger.debug('no change for route %s; skip write', route)
223
402
  return { wrote: false, reason: 'no-change' }
224
403
  }
225
404
 
405
+ const dropped = droppedOverrideIds(effectiveOverrides, mergedTarget)
406
+
226
407
  const ops: SettingsMutationOp[] = [
227
408
  { op: 'set', path: ['providers', route, 'models'], value: mergedTarget },
228
409
  ]
410
+ if (hasSettingsOverrides) {
411
+ ops.push({ op: 'unset', path: ['providers', route, 'modelOverrides'] })
412
+ }
413
+
414
+ // Store-first: stage the raw overrides in the models-store BEFORE the
415
+ // mutate that unsets them from settings. A store write failure must skip
416
+ // the mutate entirely — unsetting without a staged copy is the v0.1.5
417
+ // data loss — and settings stays untouched, so it remains the
418
+ // authoritative source. Reported honestly as 'store-unavailable': the
419
+ // mutate never ran, so 'mutate-rejected' would be a lie.
420
+ if (hasSettingsOverrides && effectiveOverrides !== undefined) {
421
+ try {
422
+ await persistOverridesToStore(store, route, effectiveOverrides)
423
+ } catch (persistErr: unknown) {
424
+ logger.warn(
425
+ 'models-store persist failed for route %s: %s',
426
+ route,
427
+ persistErr instanceof Error ? persistErr.message : String(persistErr),
428
+ )
429
+ return { wrote: false, reason: 'store-unavailable' }
430
+ }
431
+ }
229
432
 
230
433
  try {
231
434
  await settings.mutate('llm-pi-ai', ops, desc.revision)
232
- return { wrote: true, reason: 'wrote' }
435
+ return { wrote: true, reason: 'wrote', overridesSource, droppedOverrideIds: dropped }
233
436
  } catch (err: unknown) {
234
437
  // Check for SETTINGS_CONFLICT
235
438
  const code = (err as Record<string, unknown>)?.code
@@ -255,16 +458,58 @@ export async function syncToSettings(
255
458
  }
256
459
 
257
460
  const newTarget = await retranslate(newDesc.revision)
461
+ let retry: {
462
+ overrides: Record<string, Record<string, unknown>> | undefined
463
+ source: 'settings' | 'store' | undefined
464
+ }
465
+ try {
466
+ retry = await resolveOverrides(newDesc, route, store)
467
+ } catch (readErr: unknown) {
468
+ // Same fail-closed contract as the main path: with the settings key
469
+ // gone between the two attempts, the store replay is the only way
470
+ // to recover the fold; an unreadable store leaves the user values
471
+ // stranded in settings.models. Skip the retry, report honestly.
472
+ logger.warn(
473
+ 'models-store read failed for route %s on retry: %s',
474
+ route,
475
+ readErr instanceof Error ? readErr.message : String(readErr),
476
+ )
477
+ return { wrote: false, reason: 'store-unavailable' }
478
+ }
479
+ const retryHasSettingsOverrides = retry.source === 'settings'
480
+ const retryMerged = mergeOverrides(newTarget, retry.overrides)
481
+ const retryDropped = droppedOverrideIds(retry.overrides, retryMerged)
482
+
258
483
  const retryOps: SettingsMutationOp[] = [
259
- {
260
- op: 'set',
261
- path: ['providers', route, 'models'],
262
- value: mergeOverrides(newTarget, getRawUserModelOverrides(newDesc, route)),
263
- },
484
+ { op: 'set', path: ['providers', route, 'models'], value: retryMerged },
264
485
  ]
486
+ if (retryHasSettingsOverrides) {
487
+ retryOps.push({ op: 'unset', path: ['providers', route, 'modelOverrides'] })
488
+ }
489
+
490
+ // Store-first again on the retry: the overrides were re-resolved from
491
+ // the fresh descriptor, so stage them before the retry mutate (the
492
+ // user may have changed or removed the key between the attempts).
493
+ if (retryHasSettingsOverrides && retry.overrides !== undefined) {
494
+ try {
495
+ await persistOverridesToStore(store, route, retry.overrides)
496
+ } catch (persistErr: unknown) {
497
+ logger.warn(
498
+ 'models-store persist failed for route %s: %s',
499
+ route,
500
+ persistErr instanceof Error ? persistErr.message : String(persistErr),
501
+ )
502
+ return { wrote: false, reason: 'store-unavailable' }
503
+ }
504
+ }
265
505
 
266
506
  await settings.mutate('llm-pi-ai', retryOps, newDesc.revision)
267
- return { wrote: true, reason: 'conflict-retry-ok' }
507
+ return {
508
+ wrote: true,
509
+ reason: 'conflict-retry-ok',
510
+ overridesSource: retry.source,
511
+ droppedOverrideIds: retryDropped,
512
+ }
268
513
  } catch (retryErr: unknown) {
269
514
  logger.warn(
270
515
  'conflict retry failed for route %s: %s',