@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,541 +0,0 @@
1
- // P1c orchestration: one opencode-go sync round = source → planner → writer.
2
- //
3
- // The three layers stay separate (design §6.2.1): the source owns the network
4
- // read, the planner is pure, the writer owns the only settings write path.
5
- // This module adds only glue + report formatting. Every I/O dependency
6
- // (settings, ledger store, override store, fetch, logger) is injected, so the
7
- // whole round can be exercised offline with mocks and a temp-dir store.
8
- //
9
- // No timer lives here (P1c-2 owns scheduling). No command registration lives
10
- // here either (index.ts owns the cordis/command surface). No credentials are
11
- // read here — the caller resolves the key value through the existing cordis
12
- // credential seam and passes it in.
13
-
14
- import { GO_SLOT_ROUTES, type GoRouteSlot } from './opencode-go-grouping.ts'
15
- import { goOwnershipKey, planGoRoutes, type GoOwnershipEntry, type GoOwnershipLedger, type GoRouteState } from './opencode-go-planner.ts'
16
- import { fetchGoOfficialModels, type GoFetchLike, type GoSourceResult } from './opencode-go-source.ts'
17
- import {
18
- writeGoPlan,
19
- type GoCanWriteDecision,
20
- type GoOverrideStorer,
21
- type GoOwnershipStore,
22
- type GoWriteResult,
23
- } from './opencode-go-writer.ts'
24
- import type { SettingsModelProfile } from './translate.ts'
25
- import type { Logger, SettingsDescriptor, SettingsService } from './writer.ts'
26
- import { routeWriter, type MigrationStatus } from './opencode-go-migration.ts'
27
- import {
28
- formatReconcileSummary,
29
- reconcileJournals,
30
- type GoJournalStore,
31
- type ReconcileResult,
32
- } from './opencode-go-journal.ts'
33
-
34
- /**
35
- * Cordis service names used only as injection seams. Both are optional:
36
- * production falls back to the real file store and the global fetch; tests
37
- * register a temp-dir store / stub fetch under these names to run a full round
38
- * with zero filesystem writes outside a temp dir and zero network.
39
- */
40
- export const GO_OWNERSHIP_STORE_SERVICE = 'goOwnershipStore'
41
- export const GO_OVERRIDE_STORER_SERVICE = 'goOverrideStorer'
42
- export const GO_FETCH_SERVICE = 'goFetchImpl'
43
-
44
- /** The go subset of the published Config contract (design §6.2.6). */
45
- export interface GoSyncRuntimeConfig {
46
- /** Master switch (design §6.2.6: false = zero behavior change). */
47
- enabled: boolean
48
- ref: string
49
- modelsUrl: string
50
- routes: Partial<Record<GoRouteSlot, string>>
51
- pinnedModels: readonly string[]
52
- confirmRemovals: number
53
- adoptExisting: boolean
54
- }
55
-
56
- export interface GoRoundDeps {
57
- settings: SettingsService | undefined
58
- ownershipStore: GoOwnershipStore
59
- overrideStorer?: GoOverrideStorer
60
- logger: Logger
61
- config: GoSyncRuntimeConfig
62
- /**
63
- * Host runtime catalog ids for opencode-go (0.12.1). An ARRAY intersects the
64
- * desired set with it (ids the host catalog does not know are reported as
65
- * `needs-host-catalog`, never written). `null` FAILS THE ROUND CLOSED —
66
- * zero writes — because writing the unverified full listing is exactly how
67
- * 0.12.0 got the whole mutate rejected by the host. `undefined` (pure unit
68
- * callers only; production always supplies one of the two) keeps the 0.12.0
69
- * behavior.
70
- */
71
- hostCatalogIds?: readonly string[] | null
72
- /** Resolved credential VALUE; undefined/empty means no request and no write (V4). */
73
- apiKey?: string
74
- /** Injectable network; production falls back to the global fetch in the source. */
75
- fetchImpl?: GoFetchLike
76
- /** Deterministic clock for tests. */
77
- observedAt?: number
78
- /** Plugin-lifetime signal; aborted mid-round stops the fetch and blocks the writer. */
79
- signal?: AbortSignal
80
- /**
81
- * Current migration status (§14.1). Defaults to `absent` for direct unit
82
- * callers that only exercise writer mechanics; the production wiring in
83
- * index.ts always passes the real status read from the settings + record.
84
- */
85
- migration?: MigrationStatus
86
- /**
87
- * §14.7.5: re-read the PERSISTED migration status for the second gate, called
88
- * before every mutate. Production passes `loadMigrationStatus`; without it
89
- * there is NO second gate (pure writer-mechanics callers) — the round-level
90
- * snapshot is never reused. A failed re-read is reported as
91
- * `canWrite-unavailable` and skips the route (fail closed).
92
- */
93
- reloadMigration?: () => Promise<MigrationStatus>
94
- /** §14.7.4: forward the post-own-write managed ids to the record persister.
95
- * The third argument marks a whole-section unset (ledger key deleted). */
96
- onOwnWrite?: (route: string, managedIds: string[], info?: { unset: boolean }) => Promise<void>
97
- /**
98
- * O1/C2: file-backed write-ahead journal store. With `profileKey` and
99
- * `keyFingerprint`, the round reconciles surviving journals BEFORE the
100
- * migration gate (a closed gate must still self-heal). Omitted by pure unit
101
- * callers — no journal, no reconciliation, pre-C2 behavior.
102
- */
103
- journalStore?: GoJournalStore
104
- /** O1/C2: stable profile key used to scope reconciliation. */
105
- profileKey?: string
106
- /** O1/C2: current credential fingerprint; journals stamped with another key
107
- * are orphans and are discarded, never replayed. */
108
- keyFingerprint?: string
109
- }
110
-
111
- export type GoRoundReason =
112
- | 'disabled'
113
- | 'settings-unavailable'
114
- | 'no-key'
115
- | 'source-failed'
116
- // oldfox #3: an unexpected exception inside writeGoPlan is a writer error,
117
- // not a source failure. Distinct machine-readable reason matching the
118
- // "writer error" text; the scheduler only backs off on source-failed, so a
119
- // writer exception keeps normal-interval retry semantics.
120
- | 'writer-error'
121
- | 'aborted'
122
- | 'migration-gate'
123
- | 'settings-changed-during-sync'
124
- // 0.12.1: the host runtime catalog could not be read — fail closed, zero
125
- // writes (never write an unverified listing the host may reject wholesale).
126
- | 'host-catalog-unavailable'
127
- // O1-minimal: one or more routes had failedRoutes (including the truthful
128
- // "settings written but not recorded" case). The command surface reports
129
- // kind:'error' for it, not a clean success.
130
- | 'write-failed'
131
- | 'completed'
132
-
133
- export interface GoSyncRoundResult {
134
- ok: boolean
135
- reason: GoRoundReason
136
- source?: GoSourceResult
137
- write?: GoWriteResult
138
- /**
139
- * B4 (31, design §14.7.5): set only when the host settings document revision
140
- * moved while the official catalog request was in flight, i.e. the round was
141
- * abandoned before building a plan/writing anything. Machine-readable
142
- * companion to the user-visible `text` (no write, no ledger/fingerprint).
143
- */
144
- settingsChanged?: { beforeRevision: number; afterRevision: number }
145
- /** O1/C2: outcome of the pre-gate journal reconciliation (when wired). */
146
- journal?: ReconcileResult
147
- /** Human-readable lines for `/model-sync` and the auto-round logger. */
148
- text: string
149
- }
150
-
151
- function llmDescriptor(settings: SettingsService | undefined): SettingsDescriptor | undefined {
152
- return settings?.describe().find((desc) => desc.ns === 'llm-pi-ai')
153
- }
154
-
155
- function isRecord(value: unknown): value is Record<string, unknown> {
156
- return typeof value === 'object' && value !== null && !Array.isArray(value)
157
- }
158
-
159
- /** Raw current state of one route (no schema defaults — hashes must match the writer's). */
160
- function readRouteState(desc: SettingsDescriptor | undefined, route: string): GoRouteState {
161
- const providers = desc?.user?.providers
162
- const data = isRecord(providers) ? providers[route] : undefined
163
- if (!isRecord(data)) return { exists: false, models: [] }
164
- const models = Array.isArray(data.models) ? data.models as SettingsModelProfile[] : []
165
- const overrideIds = isRecord(data.modelOverrides) ? Object.keys(data.modelOverrides) : []
166
- const state: GoRouteState = { exists: true, models, overrideIds }
167
- for (const field of ['api', 'baseURL', 'displayName', 'apiKeyEnv'] as const) {
168
- const value = data[field]
169
- if (typeof value === 'string') state[field] = value
170
- }
171
- // M1: keys outside the plugin's known field set are user content (headers,
172
- // custom config) — a whole-route unset would destroy them, so the planner's
173
- // fully-managed verdict never fires while any exist.
174
- const knownFields = new Set(['api', 'baseURL', 'displayName', 'apiKeyEnv', 'models', 'modelOverrides'])
175
- const unknownKeys = Object.keys(data).filter((key) => !knownFields.has(key))
176
- if (unknownKeys.length > 0) state.unknownKeys = unknownKeys
177
- return state
178
- }
179
-
180
- /** Round stopped by a plugin-unload abort: last-good settings are untouched. */
181
- function abortedResult(source: GoSourceResult): GoSyncRoundResult {
182
- return {
183
- ok: false,
184
- reason: 'aborted',
185
- source,
186
- text: 'opencode-go: round aborted (plugin unload); kept last-good, no settings write',
187
- }
188
- }
189
-
190
- /**
191
- * B4: the user edited settings while the /v1/models request was in flight.
192
- * The pre-fetch descriptor is stale, so the round is discarded in full — no
193
- * settings mutate, no ledger commit, no fingerprint update — and a later round
194
- * re-reads current settings and retries. Never reuse the stale plan here.
195
- */
196
- function settingsChangedResult(source: GoSourceResult, beforeRevision: number, afterRevision: number): GoSyncRoundResult {
197
- return {
198
- ok: false,
199
- reason: 'settings-changed-during-sync',
200
- source,
201
- settingsChanged: { beforeRevision, afterRevision },
202
- text: [
203
- `opencode-go: settings changed during the /v1/models fetch (llm-pi-ai revision ${beforeRevision} -> ${afterRevision}); discarding this round`,
204
- ' user edits were kept as-is: no settings write, no ownership ledger change, no fingerprint update',
205
- ' the next round re-reads the current settings and retries normally',
206
- ].join('\n'),
207
- }
208
- }
209
-
210
- /**
211
- * B4/N1: the writer detected a settings revision change after the round was
212
- * validated — the plan went stale. Usually no mutate landed, but a mid-loop
213
- * race can leave earlier routes already written (S7); in that case report the
214
- * written and discarded routes explicitly instead of claiming "no settings
215
- * write". The zero-write wording is kept byte-identical when nothing landed.
216
- */
217
- function writerSettingsChangedResult(
218
- source: GoSourceResult,
219
- beforeRevision: number | undefined,
220
- afterRevision: number,
221
- write: GoWriteResult,
222
- ): GoSyncRoundResult {
223
- const landed = write.settingsLandedRoutes
224
- const discarded = write.routes
225
- .filter((r) => r.status === 'skipped' && r.reason === 'settings-changed-during-sync')
226
- .map((r) => r.route)
227
- const honesty = landed.length === 0
228
- ? ' user edits were kept as-is: no settings write, no ownership ledger change, no fingerprint update'
229
- : ` already written this round: [${landed.join(', ')}]; discarded with no settings write: [${discarded.length === 0 ? 'none' : discarded.join(', ')}]; no ownership ledger/fingerprint update for the discarded routes`
230
- return {
231
- ok: false,
232
- reason: 'settings-changed-during-sync',
233
- source,
234
- settingsChanged: { beforeRevision: beforeRevision ?? -1, afterRevision },
235
- text: [
236
- `opencode-go: settings changed during this sync round (llm-pi-ai revision ${String(beforeRevision)} -> ${afterRevision}); discarding the stale plan`,
237
- honesty,
238
- ' the next round re-reads the current settings and retries normally',
239
- ].join('\n'),
240
- }
241
- }
242
-
243
- /**
244
- * Read only this key's ledger slots. A slot that cannot be read is treated as
245
- * absent — the writer then refuses to delete (no hash), the safe direction.
246
- */
247
- async function readOwnership(
248
- store: GoOwnershipStore,
249
- fingerprint: string,
250
- routes: readonly string[],
251
- ): Promise<GoOwnershipLedger> {
252
- const ledger: Record<string, GoOwnershipEntry> = {}
253
- for (const route of new Set(routes)) {
254
- const key = goOwnershipKey(route, fingerprint)
255
- try {
256
- const entry = await store.read(key)
257
- if (entry !== undefined) ledger[key] = entry
258
- } catch {
259
- // No ledger for this route this round → never delete.
260
- }
261
- }
262
- return ledger
263
- }
264
-
265
- /** One complete go round. Never throws for expected source/store failures. */
266
- export async function runGoSyncRound(deps: GoRoundDeps): Promise<GoSyncRoundResult> {
267
- const { settings, ownershipStore, logger, config } = deps
268
- const routes = { ...GO_SLOT_ROUTES, ...(config.routes ?? {}) }
269
- const desc = llmDescriptor(settings)
270
-
271
- if (!config.enabled) {
272
- return {
273
- ok: false,
274
- reason: 'disabled',
275
- text: 'opencode-go sync is disabled — set opencode.go.enabled=true to write its routes (design §6.2.6: zero behavior change by default)',
276
- }
277
- }
278
-
279
- if (settings === undefined || desc === undefined) {
280
- return {
281
- ok: false,
282
- reason: 'settings-unavailable',
283
- text: 'opencode-go: skipped — settings service / llm-pi-ai namespace unavailable; no request, no write',
284
- }
285
- }
286
-
287
- const apiKey = typeof deps.apiKey === 'string' ? deps.apiKey.trim() : ''
288
- if (apiKey === '') {
289
- return {
290
- ok: false,
291
- reason: 'no-key',
292
- text: `opencode-go: skipped — no credential value for ${config.ref}; no /v1/models request sent, no settings write (design V4)`,
293
- }
294
- }
295
-
296
- // O1/C2: reconcile BEFORE the migration gate. A crashed first write leaves
297
- // sections present but no migration record → `legacy-inline` closes the gate
298
- // forever; reconciliation runs even on that closed-gate round so the record
299
- // can be re-committed and the gate reopened. It writes only the store/record
300
- // (never settings) and validates profile scope + key fingerprint per slot.
301
- let journalResult: ReconcileResult | undefined
302
- let journalPrefix = ''
303
- if (deps.journalStore !== undefined && deps.profileKey !== undefined && deps.keyFingerprint !== undefined) {
304
- journalResult = await reconcileJournals({
305
- journalStore: deps.journalStore,
306
- ownershipStore,
307
- settings,
308
- profileKey: deps.profileKey,
309
- keyFingerprint: deps.keyFingerprint,
310
- logger,
311
- onRecord: deps.onOwnWrite,
312
- })
313
- const summary = formatReconcileSummary(journalResult)
314
- journalPrefix = [summary, ...journalResult.lines].filter((line) => line.length > 0).join('\n') + '\n'
315
- }
316
- const withJournal = (round: GoSyncRoundResult): GoSyncRoundResult =>
317
- journalPrefix === '' ? round : { ...round, journal: journalResult, text: journalPrefix + round.text }
318
-
319
- // M-4 migration gate + single writer (§14.6 / §14.7, ADR-008). All go routes
320
- // share one authority decision; when none of them may be written the round
321
- // short-circuits BEFORE the source fetch (zero side effects, explicit report).
322
- let migration: MigrationStatus = deps.migration ?? {
323
- state: 'absent', fingerprint: '', identity: '', applying: false,
324
- fingerprintHealed: false, expectedFingerprint: '',
325
- }
326
- // Reconciliation may have just re-persisted the migration record that was
327
- // missing when this round's snapshot was taken. Re-read it so a reconciled
328
- // S1 can reopen the gate in THIS round instead of waiting for another one.
329
- if ((journalResult?.reconciled.length ?? 0) > 0 && deps.reloadMigration !== undefined) {
330
- try {
331
- migration = await deps.reloadMigration()
332
- } catch {
333
- // Keep the original snapshot; the next round re-reads it anyway.
334
- }
335
- }
336
- const authority = { caller: 'go' as const, goEnabled: config.enabled, goRoutes: Object.values(routes) }
337
- const decisions = Object.values(routes).map((route) => ({ route, decision: routeWriter(route, authority, migration) }))
338
- const blocked = decisions.filter((entry) => entry.decision.decision === 'skip')
339
- if (blocked.length === decisions.length) {
340
- return withJournal({
341
- ok: false,
342
- reason: 'migration-gate',
343
- text: [
344
- 'opencode-go: migration gate — zero settings writes, no /v1/models request',
345
- ...blocked.map(({ route, decision }) => ` [info] ${decision.reason}; route=${route}`),
346
- ].join('\n'),
347
- })
348
- }
349
-
350
- // 0.12.1: fail-closed BEFORE the source fetch (zero side effects, same spirit
351
- // as the migration gate short-circuit above). Without the host runtime
352
- // catalog there is no servable write: the 0.12.0 full-listing write is what
353
- // got rejected by the host in the first place.
354
- if (deps.hostCatalogIds === null) {
355
- return withJournal({
356
- ok: false,
357
- reason: 'host-catalog-unavailable',
358
- text: [
359
- 'opencode-go: host runtime catalog unavailable — 本轮 fail-closed 中止,零写入、零请求。',
360
- ' 宿主 llm 服务的 discoverModels 未返回目录(服务缺失/未注册/无 opencode-go catalog)。',
361
- ' 为避免再次写入宿主不认识的模型 id(宿主对整条 mutate fail-closed 拒绝),未做任何写入;目录可用后自动恢复。',
362
- ].join('\n'),
363
- })
364
- }
365
-
366
- // B4 (31, design §14.7.5): snapshot the host settings document revision
367
- // BEFORE the network wait. This is only a baseline for the post-fetch
368
- // freshness check below — never a source for the write plan itself.
369
- const preFetchRevision = desc.revision
370
-
371
- let source: GoSourceResult
372
- try {
373
- source = await fetchGoOfficialModels({
374
- url: config.modelsUrl,
375
- apiKey,
376
- fetchImpl: deps.fetchImpl,
377
- observedAt: deps.observedAt,
378
- signal: deps.signal,
379
- })
380
- } catch (err) {
381
- const message = err instanceof Error ? err.message : String(err)
382
- return withJournal({ ok: false, reason: 'source-failed', text: `opencode-go: source error — ${message}; no settings write` })
383
- }
384
-
385
- if (!source.ok) {
386
- const error = source.error
387
- return withJournal({
388
- ok: false,
389
- reason: 'source-failed',
390
- source,
391
- text: `opencode-go: source failed (${error?.kind ?? 'unknown'}${error?.status !== undefined ? ` HTTP ${error.status}` : ''}) — ${error?.message ?? 'unknown error'}; kept last-good, no settings write`,
392
- })
393
- }
394
-
395
- // The plugin may be disposed while the source request (or the ownership
396
- // reads below) is in flight. Never reach the writer after unload (§6.3 卸载).
397
- if (deps.signal?.aborted) return withJournal(abortedResult(source))
398
-
399
- // B4: re-read the descriptor AFTER the fetch. The plan must describe the
400
- // settings we are about to write, not the snapshot used to build the
401
- // request. If the host revision moved during the request window a user edit
402
- // landed here; writing the pre-fetch plan would silently drop it (no even
403
- // SETTINGS_CONFLICT, because the writer's own re-read only sees the new
404
- // revision, not the stale merged models). Discard the whole round instead.
405
- const freshDesc = llmDescriptor(settings)
406
- if (freshDesc === undefined) {
407
- return withJournal({
408
- ok: false,
409
- reason: 'settings-unavailable',
410
- source,
411
- text: 'opencode-go: llm-pi-ai descriptor disappeared during the fetch; no settings write',
412
- })
413
- }
414
- if (freshDesc.revision !== preFetchRevision) {
415
- return withJournal(settingsChangedResult(source, preFetchRevision, freshDesc.revision))
416
- }
417
-
418
- // Plan from the post-fetch descriptor so the write target and the plan are
419
- // the same object (design §14.7.5). No revision bump → no user edit in the
420
- // window → the freshly read state is the correct planning input.
421
- const currentRoutes = Object.fromEntries(
422
- Object.values(routes).map((route) => [route, readRouteState(freshDesc, route)]),
423
- )
424
- const ownership = await readOwnership(ownershipStore, source.keyFingerprint, Object.values(routes))
425
- const plan = planGoRoutes({
426
- keyFingerprint: source.keyFingerprint,
427
- entries: source.entries,
428
- hostCatalogIds: deps.hostCatalogIds,
429
- currentRoutes,
430
- ownership,
431
- ref: config.ref,
432
- routes: config.routes,
433
- pinnedModels: config.pinnedModels,
434
- })
435
-
436
- // Re-check immediately before the only settings mutation: a dispose that
437
- // lands during readOwnership/planning must still produce a zero-write round.
438
- if (deps.signal?.aborted) return withJournal(abortedResult(source))
439
-
440
- // §14.7.5: the second gate ALWAYS re-reads the persisted status on every
441
- // call — the round-level `migration` snapshot is never reused here. Without
442
- // a live reader there is no second gate (pure writer-mechanics callers); a
443
- // failed re-read is fail-closed with a `canWrite-unavailable` report line.
444
- const reloadMigration = deps.reloadMigration
445
- const canWrite = reloadMigration === undefined
446
- ? undefined
447
- : async (route: string): Promise<GoCanWriteDecision> => {
448
- try {
449
- const current = await reloadMigration()
450
- const decision = routeWriter(route, authority, current)
451
- // O1-minimal: pass the routeWriter reason through to the writer's skip
452
- // record/report. Previously every skip collapsed to `route-authority`,
453
- // hiding the real gate/applying/owner decision that revoked authority.
454
- return {
455
- allow: decision.decision === 'write',
456
- reason: decision.decision === 'skip' ? decision.reason : undefined,
457
- }
458
- } catch {
459
- return { allow: false, reason: 'canWrite-unavailable' }
460
- }
461
- }
462
-
463
- let write: GoWriteResult
464
- try {
465
- write = await writeGoPlan(plan, {
466
- settings,
467
- ownershipStore,
468
- overrideStorer: deps.overrideStorer,
469
- logger,
470
- keyFingerprint: source.keyFingerprint,
471
- hostCatalogIds: deps.hostCatalogIds,
472
- confirmRemovals: config.confirmRemovals,
473
- adoptExisting: config.adoptExisting,
474
- // B4/N1: the revision this round validated (post-fetch == pre-fetch).
475
- // The writer re-checks it before every mutate and abandons the whole
476
- // round if a user edit landed in the gap between here and the write.
477
- expectedRevision: preFetchRevision,
478
- canWrite,
479
- onOwnWrite: deps.onOwnWrite,
480
- // O1/C2: same journal store + profile scope used by the pre-gate
481
- // reconciliation, so a surviving slot is written under the key the next
482
- // round will look for.
483
- journalStore: deps.journalStore,
484
- profileKey: deps.profileKey,
485
- })
486
- } catch (err) {
487
- // The source already succeeded above; this is an unexpected writer throw.
488
- // Keep the truthful text and give it a matching reason instead of lying
489
- // with `source-failed` (oldfox #3). No failureKind is attached by the
490
- // scheduler adapter (it is source-only), so no transport/auth backoff is
491
- // scheduled for a writer exception — the normal interval still retries.
492
- const message = err instanceof Error ? err.message : String(err)
493
- return withJournal({
494
- ok: false,
495
- reason: 'writer-error',
496
- source,
497
- text: `opencode-go: writer error — ${message}; settings state is whatever landed before the error`,
498
- })
499
- }
500
-
501
- // B4/N1: the writer abandoned the round because settings changed after
502
- // validation. Do NOT expose a `completed` write or a half-plan here — report
503
- // the same zero-write reason as the fetch-window guard.
504
- if (write.settingsChanged !== undefined) {
505
- return withJournal(writerSettingsChangedResult(
506
- source,
507
- write.settingsChanged.expectedRevision,
508
- write.settingsChanged.actualRevision,
509
- write,
510
- ))
511
- }
512
-
513
- // O1-minimal: a round with failedRoutes is never a clean `completed` success,
514
- // even though some routes may have written settings. The command surface maps
515
- // this reason to kind:'error'. (Only source failures back off — see scheduler.)
516
- const hasFailedRoutes = write.failedRoutes.length > 0
517
- return withJournal({
518
- ok: !hasFailedRoutes,
519
- reason: hasFailedRoutes ? 'write-failed' : 'completed',
520
- source,
521
- write,
522
- text: formatGoRoundReport(source, write),
523
- })
524
- }
525
-
526
- /** Stable, testable report text: source summary, per-route outcome, plan notes. */
527
- export function formatGoRoundReport(source: GoSourceResult, write: GoWriteResult): string {
528
- const lines: string[] = [
529
- `opencode-go: source ok (${source.entries.length} models, key=${source.keyFingerprint}, hash=${(source.payloadHash ?? '').slice(0, 12)})`,
530
- ]
531
- for (const status of write.routes) {
532
- lines.push(` ${status.route}: ${status.status}${status.reason !== undefined ? ` (${status.reason})` : ''}`)
533
- }
534
- for (const entry of write.report) {
535
- lines.push(` [${entry.level}] ${entry.code}${entry.route !== undefined ? ` ${entry.route}` : ''}${entry.id !== undefined ? `/${entry.id}` : ''}: ${entry.message}`)
536
- }
537
- if (write.writtenRoutes.length === 0 && write.failedRoutes.length === 0) {
538
- lines.push(' no settings changes')
539
- }
540
- return lines.join('\n')
541
- }