@aiwayds/dsh-model-sync 0.2.1 → 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.
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',