@aiwayds/dsh-model-sync 0.9.0 → 0.11.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 (74) hide show
  1. package/README.md +20 -3
  2. package/README.zh-CN.md +20 -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 +379 -0
  6. package/lib/index.js +897 -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-one-shot.d.ts +276 -0
  24. package/lib/opencode-go-one-shot.js +1094 -0
  25. package/lib/opencode-go-one-shot.js.map +1 -0
  26. package/lib/opencode-go-patch-file.d.ts +123 -0
  27. package/lib/opencode-go-patch-file.js +1185 -0
  28. package/lib/opencode-go-patch-file.js.map +1 -0
  29. package/lib/opencode-go-planner.d.ts +153 -0
  30. package/lib/opencode-go-planner.js +339 -0
  31. package/lib/opencode-go-planner.js.map +1 -0
  32. package/lib/opencode-go-profile.d.ts +57 -0
  33. package/lib/opencode-go-profile.js +103 -0
  34. package/lib/opencode-go-profile.js.map +1 -0
  35. package/lib/opencode-go-scheduler.d.ts +128 -0
  36. package/lib/opencode-go-scheduler.js +241 -0
  37. package/lib/opencode-go-scheduler.js.map +1 -0
  38. package/lib/opencode-go-source.d.ts +117 -0
  39. package/lib/opencode-go-source.js +331 -0
  40. package/lib/opencode-go-source.js.map +1 -0
  41. package/lib/opencode-go-store.d.ts +18 -0
  42. package/lib/opencode-go-store.js +68 -0
  43. package/lib/opencode-go-store.js.map +1 -0
  44. package/lib/opencode-go-sync.d.ts +94 -0
  45. package/lib/opencode-go-sync.js +364 -0
  46. package/lib/opencode-go-sync.js.map +1 -0
  47. package/lib/opencode-go-writer.d.ts +132 -0
  48. package/lib/opencode-go-writer.js +966 -0
  49. package/lib/opencode-go-writer.js.map +1 -0
  50. package/lib/provider-native.d.ts +3 -1
  51. package/lib/provider-native.js +4 -2
  52. package/lib/provider-native.js.map +1 -1
  53. package/lib/remote-catalog.d.ts +61 -0
  54. package/lib/remote-catalog.js +307 -3
  55. package/lib/remote-catalog.js.map +1 -1
  56. package/package.json +15 -15
  57. package/src/builtin-catalog-snapshot.ts +6 -3
  58. package/src/index.ts +1060 -12
  59. package/src/opencode-go-diagnose.ts +222 -0
  60. package/src/opencode-go-grouping.ts +97 -0
  61. package/src/opencode-go-journal.ts +458 -0
  62. package/src/opencode-go-migrate.ts +1694 -0
  63. package/src/opencode-go-migration.ts +552 -0
  64. package/src/opencode-go-one-shot.ts +1354 -0
  65. package/src/opencode-go-patch-file.ts +1168 -0
  66. package/src/opencode-go-planner.ts +505 -0
  67. package/src/opencode-go-profile.ts +114 -0
  68. package/src/opencode-go-scheduler.ts +315 -0
  69. package/src/opencode-go-source.ts +424 -0
  70. package/src/opencode-go-store.ts +73 -0
  71. package/src/opencode-go-sync.ts +503 -0
  72. package/src/opencode-go-writer.ts +1189 -0
  73. package/src/provider-native.ts +3 -1
  74. package/src/remote-catalog.ts +359 -3
@@ -0,0 +1,552 @@
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
+ /** Queue-serialized atomic slot replacement (same models-store queue as the ledger). */
137
+ write?(record: MigrationRecord): Promise<void>
138
+ /** Advisory: unscoped legacy keys found in the shared store (reported, never claimed). */
139
+ legacyKeys?(): Promise<string[]>
140
+ /**
141
+ * D6 advisory: migration records that are NOT readable by this profile —
142
+ * a different `profileKey`, or a pre-fix record with no stamp at all.
143
+ * Pure read: never writes, never changes `read()`/gate/rollback behavior.
144
+ */
145
+ unclaimedRecords?(): Promise<UnclaimedMigrationRecord[]>
146
+ }
147
+
148
+ export interface RouteWriterConfig {
149
+ /** Which write path is asking for authority. */
150
+ caller: RouteWriterCaller
151
+ /** opencode.go.enabled — the switch that hands go routes to the go writer. */
152
+ goEnabled: boolean
153
+ /** zen routes mode (default 'login-only' = zen never writes routes). */
154
+ zenMode?: 'login-only' | 'routes'
155
+ /** Custom zen route ids (defaults to the `opencode-zen*` prefix rule). */
156
+ zenRoutes?: readonly string[]
157
+ /** Custom go route ids (defaults to GO_SLOT_ROUTES values + `opencode-go*` prefix). */
158
+ goRoutes?: readonly string[]
159
+ }
160
+
161
+ export interface RouteWriterDecision {
162
+ decision: 'write' | 'skip'
163
+ /** Machine-readable reason; skip reasons carry the report code (`skipped-route-owner`, …). */
164
+ reason: string
165
+ /** Effective owner — surfaced as `skipped-route-owner: <owner>` in reports. */
166
+ owner: GoRouteOwner
167
+ }
168
+
169
+ /** Fixed report line required by §14.6 for every migration-gate skip. */
170
+ export const MIGRATION_GATE_HINT = '检测到未迁移配置,已跳过写入;运行 /model-sync migrate plan'
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Fingerprint + state detection (pure)
174
+ // ---------------------------------------------------------------------------
175
+
176
+ function isRecord(value: unknown): value is Record<string, unknown> {
177
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
178
+ }
179
+
180
+ /** Canonical JSON (recursive key sort) — the ownership-entry hash algorithm (§14.1). */
181
+ function canonicalize(value: unknown): unknown {
182
+ if (Array.isArray(value)) return value.map(canonicalize)
183
+ if (!isRecord(value)) return value
184
+ const out: Record<string, unknown> = {}
185
+ for (const key of Object.keys(value).sort()) out[key] = canonicalize(value[key])
186
+ return out
187
+ }
188
+
189
+ /** sha256 of canonical JSON — section fingerprint (§14.1). */
190
+ export function fingerprintSection(value: unknown): string {
191
+ return createHash('sha256').update(JSON.stringify(canonicalize(value))).digest('hex')
192
+ }
193
+
194
+ /** Extract only the `opencode-go*` provider sections that currently exist. */
195
+ export function readGoProviderSections(
196
+ source: SettingsDescriptor | Record<string, unknown> | undefined,
197
+ routes: readonly string[] = Object.values(GO_SLOT_ROUTES),
198
+ ): Record<string, unknown> | undefined {
199
+ // A SettingsDescriptor carries `user.providers`; a raw providers object is
200
+ // itself the route→section map. Discriminate on `user` rather than `ns` so a
201
+ // partial descriptor fixture (no `ns`) still resolves correctly.
202
+ const providers = isRecord(source) && isRecord(source.user)
203
+ ? source.user.providers
204
+ : isRecord(source) ? source.providers : undefined
205
+ if (!isRecord(providers)) return undefined
206
+ const sections: Record<string, unknown> = {}
207
+ for (const route of routes) {
208
+ const data = providers[route]
209
+ if (isRecord(data)) sections[route] = data
210
+ }
211
+ return sections
212
+ }
213
+
214
+ /** Fingerprint of the current `opencode-go*` sections (empty object when absent). */
215
+ export function fingerprintGoRoutes(
216
+ source: SettingsDescriptor | Record<string, unknown> | undefined,
217
+ routes?: readonly string[],
218
+ ): string {
219
+ return fingerprintSection(readGoProviderSections(source, routes) ?? {})
220
+ }
221
+
222
+ // --- Two-level applied fingerprint (§14.7.4) --------------------------------
223
+ //
224
+ // Only STABLE fields take part in drift detection:
225
+ // appliedIdentity = sha256(canonical({ <route>: {api, baseURL, displayName,
226
+ // apiKeyEnv} })) — from settings
227
+ // appliedManagedIds = { <route>: sorted ids in the ownership ledger } — from ledger
228
+ // appliedFingerprint = sha256(canonical({ appliedIdentity, appliedManagedIds }))
229
+ //
230
+ // Excluded on purpose: models[] capacity/capability fields (name,
231
+ // contextWindow, maxTokens, input, reasoningEfforts, compat — all rewritten
232
+ // every sync round), user-owned ids, model order, modelOverrides, and any
233
+ // time/usage field. Those are handled by the managed-vs-user-owned repair
234
+ // rules, never by closing the gate. Identity fields are never rewritten by a
235
+ // sync round, and the ledger ids change only through our own successful
236
+ // writes (which immediately re-persist the fingerprint), so a normal sync
237
+ // cannot create an identity-level mismatch. An external identity edit →
238
+ // `drifted`; an external models edit → still `applied`.
239
+ const IDENTITY_FIELDS = ['api', 'baseURL', 'displayName', 'apiKeyEnv'] as const
240
+
241
+ /** Identity map: only the four stable fields of each present go section. */
242
+ export function goIdentityOf(sections: Record<string, unknown> | undefined): Record<string, Record<string, unknown>> {
243
+ const out: Record<string, Record<string, unknown>> = {}
244
+ for (const [route, section] of Object.entries(sections ?? {})) {
245
+ if (!isRecord(section)) continue
246
+ const entry: Record<string, unknown> = {}
247
+ for (const field of IDENTITY_FIELDS) {
248
+ if (section[field] !== undefined) entry[field] = section[field]
249
+ }
250
+ out[route] = entry
251
+ }
252
+ return out
253
+ }
254
+
255
+ /**
256
+ * Hash of the current route identities — stable across ordinary sync rounds.
257
+ * `routes` restricts the compared set: a record keeps the route set it was
258
+ * written with, so routes created later by a sync round never look like drift.
259
+ */
260
+ export function fingerprintGoIdentity(
261
+ sections: Record<string, unknown> | undefined,
262
+ routes?: readonly string[],
263
+ ): string {
264
+ const all = goIdentityOf(sections)
265
+ if (routes === undefined) return fingerprintSection(all)
266
+ return fingerprintSection(Object.fromEntries(routes.map((route) => [route, all[route] ?? {}])))
267
+ }
268
+
269
+ /** Full applied fingerprint = sha256(canonical({ identity, managedIds })). */
270
+ export function appliedFingerprintOf(
271
+ identity: string,
272
+ managedIds: Record<string, string[]> | undefined,
273
+ ): string {
274
+ return fingerprintSection({ identity, managedIds: managedIds ?? {} })
275
+ }
276
+
277
+ /**
278
+ * ONE route-set convention for the two-level applied fingerprint, shared by
279
+ * `migrationStatusOf` (loadMigrationStatus) and the writer's `onOwnWrite`:
280
+ * identity routes are the record's `appliedIdentityRoutes` (or the routes
281
+ * present in settings when the record has none); managed-id routes are exactly
282
+ * the entries present in the supplied map. A configured-but-absent route must
283
+ * NOT be fabricated as `<route>: []` — migrate/onOwnWrite persist only routes
284
+ * with a real ledger entry, and inventing empty ones here makes the first
285
+ * healthy round look like a fingerprint drift (`fingerprint-healed` noise).
286
+ */
287
+ export function appliedFingerprintFieldsOf(
288
+ sections: Record<string, unknown> | undefined,
289
+ record: { appliedIdentityRoutes?: string[] } | undefined,
290
+ managedIds: Record<string, string[]> | undefined,
291
+ ): { identity: string; appliedFingerprint: string } {
292
+ const identityRoutes = record?.appliedIdentityRoutes ?? Object.keys(sections ?? {})
293
+ const identity = fingerprintGoIdentity(sections, identityRoutes)
294
+ return { identity, appliedFingerprint: appliedFingerprintOf(identity, managedIds) }
295
+ }
296
+
297
+ /**
298
+ * Ledger ids for exactly the routes that HAVE a ledger entry. This is the
299
+ * managed-id half of the shared fingerprint convention above: no entry means
300
+ * no route in the map (never an empty array), so a normal first onboarding and
301
+ * a later own write hash identically. Unreadable entries are skipped too —
302
+ * the strict per-mutate gate already fails closed on a record read failure.
303
+ */
304
+ export async function goLedgerManagedIds(
305
+ routes: readonly string[],
306
+ readEntry: (route: string) => Promise<{ managed?: Record<string, unknown> } | undefined>,
307
+ ): Promise<Record<string, string[]>> {
308
+ const managedIds: Record<string, string[]> = {}
309
+ for (const route of routes) {
310
+ let entry: { managed?: Record<string, unknown> } | undefined
311
+ try {
312
+ entry = await readEntry(route)
313
+ } catch {
314
+ continue // unreadable ledger ⇒ no managed ids (never delete), no fabricated entry
315
+ }
316
+ if (entry !== undefined) managedIds[route] = Object.keys(entry.managed ?? {}).sort()
317
+ }
318
+ return managedIds
319
+ }
320
+
321
+ function hasInlineModels(sections: Record<string, unknown>, chatRoute: string): boolean {
322
+ const chat = sections[chatRoute]
323
+ return isRecord(chat) && Array.isArray(chat.models)
324
+ }
325
+
326
+ /**
327
+ * Determine migration state (§14.1 / §14.7.4). Order matters: absent →
328
+ * identity-based applied/drifted (new records) → full-fingerprint match
329
+ * (legacy records written before the two-level split) → recorded legacy/drifted
330
+ * → unrecorded legacy form. Only an IDENTITY mismatch is `drifted`: a models
331
+ * edit (capacity fields, user-owned ids, order) leaves identity intact and is
332
+ * repaired by the writer instead of closing the gate.
333
+ */
334
+ export function migrationStateOf(
335
+ sections: Record<string, unknown> | undefined,
336
+ record: MigrationRecord | undefined,
337
+ chatRoute: string = GO_SLOT_ROUTES.chat,
338
+ ): MigrationState {
339
+ if (sections === undefined || Object.keys(sections).length === 0) return 'absent'
340
+ const fingerprint = fingerprintSection(sections)
341
+ if (record?.appliedIdentity !== undefined) {
342
+ return fingerprintGoIdentity(sections, record.appliedIdentityRoutes) === record.appliedIdentity
343
+ ? 'applied' : 'drifted'
344
+ }
345
+ // Backward compatibility with the pre-§14.7.4 full-section fingerprint.
346
+ if (record?.appliedFingerprint !== undefined && fingerprint === record.appliedFingerprint) return 'applied'
347
+ if (record !== undefined && (record.appliedFingerprint !== undefined || record.legacyFingerprint !== undefined)) {
348
+ if (record.legacyFingerprint !== undefined && fingerprint === record.legacyFingerprint) {
349
+ return hasInlineModels(sections, chatRoute) ? 'legacy-inline' : 'legacy-inherit'
350
+ }
351
+ return 'drifted'
352
+ }
353
+ return hasInlineModels(sections, chatRoute) ? 'legacy-inline' : 'legacy-inherit'
354
+ }
355
+
356
+ /**
357
+ * Full status from a settings descriptor (or raw providers object) + record.
358
+ * `currentManagedIds`, when supplied, comes from the live ownership ledger and
359
+ * drives the §14.7.4 self-heal check (identity matches but the stored full
360
+ * fingerprint is stale because the fingerprint write failed after a commit).
361
+ */
362
+ export function migrationStatusOf(
363
+ source: SettingsDescriptor | Record<string, unknown> | undefined,
364
+ record: MigrationRecord | undefined,
365
+ routes?: readonly string[],
366
+ currentManagedIds?: Record<string, string[]>,
367
+ ): MigrationStatus {
368
+ const sections = readGoProviderSections(source, routes)
369
+ // Compare only the route set the record was written with — routes added by a
370
+ // later sync round must not invalidate an otherwise unchanged identity. The
371
+ // shared helper keeps this EXACT route set in sync with onOwnWrite, so a
372
+ // healthy round cannot emit a phantom `fingerprint-healed`.
373
+ const managedIds = currentManagedIds ?? record?.appliedManagedIds ?? {}
374
+ const { identity, appliedFingerprint: expectedFingerprint } = appliedFingerprintFieldsOf(
375
+ sections, record, managedIds,
376
+ )
377
+ return {
378
+ state: migrationStateOf(sections, record, routes?.[0] ?? GO_SLOT_ROUTES.chat),
379
+ fingerprint: fingerprintSection(sections ?? {}),
380
+ identity,
381
+ appliedIdentity: record?.appliedIdentity,
382
+ appliedManagedIds: record?.appliedManagedIds,
383
+ appliedFingerprint: record?.appliedFingerprint,
384
+ legacyFingerprint: record?.legacyFingerprint,
385
+ applying: record?.applying === true,
386
+ fingerprintHealed: record?.appliedIdentity !== undefined
387
+ && identity === record.appliedIdentity
388
+ && record.appliedFingerprint !== expectedFingerprint,
389
+ expectedFingerprint,
390
+ }
391
+ }
392
+
393
+ // ---------------------------------------------------------------------------
394
+ // Single-writer route authority (pure)
395
+ // ---------------------------------------------------------------------------
396
+
397
+ /** True for any configured go route id or the `opencode-go*` prefix. */
398
+ export function isGoRoute(route: string, customRoutes?: readonly string[]): boolean {
399
+ if (customRoutes?.includes(route) === true) return true
400
+ return Object.values(GO_SLOT_ROUTES).includes(route) || route.startsWith('opencode-go')
401
+ }
402
+
403
+ function isZenRoute(route: string, cfg: RouteWriterConfig): boolean {
404
+ if (cfg.zenRoutes?.includes(route) === true) return true
405
+ return route.startsWith('opencode-zen')
406
+ }
407
+
408
+ /**
409
+ * The single decision point every write path must call before settings.mutate.
410
+ *
411
+ * Rules (§14.7.1, task P1d-1):
412
+ * - go.enabled=true + caller≠'go' on an `opencode-go*` route → always skip;
413
+ * the legacy pi.dev path may never take over, even if the gate returned none.
414
+ * - go.enabled=true + caller='go' + state=applied with a matching fingerprint,
415
+ * or state=absent → write. legacy-inherit / legacy-inline / drifted → skip
416
+ * (migration gate) and report MIGRATION_GATE_HINT.
417
+ * - `applying` → skip (M-5: auto rounds drop while apply is in progress).
418
+ * - go.enabled=false → v0.9.0 behavior restored for go routes (pi.dev owner).
419
+ * - zen routes mode: only the zen writer owns zen routes; other routes are
420
+ * unaffected (pi.dev owner) and keep their original behavior.
421
+ */
422
+ export function routeWriter(
423
+ route: string,
424
+ cfg: RouteWriterConfig,
425
+ migration: MigrationStatus,
426
+ ): RouteWriterDecision {
427
+ const goRoute = isGoRoute(route, cfg.goRoutes)
428
+
429
+ if (goRoute && cfg.goEnabled) {
430
+ if (cfg.caller !== 'go') {
431
+ return {
432
+ decision: 'skip',
433
+ owner: 'go',
434
+ reason: 'skipped-route-owner: go (single-writer: opencode.go.enabled=true; legacy pi.dev path must never write opencode-go* routes)',
435
+ }
436
+ }
437
+ if (migration.applying) {
438
+ return {
439
+ decision: 'skip',
440
+ owner: 'none',
441
+ reason: `skipped-route-owner: none (migration applying; ${MIGRATION_GATE_HINT})`,
442
+ }
443
+ }
444
+ // §14.7.4: a record with `appliedIdentity` is judged applied by IDENTITY
445
+ // match alone — models edits must not close the gate. Legacy records fall
446
+ // back to the full-section fingerprint equality they were written with.
447
+ if (migration.state === 'applied'
448
+ && ((migration.appliedIdentity !== undefined && migration.identity === migration.appliedIdentity)
449
+ || (migration.appliedFingerprint !== undefined && migration.fingerprint === migration.appliedFingerprint))) {
450
+ return { decision: 'write', owner: 'go', reason: 'owner=go (migration applied; identity/fingerprint matched)' }
451
+ }
452
+ if (migration.state === 'absent') {
453
+ return { decision: 'write', owner: 'go', reason: 'owner=go (absent; no pre-existing section to migrate)' }
454
+ }
455
+ return {
456
+ decision: 'skip',
457
+ owner: 'none',
458
+ reason: `skipped-route-owner: none (migration gate: ${migration.state}; ${MIGRATION_GATE_HINT})`,
459
+ }
460
+ }
461
+
462
+ // go.enabled=false (or non-go route): zen routes still have a single owner.
463
+ if (cfg.zenMode === 'routes' && isZenRoute(route, cfg)) {
464
+ if (cfg.caller !== 'zen') {
465
+ return { decision: 'skip', owner: 'zen', reason: 'skipped-route-owner: zen (zen routes mode: only the zen writer owns zen routes)' }
466
+ }
467
+ return { decision: 'write', owner: 'zen', reason: 'owner=zen' }
468
+ }
469
+
470
+ // Everything else keeps the original pi.dev behavior. A go caller writing a
471
+ // non-go route is a no-op in practice; allow it so callers can pass a uniform
472
+ // decision function without changing other routes' semantics.
473
+ return { decision: 'write', owner: 'pi.dev', reason: 'owner=pi.dev' }
474
+ }
475
+
476
+ // ---------------------------------------------------------------------------
477
+ // Injected store (production adapter reads the same models-store JSON)
478
+ // ---------------------------------------------------------------------------
479
+
480
+ /**
481
+ * Build a migration store over the models-store raw-slot accessor.
482
+ *
483
+ * `profileKey` scopes the record slot to `<profileKey>#migration:opencode-go`
484
+ * and stamps the same identity into the record. Reads require the stamp to
485
+ * match — a record from another profile (or an unscoped legacy record with no
486
+ * stamp) is treated as "no record", so state detection falls back to
487
+ * legacy/absent and the migration gate stays closed. Omitting `profileKey`
488
+ * keeps the pre-fix unscoped behavior for legacy callers/tests only.
489
+ */
490
+ export function createFileMigrationStateStore(
491
+ accessor: ModelsStoreAccessor,
492
+ profileKey?: string,
493
+ ): MigrationStateStore {
494
+ const slot = profileKey === undefined
495
+ ? GO_MIGRATION_STORE_KEY
496
+ : scopedStoreKey(profileKey, GO_MIGRATION_STORE_KEY)
497
+ return {
498
+ async read(): Promise<MigrationRecord | undefined> {
499
+ let raw: unknown
500
+ try {
501
+ raw = await accessor.readRaw(slot)
502
+ } catch {
503
+ return undefined // unreadable ⇒ no record ⇒ conservative legacy detection
504
+ }
505
+ if (!isRecord(raw)) return undefined
506
+ // Read-side ownership check (B1): never adopt a record stamped for a
507
+ // different profile, and never claim an unstamped legacy record.
508
+ if (profileKey !== undefined && raw.profileKey !== profileKey) return undefined
509
+ return raw as unknown as MigrationRecord
510
+ },
511
+ async write(record: MigrationRecord): Promise<void> {
512
+ // writeRaw is queue-serialized atomic temp+rename, i.e. the SAME queue
513
+ // that persists the ownership ledger (§14.7.4: settings → ledger → fingerprint).
514
+ const stamped: MigrationRecord = profileKey === undefined ? record : { ...record, profileKey }
515
+ await accessor.writeRaw(slot, stamped as unknown as Record<string, unknown>)
516
+ },
517
+ async legacyKeys(): Promise<string[]> {
518
+ const keys = await accessor.listRawKeys()
519
+ return keys.filter((key) => key === GO_MIGRATION_STORE_KEY || isUnscopedStoreKey(key))
520
+ },
521
+ async unclaimedRecords(): Promise<UnclaimedMigrationRecord[]> {
522
+ // No resolved profile → no "foreign" notion; legacy callers keep their
523
+ // pre-fix read behavior. Status in production always has a profileKey.
524
+ if (profileKey === undefined) return []
525
+ const keys = await accessor.listRawKeys()
526
+ const out: UnclaimedMigrationRecord[] = []
527
+ for (const key of keys) {
528
+ const isUnscopedSlot = key === GO_MIGRATION_STORE_KEY
529
+ const isScopedSlot = !isUnscopedSlot && key.endsWith(`#${GO_MIGRATION_STORE_KEY}`)
530
+ if (!isUnscopedSlot && !isScopedSlot) continue
531
+ let raw: unknown
532
+ try {
533
+ raw = await accessor.readRaw(key)
534
+ } catch {
535
+ continue // unreadable slot is advisory only; never changes the gate
536
+ }
537
+ if (!isRecord(raw)) continue
538
+ const stamp = typeof raw.profileKey === 'string' && raw.profileKey.length > 0
539
+ ? raw.profileKey : undefined
540
+ if (stamp === profileKey) continue // our own record — claimable as before
541
+ const kind: UnclaimedMigrationRecord['kind'] = stamp === undefined ? 'legacy-store' : 'foreign-profile'
542
+ out.push(stamp === undefined ? { kind, key } : { kind, key, profileKey: stamp })
543
+ }
544
+ return out
545
+ },
546
+ }
547
+ }
548
+
549
+ /** Production factory; tests pass a temp-file accessor or inject a fake store. */
550
+ export function createModelsStoreMigrationStateStore(storePath?: string, profileKey?: string): MigrationStateStore {
551
+ return createFileMigrationStateStore(loadModelsStore(storePath), profileKey)
552
+ }