@aiwayds/dsh-model-sync 0.10.0 → 0.11.1

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.
@@ -14,7 +14,7 @@
14
14
  import { createHash, randomUUID } from 'node:crypto'
15
15
  import { homedir, tmpdir } from 'node:os'
16
16
  import { dirname, join } from 'node:path'
17
- import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
17
+ import { mkdir, open, readFile, rename, rm, stat, unlink, writeFile } from 'node:fs/promises'
18
18
 
19
19
  // ---------------------------------------------------------------------------
20
20
  // Constants (ported from docs-dsh-llm-pi-ai.patch:35-36)
@@ -29,6 +29,16 @@ export const REMOTE_CATALOG_REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000
29
29
  /** Path to the persistent per-provider cache. */
30
30
  export const MODELS_STORE_PATH = join(homedir(), '.dsh', 'models-store.json')
31
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
+
32
42
  // ---------------------------------------------------------------------------
33
43
  // Types
34
44
  // ---------------------------------------------------------------------------
@@ -429,6 +439,21 @@ export interface ModelsStoreAccessor {
429
439
  writeRaw(key: string, value: Record<string, unknown>): Promise<void>
430
440
  /** Queue-serialized removal of one opaque slot. */
431
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>
432
457
  /**
433
458
  * All top-level keys currently in the document, for legacy-key detection and
434
459
  * journal enumeration. An unreadable store THROWS (never an empty list): a
@@ -642,6 +667,47 @@ export function loadModelsStore(storePath?: string): ModelsStoreAccessor {
642
667
  delete (doc as unknown as Record<string, unknown>)[key]
643
668
  await writeDoc(doc)
644
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
+ }),
645
711
  listRawKeys: async (): Promise<string[]> => Object.keys(await readDoc()),
646
712
  }
647
713