@aiwayds/dsh-model-sync 0.9.0 → 0.10.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 (66) hide show
  1. package/README.md +8 -3
  2. package/README.zh-CN.md +8 -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 +366 -0
  6. package/lib/index.js +729 -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-planner.d.ts +153 -0
  24. package/lib/opencode-go-planner.js +339 -0
  25. package/lib/opencode-go-planner.js.map +1 -0
  26. package/lib/opencode-go-profile.d.ts +57 -0
  27. package/lib/opencode-go-profile.js +103 -0
  28. package/lib/opencode-go-profile.js.map +1 -0
  29. package/lib/opencode-go-scheduler.d.ts +128 -0
  30. package/lib/opencode-go-scheduler.js +241 -0
  31. package/lib/opencode-go-scheduler.js.map +1 -0
  32. package/lib/opencode-go-source.d.ts +117 -0
  33. package/lib/opencode-go-source.js +331 -0
  34. package/lib/opencode-go-source.js.map +1 -0
  35. package/lib/opencode-go-store.d.ts +18 -0
  36. package/lib/opencode-go-store.js +68 -0
  37. package/lib/opencode-go-store.js.map +1 -0
  38. package/lib/opencode-go-sync.d.ts +94 -0
  39. package/lib/opencode-go-sync.js +364 -0
  40. package/lib/opencode-go-sync.js.map +1 -0
  41. package/lib/opencode-go-writer.d.ts +132 -0
  42. package/lib/opencode-go-writer.js +966 -0
  43. package/lib/opencode-go-writer.js.map +1 -0
  44. package/lib/provider-native.d.ts +3 -1
  45. package/lib/provider-native.js +4 -2
  46. package/lib/provider-native.js.map +1 -1
  47. package/lib/remote-catalog.d.ts +37 -0
  48. package/lib/remote-catalog.js +261 -3
  49. package/lib/remote-catalog.js.map +1 -1
  50. package/package.json +15 -15
  51. package/src/builtin-catalog-snapshot.ts +6 -3
  52. package/src/index.ts +873 -12
  53. package/src/opencode-go-diagnose.ts +222 -0
  54. package/src/opencode-go-grouping.ts +97 -0
  55. package/src/opencode-go-journal.ts +458 -0
  56. package/src/opencode-go-migrate.ts +1694 -0
  57. package/src/opencode-go-migration.ts +552 -0
  58. package/src/opencode-go-planner.ts +505 -0
  59. package/src/opencode-go-profile.ts +114 -0
  60. package/src/opencode-go-scheduler.ts +315 -0
  61. package/src/opencode-go-source.ts +424 -0
  62. package/src/opencode-go-store.ts +73 -0
  63. package/src/opencode-go-sync.ts +503 -0
  64. package/src/opencode-go-writer.ts +1189 -0
  65. package/src/provider-native.ts +3 -1
  66. package/src/remote-catalog.ts +293 -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, writeFile } from 'node:fs/promises'
17
18
 
18
19
  // ---------------------------------------------------------------------------
19
20
  // Constants (ported from docs-dsh-llm-pi-ai.patch:35-36)
@@ -152,6 +153,218 @@ export function parseRemoteCatalog(
152
153
 
153
154
  let modelsStoreCache: ModelsStoreAccessor | undefined
154
155
 
156
+ // --- Cross-process write guard (B1 / R-14; D2/D3 hardening) -----------------
157
+ //
158
+ // The promise queue below serializes writes WITHIN one process only. Two dsh
159
+ // processes (two profiles sharing models-store.json) still race: both read the
160
+ // whole document, both rewrite it, and the last rename wins — silently dropping
161
+ // the other profile's newly written ledger key. Key namespacing alone cannot
162
+ // prevent that whole-document last-writer-wins loss.
163
+ //
164
+ // Guard the read-modify-write+rename critical section with a single lock file
165
+ // created by atomic exclusive `open(..., 'wx')`. The lock lives in the OS temp
166
+ // dir (name hashed from the absolute store path) so two processes derive the
167
+ // same file and no transient file is ever created under ~/.dsh. It is held
168
+ // only for the few ms of one write and removed in `finally`.
169
+ //
170
+ // Lock files carry an owner stamp { pid, nonce, createdAt }. A lock is only
171
+ // broken as stale when ALL three hold: its recorded age exceeds
172
+ // LOCK_STALE_MS, its owner PID is *conclusively* gone (kill(pid, 0) -> ESRCH;
173
+ // EPERM / any other outcome is indeterminate and conservatively keeps the
174
+ // lock), and a re-read immediately before deletion still shows the same
175
+ // nonce (compare-and-delete, so a lock replaced mid-check is never removed).
176
+ // A lock with NO parseable stamp is the crash window between `open(wx)` and
177
+ // the stamp write: it has no owner to validate, so it is only reclaimed once
178
+ // its FILE mtime is older than LOCK_STALE_MS and its raw bytes are unchanged
179
+ // at delete time — otherwise it keeps the lock (fail-closed). A lock that
180
+ // cannot be acquired within LOCK_WAIT_MS is a hard failure:
181
+ // StoreLockTimeoutError is thrown and the write does NOT run (fail-closed),
182
+ // because a bypass would reintroduce the whole-document last-writer-wins loss
183
+ // this guard exists to prevent. The store bytes are untouched on timeout.
184
+ const LOCK_STALE_MS = 10_000
185
+ const LOCK_WAIT_MS = 2_000
186
+ const LOCK_RETRY_MS = 8
187
+
188
+ /** Payload written into the lock file so a stale break can validate ownership. */
189
+ interface LockOwner {
190
+ pid: number
191
+ nonce: string
192
+ createdAt: number
193
+ }
194
+
195
+ /**
196
+ * Fail-closed error for a cross-process lock that stayed contended past
197
+ * LOCK_WAIT_MS. `name` and `code` distinguish it from an ordinary store write
198
+ * failure (corrupt JSON, EIO, ...) so callers can tell "retry / someone else
199
+ * is holding the lock" from "the store itself is broken".
200
+ */
201
+ export class StoreLockTimeoutError extends Error {
202
+ readonly code = 'DSH_STORE_LOCK_TIMEOUT'
203
+ readonly lockPath: string
204
+ readonly waitMs: number
205
+
206
+ constructor(lockPath: string, waitMs: number) {
207
+ super(
208
+ `Timed out after ${waitMs}ms waiting for the models-store lock (${lockPath}). ` +
209
+ '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. ' +
210
+ `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.`,
211
+ )
212
+ this.name = 'StoreLockTimeoutError'
213
+ this.lockPath = lockPath
214
+ this.waitMs = waitMs
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Structural check for a store lock timeout. Uses `code`/`name` rather than
220
+ * `instanceof` so a timeout that was re-wrapped (or crossed a module boundary)
221
+ * is still recognized and its actionable message is not degraded to a generic
222
+ * failure.
223
+ */
224
+ function isStoreLockTimeout(err: unknown): boolean {
225
+ if (err === null || typeof err !== 'object') return false
226
+ const value = err as { code?: unknown; name?: unknown }
227
+ return value.code === 'DSH_STORE_LOCK_TIMEOUT' || value.name === 'StoreLockTimeoutError'
228
+ }
229
+
230
+ function lockPathFor(path: string): string {
231
+ return join(tmpdir(), `${createHash('sha256').update(path).digest('hex')}.dsh-store.lock`)
232
+ }
233
+
234
+ function parseLockOwner(raw: string): LockOwner | undefined {
235
+ try {
236
+ const value = JSON.parse(raw) as Partial<LockOwner>
237
+ if (
238
+ typeof value.pid === 'number' && Number.isInteger(value.pid) && value.pid > 0
239
+ && typeof value.nonce === 'string' && value.nonce.length > 0
240
+ && typeof value.createdAt === 'number' && Number.isFinite(value.createdAt)
241
+ ) {
242
+ return { pid: value.pid, nonce: value.nonce, createdAt: value.createdAt }
243
+ }
244
+ } catch {
245
+ // Empty (just-created, not yet stamped), half-written or foreign file —
246
+ // ownership cannot be determined, so the lock must not be broken.
247
+ }
248
+ return undefined
249
+ }
250
+
251
+ /** True only when signal probe conclusively reports the owner process is gone. */
252
+ function isLockOwnerDead(pid: number): boolean {
253
+ try {
254
+ process.kill(pid, 0)
255
+ return false // process exists (or at least can be signalled): keep the lock
256
+ } catch (err: unknown) {
257
+ // ESRCH is the only "definitely gone" answer. EPERM means the process
258
+ // exists but belongs to another user; anything else is indeterminate.
259
+ // Both must be treated conservatively as "alive/unknown" — never break.
260
+ return (err as NodeJS.ErrnoException).code === 'ESRCH'
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Test-only seam (never set by dsh or the plugin): widens the gap between the
266
+ * two owner reads so a behavioral test can swap the lock file in between and
267
+ * prove compare-and-delete refuses to remove a replacement. Zero in normal
268
+ * operation, so production timing is unchanged.
269
+ */
270
+ function lockBreakVerifyDelayMs(): number {
271
+ const raw = process.env.DSH_LOCK_BREAK_VERIFY_DELAY_MS
272
+ if (raw === undefined || raw === '') return 0
273
+ const ms = Number(raw)
274
+ return Number.isFinite(ms) && ms > 0 ? ms : 0
275
+ }
276
+
277
+ type BreakOutcome = 'broken' | 'kept' | 'mismatch'
278
+
279
+ /** Attempt an owner-validated stale break. Never deletes a lock it cannot prove is stale. */
280
+ async function tryBreakStaleLock(lockPath: string, now: number): Promise<BreakOutcome> {
281
+ let raw: string
282
+ try {
283
+ raw = await readFile(lockPath, 'utf8')
284
+ } catch {
285
+ return 'kept' // vanished or unreadable between EEXIST and read — retry later
286
+ }
287
+ const owner = parseLockOwner(raw)
288
+
289
+ if (owner !== undefined) {
290
+ // Stamped lock: age comes from the stamp, not mtime (mtime can be touched).
291
+ // (1) age
292
+ if (!(now - owner.createdAt > LOCK_STALE_MS)) return 'kept'
293
+ // (2) ownership: only a conclusive ESRCH is enough to break the lock.
294
+ if (!isLockOwnerDead(owner.pid)) return 'kept'
295
+ } else {
296
+ // Unstamped / empty / half-written / foreign lock (N3): the crash window
297
+ // between `open(wx)` and the stamp write leaves a file with no owner to
298
+ // validate. Use the file's mtime as the age evidence and require it to be
299
+ // over LOCK_STALE_MS. Combine with the byte-compare at delete time below:
300
+ // if a real owner stamped the file in the meantime, its bytes changed and
301
+ // we abandon. A fresh unstamped lock keeps waiting (fail-closed).
302
+ let mtimeMs: number
303
+ try {
304
+ mtimeMs = (await stat(lockPath)).mtimeMs
305
+ } catch {
306
+ return 'kept'
307
+ }
308
+ if (!Number.isFinite(mtimeMs) || !(now - mtimeMs > LOCK_STALE_MS)) return 'kept'
309
+ }
310
+
311
+ const delay = lockBreakVerifyDelayMs()
312
+ if (delay > 0) await new Promise<void>((resolve) => setTimeout(resolve, delay))
313
+
314
+ // (3) compare-and-delete: re-read by path and require byte-identical content.
315
+ // For stamped locks this subsumes the nonce check (the nonce is part of the
316
+ // bytes); for unstamped locks it proves nobody claimed the file meanwhile.
317
+ // A replaced lock is never removed — just keep waiting (fail closed at the
318
+ // deadline).
319
+ let second: string
320
+ try {
321
+ second = await readFile(lockPath, 'utf8')
322
+ } catch {
323
+ return 'kept'
324
+ }
325
+ if (second !== raw) return 'mismatch'
326
+ try {
327
+ await rm(lockPath, { force: true })
328
+ return 'broken'
329
+ } catch {
330
+ return 'kept'
331
+ }
332
+ }
333
+
334
+ async function withCrossProcessLock(path: string, task: () => Promise<void>): Promise<void> {
335
+ const lockPath = lockPathFor(path)
336
+ const deadline = Date.now() + LOCK_WAIT_MS
337
+ let handle: Awaited<ReturnType<typeof open>> | undefined
338
+ try {
339
+ for (;;) {
340
+ try {
341
+ handle = await open(lockPath, 'wx')
342
+ // Stamp ownership right after the exclusive create. A concurrent
343
+ // contender that sees the file before the stamp cannot parse an owner
344
+ // and will conservatively refuse to break it.
345
+ await handle.writeFile(JSON.stringify({
346
+ pid: process.pid,
347
+ nonce: randomUUID(),
348
+ createdAt: Date.now(),
349
+ } satisfies LockOwner), 'utf8')
350
+ break
351
+ } catch (err: unknown) {
352
+ if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err
353
+ // Ignore the outcome: 'mismatch' and 'kept' both mean "still held".
354
+ await tryBreakStaleLock(lockPath, Date.now())
355
+ if (Date.now() >= deadline) throw new StoreLockTimeoutError(lockPath, LOCK_WAIT_MS)
356
+ await new Promise<void>((resolve) => setTimeout(resolve, LOCK_RETRY_MS))
357
+ }
358
+ }
359
+ await task()
360
+ } finally {
361
+ if (handle !== undefined) {
362
+ await handle.close().catch(() => {})
363
+ await rm(lockPath, { force: true }).catch(() => {})
364
+ }
365
+ }
366
+ }
367
+
155
368
  /**
156
369
  * Serialized read/write accessor for ~/.dsh/models-store.json.
157
370
  *
@@ -198,6 +411,31 @@ export interface ModelsStoreAccessor {
198
411
  overrides: Record<string, Record<string, unknown>>,
199
412
  ): Promise<void>
200
413
  delete(providerId: string): Promise<void>
414
+ /**
415
+ * Read an opaque top-level slot of the same document. The opencode-go
416
+ * ownership ledger stores its entries under keys shaped
417
+ * `<profileKey>#<route>#<keyFingerprint>` (B1); unscoped callers still use
418
+ * `<route>#<keyFingerprint>` (design §6.1 / ADR-004). These opaque keys never
419
+ * collide with a provider route id. Raw reads stay strict — an unreadable
420
+ * file throws, so callers can decide whether to fail closed or degrade to
421
+ * "no ledger" (store loss degrades to never-delete).
422
+ *
423
+ * The VALUE is returned verbatim (unstructured): `undefined` means the key is
424
+ * absent, while a present primitive/null slot is returned as-is so callers
425
+ * can detect and clean raw-type corruption instead of silently losing it.
426
+ */
427
+ readRaw(key: string): Promise<unknown>
428
+ /** Queue-serialized replacement of one opaque slot (atomic temp+rename). */
429
+ writeRaw(key: string, value: Record<string, unknown>): Promise<void>
430
+ /** Queue-serialized removal of one opaque slot. */
431
+ deleteRaw(key: string): Promise<void>
432
+ /**
433
+ * All top-level keys currently in the document, for legacy-key detection and
434
+ * journal enumeration. An unreadable store THROWS (never an empty list): a
435
+ * caller that would silently treat [] as "no journals / no legacy keys" must
436
+ * surface the enumeration failure instead.
437
+ */
438
+ listRawKeys(): Promise<string[]>
201
439
  }
202
440
 
203
441
  /**
@@ -251,7 +489,11 @@ export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
251
489
 
252
490
  let queue: Promise<void> = Promise.resolve()
253
491
  const enqueue = (task: () => Promise<void>): Promise<void> => {
254
- const next = queue.then(task, task)
492
+ // In-process serialization (queue) + cross-process serialization (lock
493
+ // file) around the same RMW+rename section. Reads stay outside both: the
494
+ // atomic rename makes every read see a complete pre- or post-write doc.
495
+ const guarded = (): Promise<void> => withCrossProcessLock(effectivePath, task)
496
+ const next = queue.then(guarded, guarded)
255
497
  queue = next.catch(() => {})
256
498
  return next
257
499
  }
@@ -363,6 +605,44 @@ export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
363
605
  delete doc[providerId]
364
606
  await writeDoc(doc)
365
607
  }),
608
+ // Opaque-slot API used by the go ownership ledger. It deliberately shares
609
+ // the SAME queue and atomic writeDoc as the fetch cache: a ledger write and
610
+ // a concurrent `update`/`updateOverrides` can never clobber each other's
611
+ // slots in models-store.json. Keys carrying `#` are ledger entries, not
612
+ // route ids, so `read(route)`/`update(route)` never see them.
613
+ readRaw: async (key: string): Promise<unknown> => {
614
+ // Return the slot verbatim. Only `undefined` (key absent, or a JSON doc
615
+ // that never carried the key) means "no slot"; a present string/number/
616
+ // null/array is surfaced so the journal store can warn + clean it under
617
+ // its key-shape/profile safety check instead of silently degrading to
618
+ // "no journal". Object-shape consumers still validate the type themselves.
619
+ return (await readDoc())[key]
620
+ },
621
+ writeRaw: (key: string, value: Record<string, unknown>): Promise<void> =>
622
+ enqueue(async () => {
623
+ let doc: ModelsStore
624
+ try {
625
+ doc = await readDoc()
626
+ } catch {
627
+ // A corrupt/unreadable doc is replaced atomically by writeDoc below;
628
+ // this is the same self-heal contract as `write`/`update`.
629
+ doc = {}
630
+ }
631
+ ;(doc as unknown as Record<string, unknown>)[key] = value
632
+ await writeDoc(doc)
633
+ }),
634
+ deleteRaw: (key: string): Promise<void> =>
635
+ enqueue(async () => {
636
+ let doc: ModelsStore
637
+ try {
638
+ doc = await readDoc()
639
+ } catch {
640
+ doc = {}
641
+ }
642
+ delete (doc as unknown as Record<string, unknown>)[key]
643
+ await writeDoc(doc)
644
+ }),
645
+ listRawKeys: async (): Promise<string[]> => Object.keys(await readDoc()),
366
646
  }
367
647
 
368
648
  // Only cache the default-path accessor (singleton)
@@ -520,6 +800,16 @@ export async function fetchRemoteCatalog(
520
800
  return { entries: refreshed, fromCache: false }
521
801
  } catch (err: unknown) {
522
802
  const message = err instanceof Error ? err.message : String(err)
803
+ // A store lock timeout is not a fetch/network error. Keep its actionable
804
+ // message (lock path + retry / check-other-processes guidance) verbatim so
805
+ // callers can tell "retry later" from "the catalog request itself failed".
806
+ if (isStoreLockTimeout(err)) {
807
+ return {
808
+ entries: stored?.models ?? [],
809
+ fromCache: false,
810
+ error: `store lock timeout while persisting ${route}: ${message}`,
811
+ }
812
+ }
523
813
  // On abort or network error, return cached entries
524
814
  return {
525
815
  entries: stored?.models ?? [],