@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
@@ -0,0 +1,331 @@
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
+ import { createHash } from 'node:crypto';
13
+ /** Official model-listing endpoint (design §6.2.6 default). */
14
+ export const OPENCODE_GO_MODELS_URL = 'https://opencode.ai/inference/go/v1/models';
15
+ /** P0 fixed default polling interval for the go source (design §6.2.6). */
16
+ export const OPENCODE_GO_DEFAULT_INTERVAL_MINUTES = 60;
17
+ /** Explicit UA — the gateway bans default library UAs with CF 1010 (05 §1). */
18
+ export const GO_USER_AGENT = 'dsh-model-sync/0.10.0';
19
+ // ---------------------------------------------------------------------------
20
+ // Small helpers
21
+ // ---------------------------------------------------------------------------
22
+ function isRecord(value) {
23
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
24
+ }
25
+ function positiveInt(value) {
26
+ return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined;
27
+ }
28
+ function stringList(value) {
29
+ return Array.isArray(value) ? value.filter((v) => typeof v === 'string') : [];
30
+ }
31
+ /** Irreversible key fingerprint — the only key-derived value ever retained. */
32
+ export function fingerprintKey(key) {
33
+ return createHash('sha256').update(key).digest('hex').slice(0, 16);
34
+ }
35
+ /** Canonical JSON: object keys sorted recursively so hashing is order-stable. */
36
+ function canonicalize(value) {
37
+ if (Array.isArray(value))
38
+ return value.map(canonicalize);
39
+ if (!isRecord(value))
40
+ return value;
41
+ const out = {};
42
+ for (const key of Object.keys(value).sort())
43
+ out[key] = canonicalize(value[key]);
44
+ return out;
45
+ }
46
+ /** Hash of the normalized set. `created` never reaches this function. */
47
+ export function computeGoPayloadHash(entries) {
48
+ return createHash('sha256').update(JSON.stringify(canonicalize(entries))).digest('hex');
49
+ }
50
+ // ---------------------------------------------------------------------------
51
+ // Payload normalization (pure; fixture-driven tests)
52
+ // ---------------------------------------------------------------------------
53
+ /**
54
+ * Parse the official `{ object: 'list', data: [...] }` payload into normalized
55
+ * records. Unknown fields (cost, sdk, go.monthly_usage, …) are dropped; every
56
+ * field the diagnostic or P1 planning needs is mapped explicitly. `created`
57
+ * is deliberately not copied, so it can never enter the payload hash.
58
+ */
59
+ export function parseGoModelsPayload(value) {
60
+ if (!isRecord(value) || !Array.isArray(value.data)) {
61
+ throw new Error('opencode-go payload is not a model list');
62
+ }
63
+ const entries = [];
64
+ for (const item of value.data) {
65
+ if (!isRecord(item))
66
+ continue;
67
+ const id = item.id;
68
+ if (typeof id !== 'string' || id.length === 0)
69
+ continue;
70
+ const api = isRecord(item.api) ? item.api : {};
71
+ const protocols = Object.keys(api).filter((key) => isRecord(api[key]));
72
+ const baseUrls = {};
73
+ for (const protocol of protocols) {
74
+ const base = api[protocol].base_url;
75
+ if (typeof base === 'string' && base.length > 0)
76
+ baseUrls[protocol] = base;
77
+ }
78
+ const limit = isRecord(item.limit) ? item.limit : {};
79
+ const contextWindow = positiveInt(limit.context);
80
+ const output = positiveInt(limit.output);
81
+ // An output >= context is a bad upstream value — strip it (design §6.1).
82
+ const maxOutput = output !== undefined && (contextWindow === undefined || output < contextWindow)
83
+ ? output
84
+ : undefined;
85
+ const modalities = isRecord(item.modalities) ? item.modalities : {};
86
+ // text→text, image/*→image; audio/video/pdf are ignored (design §6.1).
87
+ const inputModalities = [];
88
+ for (const modality of stringList(modalities.input)) {
89
+ const normalized = modality === 'text' ? 'text' : modality.startsWith('image/') ? 'image' : undefined;
90
+ if (normalized !== undefined && !inputModalities.includes(normalized))
91
+ inputModalities.push(normalized);
92
+ }
93
+ const capabilities = isRecord(item.capabilities) ? item.capabilities : {};
94
+ const reasoningRaw = isRecord(capabilities.reasoning) ? capabilities.reasoning : undefined;
95
+ const reasoning = reasoningRaw !== undefined
96
+ ? {
97
+ supported: reasoningRaw.supported === true,
98
+ efforts: stringList(reasoningRaw.effort).map((effort) => effort === 'none' ? 'off' : effort),
99
+ }
100
+ : undefined;
101
+ const entry = {
102
+ id,
103
+ name: typeof item.name === 'string' ? item.name : id,
104
+ protocols,
105
+ baseUrls,
106
+ inputModalities,
107
+ provenance: 'go-official',
108
+ };
109
+ if (typeof item.canonical_id === 'string')
110
+ entry.canonicalId = item.canonical_id;
111
+ if (typeof item.release_date === 'string')
112
+ entry.releaseDate = item.release_date;
113
+ if (typeof item.last_updated === 'string')
114
+ entry.lastUpdated = item.last_updated;
115
+ if (contextWindow !== undefined)
116
+ entry.contextWindow = contextWindow;
117
+ if (maxOutput !== undefined)
118
+ entry.maxOutput = maxOutput;
119
+ if (reasoning !== undefined)
120
+ entry.reasoning = reasoning;
121
+ if (typeof item.recommended_api === 'string')
122
+ entry.recommendedProtocol = item.recommended_api;
123
+ entries.push(entry);
124
+ }
125
+ if (entries.length === 0)
126
+ throw new Error('opencode-go payload lists no usable model ids');
127
+ return entries;
128
+ }
129
+ /** Read a bounded error message from an unknown error body. */
130
+ function errorMessage(body) {
131
+ if (!isRecord(body))
132
+ return '';
133
+ if (isRecord(body.error) && typeof body.error.message === 'string')
134
+ return body.error.message;
135
+ if (typeof body.message === 'string')
136
+ return body.message;
137
+ if (typeof body.detail === 'string')
138
+ return body.detail;
139
+ return '';
140
+ }
141
+ function errorCode(body) {
142
+ if (!isRecord(body))
143
+ return '';
144
+ const inner = isRecord(body.error) ? body.error : body;
145
+ if (typeof inner.code === 'string')
146
+ return inner.code;
147
+ if (typeof inner.type === 'string')
148
+ return inner.type;
149
+ if (typeof body.error_code === 'number')
150
+ return String(body.error_code);
151
+ return '';
152
+ }
153
+ /**
154
+ * Classify an official HTTP response. 401 = invalid key, 403 = either the
155
+ * documented EntitlementError (not-entitled) or the Cloudflare 1010 UA ban
156
+ * (transport), 5xx/429 = transport. Only 200 is a usable source.
157
+ */
158
+ export function classifyGoHttpStatus(status, body) {
159
+ if (status >= 200 && status < 300)
160
+ return { authStatus: 'ok', message: '' };
161
+ const code = errorCode(body);
162
+ const message = errorMessage(body);
163
+ const cfBan = code === '1010'
164
+ || /browser_signature_banned|cloudflare/i.test(message)
165
+ || (isRecord(body) && (body.error_code === 1010 || body.error === 1010));
166
+ if (status === 401) {
167
+ return { authStatus: 'invalid', failureKind: 'auth', message: message || `HTTP 401 (${code || 'unauthorized'})` };
168
+ }
169
+ if (status === 403) {
170
+ if (cfBan) {
171
+ return { authStatus: 'unreachable', failureKind: 'transport', message: message || 'HTTP 403 (Cloudflare 1010)' };
172
+ }
173
+ return { authStatus: 'not-entitled', failureKind: 'entitlement', message: message || 'HTTP 403 (Go subscription required)' };
174
+ }
175
+ return {
176
+ authStatus: 'unreachable',
177
+ failureKind: 'transport',
178
+ message: message || `HTTP ${status} from opencode-go models endpoint`,
179
+ };
180
+ }
181
+ // ---------------------------------------------------------------------------
182
+ // Fetch orchestration (the only impure function; network is injected)
183
+ // ---------------------------------------------------------------------------
184
+ function failedResult(authStatus, keyFingerprint, observedAt, error) {
185
+ return { ok: false, entries: [], authStatus, keyFingerprint, observedAt, error };
186
+ }
187
+ /**
188
+ * Read the official listing once. No key → no request (design V4), no entries,
189
+ * status 'unknown'. With a key the request carries Bearer + explicit UA; the
190
+ * key itself is never logged or stored, only its fingerprint.
191
+ */
192
+ /**
193
+ * Read the official *unauthenticated* public listing for one purpose only:
194
+ * answering "is this id official?" during migration planning (design §14.2).
195
+ * Per C2 the public list is NEVER a servable source — no authorization header
196
+ * is sent, no model is written to settings from it. If the read fails the
197
+ * caller must fail closed (ids become `unclassified`, never deleted).
198
+ */
199
+ export async function fetchGoPublicCatalogIds(options = {}) {
200
+ const url = options.url ?? OPENCODE_GO_MODELS_URL;
201
+ const fetchImpl = options.fetchImpl ?? fetch;
202
+ const controller = new AbortController();
203
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 30_000);
204
+ const relayAbort = () => controller.abort();
205
+ if (options.signal !== undefined) {
206
+ if (options.signal.aborted)
207
+ controller.abort();
208
+ else
209
+ options.signal.addEventListener('abort', relayAbort, { once: true });
210
+ }
211
+ try {
212
+ const response = await fetchImpl(url, {
213
+ headers: { accept: 'application/json', 'user-agent': GO_USER_AGENT },
214
+ signal: controller.signal,
215
+ });
216
+ if (response.status < 200 || response.status >= 300) {
217
+ return {
218
+ ok: false,
219
+ ids: [],
220
+ error: {
221
+ kind: response.status === 401 || response.status === 403 ? 'auth' : 'transport',
222
+ status: response.status,
223
+ message: `public opencode-go catalog unavailable (HTTP ${response.status})`,
224
+ },
225
+ };
226
+ }
227
+ const body = await response.json();
228
+ return { ok: true, ids: parseGoModelsPayload(body).map((entry) => entry.id) };
229
+ }
230
+ catch (error) {
231
+ return {
232
+ ok: false,
233
+ ids: [],
234
+ error: { kind: 'transport', message: error instanceof Error ? error.message : String(error) },
235
+ };
236
+ }
237
+ finally {
238
+ clearTimeout(timer);
239
+ options.signal?.removeEventListener('abort', relayAbort);
240
+ }
241
+ }
242
+ export async function fetchGoOfficialModels(options = {}) {
243
+ const url = options.url ?? OPENCODE_GO_MODELS_URL;
244
+ const observedAt = options.observedAt ?? Date.now();
245
+ const apiKey = typeof options.apiKey === 'string' ? options.apiKey.trim() : '';
246
+ if (apiKey === '') {
247
+ return failedResult('unknown', '-', observedAt, {
248
+ kind: 'no-key',
249
+ message: 'No OpenCode Go API key configured — no /v1/models request sent (design §6.3 / V4)',
250
+ });
251
+ }
252
+ const fingerprint = fingerprintKey(apiKey);
253
+ const fetchImpl = options.fetchImpl ?? fetch;
254
+ const headers = {
255
+ accept: 'application/json',
256
+ 'user-agent': GO_USER_AGENT,
257
+ authorization: `Bearer ${apiKey}`,
258
+ };
259
+ const controller = new AbortController();
260
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 30_000);
261
+ // The plugin-lifetime signal and the network timeout both abort the SAME
262
+ // controller, so fetchImpl observes a single signal. Never leave the bridge
263
+ // listener behind: a disposed plugin must not retain the round's signal.
264
+ const relayAbort = () => controller.abort();
265
+ if (options.signal !== undefined) {
266
+ if (options.signal.aborted)
267
+ controller.abort();
268
+ else
269
+ options.signal.addEventListener('abort', relayAbort, { once: true });
270
+ }
271
+ try {
272
+ let response;
273
+ try {
274
+ response = await fetchImpl(url, { headers, signal: controller.signal });
275
+ }
276
+ catch (error) {
277
+ const message = error instanceof Error ? error.message : String(error);
278
+ return failedResult('unreachable', fingerprint, observedAt, {
279
+ kind: 'transport',
280
+ message: `opencode-go models request failed: ${message}`,
281
+ });
282
+ }
283
+ if (response.status < 200 || response.status >= 300) {
284
+ let body;
285
+ try {
286
+ body = await response.json();
287
+ }
288
+ catch {
289
+ body = undefined;
290
+ }
291
+ const classification = classifyGoHttpStatus(response.status, body);
292
+ return failedResult(classification.authStatus, fingerprint, observedAt, {
293
+ kind: classification.failureKind ?? 'transport',
294
+ status: response.status,
295
+ message: classification.message,
296
+ });
297
+ }
298
+ let body;
299
+ try {
300
+ body = await response.json();
301
+ }
302
+ catch (error) {
303
+ const message = error instanceof Error ? error.message : String(error);
304
+ return failedResult('unknown', fingerprint, observedAt, {
305
+ kind: 'parse',
306
+ message: `opencode-go models body is not JSON: ${message}`,
307
+ });
308
+ }
309
+ let entries;
310
+ try {
311
+ entries = parseGoModelsPayload(body);
312
+ }
313
+ catch (error) {
314
+ const message = error instanceof Error ? error.message : String(error);
315
+ return failedResult('unknown', fingerprint, observedAt, { kind: 'parse', message });
316
+ }
317
+ return {
318
+ ok: true,
319
+ entries,
320
+ authStatus: 'ok',
321
+ keyFingerprint: fingerprint,
322
+ payloadHash: computeGoPayloadHash(entries),
323
+ observedAt,
324
+ };
325
+ }
326
+ finally {
327
+ clearTimeout(timer);
328
+ options.signal?.removeEventListener('abort', relayAbort);
329
+ }
330
+ }
331
+ //# sourceMappingURL=opencode-go-source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opencode-go-source.js","sourceRoot":"","sources":["../src/opencode-go-source.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,EAAE;AACF,yEAAyE;AACzE,4EAA4E;AAC5E,4EAA4E;AAC5E,8EAA8E;AAC9E,sEAAsE;AACtE,EAAE;AACF,uEAAuE;AACvE,8EAA8E;AAC9E,0EAA0E;AAE1E,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AAExC,+DAA+D;AAC/D,MAAM,CAAC,MAAM,sBAAsB,GAAG,4CAA4C,CAAA;AAElF,2EAA2E;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QAC9B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACtE,OAAO,YAAY,CAAC,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE;gBACtD,IAAI,EAAE,OAAO;gBACb,OAAO,EAAE,wCAAwC,OAAO,EAAE;aAC3D,CAAC,CAAA;QACJ,CAAC;QAED,IAAI,OAAwB,CAAA;QAC5B,IAAI,CAAC;YACH,OAAO,GAAG,oBAAoB,CAAC,IAAI,CAAC,CAAA;QACtC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACtE,OAAO,YAAY,CAAC,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAA;QACrF,CAAC;QAED,OAAO;YACL,EAAE,EAAE,IAAI;YACR,OAAO;YACP,UAAU,EAAE,IAAI;YAChB,cAAc,EAAE,WAAW;YAC3B,WAAW,EAAE,oBAAoB,CAAC,OAAO,CAAC;YAC1C,UAAU;SACX,CAAA;IACH,CAAC;YAAS,CAAC;QACT,YAAY,CAAC,KAAK,CAAC,CAAA;QACnB,OAAO,CAAC,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,UAAU,CAAC,CAAA;IAC1D,CAAC;AACH,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { type ModelsStoreAccessor } from './remote-catalog.ts';
2
+ import type { GoOwnershipStore } from './opencode-go-writer.ts';
3
+ /**
4
+ * Build a `GoOwnershipStore` on top of an existing models-store accessor.
5
+ *
6
+ * `profileKey` prefixes every opaque key, turning `<route>#<keyFingerprint>`
7
+ * into `<profileKey>#<route>#<keyFingerprint>` (B1). Two profiles using the
8
+ * same Go key occupy disjoint slots in the shared document, and a rollback
9
+ * deletes only the calling profile's slots. Omitting `profileKey` keeps the
10
+ * pre-fix unscoped behavior for legacy callers/tests only.
11
+ */
12
+ export declare function createFileOwnershipStore(accessor: ModelsStoreAccessor, profileKey?: string): GoOwnershipStore;
13
+ /**
14
+ * Production factory: the ledger lives in ~/.dsh/models-store.json. Tests pass
15
+ * `loadModelsStore(tempPath)` through `createFileOwnershipStore` instead, so no
16
+ * test ever touches the real ~/.dsh.
17
+ */
18
+ export declare function createModelsStoreOwnershipStore(storePath?: string, profileKey?: string): GoOwnershipStore;
@@ -0,0 +1,68 @@
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
+ import { scopedStoreKey } from "./opencode-go-profile.js";
19
+ import { loadModelsStore } from "./remote-catalog.js";
20
+ /**
21
+ * Build a `GoOwnershipStore` on top of an existing models-store accessor.
22
+ *
23
+ * `profileKey` prefixes every opaque key, turning `<route>#<keyFingerprint>`
24
+ * into `<profileKey>#<route>#<keyFingerprint>` (B1). Two profiles using the
25
+ * same Go key occupy disjoint slots in the shared document, and a rollback
26
+ * deletes only the calling profile's slots. Omitting `profileKey` keeps the
27
+ * pre-fix unscoped behavior for legacy callers/tests only.
28
+ */
29
+ export function createFileOwnershipStore(accessor, profileKey) {
30
+ const slot = (key) => profileKey === undefined ? key : scopedStoreKey(profileKey, key);
31
+ return {
32
+ async read(key) {
33
+ let raw;
34
+ try {
35
+ raw = await accessor.readRaw(slot(key));
36
+ }
37
+ catch {
38
+ // Corrupt file / EACCES: no ledger. Never infer one, never delete.
39
+ return undefined;
40
+ }
41
+ // readRaw now returns the slot verbatim; a present primitive/null slot is
42
+ // NOT a ledger entry (same conservative "no ledger" direction as before).
43
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
44
+ return undefined;
45
+ const record = raw;
46
+ if (typeof record.managed !== 'object' || record.managed === null
47
+ || Array.isArray(record.managed)) {
48
+ return undefined;
49
+ }
50
+ return record;
51
+ },
52
+ async write(key, entry) {
53
+ await accessor.writeRaw(slot(key), entry);
54
+ },
55
+ async delete(key) {
56
+ await accessor.deleteRaw(slot(key));
57
+ },
58
+ };
59
+ }
60
+ /**
61
+ * Production factory: the ledger lives in ~/.dsh/models-store.json. Tests pass
62
+ * `loadModelsStore(tempPath)` through `createFileOwnershipStore` instead, so no
63
+ * test ever touches the real ~/.dsh.
64
+ */
65
+ export function createModelsStoreOwnershipStore(storePath, profileKey) {
66
+ return createFileOwnershipStore(loadModelsStore(storePath), profileKey);
67
+ }
68
+ //# sourceMappingURL=opencode-go-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"opencode-go-store.js","sourceRoot":"","sources":["../src/opencode-go-store.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,+EAA+E;AAC/E,0EAA0E;AAC1E,0CAA0C;AAC1C,EAAE;AACF,kEAAkE;AAClE,8DAA8D;AAC9D,qFAAqF;AACrF,0EAA0E;AAC1E,yEAAyE;AACzE,8EAA8E;AAC9E,wCAAwC;AACxC,EAAE;AACF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,CAAC,MAAM,CAAC,GAAW;YACtB,MAAM,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;QACrC,CAAC;KACF,CAAA;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,+BAA+B,CAAC,SAAkB,EAAE,UAAmB;IACrF,OAAO,wBAAwB,CAAC,eAAe,CAAC,SAAS,CAAC,EAAE,UAAU,CAAC,CAAA;AACzE,CAAC"}
@@ -0,0 +1,94 @@
1
+ import { type GoRouteSlot } from './opencode-go-grouping.ts';
2
+ import { type GoFetchLike, type GoSourceResult } from './opencode-go-source.ts';
3
+ import { type GoOverrideStorer, type GoOwnershipStore, type GoWriteResult } from './opencode-go-writer.ts';
4
+ import type { Logger, SettingsService } from './writer.ts';
5
+ import { type MigrationStatus } from './opencode-go-migration.ts';
6
+ import { type GoJournalStore, type ReconcileResult } from './opencode-go-journal.ts';
7
+ /**
8
+ * Cordis service names used only as injection seams. Both are optional:
9
+ * production falls back to the real file store and the global fetch; tests
10
+ * register a temp-dir store / stub fetch under these names to run a full round
11
+ * with zero filesystem writes outside a temp dir and zero network.
12
+ */
13
+ export declare const GO_OWNERSHIP_STORE_SERVICE = "goOwnershipStore";
14
+ export declare const GO_OVERRIDE_STORER_SERVICE = "goOverrideStorer";
15
+ export declare const GO_FETCH_SERVICE = "goFetchImpl";
16
+ /** The go subset of the published Config contract (design §6.2.6). */
17
+ export interface GoSyncRuntimeConfig {
18
+ /** Master switch (design §6.2.6: false = zero behavior change). */
19
+ enabled: boolean;
20
+ ref: string;
21
+ modelsUrl: string;
22
+ routes: Partial<Record<GoRouteSlot, string>>;
23
+ pinnedModels: readonly string[];
24
+ confirmRemovals: number;
25
+ adoptExisting: boolean;
26
+ }
27
+ export interface GoRoundDeps {
28
+ settings: SettingsService | undefined;
29
+ ownershipStore: GoOwnershipStore;
30
+ overrideStorer?: GoOverrideStorer;
31
+ logger: Logger;
32
+ config: GoSyncRuntimeConfig;
33
+ /** Resolved credential VALUE; undefined/empty means no request and no write (V4). */
34
+ apiKey?: string;
35
+ /** Injectable network; production falls back to the global fetch in the source. */
36
+ fetchImpl?: GoFetchLike;
37
+ /** Deterministic clock for tests. */
38
+ observedAt?: number;
39
+ /** Plugin-lifetime signal; aborted mid-round stops the fetch and blocks the writer. */
40
+ signal?: AbortSignal;
41
+ /**
42
+ * Current migration status (§14.1). Defaults to `absent` for direct unit
43
+ * callers that only exercise writer mechanics; the production wiring in
44
+ * index.ts always passes the real status read from the settings + record.
45
+ */
46
+ migration?: MigrationStatus;
47
+ /**
48
+ * §14.7.5: re-read the PERSISTED migration status for the second gate, called
49
+ * before every mutate. Production passes `loadMigrationStatus`; without it
50
+ * there is NO second gate (pure writer-mechanics callers) — the round-level
51
+ * snapshot is never reused. A failed re-read is reported as
52
+ * `canWrite-unavailable` and skips the route (fail closed).
53
+ */
54
+ reloadMigration?: () => Promise<MigrationStatus>;
55
+ /** §14.7.4: forward the post-own-write managed ids to the record persister. */
56
+ onOwnWrite?: (route: string, managedIds: string[]) => Promise<void>;
57
+ /**
58
+ * O1/C2: file-backed write-ahead journal store. With `profileKey` and
59
+ * `keyFingerprint`, the round reconciles surviving journals BEFORE the
60
+ * migration gate (a closed gate must still self-heal). Omitted by pure unit
61
+ * callers — no journal, no reconciliation, pre-C2 behavior.
62
+ */
63
+ journalStore?: GoJournalStore;
64
+ /** O1/C2: stable profile key used to scope reconciliation. */
65
+ profileKey?: string;
66
+ /** O1/C2: current credential fingerprint; journals stamped with another key
67
+ * are orphans and are discarded, never replayed. */
68
+ keyFingerprint?: string;
69
+ }
70
+ export type GoRoundReason = 'disabled' | 'settings-unavailable' | 'no-key' | 'source-failed' | 'writer-error' | 'aborted' | 'migration-gate' | 'settings-changed-during-sync' | 'write-failed' | 'completed';
71
+ export interface GoSyncRoundResult {
72
+ ok: boolean;
73
+ reason: GoRoundReason;
74
+ source?: GoSourceResult;
75
+ write?: GoWriteResult;
76
+ /**
77
+ * B4 (31, design §14.7.5): set only when the host settings document revision
78
+ * moved while the official catalog request was in flight, i.e. the round was
79
+ * abandoned before building a plan/writing anything. Machine-readable
80
+ * companion to the user-visible `text` (no write, no ledger/fingerprint).
81
+ */
82
+ settingsChanged?: {
83
+ beforeRevision: number;
84
+ afterRevision: number;
85
+ };
86
+ /** O1/C2: outcome of the pre-gate journal reconciliation (when wired). */
87
+ journal?: ReconcileResult;
88
+ /** Human-readable lines for `/model-sync` and the auto-round logger. */
89
+ text: string;
90
+ }
91
+ /** One complete go round. Never throws for expected source/store failures. */
92
+ export declare function runGoSyncRound(deps: GoRoundDeps): Promise<GoSyncRoundResult>;
93
+ /** Stable, testable report text: source summary, per-route outcome, plan notes. */
94
+ export declare function formatGoRoundReport(source: GoSourceResult, write: GoWriteResult): string;