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