@aiwayds/dsh-model-sync 0.2.1 → 0.2.3

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 } 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,10 +210,101 @@ 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
168
217
  })
169
218
  }
170
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 RMW runs inside the accessor's
272
+ * serialized write queue via `updateOverrides` — the previous read-then-
273
+ * write pattern read OUTSIDE the queue, which let the fetch side's
274
+ * `store.write` clobber any staged overrides that landed in the window
275
+ * between this read and the eventual write. The queue-internal field-
276
+ * level seed (B1) merges the stage with whatever the route currently
277
+ * holds: `overrides` is replaced by the new value, every other field
278
+ * (`models` / `checkedAt` / `lastModified` / `etag`) is preserved
279
+ * verbatim when present, otherwise seeded with a sensible default.
280
+ * A concurrent fetch write (the C1 race surface) can no longer wipe
281
+ * the stage: the fetch-side patch only names fetch-owned fields, so
282
+ * the seed leaves `overrides` alone. While the settings key is present
283
+ * it always wins over the store (resolveOverrides order); the stored
284
+ * copy is only ever replayed once the key is gone. Callers must treat
285
+ * a throw from here as "skip the mutate": unsetting without a staged
286
+ * copy is the v0.1.5 data loss.
287
+ *
288
+ * The store read may fail on corruption / permission errors (the
289
+ * queue's internal read tolerates them by treating the doc as empty,
290
+ * then the atomic writeDoc replaces the bad file with a fresh,
291
+ * well-formed entry — the self-heal). The field-level seed keeps the
292
+ * resulting entry well-formed (models: [], checkedAt: Date.now(),
293
+ * lastModified: 0, etag: undefined, overrides: <stage>), so the fetch
294
+ * side can consume it on its next round. (A storeless call — store
295
+ * undefined — cannot stage anything and keeps the legacy
296
+ * unset-without-copy behavior; production wiring in index.ts always
297
+ * passes a store.)
298
+ */
299
+ async function persistOverridesToStore(
300
+ store: ModelsStoreAccessor | undefined,
301
+ route: string,
302
+ overrides: Record<string, Record<string, unknown>>,
303
+ ): Promise<void> {
304
+ if (store === undefined) return
305
+ await store.updateOverrides(route, overrides)
306
+ }
307
+
171
308
  // ---------------------------------------------------------------------------
172
309
  // syncToSettings (§4)
173
310
  // ---------------------------------------------------------------------------
@@ -175,20 +312,32 @@ function mergeOverrides(
175
312
  /**
176
313
  * Write translated model profiles to settings for a given route.
177
314
  *
178
- * Implements the full §4 protocol:
315
+ * Implements the full §4 protocol (revised for the modelOverrides mutual
316
+ * exclusion):
179
317
  * 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
318
+ * 2. Resolve the overrides to fold: the settings key when non-empty, the
319
+ * models-store replay otherwise; merge into the target (override wins per
320
+ * field)
182
321
  * 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
322
+ * the merged target — except when the settings key is present, because the
323
+ * models+overrides combo is refused by the llm-pi-ai validation (the
324
+ * set+unset must run to move the document out of the refused shape)
325
+ * 4. Store-first: when the settings key is present, stage the raw overrides
326
+ * in the models-store BEFORE the mutate; a store write failure skips the
327
+ * mutate entirely and reports 'store-unavailable' (settings untouched —
328
+ * the key is never unset without a stored copy). Then call mutate with
329
+ * expectedRevision: one `set` on the models path, plus an `unset` on the
330
+ * modelOverrides path (atomic in a single mutate).
331
+ * 5. On SETTINGS_CONFLICT: re-read, re-translate (caller's job), re-resolve
332
+ * the overrides from the fresh descriptor, stage again (store-first),
333
+ * re-write once
186
334
  *
187
335
  * @param settings The settings service (injected, not imported)
188
336
  * @param route The provider route id
189
337
  * @param target Translated settings-writable entries (sorted by id)
190
338
  * @param logger Logger for warnings/errors
191
339
  * @param retranslate Callback to re-translate on conflict (receives new revision)
340
+ * @param store The models-store accessor for the overrides replay/persist
192
341
  */
193
342
  export async function syncToSettings(
194
343
  settings: SettingsService | undefined,
@@ -196,6 +345,7 @@ export async function syncToSettings(
196
345
  target: SettingsModelProfile[],
197
346
  logger: Logger,
198
347
  retranslate?: (newRevision: number) => Promise<SettingsModelProfile[]>,
348
+ store?: ModelsStoreAccessor,
199
349
  ): Promise<SyncResult> {
200
350
  if (settings === undefined) {
201
351
  logger.debug('settings service unavailable; skip write for route %s', route)
@@ -210,26 +360,72 @@ export async function syncToSettings(
210
360
  }
211
361
 
212
362
  const rawModels = getRawUserModels(desc, route)
213
- const rawOverrides = getRawUserModelOverrides(desc, route)
363
+ let effectiveOverrides: Record<string, Record<string, unknown>> | undefined
364
+ let overridesSource: 'settings' | 'store' | undefined
365
+ try {
366
+ ({ overrides: effectiveOverrides, source: overridesSource } =
367
+ await resolveOverrides(desc, route, store))
368
+ } catch (readErr: unknown) {
369
+ // The store is unreadable (corrupted JSON, EACCES, …) and settings
370
+ // carries no overrides key — there is no authoritative source for the
371
+ // user's folded values other than the existing settings.models. Skip
372
+ // the round with reason 'store-unavailable': writing the raw pi.dev
373
+ // target now would overwrite settings.models with unreplayed values
374
+ // and silently clobber the user's fold (the same data-loss shape
375
+ // v0.1.5 hit, just via a different path). The next refresh attempts
376
+ // the same round again; a manual re-add of the key (or a fresh
377
+ // successful settings-side write that heals the file) unblocks it.
378
+ logger.warn(
379
+ 'models-store read failed for route %s: %s',
380
+ route,
381
+ readErr instanceof Error ? readErr.message : String(readErr),
382
+ )
383
+ return { wrote: false, reason: 'store-unavailable' }
384
+ }
385
+ const hasSettingsOverrides = overridesSource === 'settings'
214
386
 
215
- const mergedTarget = mergeOverrides(target, rawOverrides)
387
+ const mergedTarget = mergeOverrides(target, effectiveOverrides)
216
388
 
217
389
  // 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)) {
390
+ // target ⊕ overrides. Skipped when the settings key is present — the unset
391
+ // must run in this mutate to clear the refused models+overrides combo, and
392
+ // after it lands the replay keeps later rounds change-only.
393
+ if (!hasSettingsOverrides && rawModels !== undefined && profilesEqual(rawModels, mergedTarget)) {
222
394
  logger.debug('no change for route %s; skip write', route)
223
395
  return { wrote: false, reason: 'no-change' }
224
396
  }
225
397
 
398
+ const dropped = droppedOverrideIds(effectiveOverrides, mergedTarget)
399
+
226
400
  const ops: SettingsMutationOp[] = [
227
401
  { op: 'set', path: ['providers', route, 'models'], value: mergedTarget },
228
402
  ]
403
+ if (hasSettingsOverrides) {
404
+ ops.push({ op: 'unset', path: ['providers', route, 'modelOverrides'] })
405
+ }
406
+
407
+ // Store-first: stage the raw overrides in the models-store BEFORE the
408
+ // mutate that unsets them from settings. A store write failure must skip
409
+ // the mutate entirely — unsetting without a staged copy is the v0.1.5
410
+ // data loss — and settings stays untouched, so it remains the
411
+ // authoritative source. Reported honestly as 'store-unavailable': the
412
+ // mutate never ran, so 'mutate-rejected' would be a lie.
413
+ if (hasSettingsOverrides && effectiveOverrides !== undefined) {
414
+ try {
415
+ await persistOverridesToStore(store, route, effectiveOverrides)
416
+ } catch (persistErr: unknown) {
417
+ logger.warn(
418
+ 'models-store persist failed for route %s: %s',
419
+ route,
420
+ persistErr instanceof Error ? persistErr.message : String(persistErr),
421
+ )
422
+ return { wrote: false, reason: 'store-unavailable' }
423
+ }
424
+ }
229
425
 
230
426
  try {
231
427
  await settings.mutate('llm-pi-ai', ops, desc.revision)
232
- return { wrote: true, reason: 'wrote' }
428
+ return { wrote: true, reason: 'wrote', overridesSource, droppedOverrideIds: dropped }
233
429
  } catch (err: unknown) {
234
430
  // Check for SETTINGS_CONFLICT
235
431
  const code = (err as Record<string, unknown>)?.code
@@ -255,16 +451,58 @@ export async function syncToSettings(
255
451
  }
256
452
 
257
453
  const newTarget = await retranslate(newDesc.revision)
454
+ let retry: {
455
+ overrides: Record<string, Record<string, unknown>> | undefined
456
+ source: 'settings' | 'store' | undefined
457
+ }
458
+ try {
459
+ retry = await resolveOverrides(newDesc, route, store)
460
+ } catch (readErr: unknown) {
461
+ // Same fail-closed contract as the main path: with the settings key
462
+ // gone between the two attempts, the store replay is the only way
463
+ // to recover the fold; an unreadable store leaves the user values
464
+ // stranded in settings.models. Skip the retry, report honestly.
465
+ logger.warn(
466
+ 'models-store read failed for route %s on retry: %s',
467
+ route,
468
+ readErr instanceof Error ? readErr.message : String(readErr),
469
+ )
470
+ return { wrote: false, reason: 'store-unavailable' }
471
+ }
472
+ const retryHasSettingsOverrides = retry.source === 'settings'
473
+ const retryMerged = mergeOverrides(newTarget, retry.overrides)
474
+ const retryDropped = droppedOverrideIds(retry.overrides, retryMerged)
475
+
258
476
  const retryOps: SettingsMutationOp[] = [
259
- {
260
- op: 'set',
261
- path: ['providers', route, 'models'],
262
- value: mergeOverrides(newTarget, getRawUserModelOverrides(newDesc, route)),
263
- },
477
+ { op: 'set', path: ['providers', route, 'models'], value: retryMerged },
264
478
  ]
479
+ if (retryHasSettingsOverrides) {
480
+ retryOps.push({ op: 'unset', path: ['providers', route, 'modelOverrides'] })
481
+ }
482
+
483
+ // Store-first again on the retry: the overrides were re-resolved from
484
+ // the fresh descriptor, so stage them before the retry mutate (the
485
+ // user may have changed or removed the key between the attempts).
486
+ if (retryHasSettingsOverrides && retry.overrides !== undefined) {
487
+ try {
488
+ await persistOverridesToStore(store, route, retry.overrides)
489
+ } catch (persistErr: unknown) {
490
+ logger.warn(
491
+ 'models-store persist failed for route %s: %s',
492
+ route,
493
+ persistErr instanceof Error ? persistErr.message : String(persistErr),
494
+ )
495
+ return { wrote: false, reason: 'store-unavailable' }
496
+ }
497
+ }
265
498
 
266
499
  await settings.mutate('llm-pi-ai', retryOps, newDesc.revision)
267
- return { wrote: true, reason: 'conflict-retry-ok' }
500
+ return {
501
+ wrote: true,
502
+ reason: 'conflict-retry-ok',
503
+ overridesSource: retry.source,
504
+ droppedOverrideIds: retryDropped,
505
+ }
268
506
  } catch (retryErr: unknown) {
269
507
  logger.warn(
270
508
  'conflict retry failed for route %s: %s',