@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
@@ -107,8 +107,10 @@ export async function resolveRouteCredentialValue(
107
107
  ctx: NativeCredentialContext,
108
108
  desc: RouteCredentialSettingsDescriptor | undefined,
109
109
  route: string,
110
+ /** Explicit ref from the go/zen Config contract; wins over the settings/derived ref. */
111
+ refOverride?: string,
110
112
  ): Promise<string | undefined> {
111
- const declared = getRawUserApiKeyEnv(desc, route)
113
+ const declared = refOverride ?? getRawUserApiKeyEnv(desc, route)
112
114
  const ref = declared ?? deriveKeyRef(route)
113
115
  const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/
114
116
 
@@ -11,9 +11,10 @@
11
11
  * @module dsh-model-sync/remote-catalog
12
12
  */
13
13
 
14
- import { homedir } from 'node:os'
14
+ import { createHash, randomUUID } from 'node:crypto'
15
+ import { homedir, tmpdir } from 'node:os'
15
16
  import { dirname, join } from 'node:path'
16
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
17
+ import { mkdir, open, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises'
17
18
 
18
19
  // ---------------------------------------------------------------------------
19
20
  // Constants (ported from docs-dsh-llm-pi-ai.patch:35-36)
@@ -28,6 +29,16 @@ export const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000
28
29
  /** Path to the persistent per-provider cache. */
29
30
  export const MODELS_STORE_PATH = join(homedir(), '.dsh', 'models-store.json')
30
31
 
32
+ /**
33
+ * `code` of the error `restoreRawDocument` throws when the in-lock re-verify
34
+ * (round 3) finds the current document's sha256 different from the caller's
35
+ * expected baseline — another writer changed the store between the caller's
36
+ * pre-lock check and this restore. Callers match on `code` (not instanceof)
37
+ * so the failure can degrade to a "concurrent modification, not restored"
38
+ * outcome instead of a generic restore failure.
39
+ */
40
+ export const STORE_RESTORE_SHA_MISMATCH = 'STORE_RESTORE_SHA_MISMATCH'
41
+
31
42
  // ---------------------------------------------------------------------------
32
43
  // Types
33
44
  // ---------------------------------------------------------------------------
@@ -152,6 +163,218 @@ export function parseRemoteCatalog(
152
163
 
153
164
  let modelsStoreCache: ModelsStoreAccessor | undefined
154
165
 
166
+ // --- Cross-process write guard (B1 / R-14; D2/D3 hardening) -----------------
167
+ //
168
+ // The promise queue below serializes writes WITHIN one process only. Two dsh
169
+ // processes (two profiles sharing models-store.json) still race: both read the
170
+ // whole document, both rewrite it, and the last rename wins — silently dropping
171
+ // the other profile's newly written ledger key. Key namespacing alone cannot
172
+ // prevent that whole-document last-writer-wins loss.
173
+ //
174
+ // Guard the read-modify-write+rename critical section with a single lock file
175
+ // created by atomic exclusive `open(..., 'wx')`. The lock lives in the OS temp
176
+ // dir (name hashed from the absolute store path) so two processes derive the
177
+ // same file and no transient file is ever created under ~/.dsh. It is held
178
+ // only for the few ms of one write and removed in `finally`.
179
+ //
180
+ // Lock files carry an owner stamp { pid, nonce, createdAt }. A lock is only
181
+ // broken as stale when ALL three hold: its recorded age exceeds
182
+ // LOCK_STALE_MS, its owner PID is *conclusively* gone (kill(pid, 0) -> ESRCH;
183
+ // EPERM / any other outcome is indeterminate and conservatively keeps the
184
+ // lock), and a re-read immediately before deletion still shows the same
185
+ // nonce (compare-and-delete, so a lock replaced mid-check is never removed).
186
+ // A lock with NO parseable stamp is the crash window between `open(wx)` and
187
+ // the stamp write: it has no owner to validate, so it is only reclaimed once
188
+ // its FILE mtime is older than LOCK_STALE_MS and its raw bytes are unchanged
189
+ // at delete time — otherwise it keeps the lock (fail-closed). A lock that
190
+ // cannot be acquired within LOCK_WAIT_MS is a hard failure:
191
+ // StoreLockTimeoutError is thrown and the write does NOT run (fail-closed),
192
+ // because a bypass would reintroduce the whole-document last-writer-wins loss
193
+ // this guard exists to prevent. The store bytes are untouched on timeout.
194
+ const LOCK_STALE_MS = 10_000
195
+ const LOCK_WAIT_MS = 2_000
196
+ const LOCK_RETRY_MS = 8
197
+
198
+ /** Payload written into the lock file so a stale break can validate ownership. */
199
+ interface LockOwner {
200
+ pid: number
201
+ nonce: string
202
+ createdAt: number
203
+ }
204
+
205
+ /**
206
+ * Fail-closed error for a cross-process lock that stayed contended past
207
+ * LOCK_WAIT_MS. `name` and `code` distinguish it from an ordinary store write
208
+ * failure (corrupt JSON, EIO, ...) so callers can tell "retry / someone else
209
+ * is holding the lock" from "the store itself is broken".
210
+ */
211
+ export class StoreLockTimeoutError extends Error {
212
+ readonly code = 'DSH_STORE_LOCK_TIMEOUT'
213
+ readonly lockPath: string
214
+ readonly waitMs: number
215
+
216
+ constructor(lockPath: string, waitMs: number) {
217
+ super(
218
+ `Timed out after ${waitMs}ms waiting for the models-store lock (${lockPath}). ` +
219
+ 'The store was NOT modified. Retry the operation; if it keeps failing, check other running dsh processes for a stalled sync round holding the lock. ' +
220
+ `A lock left by a crashed process is broken automatically once it is older than ${LOCK_STALE_MS}ms and its owner PID is no longer alive.`,
221
+ )
222
+ this.name = 'StoreLockTimeoutError'
223
+ this.lockPath = lockPath
224
+ this.waitMs = waitMs
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Structural check for a store lock timeout. Uses `code`/`name` rather than
230
+ * `instanceof` so a timeout that was re-wrapped (or crossed a module boundary)
231
+ * is still recognized and its actionable message is not degraded to a generic
232
+ * failure.
233
+ */
234
+ function isStoreLockTimeout(err: unknown): boolean {
235
+ if (err === null || typeof err !== 'object') return false
236
+ const value = err as { code?: unknown; name?: unknown }
237
+ return value.code === 'DSH_STORE_LOCK_TIMEOUT' || value.name === 'StoreLockTimeoutError'
238
+ }
239
+
240
+ function lockPathFor(path: string): string {
241
+ return join(tmpdir(), `${createHash('sha256').update(path).digest('hex')}.dsh-store.lock`)
242
+ }
243
+
244
+ function parseLockOwner(raw: string): LockOwner | undefined {
245
+ try {
246
+ const value = JSON.parse(raw) as Partial<LockOwner>
247
+ if (
248
+ typeof value.pid === 'number' && Number.isInteger(value.pid) && value.pid > 0
249
+ && typeof value.nonce === 'string' && value.nonce.length > 0
250
+ && typeof value.createdAt === 'number' && Number.isFinite(value.createdAt)
251
+ ) {
252
+ return { pid: value.pid, nonce: value.nonce, createdAt: value.createdAt }
253
+ }
254
+ } catch {
255
+ // Empty (just-created, not yet stamped), half-written or foreign file —
256
+ // ownership cannot be determined, so the lock must not be broken.
257
+ }
258
+ return undefined
259
+ }
260
+
261
+ /** True only when signal probe conclusively reports the owner process is gone. */
262
+ function isLockOwnerDead(pid: number): boolean {
263
+ try {
264
+ process.kill(pid, 0)
265
+ return false // process exists (or at least can be signalled): keep the lock
266
+ } catch (err: unknown) {
267
+ // ESRCH is the only "definitely gone" answer. EPERM means the process
268
+ // exists but belongs to another user; anything else is indeterminate.
269
+ // Both must be treated conservatively as "alive/unknown" — never break.
270
+ return (err as NodeJS.ErrnoException).code === 'ESRCH'
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Test-only seam (never set by dsh or the plugin): widens the gap between the
276
+ * two owner reads so a behavioral test can swap the lock file in between and
277
+ * prove compare-and-delete refuses to remove a replacement. Zero in normal
278
+ * operation, so production timing is unchanged.
279
+ */
280
+ function lockBreakVerifyDelayMs(): number {
281
+ const raw = process.env.DSH_LOCK_BREAK_VERIFY_DELAY_MS
282
+ if (raw === undefined || raw === '') return 0
283
+ const ms = Number(raw)
284
+ return Number.isFinite(ms) && ms > 0 ? ms : 0
285
+ }
286
+
287
+ type BreakOutcome = 'broken' | 'kept' | 'mismatch'
288
+
289
+ /** Attempt an owner-validated stale break. Never deletes a lock it cannot prove is stale. */
290
+ async function tryBreakStaleLock(lockPath: string, now: number): Promise<BreakOutcome> {
291
+ let raw: string
292
+ try {
293
+ raw = await readFile(lockPath, 'utf8')
294
+ } catch {
295
+ return 'kept' // vanished or unreadable between EEXIST and read — retry later
296
+ }
297
+ const owner = parseLockOwner(raw)
298
+
299
+ if (owner !== undefined) {
300
+ // Stamped lock: age comes from the stamp, not mtime (mtime can be touched).
301
+ // (1) age
302
+ if (!(now - owner.createdAt > LOCK_STALE_MS)) return 'kept'
303
+ // (2) ownership: only a conclusive ESRCH is enough to break the lock.
304
+ if (!isLockOwnerDead(owner.pid)) return 'kept'
305
+ } else {
306
+ // Unstamped / empty / half-written / foreign lock (N3): the crash window
307
+ // between `open(wx)` and the stamp write leaves a file with no owner to
308
+ // validate. Use the file's mtime as the age evidence and require it to be
309
+ // over LOCK_STALE_MS. Combine with the byte-compare at delete time below:
310
+ // if a real owner stamped the file in the meantime, its bytes changed and
311
+ // we abandon. A fresh unstamped lock keeps waiting (fail-closed).
312
+ let mtimeMs: number
313
+ try {
314
+ mtimeMs = (await stat(lockPath)).mtimeMs
315
+ } catch {
316
+ return 'kept'
317
+ }
318
+ if (!Number.isFinite(mtimeMs) || !(now - mtimeMs > LOCK_STALE_MS)) return 'kept'
319
+ }
320
+
321
+ const delay = lockBreakVerifyDelayMs()
322
+ if (delay > 0) await new Promise<void>((resolve) => setTimeout(resolve, delay))
323
+
324
+ // (3) compare-and-delete: re-read by path and require byte-identical content.
325
+ // For stamped locks this subsumes the nonce check (the nonce is part of the
326
+ // bytes); for unstamped locks it proves nobody claimed the file meanwhile.
327
+ // A replaced lock is never removed — just keep waiting (fail closed at the
328
+ // deadline).
329
+ let second: string
330
+ try {
331
+ second = await readFile(lockPath, 'utf8')
332
+ } catch {
333
+ return 'kept'
334
+ }
335
+ if (second !== raw) return 'mismatch'
336
+ try {
337
+ await rm(lockPath, { force: true })
338
+ return 'broken'
339
+ } catch {
340
+ return 'kept'
341
+ }
342
+ }
343
+
344
+ async function withCrossProcessLock(path: string, task: () => Promise<void>): Promise<void> {
345
+ const lockPath = lockPathFor(path)
346
+ const deadline = Date.now() + LOCK_WAIT_MS
347
+ let handle: Awaited<ReturnType<typeof open>> | undefined
348
+ try {
349
+ for (;;) {
350
+ try {
351
+ handle = await open(lockPath, 'wx')
352
+ // Stamp ownership right after the exclusive create. A concurrent
353
+ // contender that sees the file before the stamp cannot parse an owner
354
+ // and will conservatively refuse to break it.
355
+ await handle.writeFile(JSON.stringify({
356
+ pid: process.pid,
357
+ nonce: randomUUID(),
358
+ createdAt: Date.now(),
359
+ } satisfies LockOwner), 'utf8')
360
+ break
361
+ } catch (err: unknown) {
362
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err
363
+ // Ignore the outcome: 'mismatch' and 'kept' both mean "still held".
364
+ await tryBreakStaleLock(lockPath, Date.now())
365
+ if (Date.now() >= deadline) throw new StoreLockTimeoutError(lockPath, LOCK_WAIT_MS)
366
+ await new Promise<void>((resolve) => setTimeout(resolve, LOCK_RETRY_MS))
367
+ }
368
+ }
369
+ await task()
370
+ } finally {
371
+ if (handle !== undefined) {
372
+ await handle.close().catch(() => {})
373
+ await rm(lockPath, { force: true }).catch(() => {})
374
+ }
375
+ }
376
+ }
377
+
155
378
  /**
156
379
  * Serialized read/write accessor for ~/.dsh/models-store.json.
157
380
  *
@@ -198,6 +421,46 @@ export interface ModelsStoreAccessor {
198
421
  overrides: Record<string, Record<string, unknown>>,
199
422
  ): Promise<void>
200
423
  delete(providerId: string): Promise<void>
424
+ /**
425
+ * Read an opaque top-level slot of the same document. The opencode-go
426
+ * ownership ledger stores its entries under keys shaped
427
+ * `<profileKey>#<route>#<keyFingerprint>` (B1); unscoped callers still use
428
+ * `<route>#<keyFingerprint>` (design §6.1 / ADR-004). These opaque keys never
429
+ * collide with a provider route id. Raw reads stay strict — an unreadable
430
+ * file throws, so callers can decide whether to fail closed or degrade to
431
+ * "no ledger" (store loss degrades to never-delete).
432
+ *
433
+ * The VALUE is returned verbatim (unstructured): `undefined` means the key is
434
+ * absent, while a present primitive/null slot is returned as-is so callers
435
+ * can detect and clean raw-type corruption instead of silently losing it.
436
+ */
437
+ readRaw(key: string): Promise<unknown>
438
+ /** Queue-serialized replacement of one opaque slot (atomic temp+rename). */
439
+ writeRaw(key: string, value: Record<string, unknown>): Promise<void>
440
+ /** Queue-serialized removal of one opaque slot. */
441
+ deleteRaw(key: string): Promise<void>
442
+ /**
443
+ * Whole-document BYTE restore (migrate-go rollback): under the SAME promise
444
+ * queue + cross-process lock as every other mutation, atomically replace the
445
+ * document with the EXACT bytes given (sibling temp file + rename). Unlike a
446
+ * per-key rebuild this preserves the backup's key order verbatim and is
447
+ * transactional — a failure mid-restore leaves the previous document intact.
448
+ * The text is written as-is, no re-serialization. When `expectedCurrentSha`
449
+ * is given, the CURRENT document is re-hashed INSIDE the queue + lock and
450
+ * the restore refuses (throws, `code: STORE_RESTORE_SHA_MISMATCH`) when it
451
+ * differs — a caller's pre-lock check cannot cover the check→write window,
452
+ * so the baseline is re-verified at the write site itself (round 3). A
453
+ * failed stage/rename cleans the `<pid>.restore-tmp` staging file it
454
+ * created.
455
+ */
456
+ restoreRawDocument(text: string, expectedCurrentSha?: string): Promise<void>
457
+ /**
458
+ * All top-level keys currently in the document, for legacy-key detection and
459
+ * journal enumeration. An unreadable store THROWS (never an empty list): a
460
+ * caller that would silently treat [] as "no journals / no legacy keys" must
461
+ * surface the enumeration failure instead.
462
+ */
463
+ listRawKeys(): Promise<string[]>
201
464
  }
202
465
 
203
466
  /**
@@ -251,7 +514,11 @@ export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
251
514
 
252
515
  let queue: Promise<void> = Promise.resolve()
253
516
  const enqueue = (task: () => Promise<void>): Promise<void> => {
254
- const next = queue.then(task, task)
517
+ // In-process serialization (queue) + cross-process serialization (lock
518
+ // file) around the same RMW+rename section. Reads stay outside both: the
519
+ // atomic rename makes every read see a complete pre- or post-write doc.
520
+ const guarded = (): Promise<void> => withCrossProcessLock(effectivePath, task)
521
+ const next = queue.then(guarded, guarded)
255
522
  queue = next.catch(() => {})
256
523
  return next
257
524
  }
@@ -363,6 +630,85 @@ export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
363
630
  delete doc[providerId]
364
631
  await writeDoc(doc)
365
632
  }),
633
+ // Opaque-slot API used by the go ownership ledger. It deliberately shares
634
+ // the SAME queue and atomic writeDoc as the fetch cache: a ledger write and
635
+ // a concurrent `update`/`updateOverrides` can never clobber each other's
636
+ // slots in models-store.json. Keys carrying `#` are ledger entries, not
637
+ // route ids, so `read(route)`/`update(route)` never see them.
638
+ readRaw: async (key: string): Promise<unknown> => {
639
+ // Return the slot verbatim. Only `undefined` (key absent, or a JSON doc
640
+ // that never carried the key) means "no slot"; a present string/number/
641
+ // null/array is surfaced so the journal store can warn + clean it under
642
+ // its key-shape/profile safety check instead of silently degrading to
643
+ // "no journal". Object-shape consumers still validate the type themselves.
644
+ return (await readDoc())[key]
645
+ },
646
+ writeRaw: (key: string, value: Record<string, unknown>): Promise<void> =>
647
+ enqueue(async () => {
648
+ let doc: ModelsStore
649
+ try {
650
+ doc = await readDoc()
651
+ } catch {
652
+ // A corrupt/unreadable doc is replaced atomically by writeDoc below;
653
+ // this is the same self-heal contract as `write`/`update`.
654
+ doc = {}
655
+ }
656
+ ;(doc as unknown as Record<string, unknown>)[key] = value
657
+ await writeDoc(doc)
658
+ }),
659
+ deleteRaw: (key: string): Promise<void> =>
660
+ enqueue(async () => {
661
+ let doc: ModelsStore
662
+ try {
663
+ doc = await readDoc()
664
+ } catch {
665
+ doc = {}
666
+ }
667
+ delete (doc as unknown as Record<string, unknown>)[key]
668
+ await writeDoc(doc)
669
+ }),
670
+ restoreRawDocument: (text: string, expectedCurrentSha?: string): Promise<void> =>
671
+ enqueue(async () => {
672
+ // In-lock re-verify (round 3): the caller's pre-lock sha check cannot
673
+ // cover the window between the check and this write, so the baseline
674
+ // is re-hashed here under the SAME queue + cross-process lock as the
675
+ // write itself. A missing file is a mismatch too (the store vanished
676
+ // mid-run — nothing sane to restore onto).
677
+ if (expectedCurrentSha !== undefined) {
678
+ let current: string | undefined
679
+ try {
680
+ current = await readFile(effectivePath, 'utf8')
681
+ } catch {
682
+ current = undefined
683
+ }
684
+ const currentSha = current === undefined ? undefined : createHash('sha256').update(current).digest('hex')
685
+ if (currentSha !== expectedCurrentSha) {
686
+ throw Object.assign(
687
+ new Error(
688
+ `models-store changed since the post-write baseline was taken ` +
689
+ `(expected sha ${expectedCurrentSha}, current ${currentSha ?? 'absent'}); restore refused`,
690
+ ),
691
+ { code: STORE_RESTORE_SHA_MISMATCH },
692
+ )
693
+ }
694
+ }
695
+ // Byte-exact whole-document replacement under the same lock every
696
+ // other writer uses (migrate-go rollback). Same atomic tmp+rename
697
+ // contract as writeDoc — a crash leaves either the pre-restore doc or
698
+ // the restored backup, never a torn hybrid. A failed stage/rename
699
+ // cleans the staging file this call created (round 3: no
700
+ // `<pid>.restore-tmp` residue).
701
+ await mkdir(dirname(effectivePath), { recursive: true })
702
+ const tmpPath = `${effectivePath}.${process.pid}.restore-tmp`
703
+ try {
704
+ await writeFile(tmpPath, text)
705
+ await rename(tmpPath, effectivePath)
706
+ } catch (err) {
707
+ await unlink(tmpPath).catch(() => {})
708
+ throw err
709
+ }
710
+ }),
711
+ listRawKeys: async (): Promise<string[]> => Object.keys(await readDoc()),
366
712
  }
367
713
 
368
714
  // Only cache the default-path accessor (singleton)
@@ -520,6 +866,16 @@ export async function fetchRemoteCatalog(
520
866
  return { entries: refreshed, fromCache: false }
521
867
  } catch (err: unknown) {
522
868
  const message = err instanceof Error ? err.message : String(err)
869
+ // A store lock timeout is not a fetch/network error. Keep its actionable
870
+ // message (lock path + retry / check-other-processes guidance) verbatim so
871
+ // callers can tell "retry later" from "the catalog request itself failed".
872
+ if (isStoreLockTimeout(err)) {
873
+ return {
874
+ entries: stored?.models ?? [],
875
+ fromCache: false,
876
+ error: `store lock timeout while persisting ${route}: ${message}`,
877
+ }
878
+ }
523
879
  // On abort or network error, return cached entries
524
880
  return {
525
881
  entries: stored?.models ?? [],