@aiwayds/dsh-model-sync 0.12.1 → 0.13.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.
Files changed (88) hide show
  1. package/README.md +18 -17
  2. package/README.zh-CN.md +18 -17
  3. package/lib/index.d.ts +54 -384
  4. package/lib/index.js +306 -1107
  5. package/lib/index.js.map +1 -1
  6. package/lib/official-adapter.d.ts +80 -0
  7. package/lib/official-adapter.js +34 -0
  8. package/lib/official-adapter.js.map +1 -0
  9. package/lib/official-migrate.d.ts +122 -0
  10. package/lib/official-migrate.js +653 -0
  11. package/lib/official-migrate.js.map +1 -0
  12. package/lib/official-scheduler.d.ts +72 -0
  13. package/lib/official-scheduler.js +195 -0
  14. package/lib/official-scheduler.js.map +1 -0
  15. package/lib/official-store.d.ts +41 -0
  16. package/lib/official-store.js +84 -0
  17. package/lib/official-store.js.map +1 -0
  18. package/lib/official-sync.d.ts +68 -0
  19. package/lib/official-sync.js +274 -0
  20. package/lib/official-sync.js.map +1 -0
  21. package/lib/opencode-go-adapter.d.ts +56 -0
  22. package/lib/opencode-go-adapter.js +455 -0
  23. package/lib/opencode-go-adapter.js.map +1 -0
  24. package/lib/opencode-go-patch-file.d.ts +11 -0
  25. package/lib/opencode-go-patch-file.js +175 -11
  26. package/lib/opencode-go-patch-file.js.map +1 -1
  27. package/lib/opencode-go-source.d.ts +1 -1
  28. package/lib/opencode-go-source.js +1 -1
  29. package/locale/en.json +1 -1
  30. package/locale/zh.json +1 -1
  31. package/package.json +3 -3
  32. package/src/index.ts +352 -1281
  33. package/src/official-adapter.ts +111 -0
  34. package/src/official-migrate.ts +863 -0
  35. package/src/official-scheduler.ts +235 -0
  36. package/src/official-store.ts +122 -0
  37. package/src/official-sync.ts +371 -0
  38. package/src/opencode-go-adapter.ts +494 -0
  39. package/src/opencode-go-patch-file.ts +175 -9
  40. package/src/opencode-go-source.ts +1 -1
  41. package/lib/opencode-go-diagnose.d.ts +0 -96
  42. package/lib/opencode-go-diagnose.js +0 -177
  43. package/lib/opencode-go-diagnose.js.map +0 -1
  44. package/lib/opencode-go-grouping.d.ts +0 -7
  45. package/lib/opencode-go-grouping.js +0 -21
  46. package/lib/opencode-go-grouping.js.map +0 -1
  47. package/lib/opencode-go-host-catalog.d.ts +0 -42
  48. package/lib/opencode-go-host-catalog.js +0 -98
  49. package/lib/opencode-go-host-catalog.js.map +0 -1
  50. package/lib/opencode-go-journal.d.ts +0 -114
  51. package/lib/opencode-go-journal.js +0 -406
  52. package/lib/opencode-go-journal.js.map +0 -1
  53. package/lib/opencode-go-migrate.d.ts +0 -378
  54. package/lib/opencode-go-migrate.js +0 -1529
  55. package/lib/opencode-go-migrate.js.map +0 -1
  56. package/lib/opencode-go-migration.d.ts +0 -270
  57. package/lib/opencode-go-migration.js +0 -473
  58. package/lib/opencode-go-migration.js.map +0 -1
  59. package/lib/opencode-go-one-shot.d.ts +0 -282
  60. package/lib/opencode-go-one-shot.js +0 -1131
  61. package/lib/opencode-go-one-shot.js.map +0 -1
  62. package/lib/opencode-go-planner.d.ts +0 -168
  63. package/lib/opencode-go-planner.js +0 -407
  64. package/lib/opencode-go-planner.js.map +0 -1
  65. package/lib/opencode-go-scheduler.d.ts +0 -128
  66. package/lib/opencode-go-scheduler.js +0 -241
  67. package/lib/opencode-go-scheduler.js.map +0 -1
  68. package/lib/opencode-go-store.d.ts +0 -18
  69. package/lib/opencode-go-store.js +0 -68
  70. package/lib/opencode-go-store.js.map +0 -1
  71. package/lib/opencode-go-sync.d.ts +0 -107
  72. package/lib/opencode-go-sync.js +0 -388
  73. package/lib/opencode-go-sync.js.map +0 -1
  74. package/lib/opencode-go-writer.d.ts +0 -148
  75. package/lib/opencode-go-writer.js +0 -1061
  76. package/lib/opencode-go-writer.js.map +0 -1
  77. package/src/opencode-go-diagnose.ts +0 -276
  78. package/src/opencode-go-grouping.ts +0 -26
  79. package/src/opencode-go-host-catalog.ts +0 -125
  80. package/src/opencode-go-journal.ts +0 -460
  81. package/src/opencode-go-migrate.ts +0 -1951
  82. package/src/opencode-go-migration.ts +0 -666
  83. package/src/opencode-go-one-shot.ts +0 -1399
  84. package/src/opencode-go-planner.ts +0 -582
  85. package/src/opencode-go-scheduler.ts +0 -315
  86. package/src/opencode-go-store.ts +0 -73
  87. package/src/opencode-go-sync.ts +0 -541
  88. package/src/opencode-go-writer.ts +0 -1301
@@ -1,666 +0,0 @@
1
- // P1d-1: migration gate + single-writer route authority (design §14.1 / §14.6 /
2
- // §14.7, M-4 / M-5; ADR-008). Pure state/fingerprint/routeWriter functions plus
3
- // an injected migration-record store seam. No timer, no network, no settings
4
- // write lives here — the migrate *command* itself is P1d-2. Tests inject an
5
- // `appliedFingerprint` record to exercise the applied state without apply().
6
- //
7
- // Priority (§14.7.1): ① migration gate (`none`) > ② single-writer ownership >
8
- // ③ ordinary §6.2.4 write semantics. A skipped route must always produce a
9
- // report line (never silent), which callers build from RouteWriterDecision.
10
-
11
- import { createHash } from 'node:crypto'
12
- import { GO_SLOT_ROUTES } from './opencode-go-grouping.ts'
13
- import { GO_MIGRATION_STORE_KEY_BASE, isUnscopedStoreKey, scopedStoreKey } from './opencode-go-profile.ts'
14
- import { loadModelsStore, type ModelsStoreAccessor } from './remote-catalog.ts'
15
- import type { SettingsDescriptor } from './writer.ts'
16
-
17
- /** Cordis service seam: tests register a fake record store under this name. */
18
- export const GO_MIGRATION_STORE_SERVICE = 'goMigrationStore'
19
- /**
20
- * Base name of the models-store raw slot holding the go migration record
21
- * (P1d-1). B1: profile-scoped stores persist it as
22
- * `<profileKey>#migration:opencode-go`; the unscoped name is kept only for
23
- * legacy callers/tests and is never claimed by a scoped store. The literal is
24
- * owned by opencode-go-profile.ts so `isUnscopedStoreKey` can distinguish a
25
- * scoped migration record from a legacy key without guessing the key shape.
26
- */
27
- export const GO_MIGRATION_STORE_KEY = GO_MIGRATION_STORE_KEY_BASE
28
-
29
- /**
30
- * D6 (design §6.1 / §14.1): `foreign-profile` and `legacy-store` describe a
31
- * migration RECORD this profile will never claim. They are read-only labels —
32
- * both keep the gate closed (write authority `none`), never open `applied`,
33
- * and never authorize rollback deletion. They must remain distinguishable
34
- * from `absent` (no record) and `legacy-inline` (unrecorded section with models).
35
- */
36
- export type MigrationState = 'absent' | 'legacy-inherit' | 'legacy-inline' | 'drifted' | 'applied'
37
- | 'foreign-profile' | 'legacy-store'
38
- /** The writer identity used by the single-writer priority table. */
39
- export type RouteWriterCaller = 'go' | 'zen' | 'pi.dev'
40
- /** Effective owner of a route (`none` = migration gate closed). */
41
- export type GoRouteOwner = 'go' | 'zen' | 'pi.dev' | 'none'
42
-
43
- /** Original settings/ledger state captured before apply (P1d-2, M-3/M-5). */
44
- export interface MigrationBackup {
45
- planHash: string
46
- capturedAt: number
47
- /** Per-route pre-apply snapshot; `section` absent means the route did not exist. */
48
- routes: Record<string, {
49
- section?: Record<string, unknown>
50
- ledger?: Record<string, unknown>
51
- }>
52
- }
53
-
54
- /** Migration record persisted by `/model-sync migrate apply` (P1d-2). */
55
- export interface MigrationRecord {
56
- /**
57
- * B1: profile identity stamped by the scoped store on every write. Reads
58
- * reject a record whose `profileKey` differs from the current profile, so a
59
- * record written by another profile is never treated as `applied`. Absent on
60
- * pre-fix (unscoped) records — those are legacy/unknown-owner and not claimed.
61
- */
62
- profileKey?: string
63
- /** Audit backup written with `applying:true` BEFORE the first settings mutate. */
64
- backup?: MigrationBackup
65
- legacyFingerprint?: string
66
- /** sha256(canonical({ identity, appliedManagedIds })) — §14.7.4 two-level fingerprint. */
67
- appliedFingerprint?: string
68
- /** sha256 of the stable identity fields of the go sections at apply/last own write. */
69
- appliedIdentity?: string
70
- /** Route set `appliedIdentity` was computed over — later-added routes must not drift. */
71
- appliedIdentityRoutes?: string[]
72
- /** Per-route sorted ledger-managed ids captured with `appliedFingerprint`. */
73
- appliedManagedIds?: Record<string, string[]>
74
- planHash?: string
75
- appliedAt?: number
76
- backupPath?: string
77
- movedIds?: string[]
78
- /** M-5: apply in progress — every auto round must drop, never queue. */
79
- applying?: boolean
80
- }
81
-
82
- export interface MigrationStatus {
83
- state: MigrationState
84
- /** sha256 of the canonical FULL `opencode-go*` sections (legacy-shape compat only). */
85
- fingerprint: string
86
- /** sha256 of the current stable identity fields of the go sections. */
87
- identity: string
88
- appliedFingerprint?: string
89
- appliedIdentity?: string
90
- appliedManagedIds?: Record<string, string[]>
91
- legacyFingerprint?: string
92
- applying: boolean
93
- /** Identity matches but the stored full fingerprint is stale → self-heal (§14.7.4). */
94
- fingerprintHealed: boolean
95
- /** Fingerprint the healed record should carry. */
96
- expectedFingerprint: string
97
- /**
98
- * Set by the non-strict refresh in index.ts when the file-backed migration
99
- * store / ownership ledger could not be built because the host supplied no
100
- * profile identity (fail-closed). Status output must surface this instead of
101
- * presenting a normal legacy state. Never set on injected-store hosts (they
102
- * have a usable ledger even without a resolved identity) or with identity.
103
- */
104
- identityUnavailable?: boolean
105
- }
106
-
107
- /** D6: a migration record this profile must not claim (read-only provenance). */
108
- export interface UnclaimedMigrationRecord {
109
- /** Which design-required status label this record maps to. */
110
- kind: 'foreign-profile' | 'legacy-store'
111
- /** models-store raw slot the record was found under. */
112
- key: string
113
- /** Profile stamp found in the record, when present. */
114
- profileKey?: string
115
- }
116
-
117
- /**
118
- * D6: the ONE computation of the "unclaimable record" status label. Both
119
- * `migrate status` (opencode-go-migrate.ts) and the go report's status refresh
120
- * (index.ts `loadMigrationStatus`) use this helper, so the same store state
121
- * yields the same label in both commands (W1). Call only when the profile's own
122
- * scoped read() found no record — a foreign record must never relabel a profile
123
- * that already has its own applied/drifted record (B1 isolation).
124
- */
125
- export function unclaimedRecordState(
126
- unclaimed: readonly UnclaimedMigrationRecord[],
127
- ): MigrationState | undefined {
128
- if (unclaimed.some((record) => record.kind === 'foreign-profile')) return 'foreign-profile'
129
- if (unclaimed.length > 0) return 'legacy-store'
130
- return undefined
131
- }
132
-
133
- /** Migration record seam. `write` / `legacyKeys` are optional so read-only test stores keep working. */
134
- export interface MigrationStateStore {
135
- read(): Promise<MigrationRecord | undefined>
136
- /**
137
- * H4: strict read for write paths — `undefined` ONLY when the slot does not
138
- * exist; a store error is THROWN so the caller (onOwnWrite /
139
- * loadMigrationStatus({strict:true})) can fail closed instead of mistaking
140
- * an unreadable record for "no prior record" and overwriting a live
141
- * MigrationRecord (backup/planHash/movedIds would be lost). The plain
142
- * `read()` keeps its tolerant read-only semantics for status/plan paths.
143
- */
144
- readStrict?(): Promise<MigrationRecord | undefined>
145
- /** Queue-serialized atomic slot replacement (same models-store queue as the ledger). */
146
- write?(record: MigrationRecord): Promise<void>
147
- /** Advisory: unscoped legacy keys found in the shared store (reported, never claimed). */
148
- legacyKeys?(): Promise<string[]>
149
- /**
150
- * D6 advisory: migration records that are NOT readable by this profile —
151
- * a different `profileKey`, or a pre-fix record with no stamp at all.
152
- * Pure read: never writes, never changes `read()`/gate/rollback behavior.
153
- */
154
- unclaimedRecords?(): Promise<UnclaimedMigrationRecord[]>
155
- }
156
-
157
- export interface RouteWriterConfig {
158
- /** Which write path is asking for authority. */
159
- caller: RouteWriterCaller
160
- /** opencode.go.enabled — the switch that hands go routes to the go writer. */
161
- goEnabled: boolean
162
- /** zen routes mode (default 'login-only' = zen never writes routes). */
163
- zenMode?: 'login-only' | 'routes'
164
- /** Custom zen route ids (defaults to the `opencode-zen*` prefix rule). */
165
- zenRoutes?: readonly string[]
166
- /** Custom go route ids (defaults to GO_SLOT_ROUTES values + `opencode-go*` prefix). */
167
- goRoutes?: readonly string[]
168
- }
169
-
170
- export interface RouteWriterDecision {
171
- decision: 'write' | 'skip'
172
- /** Machine-readable reason; skip reasons carry the report code (`skipped-route-owner`, …). */
173
- reason: string
174
- /** Effective owner — surfaced as `skipped-route-owner: <owner>` in reports. */
175
- owner: GoRouteOwner
176
- }
177
-
178
- /** Fixed report line required by §14.6 for every migration-gate skip. */
179
- export const MIGRATION_GATE_HINT = '检测到未迁移配置,已跳过写入;运行 /model-sync migrate plan'
180
-
181
- // ---------------------------------------------------------------------------
182
- // Fingerprint + state detection (pure)
183
- // ---------------------------------------------------------------------------
184
-
185
- function isRecord(value: unknown): value is Record<string, unknown> {
186
- return typeof value === 'object' && value !== null && !Array.isArray(value)
187
- }
188
-
189
- /** Canonical JSON (recursive key sort) — the ownership-entry hash algorithm (§14.1). */
190
- function canonicalize(value: unknown): unknown {
191
- if (Array.isArray(value)) return value.map(canonicalize)
192
- if (!isRecord(value)) return value
193
- const out: Record<string, unknown> = {}
194
- for (const key of Object.keys(value).sort()) out[key] = canonicalize(value[key])
195
- return out
196
- }
197
-
198
- /** sha256 of canonical JSON — section fingerprint (§14.1). */
199
- export function fingerprintSection(value: unknown): string {
200
- return createHash('sha256').update(JSON.stringify(canonicalize(value))).digest('hex')
201
- }
202
-
203
- /** Extract only the `opencode-go*` provider sections that currently exist. */
204
- export function readGoProviderSections(
205
- source: SettingsDescriptor | Record<string, unknown> | undefined,
206
- routes: readonly string[] = Object.values(GO_SLOT_ROUTES),
207
- ): Record<string, unknown> | undefined {
208
- // A SettingsDescriptor carries `user.providers`; a raw providers object is
209
- // itself the route→section map. Discriminate on `user` rather than `ns` so a
210
- // partial descriptor fixture (no `ns`) still resolves correctly.
211
- const providers = isRecord(source) && isRecord(source.user)
212
- ? source.user.providers
213
- : isRecord(source) ? source.providers : undefined
214
- if (!isRecord(providers)) return undefined
215
- const sections: Record<string, unknown> = {}
216
- for (const route of routes) {
217
- const data = providers[route]
218
- if (isRecord(data)) sections[route] = data
219
- }
220
- return sections
221
- }
222
-
223
- /** Fingerprint of the current `opencode-go*` sections (empty object when absent). */
224
- export function fingerprintGoRoutes(
225
- source: SettingsDescriptor | Record<string, unknown> | undefined,
226
- routes?: readonly string[],
227
- ): string {
228
- return fingerprintSection(readGoProviderSections(source, routes) ?? {})
229
- }
230
-
231
- // --- Two-level applied fingerprint (§14.7.4) --------------------------------
232
- //
233
- // Only STABLE fields take part in drift detection:
234
- // appliedIdentity = sha256(canonical({ <route>: {api, baseURL, displayName,
235
- // apiKeyEnv} })) — from settings
236
- // appliedManagedIds = { <route>: sorted ids in the ownership ledger } — from ledger
237
- // appliedFingerprint = sha256(canonical({ appliedIdentity, appliedManagedIds }))
238
- //
239
- // Excluded on purpose: models[] capacity/capability fields (name,
240
- // contextWindow, maxTokens, input, reasoningEfforts, compat — all rewritten
241
- // every sync round), user-owned ids, model order, modelOverrides, and any
242
- // time/usage field. Those are handled by the managed-vs-user-owned repair
243
- // rules, never by closing the gate. Identity fields are never rewritten by a
244
- // sync round, and the ledger ids change only through our own successful
245
- // writes (which immediately re-persist the fingerprint), so a normal sync
246
- // cannot create an identity-level mismatch. An external identity edit →
247
- // `drifted`; an external models edit → still `applied`.
248
- const IDENTITY_FIELDS = ['api', 'baseURL', 'displayName', 'apiKeyEnv'] as const
249
-
250
- /** Identity map: only the four stable fields of each present go section. */
251
- export function goIdentityOf(sections: Record<string, unknown> | undefined): Record<string, Record<string, unknown>> {
252
- const out: Record<string, Record<string, unknown>> = {}
253
- for (const [route, section] of Object.entries(sections ?? {})) {
254
- if (!isRecord(section)) continue
255
- const entry: Record<string, unknown> = {}
256
- for (const field of IDENTITY_FIELDS) {
257
- if (section[field] !== undefined) entry[field] = section[field]
258
- }
259
- out[route] = entry
260
- }
261
- return out
262
- }
263
-
264
- /**
265
- * Hash of the current route identities — stable across ordinary sync rounds.
266
- * `routes` restricts the compared set: a record keeps the route set it was
267
- * written with, so routes created later by a sync round never look like drift.
268
- */
269
- export function fingerprintGoIdentity(
270
- sections: Record<string, unknown> | undefined,
271
- routes?: readonly string[],
272
- ): string {
273
- const all = goIdentityOf(sections)
274
- if (routes === undefined) return fingerprintSection(all)
275
- return fingerprintSection(Object.fromEntries(routes.map((route) => [route, all[route] ?? {}])))
276
- }
277
-
278
- /** Full applied fingerprint = sha256(canonical({ identity, managedIds })). */
279
- export function appliedFingerprintOf(
280
- identity: string,
281
- managedIds: Record<string, string[]> | undefined,
282
- ): string {
283
- return fingerprintSection({ identity, managedIds: managedIds ?? {} })
284
- }
285
-
286
- /**
287
- * ONE route-set convention for the two-level applied fingerprint, shared by
288
- * `migrationStatusOf` (loadMigrationStatus) and the writer's `onOwnWrite`:
289
- * identity routes are the record's `appliedIdentityRoutes` (or the routes
290
- * present in settings when the record has none); managed-id routes are exactly
291
- * the entries present in the supplied map. A configured-but-absent route must
292
- * NOT be fabricated as `<route>: []` — migrate/onOwnWrite persist only routes
293
- * with a real ledger entry, and inventing empty ones here makes the first
294
- * healthy round look like a fingerprint drift (`fingerprint-healed` noise).
295
- */
296
- export function appliedFingerprintFieldsOf(
297
- sections: Record<string, unknown> | undefined,
298
- record: { appliedIdentityRoutes?: string[] } | undefined,
299
- managedIds: Record<string, string[]> | undefined,
300
- ): { identity: string; appliedFingerprint: string } {
301
- const identityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {})
302
- const identity = fingerprintGoIdentity(sections, identityRoutes)
303
- return { identity, appliedFingerprint: appliedFingerprintOf(identity, managedIds) }
304
- }
305
-
306
- /** Inputs to `ownWriteRecordUpdate` — everything the go writer knows post-write. */
307
- export interface OwnWriteRecordInput {
308
- /** The migration record read BEFORE this update (strict read; may be undefined). */
309
- record: MigrationRecord | undefined
310
- /** Live llm-pi-ai descriptor (or raw providers map) read AFTER the settings write. */
311
- source: SettingsDescriptor | Record<string, unknown> | undefined
312
- /** Configured go route ids (the identity comparison universe). */
313
- routes: readonly string[]
314
- /** The route this write landed on. */
315
- route: string
316
- /** Ledger-managed ids just committed for this route (sorted by the writer). */
317
- managedIds: readonly string[]
318
- /** True when this write was a whole-section unset (the ledger key was deleted). */
319
- unset?: boolean
320
- }
321
-
322
- /**
323
- * The ONE post-own-write migration record update — extracted from index.ts so
324
- * tests (H2: the 0.11.x four-route convergence) drive the exact code the
325
- * plugin runs. Semantics:
326
- * - `appliedIdentityRoutes` shrinks to the routes still PRESENT in settings
327
- * (0.12.0 catalog-reuse unsets the legacy protocol routes; keeping them in
328
- * the identity set would make every later read look like drift) — with the
329
- * just-written route always included (M2: prevents the degenerate
330
- * constant `sha256('{}')` identity when every section is gone).
331
- * - `appliedManagedIds[route]` is SET for a normal write and DELETED for an
332
- * unset (M2: the ledger key was deleted — a persisted `[]` entry no ledger
333
- * backs makes the stored fingerprint disagree with every status read and
334
- * costs a fingerprint-healed round).
335
- * - `appliedIdentity` / `appliedFingerprint` are recomputed from the live
336
- * sections + the updated managed-id map, so the persisted record always
337
- * matches what `migrationStatusOf` recomputes (no phantom heal).
338
- * Pure: returns the next record; the caller persists it.
339
- */
340
- export function ownWriteRecordUpdate(input: OwnWriteRecordInput): MigrationRecord {
341
- const sections = readGoProviderSections(input.source, input.routes) ?? {}
342
- const presentRoutes = Object.keys(sections)
343
- const prior = input.record ?? {}
344
- // The just-written route joins the identity set ONLY on a real write. An
345
- // unset drops it together with its section: identity and fingerprint are
346
- // always recomputed from the SAME list the status read will use, so the
347
- // degenerate empty-set hash (`sha256('{}')`) can only ever arise on BOTH
348
- // sides simultaneously — never as a one-sided drift.
349
- const includeRoute = input.unset !== true
350
- const identityRoutes = [...new Set([
351
- ...(prior.appliedIdentityRoutes ?? presentRoutes).filter((candidate) =>
352
- presentRoutes.includes(candidate) || (includeRoute && candidate === input.route)),
353
- ...(includeRoute ? [input.route] : []),
354
- ])]
355
- const appliedManagedIds: Record<string, string[]> = { ...(prior.appliedManagedIds ?? {}) }
356
- if (input.unset === true) delete appliedManagedIds[input.route]
357
- else appliedManagedIds[input.route] = [...input.managedIds].sort((a, b) => a.localeCompare(b))
358
- // P2-②: an EMPTY identity route set means "no verifiable applied identity".
359
- // Persisting `appliedIdentityRoutes: []` (+ the constant `sha256('{}')`
360
- // identity it hashes to) would make ANY later config — including an
361
- // unmigrated legacy-inline one — constant-match and read as `applied`
362
- // (migration-gate penetration). Drop the applied-state fields instead: the
363
- // record keeps everything else and state detection falls back to the
364
- // closed-gate legacy path. `migrationStateOf` carries the matching
365
- // read-side guard, so an old record that already carries `[]` cannot
366
- // penetrate either.
367
- if (identityRoutes.length === 0) {
368
- const rest = { ...prior, appliedManagedIds }
369
- delete rest.appliedIdentity
370
- delete rest.appliedIdentityRoutes
371
- delete rest.appliedFingerprint
372
- return rest
373
- }
374
- const { identity, appliedFingerprint } = appliedFingerprintFieldsOf(
375
- sections, { appliedIdentityRoutes: identityRoutes }, appliedManagedIds,
376
- )
377
- return {
378
- ...prior,
379
- appliedIdentity: identity,
380
- appliedIdentityRoutes: identityRoutes,
381
- appliedManagedIds,
382
- appliedFingerprint,
383
- }
384
- }
385
-
386
- /**
387
- * Ledger ids for exactly the routes that HAVE a ledger entry. This is the
388
- * managed-id half of the shared fingerprint convention above: no entry means
389
- * no route in the map (never an empty array), so a normal first onboarding and
390
- * a later own write hash identically. Unreadable entries are skipped too —
391
- * the strict per-mutate gate already fails closed on a record read failure.
392
- */
393
- export async function goLedgerManagedIds(
394
- routes: readonly string[],
395
- readEntry: (route: string) => Promise<{ managed?: Record<string, unknown> } | undefined>,
396
- ): Promise<Record<string, string[]>> {
397
- const managedIds: Record<string, string[]> = {}
398
- for (const route of routes) {
399
- let entry: { managed?: Record<string, unknown> } | undefined
400
- try {
401
- entry = await readEntry(route)
402
- } catch {
403
- continue // unreadable ledger ⇒ no managed ids (never delete), no fabricated entry
404
- }
405
- if (entry !== undefined) managedIds[route] = Object.keys(entry.managed ?? {}).sort()
406
- }
407
- return managedIds
408
- }
409
-
410
- function hasInlineModels(sections: Record<string, unknown>, chatRoute: string): boolean {
411
- const chat = sections[chatRoute]
412
- return isRecord(chat) && Array.isArray(chat.models)
413
- }
414
-
415
- /**
416
- * Determine migration state (§14.1 / §14.7.4). Order matters: absent →
417
- * identity-based applied/drifted (new records) → full-fingerprint match
418
- * (legacy records written before the two-level split) → recorded legacy/drifted
419
- * → unrecorded legacy form. Only an IDENTITY mismatch is `drifted`: a models
420
- * edit (capacity fields, user-owned ids, order) leaves identity intact and is
421
- * repaired by the writer instead of closing the gate.
422
- */
423
- export function migrationStateOf(
424
- sections: Record<string, unknown> | undefined,
425
- record: MigrationRecord | undefined,
426
- chatRoute: string = GO_SLOT_ROUTES.chat,
427
- ): MigrationState {
428
- if (sections === undefined || Object.keys(sections).length === 0) return 'absent'
429
- const fingerprint = fingerprintSection(sections)
430
- if (record?.appliedIdentity !== undefined) {
431
- // P2-②: an explicit EMPTY appliedIdentityRoutes hashes every config to the
432
- // same constant (`sha256('{}')`), so it must never count as a valid
433
- // applied identity — treat it as absent and fall through to the legacy
434
- // fingerprint comparison (which can only match the truly applied bytes).
435
- const identityRoutes = record.appliedIdentityRoutes
436
- if (identityRoutes === undefined || identityRoutes.length > 0) {
437
- return fingerprintGoIdentity(sections, identityRoutes) === record.appliedIdentity
438
- ? 'applied' : 'drifted'
439
- }
440
- }
441
- // Backward compatibility with the pre-§14.7.4 full-section fingerprint.
442
- if (record?.appliedFingerprint !== undefined && fingerprint === record.appliedFingerprint) return 'applied'
443
- if (record !== undefined && (record.appliedFingerprint !== undefined || record.legacyFingerprint !== undefined)) {
444
- if (record.legacyFingerprint !== undefined && fingerprint === record.legacyFingerprint) {
445
- return hasInlineModels(sections, chatRoute) ? 'legacy-inline' : 'legacy-inherit'
446
- }
447
- return 'drifted'
448
- }
449
- return hasInlineModels(sections, chatRoute) ? 'legacy-inline' : 'legacy-inherit'
450
- }
451
-
452
- /**
453
- * Full status from a settings descriptor (or raw providers object) + record.
454
- * `currentManagedIds`, when supplied, comes from the live ownership ledger and
455
- * drives the §14.7.4 self-heal check (identity matches but the stored full
456
- * fingerprint is stale because the fingerprint write failed after a commit).
457
- */
458
- export function migrationStatusOf(
459
- source: SettingsDescriptor | Record<string, unknown> | undefined,
460
- record: MigrationRecord | undefined,
461
- routes?: readonly string[],
462
- currentManagedIds?: Record<string, string[]>,
463
- ): MigrationStatus {
464
- const sections = readGoProviderSections(source, routes)
465
- // Compare only the route set the record was written with — routes added by a
466
- // later sync round must not invalidate an otherwise unchanged identity. The
467
- // shared helper keeps this EXACT route set in sync with onOwnWrite, so a
468
- // healthy round cannot emit a phantom `fingerprint-healed`.
469
- const managedIds = currentManagedIds ?? record?.appliedManagedIds ?? {}
470
- const { identity, appliedFingerprint: expectedFingerprint } = appliedFingerprintFieldsOf(
471
- sections, record, managedIds,
472
- )
473
- return {
474
- state: migrationStateOf(sections, record, routes?.[0] ?? GO_SLOT_ROUTES.chat),
475
- fingerprint: fingerprintSection(sections ?? {}),
476
- identity,
477
- appliedIdentity: record?.appliedIdentity,
478
- appliedManagedIds: record?.appliedManagedIds,
479
- appliedFingerprint: record?.appliedFingerprint,
480
- legacyFingerprint: record?.legacyFingerprint,
481
- applying: record?.applying === true,
482
- // P2-② (agy final): a degenerate record (`appliedIdentityRoutes: []`,
483
- // constant `sha256('{}')` identity) constant-matches ANY config, so the
484
- // raw identity equality below is trivially true — gating `fingerprintHealed`
485
- // on the same valid-identity condition `migrationStateOf` uses keeps the
486
- // §14.7.4 self-heal write-back (index.ts persists `expectedFingerprint`
487
- // when this flag fires) away from records no state detector reads as
488
- // applied. `undefined` routes stay valid (pre-identity-list records fall
489
- // back to the routes present in settings).
490
- fingerprintHealed: record?.appliedIdentity !== undefined
491
- && (record.appliedIdentityRoutes === undefined || record.appliedIdentityRoutes.length > 0)
492
- && identity === record.appliedIdentity
493
- && record.appliedFingerprint !== expectedFingerprint,
494
- expectedFingerprint,
495
- }
496
- }
497
-
498
- // ---------------------------------------------------------------------------
499
- // Single-writer route authority (pure)
500
- // ---------------------------------------------------------------------------
501
-
502
- /** True for any configured go route id or the `opencode-go*` prefix. */
503
- export function isGoRoute(route: string, customRoutes?: readonly string[]): boolean {
504
- if (customRoutes?.includes(route) === true) return true
505
- return Object.values(GO_SLOT_ROUTES).includes(route) || route.startsWith('opencode-go')
506
- }
507
-
508
- function isZenRoute(route: string, cfg: RouteWriterConfig): boolean {
509
- if (cfg.zenRoutes?.includes(route) === true) return true
510
- return route.startsWith('opencode-zen')
511
- }
512
-
513
- /**
514
- * The single decision point every write path must call before settings.mutate.
515
- *
516
- * Rules (§14.7.1, task P1d-1):
517
- * - go.enabled=true + caller≠'go' on an `opencode-go*` route → always skip;
518
- * the legacy pi.dev path may never take over, even if the gate returned none.
519
- * - go.enabled=true + caller='go' + state=applied with a matching fingerprint,
520
- * or state=absent → write. legacy-inherit / legacy-inline / drifted → skip
521
- * (migration gate) and report MIGRATION_GATE_HINT.
522
- * - `applying` → skip (M-5: auto rounds drop while apply is in progress).
523
- * - go.enabled=false → v0.9.0 behavior restored for go routes (pi.dev owner).
524
- * - zen routes mode: only the zen writer owns zen routes; other routes are
525
- * unaffected (pi.dev owner) and keep their original behavior.
526
- */
527
- export function routeWriter(
528
- route: string,
529
- cfg: RouteWriterConfig,
530
- migration: MigrationStatus,
531
- ): RouteWriterDecision {
532
- const goRoute = isGoRoute(route, cfg.goRoutes)
533
-
534
- if (goRoute && cfg.goEnabled) {
535
- if (cfg.caller !== 'go') {
536
- return {
537
- decision: 'skip',
538
- owner: 'go',
539
- reason: 'skipped-route-owner: go (single-writer: opencode.go.enabled=true; legacy pi.dev path must never write opencode-go* routes)',
540
- }
541
- }
542
- if (migration.applying) {
543
- return {
544
- decision: 'skip',
545
- owner: 'none',
546
- reason: `skipped-route-owner: none (migration applying; ${MIGRATION_GATE_HINT})`,
547
- }
548
- }
549
- // §14.7.4: a record with `appliedIdentity` is judged applied by IDENTITY
550
- // match alone — models edits must not close the gate. Legacy records fall
551
- // back to the full-section fingerprint equality they were written with.
552
- if (migration.state === 'applied'
553
- && ((migration.appliedIdentity !== undefined && migration.identity === migration.appliedIdentity)
554
- || (migration.appliedFingerprint !== undefined && migration.fingerprint === migration.appliedFingerprint))) {
555
- return { decision: 'write', owner: 'go', reason: 'owner=go (migration applied; identity/fingerprint matched)' }
556
- }
557
- if (migration.state === 'absent') {
558
- return { decision: 'write', owner: 'go', reason: 'owner=go (absent; no pre-existing section to migrate)' }
559
- }
560
- return {
561
- decision: 'skip',
562
- owner: 'none',
563
- reason: `skipped-route-owner: none (migration gate: ${migration.state}; ${MIGRATION_GATE_HINT})`,
564
- }
565
- }
566
-
567
- // go.enabled=false (or non-go route): zen routes still have a single owner.
568
- if (cfg.zenMode === 'routes' && isZenRoute(route, cfg)) {
569
- if (cfg.caller !== 'zen') {
570
- return { decision: 'skip', owner: 'zen', reason: 'skipped-route-owner: zen (zen routes mode: only the zen writer owns zen routes)' }
571
- }
572
- return { decision: 'write', owner: 'zen', reason: 'owner=zen' }
573
- }
574
-
575
- // Everything else keeps the original pi.dev behavior. A go caller writing a
576
- // non-go route is a no-op in practice; allow it so callers can pass a uniform
577
- // decision function without changing other routes' semantics.
578
- return { decision: 'write', owner: 'pi.dev', reason: 'owner=pi.dev' }
579
- }
580
-
581
- // ---------------------------------------------------------------------------
582
- // Injected store (production adapter reads the same models-store JSON)
583
- // ---------------------------------------------------------------------------
584
-
585
- /**
586
- * Build a migration store over the models-store raw-slot accessor.
587
- *
588
- * `profileKey` scopes the record slot to `<profileKey>#migration:opencode-go`
589
- * and stamps the same identity into the record. Reads require the stamp to
590
- * match — a record from another profile (or an unscoped legacy record with no
591
- * stamp) is treated as "no record", so state detection falls back to
592
- * legacy/absent and the migration gate stays closed. Omitting `profileKey`
593
- * keeps the pre-fix unscoped behavior for legacy callers/tests only.
594
- */
595
- export function createFileMigrationStateStore(
596
- accessor: ModelsStoreAccessor,
597
- profileKey?: string,
598
- ): MigrationStateStore {
599
- const slot = profileKey === undefined
600
- ? GO_MIGRATION_STORE_KEY
601
- : scopedStoreKey(profileKey, GO_MIGRATION_STORE_KEY)
602
- return {
603
- async read(): Promise<MigrationRecord | undefined> {
604
- let raw: unknown
605
- try {
606
- raw = await accessor.readRaw(slot)
607
- } catch {
608
- return undefined // unreadable ⇒ no record ⇒ conservative legacy detection
609
- }
610
- if (!isRecord(raw)) return undefined
611
- // Read-side ownership check (B1): never adopt a record stamped for a
612
- // different profile, and never claim an unstamped legacy record.
613
- if (profileKey !== undefined && raw.profileKey !== profileKey) return undefined
614
- return raw as unknown as MigrationRecord
615
- },
616
- // H4: write paths must see store errors, never "no prior record". Only a
617
- // genuinely absent slot (or a foreign stamp, which is an ownership
618
- // verdict — not an error) reads as undefined here.
619
- async readStrict(): Promise<MigrationRecord | undefined> {
620
- const raw = await accessor.readRaw(slot)
621
- if (!isRecord(raw)) return undefined
622
- if (profileKey !== undefined && raw.profileKey !== profileKey) return undefined
623
- return raw as unknown as MigrationRecord
624
- },
625
- async write(record: MigrationRecord): Promise<void> {
626
- // writeRaw is queue-serialized atomic temp+rename, i.e. the SAME queue
627
- // that persists the ownership ledger (§14.7.4: settings → ledger → fingerprint).
628
- const stamped: MigrationRecord = profileKey === undefined ? record : { ...record, profileKey }
629
- await accessor.writeRaw(slot, stamped as unknown as Record<string, unknown>)
630
- },
631
- async legacyKeys(): Promise<string[]> {
632
- const keys = await accessor.listRawKeys()
633
- return keys.filter((key) => key === GO_MIGRATION_STORE_KEY || isUnscopedStoreKey(key))
634
- },
635
- async unclaimedRecords(): Promise<UnclaimedMigrationRecord[]> {
636
- // No resolved profile → no "foreign" notion; legacy callers keep their
637
- // pre-fix read behavior. Status in production always has a profileKey.
638
- if (profileKey === undefined) return []
639
- const keys = await accessor.listRawKeys()
640
- const out: UnclaimedMigrationRecord[] = []
641
- for (const key of keys) {
642
- const isUnscopedSlot = key === GO_MIGRATION_STORE_KEY
643
- const isScopedSlot = !isUnscopedSlot && key.endsWith(`#${GO_MIGRATION_STORE_KEY}`)
644
- if (!isUnscopedSlot && !isScopedSlot) continue
645
- let raw: unknown
646
- try {
647
- raw = await accessor.readRaw(key)
648
- } catch {
649
- continue // unreadable slot is advisory only; never changes the gate
650
- }
651
- if (!isRecord(raw)) continue
652
- const stamp = typeof raw.profileKey === 'string' && raw.profileKey.length > 0
653
- ? raw.profileKey : undefined
654
- if (stamp === profileKey) continue // our own record — claimable as before
655
- const kind: UnclaimedMigrationRecord['kind'] = stamp === undefined ? 'legacy-store' : 'foreign-profile'
656
- out.push(stamp === undefined ? { kind, key } : { kind, key, profileKey: stamp })
657
- }
658
- return out
659
- },
660
- }
661
- }
662
-
663
- /** Production factory; tests pass a temp-file accessor or inject a fake store. */
664
- export function createModelsStoreMigrationStateStore(storePath?: string, profileKey?: string): MigrationStateStore {
665
- return createFileMigrationStateStore(loadModelsStore(storePath), profileKey)
666
- }