@aiwayds/dsh-model-sync 0.8.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 (68) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +9 -4
  3. package/README.zh-CN.md +9 -4
  4. package/lib/builtin-catalog-snapshot.d.ts +5 -1
  5. package/lib/builtin-catalog-snapshot.js +13 -10
  6. package/lib/builtin-catalog-snapshot.js.map +1 -1
  7. package/lib/index.d.ts +366 -0
  8. package/lib/index.js +729 -13
  9. package/lib/index.js.map +1 -1
  10. package/lib/opencode-go-diagnose.d.ts +74 -0
  11. package/lib/opencode-go-diagnose.js +146 -0
  12. package/lib/opencode-go-diagnose.js.map +1 -0
  13. package/lib/opencode-go-grouping.d.ts +29 -0
  14. package/lib/opencode-go-grouping.js +77 -0
  15. package/lib/opencode-go-grouping.js.map +1 -0
  16. package/lib/opencode-go-journal.d.ts +110 -0
  17. package/lib/opencode-go-journal.js +406 -0
  18. package/lib/opencode-go-journal.js.map +1 -0
  19. package/lib/opencode-go-migrate.d.ts +343 -0
  20. package/lib/opencode-go-migrate.js +1300 -0
  21. package/lib/opencode-go-migrate.js.map +1 -0
  22. package/lib/opencode-go-migration.d.ts +227 -0
  23. package/lib/opencode-go-migration.js +384 -0
  24. package/lib/opencode-go-migration.js.map +1 -0
  25. package/lib/opencode-go-planner.d.ts +153 -0
  26. package/lib/opencode-go-planner.js +339 -0
  27. package/lib/opencode-go-planner.js.map +1 -0
  28. package/lib/opencode-go-profile.d.ts +57 -0
  29. package/lib/opencode-go-profile.js +103 -0
  30. package/lib/opencode-go-profile.js.map +1 -0
  31. package/lib/opencode-go-scheduler.d.ts +128 -0
  32. package/lib/opencode-go-scheduler.js +241 -0
  33. package/lib/opencode-go-scheduler.js.map +1 -0
  34. package/lib/opencode-go-source.d.ts +117 -0
  35. package/lib/opencode-go-source.js +331 -0
  36. package/lib/opencode-go-source.js.map +1 -0
  37. package/lib/opencode-go-store.d.ts +18 -0
  38. package/lib/opencode-go-store.js +68 -0
  39. package/lib/opencode-go-store.js.map +1 -0
  40. package/lib/opencode-go-sync.d.ts +94 -0
  41. package/lib/opencode-go-sync.js +364 -0
  42. package/lib/opencode-go-sync.js.map +1 -0
  43. package/lib/opencode-go-writer.d.ts +132 -0
  44. package/lib/opencode-go-writer.js +966 -0
  45. package/lib/opencode-go-writer.js.map +1 -0
  46. package/lib/provider-native.d.ts +3 -1
  47. package/lib/provider-native.js +4 -2
  48. package/lib/provider-native.js.map +1 -1
  49. package/lib/remote-catalog.d.ts +37 -0
  50. package/lib/remote-catalog.js +261 -3
  51. package/lib/remote-catalog.js.map +1 -1
  52. package/package.json +18 -18
  53. package/src/builtin-catalog-snapshot.ts +18 -11
  54. package/src/index.ts +873 -12
  55. package/src/opencode-go-diagnose.ts +222 -0
  56. package/src/opencode-go-grouping.ts +97 -0
  57. package/src/opencode-go-journal.ts +458 -0
  58. package/src/opencode-go-migrate.ts +1694 -0
  59. package/src/opencode-go-migration.ts +552 -0
  60. package/src/opencode-go-planner.ts +505 -0
  61. package/src/opencode-go-profile.ts +114 -0
  62. package/src/opencode-go-scheduler.ts +315 -0
  63. package/src/opencode-go-source.ts +424 -0
  64. package/src/opencode-go-store.ts +73 -0
  65. package/src/opencode-go-sync.ts +503 -0
  66. package/src/opencode-go-writer.ts +1189 -0
  67. package/src/provider-native.ts +3 -1
  68. package/src/remote-catalog.ts +293 -3
@@ -0,0 +1,424 @@
1
+ // P0 (read-only diagnostic): opencode-go official /v1/models source.
2
+ //
3
+ // Fetches the official listing, normalizes each entry into the shape the
4
+ // diagnostic needs, and classifies auth / entitlement failures. This module
5
+ // is deliberately side-effect free apart from the injected network call: it
6
+ // never touches settings, credentials, or the filesystem. P1 will consume the
7
+ // same normalized records for route planning; P0 stops at the report.
8
+ //
9
+ // Design: 07-design.md §6.1 (ModelRecord), §6.3 (authStatus), ADR-001.
10
+ // The no-key branch follows §6.3 / V4: warn, send no request, write nothing —
11
+ // the unauthenticated public 30-model list is NOT a servable source (C2).
12
+
13
+ import { createHash } from 'node:crypto'
14
+
15
+ /** Official model-listing endpoint (design §6.2.6 default). */
16
+ export const OPENCODE_GO_MODELS_URL = 'https://opencode.ai/inference/go/v1/models'
17
+
18
+ /** P0 fixed default polling interval for the go source (design §6.2.6). */
19
+ export const OPENCODE_GO_DEFAULT_INTERVAL_MINUTES = 60
20
+
21
+ /** Explicit UA — the gateway bans default library UAs with CF 1010 (05 §1). */
22
+ export const GO_USER_AGENT = 'dsh-model-sync/0.10.0'
23
+
24
+ /** Auth states carried by the diagnostic report (design §6.1 SourceSnapshot). */
25
+ export type GoAuthStatus = 'unknown' | 'ok' | 'invalid' | 'not-entitled' | 'unreachable'
26
+
27
+ /** Failure taxonomy (design §6.1 lastError.kind + no-key for the opt-out path). */
28
+ export type GoFailureKind = 'auth' | 'entitlement' | 'transport' | 'parse' | 'offline' | 'no-key'
29
+
30
+ /** One normalized official model entry. `created` is intentionally absent. */
31
+ export interface GoModelRecord {
32
+ id: string
33
+ name: string
34
+ canonicalId?: string
35
+ releaseDate?: string
36
+ lastUpdated?: string
37
+ contextWindow?: number
38
+ maxOutput?: number
39
+ inputModalities: string[]
40
+ reasoning?: { supported: boolean; efforts: string[] }
41
+ /** Keys of the official `api` dictionary (the protocol names). */
42
+ protocols: string[]
43
+ recommendedProtocol?: string
44
+ /** Official per-protocol `base_url`, used by P1 route planning only. */
45
+ baseUrls: Record<string, string>
46
+ provenance: 'go-official'
47
+ }
48
+
49
+ /** Failure detail attached to a source result (never contains a key value). */
50
+ export interface GoSourceError {
51
+ kind: GoFailureKind
52
+ status?: number
53
+ message: string
54
+ }
55
+
56
+ /** Outcome of one source read. */
57
+ export interface GoSourceResult {
58
+ ok: boolean
59
+ entries: GoModelRecord[]
60
+ authStatus: GoAuthStatus
61
+ /** sha256(key) first 16 hex; '-' when no key was available. */
62
+ keyFingerprint: string
63
+ /** sha256 of canonical normalized JSON; excludes `created`. */
64
+ payloadHash?: string
65
+ observedAt: number
66
+ error?: GoSourceError
67
+ }
68
+
69
+ /** Outcome of the unauthenticated *public* catalog read (classification only, C2). */
70
+ export interface GoPublicCatalogResult {
71
+ ok: boolean
72
+ ids: string[]
73
+ error?: GoSourceError
74
+ }
75
+
76
+ /** Minimal response shape the fetch accepts (injected in tests). */
77
+ export interface GoFetchResponse {
78
+ status: number
79
+ json(): Promise<unknown>
80
+ }
81
+
82
+ /** Injectable fetch: a plain function, like provider-native.ts's FetchLike. */
83
+ export type GoFetchLike = (url: string, init: {
84
+ headers: Record<string, string>
85
+ signal: AbortSignal
86
+ }) => Promise<GoFetchResponse>
87
+
88
+ /** Options for one source read. */
89
+ export interface FetchGoOfficialOptions {
90
+ url?: string
91
+ apiKey?: string
92
+ timeoutMs?: number
93
+ observedAt?: number
94
+ fetchImpl?: GoFetchLike
95
+ /** Plugin-lifetime signal: aborting it aborts the in-flight fetch (design §6.3 卸载). */
96
+ signal?: AbortSignal
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Small helpers
101
+ // ---------------------------------------------------------------------------
102
+
103
+ function isRecord(value: unknown): value is Record<string, unknown> {
104
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
105
+ }
106
+
107
+ function positiveInt(value: unknown): number | undefined {
108
+ return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined
109
+ }
110
+
111
+ function stringList(value: unknown): string[] {
112
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
113
+ }
114
+
115
+ /** Irreversible key fingerprint — the only key-derived value ever retained. */
116
+ export function fingerprintKey(key: string): string {
117
+ return createHash('sha256').update(key).digest('hex').slice(0, 16)
118
+ }
119
+
120
+ /** Canonical JSON: object keys sorted recursively so hashing is order-stable. */
121
+ function canonicalize(value: unknown): unknown {
122
+ if (Array.isArray(value)) return value.map(canonicalize)
123
+ if (!isRecord(value)) return value
124
+ const out: Record<string, unknown> = {}
125
+ for (const key of Object.keys(value).sort()) out[key] = canonicalize(value[key])
126
+ return out
127
+ }
128
+
129
+ /** Hash of the normalized set. `created` never reaches this function. */
130
+ export function computeGoPayloadHash(entries: readonly GoModelRecord[]): string {
131
+ return createHash('sha256').update(JSON.stringify(canonicalize(entries))).digest('hex')
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Payload normalization (pure; fixture-driven tests)
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /**
139
+ * Parse the official `{ object: 'list', data: [...] }` payload into normalized
140
+ * records. Unknown fields (cost, sdk, go.monthly_usage, …) are dropped; every
141
+ * field the diagnostic or P1 planning needs is mapped explicitly. `created`
142
+ * is deliberately not copied, so it can never enter the payload hash.
143
+ */
144
+ export function parseGoModelsPayload(value: unknown): GoModelRecord[] {
145
+ if (!isRecord(value) || !Array.isArray(value.data)) {
146
+ throw new Error('opencode-go payload is not a model list')
147
+ }
148
+ const entries: GoModelRecord[] = []
149
+ for (const item of value.data) {
150
+ if (!isRecord(item)) continue
151
+ const id = item.id
152
+ if (typeof id !== 'string' || id.length === 0) continue
153
+
154
+ const api = isRecord(item.api) ? item.api : {}
155
+ const protocols = Object.keys(api).filter((key) => isRecord(api[key]))
156
+ const baseUrls: Record<string, string> = {}
157
+ for (const protocol of protocols) {
158
+ const base = (api[protocol] as Record<string, unknown>).base_url
159
+ if (typeof base === 'string' && base.length > 0) baseUrls[protocol] = base
160
+ }
161
+
162
+ const limit = isRecord(item.limit) ? item.limit : {}
163
+ const contextWindow = positiveInt(limit.context)
164
+ const output = positiveInt(limit.output)
165
+ // An output >= context is a bad upstream value — strip it (design §6.1).
166
+ const maxOutput = output !== undefined && (contextWindow === undefined || output < contextWindow)
167
+ ? output
168
+ : undefined
169
+
170
+ const modalities = isRecord(item.modalities) ? item.modalities : {}
171
+ // text→text, image/*→image; audio/video/pdf are ignored (design §6.1).
172
+ const inputModalities: string[] = []
173
+ for (const modality of stringList(modalities.input)) {
174
+ const normalized = modality === 'text' ? 'text' : modality.startsWith('image/') ? 'image' : undefined
175
+ if (normalized !== undefined && !inputModalities.includes(normalized)) inputModalities.push(normalized)
176
+ }
177
+
178
+ const capabilities = isRecord(item.capabilities) ? item.capabilities : {}
179
+ const reasoningRaw = isRecord(capabilities.reasoning) ? capabilities.reasoning : undefined
180
+ const reasoning = reasoningRaw !== undefined
181
+ ? {
182
+ supported: reasoningRaw.supported === true,
183
+ efforts: stringList(reasoningRaw.effort).map((effort) => effort === 'none' ? 'off' : effort),
184
+ }
185
+ : undefined
186
+
187
+ const entry: GoModelRecord = {
188
+ id,
189
+ name: typeof item.name === 'string' ? item.name : id,
190
+ protocols,
191
+ baseUrls,
192
+ inputModalities,
193
+ provenance: 'go-official',
194
+ }
195
+ if (typeof item.canonical_id === 'string') entry.canonicalId = item.canonical_id
196
+ if (typeof item.release_date === 'string') entry.releaseDate = item.release_date
197
+ if (typeof item.last_updated === 'string') entry.lastUpdated = item.last_updated
198
+ if (contextWindow !== undefined) entry.contextWindow = contextWindow
199
+ if (maxOutput !== undefined) entry.maxOutput = maxOutput
200
+ if (reasoning !== undefined) entry.reasoning = reasoning
201
+ if (typeof item.recommended_api === 'string') entry.recommendedProtocol = item.recommended_api
202
+ entries.push(entry)
203
+ }
204
+ if (entries.length === 0) throw new Error('opencode-go payload lists no usable model ids')
205
+ return entries
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // Auth / entitlement classification (pure)
210
+ // ---------------------------------------------------------------------------
211
+
212
+ export interface GoHttpClassification {
213
+ authStatus: GoAuthStatus
214
+ failureKind?: GoFailureKind
215
+ /** Human-readable reason; never includes a key value. */
216
+ message: string
217
+ }
218
+
219
+ /** Read a bounded error message from an unknown error body. */
220
+ function errorMessage(body: unknown): string {
221
+ if (!isRecord(body)) return ''
222
+ if (isRecord(body.error) && typeof body.error.message === 'string') return body.error.message
223
+ if (typeof body.message === 'string') return body.message
224
+ if (typeof body.detail === 'string') return body.detail
225
+ return ''
226
+ }
227
+
228
+ function errorCode(body: unknown): string {
229
+ if (!isRecord(body)) return ''
230
+ const inner = isRecord(body.error) ? body.error : body
231
+ if (typeof inner.code === 'string') return inner.code
232
+ if (typeof inner.type === 'string') return inner.type
233
+ if (typeof body.error_code === 'number') return String(body.error_code)
234
+ return ''
235
+ }
236
+
237
+ /**
238
+ * Classify an official HTTP response. 401 = invalid key, 403 = either the
239
+ * documented EntitlementError (not-entitled) or the Cloudflare 1010 UA ban
240
+ * (transport), 5xx/429 = transport. Only 200 is a usable source.
241
+ */
242
+ export function classifyGoHttpStatus(status: number, body: unknown): GoHttpClassification {
243
+ if (status >= 200 && status < 300) return { authStatus: 'ok', message: '' }
244
+ const code = errorCode(body)
245
+ const message = errorMessage(body)
246
+ const cfBan = code === '1010'
247
+ || /browser_signature_banned|cloudflare/i.test(message)
248
+ || (isRecord(body) && (body.error_code === 1010 || body.error === 1010))
249
+
250
+ if (status === 401) {
251
+ return { authStatus: 'invalid', failureKind: 'auth', message: message || `HTTP 401 (${code || 'unauthorized'})` }
252
+ }
253
+ if (status === 403) {
254
+ if (cfBan) {
255
+ return { authStatus: 'unreachable', failureKind: 'transport', message: message || 'HTTP 403 (Cloudflare 1010)' }
256
+ }
257
+ return { authStatus: 'not-entitled', failureKind: 'entitlement', message: message || 'HTTP 403 (Go subscription required)' }
258
+ }
259
+ return {
260
+ authStatus: 'unreachable',
261
+ failureKind: 'transport',
262
+ message: message || `HTTP ${status} from opencode-go models endpoint`,
263
+ }
264
+ }
265
+
266
+ // ---------------------------------------------------------------------------
267
+ // Fetch orchestration (the only impure function; network is injected)
268
+ // ---------------------------------------------------------------------------
269
+
270
+ function failedResult(
271
+ authStatus: GoAuthStatus,
272
+ keyFingerprint: string,
273
+ observedAt: number,
274
+ error: GoSourceError,
275
+ ): GoSourceResult {
276
+ return { ok: false, entries: [], authStatus, keyFingerprint, observedAt, error }
277
+ }
278
+
279
+ /**
280
+ * Read the official listing once. No key → no request (design V4), no entries,
281
+ * status 'unknown'. With a key the request carries Bearer + explicit UA; the
282
+ * key itself is never logged or stored, only its fingerprint.
283
+ */
284
+ /**
285
+ * Read the official *unauthenticated* public listing for one purpose only:
286
+ * answering "is this id official?" during migration planning (design §14.2).
287
+ * Per C2 the public list is NEVER a servable source — no authorization header
288
+ * is sent, no model is written to settings from it. If the read fails the
289
+ * caller must fail closed (ids become `unclassified`, never deleted).
290
+ */
291
+ export async function fetchGoPublicCatalogIds(options: {
292
+ url?: string
293
+ timeoutMs?: number
294
+ fetchImpl?: GoFetchLike
295
+ signal?: AbortSignal
296
+ } = {}): Promise<GoPublicCatalogResult> {
297
+ const url = options.url ?? OPENCODE_GO_MODELS_URL
298
+ const fetchImpl = options.fetchImpl ?? (fetch as unknown as GoFetchLike)
299
+ const controller = new AbortController()
300
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 30_000)
301
+ const relayAbort = (): void => controller.abort()
302
+ if (options.signal !== undefined) {
303
+ if (options.signal.aborted) controller.abort()
304
+ else options.signal.addEventListener('abort', relayAbort, { once: true })
305
+ }
306
+ try {
307
+ const response = await fetchImpl(url, {
308
+ headers: { accept: 'application/json', 'user-agent': GO_USER_AGENT },
309
+ signal: controller.signal,
310
+ })
311
+ if (response.status < 200 || response.status >= 300) {
312
+ return {
313
+ ok: false,
314
+ ids: [],
315
+ error: {
316
+ kind: response.status === 401 || response.status === 403 ? 'auth' : 'transport',
317
+ status: response.status,
318
+ message: `public opencode-go catalog unavailable (HTTP ${response.status})`,
319
+ },
320
+ }
321
+ }
322
+ const body = await response.json()
323
+ return { ok: true, ids: parseGoModelsPayload(body).map((entry) => entry.id) }
324
+ } catch (error) {
325
+ return {
326
+ ok: false,
327
+ ids: [],
328
+ error: { kind: 'transport', message: error instanceof Error ? error.message : String(error) },
329
+ }
330
+ } finally {
331
+ clearTimeout(timer)
332
+ options.signal?.removeEventListener('abort', relayAbort)
333
+ }
334
+ }
335
+
336
+ export async function fetchGoOfficialModels(options: FetchGoOfficialOptions = {}): Promise<GoSourceResult> {
337
+ const url = options.url ?? OPENCODE_GO_MODELS_URL
338
+ const observedAt = options.observedAt ?? Date.now()
339
+ const apiKey = typeof options.apiKey === 'string' ? options.apiKey.trim() : ''
340
+
341
+ if (apiKey === '') {
342
+ return failedResult('unknown', '-', observedAt, {
343
+ kind: 'no-key',
344
+ message: 'No OpenCode Go API key configured — no /v1/models request sent (design §6.3 / V4)',
345
+ })
346
+ }
347
+
348
+ const fingerprint = fingerprintKey(apiKey)
349
+ const fetchImpl = options.fetchImpl ?? (fetch as unknown as GoFetchLike)
350
+ const headers: Record<string, string> = {
351
+ accept: 'application/json',
352
+ 'user-agent': GO_USER_AGENT,
353
+ authorization: `Bearer ${apiKey}`,
354
+ }
355
+ const controller = new AbortController()
356
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 30_000)
357
+ // The plugin-lifetime signal and the network timeout both abort the SAME
358
+ // controller, so fetchImpl observes a single signal. Never leave the bridge
359
+ // listener behind: a disposed plugin must not retain the round's signal.
360
+ const relayAbort = (): void => controller.abort()
361
+ if (options.signal !== undefined) {
362
+ if (options.signal.aborted) controller.abort()
363
+ else options.signal.addEventListener('abort', relayAbort, { once: true })
364
+ }
365
+
366
+ try {
367
+ let response: GoFetchResponse
368
+ try {
369
+ response = await fetchImpl(url, { headers, signal: controller.signal })
370
+ } catch (error) {
371
+ const message = error instanceof Error ? error.message : String(error)
372
+ return failedResult('unreachable', fingerprint, observedAt, {
373
+ kind: 'transport',
374
+ message: `opencode-go models request failed: ${message}`,
375
+ })
376
+ }
377
+
378
+ if (response.status < 200 || response.status >= 300) {
379
+ let body: unknown
380
+ try {
381
+ body = await response.json()
382
+ } catch {
383
+ body = undefined
384
+ }
385
+ const classification = classifyGoHttpStatus(response.status, body)
386
+ return failedResult(classification.authStatus, fingerprint, observedAt, {
387
+ kind: classification.failureKind ?? 'transport',
388
+ status: response.status,
389
+ message: classification.message,
390
+ })
391
+ }
392
+
393
+ let body: unknown
394
+ try {
395
+ body = await response.json()
396
+ } catch (error) {
397
+ const message = error instanceof Error ? error.message : String(error)
398
+ return failedResult('unknown', fingerprint, observedAt, {
399
+ kind: 'parse',
400
+ message: `opencode-go models body is not JSON: ${message}`,
401
+ })
402
+ }
403
+
404
+ let entries: GoModelRecord[]
405
+ try {
406
+ entries = parseGoModelsPayload(body)
407
+ } catch (error) {
408
+ const message = error instanceof Error ? error.message : String(error)
409
+ return failedResult('unknown', fingerprint, observedAt, { kind: 'parse', message })
410
+ }
411
+
412
+ return {
413
+ ok: true,
414
+ entries,
415
+ authStatus: 'ok',
416
+ keyFingerprint: fingerprint,
417
+ payloadHash: computeGoPayloadHash(entries),
418
+ observedAt,
419
+ }
420
+ } finally {
421
+ clearTimeout(timer)
422
+ options.signal?.removeEventListener('abort', relayAbort)
423
+ }
424
+ }
@@ -0,0 +1,73 @@
1
+ // P1c file adapter: persist the opencode-go ownership ledger in the SAME file
2
+ // and through the SAME serialized queue as the pi.dev fetch cache, so a ledger
3
+ // write can never clobber a concurrent fetch/override stage (design §6.1,
4
+ // ADR-004; verification 21 §9 concern ②).
5
+ //
6
+ // Wire format (design §6.1, B1): a top-level slot per ledger key,
7
+ // <profileKey>#<route>#<keyFingerprint> -> GoOwnershipEntry
8
+ // in ~/.dsh/models-store.json (unscoped callers still use <route>#<keyFingerprint>).
9
+ // Keys containing `#` are never valid provider route ids, so the existing
10
+ // `read(route)` / `update(route)` paths cannot see these entries. Atomic
11
+ // temp+rename and the write queue come from `loadModelsStore()` — this module
12
+ // adds no second persistence mechanism.
13
+ //
14
+ // Failure direction: a corrupt/unreadable document reads as "no ledger"
15
+ // (`undefined`). The writer then does a conservative first-round claim — it
16
+ // never deletes without a hash (ADR-004: store loss degrades to no-delete).
17
+ // The next write replaces the bad file atomically and heals it.
18
+
19
+ import type { GoOwnershipEntry } from './opencode-go-planner.ts'
20
+ import { scopedStoreKey } from './opencode-go-profile.ts'
21
+ import { loadModelsStore, type ModelsStoreAccessor } from './remote-catalog.ts'
22
+ import type { GoOwnershipStore } from './opencode-go-writer.ts'
23
+
24
+ /**
25
+ * Build a `GoOwnershipStore` on top of an existing models-store accessor.
26
+ *
27
+ * `profileKey` prefixes every opaque key, turning `<route>#<keyFingerprint>`
28
+ * into `<profileKey>#<route>#<keyFingerprint>` (B1). Two profiles using the
29
+ * same Go key occupy disjoint slots in the shared document, and a rollback
30
+ * deletes only the calling profile's slots. Omitting `profileKey` keeps the
31
+ * pre-fix unscoped behavior for legacy callers/tests only.
32
+ */
33
+ export function createFileOwnershipStore(
34
+ accessor: ModelsStoreAccessor,
35
+ profileKey?: string,
36
+ ): GoOwnershipStore {
37
+ const slot = (key: string): string => profileKey === undefined ? key : scopedStoreKey(profileKey, key)
38
+ return {
39
+ async read(key: string): Promise<GoOwnershipEntry | undefined> {
40
+ let raw: unknown
41
+ try {
42
+ raw = await accessor.readRaw(slot(key))
43
+ } catch {
44
+ // Corrupt file / EACCES: no ledger. Never infer one, never delete.
45
+ return undefined
46
+ }
47
+ // readRaw now returns the slot verbatim; a present primitive/null slot is
48
+ // NOT a ledger entry (same conservative "no ledger" direction as before).
49
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return undefined
50
+ const record = raw as Record<string, unknown>
51
+ if (typeof record.managed !== 'object' || record.managed === null
52
+ || Array.isArray(record.managed)) {
53
+ return undefined
54
+ }
55
+ return record as unknown as GoOwnershipEntry
56
+ },
57
+ async write(key: string, entry: GoOwnershipEntry): Promise<void> {
58
+ await accessor.writeRaw(slot(key), entry as unknown as Record<string, unknown>)
59
+ },
60
+ async delete(key: string): Promise<void> {
61
+ await accessor.deleteRaw(slot(key))
62
+ },
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Production factory: the ledger lives in ~/.dsh/models-store.json. Tests pass
68
+ * `loadModelsStore(tempPath)` through `createFileOwnershipStore` instead, so no
69
+ * test ever touches the real ~/.dsh.
70
+ */
71
+ export function createModelsStoreOwnershipStore(storePath?: string, profileKey?: string): GoOwnershipStore {
72
+ return createFileOwnershipStore(loadModelsStore(storePath), profileKey)
73
+ }