@aiwayds/dsh-model-sync 0.12.1 → 0.13.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 (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 +116 -0
  10. package/lib/official-migrate.js +643 -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 +840 -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,1301 +0,0 @@
1
- // P1b writer: the one layer that turns an opencode-go route plan into real
2
- // settings writes for the user's profile.
3
- //
4
- // Hard boundary: this module owns the ONLY settings write path for the three
5
- // go routes. It never schedules timers, never fetches, never touches
6
- // credentials, and never edits a patch/doc file directly — every settings
7
- // change goes through `settings.mutate('llm-pi-ai', ops, revision)` (design C6).
8
- // The ownership ledger is persisted through an injected store seam so tests
9
- // can run entirely in memory (no real ~/.dsh). The concrete store-v2 adapter
10
- // (design §6.1) is supplied by the caller when this layer is wired up; wiring
11
- // into the plugin commands/scheduler is deliberately a separate step.
12
- //
13
- // Design refs: §6.1 (ledger key + preManagedSnapshot), §6.2.4 (ownership-aware
14
- // merge, double confirmation), §6.2.5 (route-field ownership), §9.1 (one
15
- // mutate per route), §9.4 (empty route → unset, never `models: []`),
16
- // ADR-004, V5/V9/V13. Rollback lives in opencode-go-migrate.ts.
17
-
18
- import type { SettingsModelProfile } from './translate.ts'
19
- import type { GoRouteSlot } from './opencode-go-grouping.ts'
20
- import {
21
- goOwnershipKey,
22
- profileHash,
23
- GO_LEGACY_ROUTE_FIELDS,
24
- type GoManagedModel,
25
- type GoOwnershipEntry,
26
- type GoPlanReportEntry,
27
- type GoPlanResult,
28
- type GoPlannedRoute,
29
- } from './opencode-go-planner.ts'
30
- import { HOST_CATALOG_PROVIDER } from './opencode-go-host-catalog.ts'
31
- import {
32
- profilesEqual,
33
- type Logger,
34
- type SettingsDescriptor,
35
- type SettingsMutationOp,
36
- type SettingsService,
37
- } from './writer.ts'
38
- import {
39
- goJournalKey,
40
- journalContentHash,
41
- type GoJournalStore,
42
- type GoWriteJournal,
43
- } from './opencode-go-journal.ts'
44
- import { fingerprintSection } from './opencode-go-migration.ts'
45
-
46
- const SETTINGS_CONFLICT = 'SETTINGS_CONFLICT'
47
- // 0.12.0 catalog-reuse: the ONLY route field the writer sets is `apiKeyEnv`.
48
- // `api`/`baseURL` must stay UNSET (they make the host build the provider from
49
- // the bare PROTOCOLS implementation — missing `x-opencode-session` → HTTP 400
50
- // — instead of pi-ai's builtin catalog provider), and `displayName` is a
51
- // display field deliberately never rewritten so a user rename survives.
52
- const OWNED_FIELDS = ['apiKeyEnv'] as const
53
-
54
- // O1-minimal: a settings.mutate can land while the ledger/record write after it
55
- // fails. That route is NOT a clean success (no ledger => next round keeps it as
56
- // user-owned) and NOT a lock-only failure either (retrying does nothing). Report
57
- // it truthfully with its own code + reason + actionable advice.
58
- const UNACCOUNTED_CODE = 'settings-written-unaccounted'
59
- // O1 residual: once settings landed, "the store was NOT modified / retry the
60
- // operation" is a lie — the store that failed is the ledger, not settings, and
61
- // a retry cannot re-claim the route. State the real consequence and recovery.
62
- const UNACCOUNTED_ADVICE = 'settings were written but the ownership ledger was not updated; retrying cannot re-claim the route; the next round reconciles the write-ahead journal (otherwise keeps this route as user-owned: no refresh, no deletion); re-claim it with `/model-sync adopt go`'
63
- // Settings + ledger landed, but the migration record persist failed (S1).
64
- // This is not a failed route (fingerprint-healed next round), but it must not
65
- // be silent: the next round may see the route as un-migrated and close the gate.
66
- const RECORD_ADVICE = 'settings and the ownership ledger landed but the migration record could not be persisted; the next round reconciles the write-ahead journal or self-heals via fingerprint-healed, do not simply retry; re-claim it with `/model-sync adopt go`'
67
-
68
- // ---------------------------------------------------------------------------
69
- // Injected seams
70
- // ---------------------------------------------------------------------------
71
-
72
- /**
73
- * Ownership ledger store (store v2 in design §6.1). Entries are keyed by
74
- * `<route>#<keyFingerprint>`, so one route's ledger is invisible under a
75
- * different key. All methods are async so a file-backed adapter can be used
76
- * in production while tests stay in memory.
77
- */
78
- export interface GoOwnershipStore {
79
- read(key: string): Promise<GoOwnershipEntry | undefined>
80
- write(key: string, entry: GoOwnershipEntry): Promise<void>
81
- delete(key: string): Promise<void>
82
- }
83
-
84
- /** Minimal models-store seam for store-first `modelOverrides` staging (§6.2.4). */
85
- export interface GoOverrideStorer {
86
- read?(route: string): Promise<{ overrides?: Record<string, Record<string, unknown>> } | undefined>
87
- updateOverrides(route: string, overrides: Record<string, Record<string, unknown>>): Promise<void>
88
- }
89
-
90
- export interface GoWriterDeps {
91
- settings: SettingsService | undefined
92
- ownershipStore: GoOwnershipStore
93
- logger: Logger
94
- /** sha256(key) prefix from the source result; `-` when no key. */
95
- keyFingerprint: string
96
- /**
97
- * Host runtime catalog ids for opencode-go (0.12.1). `undefined` keeps the
98
- * 0.12.0 writer behavior. With an array the writer (H5): removes
99
- * deletion-candidates the host catalog does not know IMMEDIATELY (the
100
- * double-round confirmation deadlocks when round 1's write-back is rejected
101
- * wholesale and the counter can never persist), and refuses to write any
102
- * route whose final models array still carries ids outside the catalog
103
- * (fail-closed with an actionable message instead of a raw host rejection).
104
- */
105
- hostCatalogIds?: readonly string[]
106
- /** go.confirmRemovals; default 2 (schema min 2, design §6.2.6). */
107
- confirmRemovals?: number
108
- /**
109
- * go.adoptExisting / `/model-sync adopt go` (design §14.1). With no prior
110
- * ledger the writer claims only desired∩current by default; adopt also
111
- * claims the route's pre-existing models so they become deletion candidates
112
- * on later rounds (still subject to the two-round confirmation + 3 gates).
113
- */
114
- adoptExisting?: boolean
115
- /** Optional models-store seam for override fold + unset (store-first). */
116
- overrideStorer?: GoOverrideStorer
117
- /**
118
- * B4/N1 fail-closed guard: the llm-pi-ai revision the plan was built against
119
- * (the fetch-time / post-validation revision). The writer re-reads the
120
- * descriptor before ANY settings mutate or ledger commit; if the revision
121
- * moved since the round was validated, the plan is stale and the WHOLE round
122
- * is abandoned (zero writes, no ledger/fingerprint). Omitted only by pure
123
- * unit writers that do not have a round-level revision to validate.
124
- */
125
- expectedRevision?: number
126
- /**
127
- * §14.7.5 second gate: called immediately before EACH mutate (and again on a
128
- * SETTINGS_CONFLICT retry). Must re-read the persisted migration status —
129
- * never reuse the round-level snapshot. A false result leaves the route
130
- * untouched (including the ledger); `reason: 'canWrite-unavailable'` is
131
- * reported when the status re-read itself failed (fail closed). Absent means
132
- * no second gate (pure unit writers). A plain boolean is accepted for tests.
133
- */
134
- canWrite?: (route: string) =>
135
- | boolean
136
- | GoCanWriteDecision
137
- | Promise<boolean>
138
- | Promise<GoCanWriteDecision>
139
- /**
140
- * §14.7.4: called ONLY after a route's settings.mutate AND its ledger commit
141
- * both succeeded, with the ledger-managed ids just committed. The callback
142
- * re-persists `appliedFingerprint` through the same store queue. Never called
143
- * for a failed write, a no-change round, or another writer's no-op success.
144
- * H4/M2: the third argument marks a whole-section unset (the ledger key was
145
- * deleted, not written) so the record update can DROP the route's
146
- * `appliedManagedIds` key instead of persisting a phantom `[]` entry no
147
- * ledger backs.
148
- */
149
- onOwnWrite?: (route: string, managedIds: string[], info?: { unset: boolean }) => Promise<void> | void
150
- /**
151
- * O1/C2: write-ahead journal store. When present together with `profileKey`,
152
- * each settings mutate is preceded by a journal slot recording the intended
153
- * ledger entry + the post-write content hash; it is removed only after the
154
- * ledger AND migration record both landed. The next round reconciles any
155
- * surviving journal before the migration gate. Omitted by pure unit writers
156
- * (no file-backed store) — those keep the pre-C2 behavior.
157
- */
158
- journalStore?: GoJournalStore
159
- /** O1/C2: stable profile key for the journal slot (must match reconciliation). */
160
- profileKey?: string
161
- /** O1/C2: injectable clock for the journal timestamp; defaults to Date.now. */
162
- now?: () => number
163
- }
164
-
165
- export interface GoCanWriteDecision {
166
- allow: boolean
167
- /** `canWrite-unavailable` when the live status re-read failed. */
168
- reason?: string
169
- }
170
-
171
- // ---------------------------------------------------------------------------
172
- // Result types
173
- // ---------------------------------------------------------------------------
174
-
175
- export type GoRouteStatus = 'wrote' | 'no-change' | 'unset' | 'skipped' | 'conflict' | 'failed'
176
-
177
- export interface GoRouteWriteStatus {
178
- route: string
179
- slot?: GoRouteSlot
180
- status: GoRouteStatus
181
- reason?: string
182
- }
183
-
184
- export interface GoWriteResult {
185
- /** One entry per planned route, plus one per conflicted route. */
186
- routes: GoRouteWriteStatus[]
187
- /** Routes whose settings.mutate resolved (wrote or unset). */
188
- writtenRoutes: string[]
189
- /** Routes whose mutate failed, with an honest reason. */
190
- failedRoutes: { route: string; reason: string }[]
191
- /**
192
- * O1-minimal: routes whose settings.mutate landed this round, whether or not
193
- * the ledger commit after it succeeded. Used for an honest N1-abandon report
194
- * (a route may have been written before the round was abandoned).
195
- */
196
- settingsLandedRoutes: string[]
197
- /**
198
- * B4/N1: set when the round was abandoned because the host settings revision
199
- * moved mid-round. The caller must report this as
200
- * `settings-changed-during-sync` and treat the round as a zero-write no-op.
201
- */
202
- settingsChanged?: { expectedRevision: number | undefined; actualRevision: number }
203
- /** Planner report adjusted by writer decisions + `moved` association. */
204
- report: GoPlanReportEntry[]
205
- }
206
-
207
- // ---------------------------------------------------------------------------
208
- // Small helpers
209
- // ---------------------------------------------------------------------------
210
-
211
- function findLlmDescriptor(settings: SettingsService): SettingsDescriptor | undefined {
212
- return settings.describe().find((desc) => desc.ns === 'llm-pi-ai')
213
- }
214
-
215
- function rawRoute(desc: SettingsDescriptor | undefined, route: string): Record<string, unknown> | undefined {
216
- if (desc === undefined) return undefined
217
- const providers = desc.user?.providers as Record<string, unknown> | undefined
218
- if (providers === undefined) return undefined
219
- const data = providers[route]
220
- if (data === undefined || data === null || typeof data !== 'object' || Array.isArray(data)) return undefined
221
- return data as Record<string, unknown>
222
- }
223
-
224
- function rawModels(desc: SettingsDescriptor | undefined, route: string): SettingsModelProfile[] {
225
- const models = rawRoute(desc, route)?.models
226
- return Array.isArray(models) ? (models as SettingsModelProfile[]) : []
227
- }
228
-
229
- function sortedModels(models: readonly SettingsModelProfile[]): SettingsModelProfile[] {
230
- return [...models].sort((a, b) => a.id.localeCompare(b.id))
231
- }
232
-
233
- function rawOverrides(
234
- desc: SettingsDescriptor | undefined,
235
- route: string,
236
- ): Record<string, Record<string, unknown>> | undefined {
237
- const value = rawRoute(desc, route)?.modelOverrides
238
- if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
239
- const overrides = value as Record<string, Record<string, unknown>>
240
- return Object.keys(overrides).length > 0 ? overrides : undefined
241
- }
242
-
243
- /** Fold user `modelOverrides` into the target, override wins per field. */
244
- function mergeOverrides(
245
- target: readonly SettingsModelProfile[],
246
- overrides: Record<string, Record<string, unknown>> | undefined,
247
- ): SettingsModelProfile[] {
248
- if (overrides === undefined) return [...target]
249
- return target.map((entry) => {
250
- const override = overrides[entry.id]
251
- if (override === undefined) return entry
252
- return { ...entry, ...override, id: entry.id } as SettingsModelProfile
253
- })
254
- }
255
-
256
- /** Error code on a revision mismatch (matches writer.ts's contract). */
257
- function isConflictError(err: unknown): boolean {
258
- return (err as Record<string, unknown> | undefined)?.code === SETTINGS_CONFLICT
259
- }
260
-
261
- function errorText(err: unknown): string {
262
- // Prefer a structured `message` so re-wrapped plain-object errors still carry
263
- // the actionable text (lock path / retry advice) instead of "[object Object]".
264
- // Error instances already expose `message`; everything else falls back to
265
- // String(err) exactly as before.
266
- const message = (err as { message?: unknown } | null | undefined)?.message
267
- return typeof message === 'string' ? message : String(err)
268
- }
269
-
270
- function isPlainRecord(value: unknown): value is Record<string, unknown> {
271
- return value !== null && typeof value === 'object' && !Array.isArray(value)
272
- }
273
-
274
- /** Clone a JSON-ish settings value without relying on host-specific prototypes. */
275
- function cloneSettingsValue(value: unknown): unknown {
276
- if (Array.isArray(value)) return value.map(cloneSettingsValue)
277
- if (isPlainRecord(value)) {
278
- const out: Record<string, unknown> = {}
279
- for (const [key, nested] of Object.entries(value)) out[key] = cloneSettingsValue(nested)
280
- return out
281
- }
282
- return value
283
- }
284
-
285
- /**
286
- * The exact `user` object this writer's ops would leave behind. Used only to
287
- * hash the expected post-mutate content in the N1 residual-window check; it
288
- * never writes settings. General `providers.*` path handling keeps a future op
289
- * from silently escaping the check.
290
- */
291
- function expectedUserAfterOps(
292
- user: Record<string, unknown> | undefined,
293
- ops: readonly SettingsMutationOp[],
294
- ): Record<string, unknown> {
295
- const out = isPlainRecord(user) ? cloneSettingsValue(user) as Record<string, unknown> : {}
296
- for (const op of ops) {
297
- const [section, route, field, ...rest] = op.path
298
- if (section !== 'providers' || route === undefined || rest.length > 0) continue
299
- const providers = isPlainRecord(out.providers) ? out.providers as Record<string, unknown> : {}
300
- out.providers = providers
301
- if (field === undefined) {
302
- if (op.op === 'unset') delete providers[route]
303
- else providers[route] = cloneSettingsValue(op.value)
304
- continue
305
- }
306
- const base = isPlainRecord(providers[route]) ? providers[route] as Record<string, unknown> : {}
307
- providers[route] = base
308
- if (op.op === 'unset') delete base[field]
309
- else base[field] = cloneSettingsValue(op.value)
310
- }
311
- return out
312
- }
313
-
314
- /**
315
- * O1 residual: a settings-landed ledger timeout must not repeat the stock
316
- * "store NOT modified / retry" claim. Keep the lock diagnostics (path, wait,
317
- * stale-lock note) but drop those two false sentences. A final guard covers
318
- * re-wrapped errors whose wording differs from the stock seam.
319
- */
320
- function truthfulLockDetail(detail: string): string {
321
- const cleaned = detail
322
- .replace(/The store was NOT modified\.?\s*/gi, '')
323
- .replace(/Retry the operation\s*[;,.]\s*/gi, '')
324
- .replace(/if it keeps failing, check other running dsh processes(?: for a stalled sync round holding the lock)?\.?\s*/gi, '')
325
- .replace(/\s{2,}/g, ' ')
326
- .trim()
327
- return /not modified|retry the operation/i.test(cleaned)
328
- ? 'lock error detail contained misleading retry advice (the ownership ledger store was not written; see the actionable note below)'
329
- : cleaned
330
- }
331
-
332
- /** Structural check for a store lock timeout (survives re-wrapping / module boundaries). */
333
- function isStoreLockTimeout(err: unknown): boolean {
334
- if (err === null || typeof err !== 'object') return false
335
- const value = err as { code?: unknown; name?: unknown }
336
- return value.code === 'DSH_STORE_LOCK_TIMEOUT' || value.name === 'StoreLockTimeoutError'
337
- }
338
-
339
- /**
340
- * Record a route whose write hit a store lock timeout. The original error
341
- * message carries the lock path and the retry / check-other-processes advice:
342
- * keep it verbatim in the report and in the failed-route reason so the user
343
- * sees an actionable cause instead of a generic failure. The route is marked
344
- * `failed` and deliberately NOT added to `writtenRoutes`.
345
- *
346
- * O1-minimal: when `settingsLanded` is true the timeout happened on the ledger
347
- * AFTER settings were written. The stock "The store was NOT modified. Retry the
348
- * operation" text is then misleading (retry will not re-claim the route), so
349
- * the report uses the truthful `settings-written-unaccounted` code, strips those
350
- * two false sentences from the detail, and carries the real advice. The zero-
351
- * write path keeps the original detail verbatim for diagnosis.
352
- */
353
- function recordLockTimeout(
354
- result: GoWriteResult,
355
- report: GoPlanReportEntry[],
356
- planned: GoPlannedRoute,
357
- err: unknown,
358
- phase: string,
359
- settingsLanded = false,
360
- ): void {
361
- const reason = settingsLanded ? UNACCOUNTED_CODE : 'store-lock-timeout'
362
- const detail = settingsLanded ? truthfulLockDetail(errorText(err)) : errorText(err)
363
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'failed', reason })
364
- result.failedRoutes.push({ route: planned.route, reason })
365
- report.push({
366
- level: 'error',
367
- code: reason,
368
- route: planned.route,
369
- slot: planned.slot,
370
- message: settingsLanded
371
- ? `route ${planned.route} ${phase} hit a store lock timeout after settings were written: ${detail}. ${UNACCOUNTED_ADVICE}`
372
- : `route ${planned.route} ${phase} hit a store lock timeout: ${detail}`,
373
- })
374
- }
375
-
376
- /** Outcome of a ledger commit: `lockTimeout` is the original error when it was a lock wait timeout. */
377
- interface LedgerCommitResult {
378
- committed: boolean
379
- lockTimeout?: unknown
380
- }
381
-
382
- /** Normalize the second-gate seam (boolean shorthand or structured decision). */
383
- async function canWriteDecision(deps: GoWriterDeps, route: string): Promise<GoCanWriteDecision | undefined> {
384
- if (deps.canWrite === undefined) return undefined
385
- const raw = await deps.canWrite(route)
386
- return typeof raw === 'boolean' ? { allow: raw } : raw
387
- }
388
-
389
- /** Non-silent skip for a route whose authority was revoked before its mutate. */
390
- function skipByCanWrite(
391
- result: GoWriteResult,
392
- report: GoPlanReportEntry[],
393
- planned: GoPlannedRoute,
394
- decision: GoCanWriteDecision,
395
- ): void {
396
- const reason = decision.reason ?? 'route-authority'
397
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'skipped', reason })
398
- report.push({
399
- level: decision.reason === 'canWrite-unavailable' ? 'warn' : 'info',
400
- code: decision.reason === 'canWrite-unavailable' ? 'canWrite-unavailable' : 'skipped-route-owner',
401
- route: planned.route,
402
- slot: planned.slot,
403
- message: `route ${planned.route} skipped by routeWriter (${reason}); no settings write`,
404
- })
405
- }
406
-
407
- /**
408
- * §14.7.4: persist the new applied fingerprint only after settings+ledger
409
- * success. Returns true only when the record is actually persisted (or there
410
- * is nothing to persist) — C2 keeps the journal open on false so the next
411
- * round can re-persist it instead of silently closing the migration gate.
412
- */
413
- async function recordOwnWrite(
414
- deps: GoWriterDeps,
415
- route: string,
416
- managedIds: string[],
417
- report: GoPlanReportEntry[],
418
- unset = false,
419
- ): Promise<boolean> {
420
- if (deps.onOwnWrite === undefined) return true
421
- try {
422
- await deps.onOwnWrite(route, managedIds, { unset })
423
- return true
424
- } catch (err) {
425
- if (isStoreLockTimeout(err)) {
426
- // Settings + ledger already landed, so this is not a failed route, but a
427
- // lock timeout here must still be visible with its actionable message.
428
- deps.logger.warn('appliedFingerprint lock timeout for %s: %s', route, errorText(err))
429
- report.push({
430
- level: 'warn',
431
- code: UNACCOUNTED_CODE,
432
- route,
433
- message: `route ${route} appliedFingerprint re-persist hit a store lock timeout: ${truthfulLockDetail(errorText(err))}. ${RECORD_ADVICE}`,
434
- })
435
- return false
436
- }
437
- // Settings + ledger already landed; a failed fingerprint write is NOT a
438
- // failed route. H4: this failure must reach recordOwnWrite (report +
439
- // `false`) so the C2 write-ahead journal is KEPT and the next round's
440
- // reconciliation re-commits the record — "fingerprint-healed" cannot cover
441
- // it (it only fires on an identity match, and this write changed the
442
- // identity). O1: still report it truthfully instead of leaving the record
443
- // gap silent.
444
- deps.logger.warn('appliedFingerprint update failed for %s: %s', route, errorText(err))
445
- report.push({
446
- level: 'warn',
447
- code: UNACCOUNTED_CODE,
448
- route,
449
- message: `route ${route} ${RECORD_ADVICE} (record error: ${truthfulLockDetail(errorText(err))})`,
450
- })
451
- return false
452
- }
453
- }
454
-
455
- /** O1/C2: write the intent BEFORE settings.mutate so a later crash is recoverable. */
456
- async function writeJournal(
457
- deps: GoWriterDeps,
458
- key: string,
459
- input: {
460
- route: string
461
- models: readonly SettingsModelProfile[]
462
- entry: GoOwnershipEntry | undefined
463
- unset: boolean
464
- expectedRevision?: number
465
- },
466
- ): Promise<boolean> {
467
- if (deps.journalStore === undefined || deps.profileKey === undefined) return false
468
- const journal: GoWriteJournal = {
469
- version: 1,
470
- profileKey: deps.profileKey,
471
- route: input.route,
472
- keyFingerprint: deps.keyFingerprint,
473
- modelIds: Object.keys(input.entry?.managed ?? {}).sort(),
474
- contentHash: journalContentHash(input.models),
475
- unset: input.unset,
476
- at: deps.now?.() ?? Date.now(),
477
- }
478
- if (input.expectedRevision !== undefined) journal.expectedRevision = input.expectedRevision
479
- if (input.entry !== undefined) journal.entry = input.entry
480
- try {
481
- await deps.journalStore.write(key, journal)
482
- return true
483
- } catch (err) {
484
- // Fail closed: the caller refuses the settings mutate when the journal did
485
- // not land. Writing settings without a journal recreates the S1/S2/S3
486
- // window (user-owned route, closed gate, hash-mismatch rollback) with no
487
- // record to reconcile on the next round.
488
- deps.logger.warn('write-ahead journal write failed for %s: %s', input.route, errorText(err))
489
- return false
490
- }
491
- }
492
-
493
- /** O1/C2: remove a journal only after a fully accounted write (or an abandoned one). */
494
- async function deleteJournal(deps: GoWriterDeps, key: string | undefined): Promise<void> {
495
- if (key === undefined || deps.journalStore === undefined) return
496
- try {
497
- await deps.journalStore.delete(key)
498
- } catch (err) {
499
- deps.logger.warn('write-ahead journal cleanup failed for %s: %s', key, errorText(err))
500
- }
501
- }
502
-
503
- /**
504
- * B4/N1: abandon the WHOLE round the moment the host settings revision moved
505
- * underneath a validated plan. Nothing is written — no settings mutate, no
506
- * ledger commit, no fingerprint — so a user edit that landed mid-round is kept
507
- * byte-for-byte. `plan.routes` that were never touched are reported as skipped
508
- * for observability; routes that already wrote (a mid-loop race) are left as-is
509
- * and the report stays honest.
510
- */
511
- function abandonForSettingsChange(
512
- result: GoWriteResult,
513
- report: GoPlanReportEntry[],
514
- plan: GoPlanResult,
515
- expectedRevision: number | undefined,
516
- actualRevision: number,
517
- ): GoWriteResult {
518
- result.settingsChanged = { expectedRevision, actualRevision }
519
- const touched = new Set([
520
- ...result.routes.map((status) => status.route),
521
- ...result.failedRoutes.map((failed) => failed.route),
522
- ...result.writtenRoutes,
523
- // O1-minimal (S7): a mutate may have landed even if its ledger commit then
524
- // failed. Count it as touched and report it as already written.
525
- ...result.settingsLandedRoutes,
526
- ])
527
- for (const planned of plan.routes) {
528
- if (planned.skip || touched.has(planned.route)) continue
529
- result.routes.push({
530
- route: planned.route,
531
- slot: planned.slot,
532
- status: 'skipped',
533
- reason: 'settings-changed-during-sync',
534
- })
535
- }
536
- // O1-minimal (S7): never claim "zero settings writes" when a mutate already
537
- // landed earlier in this round. List written vs discarded routes explicitly;
538
- // keep the original zero-write wording byte-identical when nothing landed.
539
- const landed = result.settingsLandedRoutes
540
- const discarded = plan.routes
541
- .filter((p) => !p.skip && !touched.has(p.route))
542
- .map((p) => p.route)
543
- const writeState = landed.length === 0
544
- ? 'zero settings writes, no ledger/fingerprint update'
545
- : `already written: [${landed.join(', ')}]; discarded (no settings write): [${discarded.length === 0 ? 'none' : discarded.join(', ')}]; no ledger/fingerprint update for discarded routes`
546
- report.push({
547
- level: 'warn',
548
- code: 'settings-changed-during-sync',
549
- message: `llm-pi-ai revision ${String(expectedRevision)} -> ${actualRevision} during this round; stale plan discarded (${writeState}); the next round re-reads current settings`,
550
- })
551
- result.report = associateGoMoves(report)
552
- return result
553
- }
554
-
555
- // ---------------------------------------------------------------------------
556
- // Per-route mutation building
557
- // ---------------------------------------------------------------------------
558
-
559
- interface RouteOps {
560
- ops: SettingsMutationOp[]
561
- /** A non-empty settings overrides key was present (must be staged + unset). */
562
- settingsOverrides: Record<string, Record<string, unknown>> | undefined
563
- /** The exact models array settings will hold after this mutate (C2 hash input). */
564
- models: SettingsModelProfile[]
565
- }
566
-
567
- /**
568
- * Build one route's ops. Set `apiKeyEnv` + unset any legacy `api`/`baseURL`
569
- * (or a whole-route `unset`) + set `models`, all in ONE mutate, so a route
570
- * never ends up with fields from one round and models from another
571
- * (§6.2.4 atomicity). Returns `undefined` when nothing would change
572
- * (`profilesEqual` gate).
573
- */
574
- async function buildRouteOps(
575
- planned: GoPlannedRoute,
576
- desc: SettingsDescriptor,
577
- finalModels: readonly SettingsModelProfile[],
578
- overrideStorer: GoOverrideStorer | undefined,
579
- ): Promise<RouteOps | undefined> {
580
- const data = rawRoute(desc, planned.route)
581
- // M3: a planned whole-route unset with NO live section needs only the LEDGER
582
- // delete — a settings unset of an absent section is a pointless mutate (and
583
- // a revision bump). Return no ops; the caller's no-change path still deletes
584
- // the ledger key via persistLedger's unset branch. Checked before any
585
- // override-store read so the cleanup does zero pointless I/O.
586
- if (planned.unset && data === undefined) return undefined
587
- const settingsOverrides = rawOverrides(desc, planned.route)
588
-
589
- // Settings key wins; store replay is the fallback (§6.2.4 store-first).
590
- let overrides = settingsOverrides
591
- if (overrides === undefined && overrideStorer?.read !== undefined) {
592
- const stored = await overrideStorer.read(planned.route)
593
- if (stored?.overrides !== undefined && Object.keys(stored.overrides).length > 0) {
594
- overrides = stored.overrides
595
- }
596
- }
597
- const mergedModels = mergeOverrides(finalModels, overrides)
598
-
599
- const ops: SettingsMutationOp[] = []
600
- // C2: the post-write models array (empty for an unset). We hash THIS on the
601
- // journal; reconciliation hashes the models read back from settings and
602
- // compares, so a user edit after our write is detected without ever writing
603
- // settings from the reconciler.
604
- let postWriteModels: SettingsModelProfile[] = []
605
- if (planned.unset) {
606
- // §9.4: an empty fully-managed route is removed wholesale — never `models: []`.
607
- ops.push({ op: 'unset', path: ['providers', planned.route] })
608
- } else {
609
- for (const field of OWNED_FIELDS) {
610
- if (data?.[field] !== planned.fields[field]) {
611
- ops.push({ op: 'set', path: ['providers', planned.route, field], value: planned.fields[field] })
612
- }
613
- }
614
- // Catalog-reuse (H3 scope): only the BUILTIN catalog provider route
615
- // ('opencode-go') may lose non-empty `api`/`baseURL` — the host reuses
616
- // pi-ai's builtin catalog provider (and its x-opencode-session wrapping)
617
- // for that id alone. A custom go.routes.chat name or any other route
618
- // NEEDS api/baseURL to be servable, so they are preserved. Empty-string
619
- // fields are broken values the host rejects outright and are stripped
620
- // everywhere.
621
- const stripCatalogReuse = planned.route === HOST_CATALOG_PROVIDER
622
- for (const field of GO_LEGACY_ROUTE_FIELDS) {
623
- const value = data?.[field]
624
- if (value === undefined) continue
625
- if (value === '' || stripCatalogReuse) {
626
- ops.push({ op: 'unset', path: ['providers', planned.route, field] })
627
- }
628
- }
629
- const currentRaw = sortedModels(rawModels(desc, planned.route))
630
- const mergedSorted = sortedModels(mergedModels)
631
- postWriteModels = mergedSorted
632
- const modelsEqual = overrides === undefined
633
- && currentRaw.length === mergedSorted.length
634
- && profilesEqual(currentRaw, mergedSorted)
635
- // `profilesEqual` (ADR-007's final gate): a hash-only upstream change must
636
- // not cause a revision bump when the written array would be identical.
637
- if (!modelsEqual) {
638
- ops.push({ op: 'set', path: ['providers', planned.route, 'models'], value: mergedSorted })
639
- }
640
- if (settingsOverrides !== undefined) {
641
- ops.push({ op: 'unset', path: ['providers', planned.route, 'modelOverrides'] })
642
- }
643
- }
644
- return ops.length === 0 ? undefined : { ops, settingsOverrides, models: postWriteModels }
645
- }
646
-
647
- async function stageOverrides(
648
- storer: GoOverrideStorer | undefined,
649
- route: string,
650
- overrides: Record<string, Record<string, unknown>> | undefined,
651
- ): Promise<void> {
652
- if (storer === undefined || overrides === undefined) return
653
- await storer.updateOverrides(route, overrides)
654
- }
655
-
656
- // ---------------------------------------------------------------------------
657
- // writeGoPlan: the settings write path
658
- // ---------------------------------------------------------------------------
659
-
660
- /**
661
- * Apply a planner result to the injected settings service and persist the
662
- * updated ownership ledger. Multi-route writes are isolated per route: one
663
- * route's failure never poisons the others, and the result names both the
664
- * routes written and the routes failed (§19 single-point-failure guidance).
665
- */
666
- export async function writeGoPlan(plan: GoPlanResult, deps: GoWriterDeps): Promise<GoWriteResult> {
667
- const { settings, ownershipStore, logger, keyFingerprint } = deps
668
- const confirmRemovals = Math.max(2, deps.confirmRemovals ?? 2)
669
- const result: GoWriteResult = { routes: [], writtenRoutes: [], failedRoutes: [], settingsLandedRoutes: [], report: [] }
670
- const report = plan.report.map((entry) => ({ ...entry }))
671
- // O1-minimal: routes whose settings landed but whose ledger did not commit.
672
- // Their planner `added` lines must be suppressed (they were not claimed).
673
- const unaccounted = new Set<string>()
674
-
675
- for (const conflict of plan.conflicts) {
676
- result.routes.push({
677
- route: conflict.route,
678
- slot: conflict.slot,
679
- status: 'conflict',
680
- reason: `${conflict.field}: ${conflict.actual} != ${conflict.expected}`,
681
- })
682
- }
683
-
684
- // H2: whether the main (chat-slot) route's write landed healthy this round.
685
- // Legacy route unsets are gated on it — the writer executes routes
686
- // independently and the host validates route REMOVAL against no catalog, so
687
- // a failed/conflicted main-route write followed by successful legacy unsets
688
- // would silently lose the user's non-chat-protocol models.
689
- const mainRouteReady = (): boolean => {
690
- const rows = result.routes.filter((row) => row.slot === 'chat')
691
- return rows.some((row) => row.status === 'wrote' || row.status === 'no-change')
692
- && !rows.some((row) => row.status === 'failed' || row.status === 'conflict')
693
- }
694
-
695
- const desc = settings === undefined ? undefined : findLlmDescriptor(settings)
696
- if (settings === undefined || desc === undefined) {
697
- for (const planned of plan.routes) {
698
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'skipped', reason: 'settings-unavailable' })
699
- }
700
- result.report = associateGoMoves(report)
701
- return result
702
- }
703
-
704
- // B4/N1 window ②: the user changed settings after the round validated the
705
- // revision but before the writer first read the descriptor. The plan was
706
- // built from the OLD settings, so even a fresh-revision mutate would silently
707
- // delete the just-saved model. Abandon before touching anything.
708
- const expectedRevision = deps.expectedRevision
709
- let currentExpectedRevision = expectedRevision
710
- if (expectedRevision !== undefined && desc.revision !== expectedRevision) {
711
- return abandonForSettingsChange(result, report, plan, expectedRevision, desc.revision)
712
- }
713
-
714
- for (const planned of plan.routes) {
715
- if (planned.skip) {
716
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'skipped', reason: 'planner-skip' })
717
- continue
718
- }
719
-
720
- // H2: legacy teardown is gated on a healthy main-route write this round
721
- // (see mainRouteReady above). No settings write, no ledger touch.
722
- if (planned.unset && planned.slot !== 'chat' && !mainRouteReady()) {
723
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'skipped', reason: 'main-route-not-ready' })
724
- report.push({
725
- level: 'warn',
726
- code: 'main-route-not-ready',
727
- route: planned.route,
728
- slot: planned.slot,
729
- message: `legacy route ${planned.route} unset deferred: the main route write did not land this round; no teardown while the managed route is not healthy`,
730
- })
731
- continue
732
- }
733
-
734
- // Single-writer second gate (§14.7.5): re-read the persisted status here,
735
- // never reuse the round-level snapshot. A route whose authority was revoked
736
- // between the round gate and this point is skipped with a report line —
737
- // never silently, never touched (not even the ledger).
738
- const gate = await canWriteDecision(deps, planned.route)
739
- if (gate !== undefined && !gate.allow) {
740
- skipByCanWrite(result, report, planned, gate)
741
- continue
742
- }
743
-
744
- const key = goOwnershipKey(planned.route, keyFingerprint)
745
- let prior: GoOwnershipEntry | undefined
746
- try {
747
- prior = await ownershipStore.read(key)
748
- } catch (err) {
749
- if (isStoreLockTimeout(err)) {
750
- logger.warn('ownership store read lock timeout for %s: %s', key, errorText(err))
751
- recordLockTimeout(result, report, planned, err, 'ledger read')
752
- continue
753
- }
754
- // Fail closed: with no ledger we cannot verify hashes, so do not write.
755
- logger.warn('ownership store read failed for %s: %s', key, errorText(err))
756
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'failed', reason: 'store-unavailable' })
757
- result.failedRoutes.push({ route: planned.route, reason: 'store-unavailable' })
758
- continue
759
- }
760
-
761
- const current = rawModels(desc, planned.route)
762
- const currentById = new Map(current.map((model) => [model.id, model]))
763
- // Use the planner's mapped desired set, not the merged output (which also
764
- // contains kept user-owned entries).
765
- const desiredProfiles = plan.desiredByRoute[planned.route] ?? []
766
- const desiredById = new Map(desiredProfiles.map((model) => [model.id, model]))
767
- const candidates = report.filter((entry) =>
768
- entry.code === 'deletion-candidate'
769
- && entry.route === planned.route
770
- && entry.slot === planned.slot
771
- && entry.id !== undefined)
772
-
773
- // --- Double-round deletion confirmation (V5) ---------------------------
774
- // The planner flags a candidate after its three gates pass; only the
775
- // writer knows how many consecutive successful rounds have flagged it.
776
- // H5: a candidate the HOST RUNTIME CATALOG does not know skips the counter
777
- // entirely — the host rejects the whole models array on such an id, so
778
- // round 1's write-back fails and the counter can never persist (a
779
- // permanent write-failed loop). Removing it immediately is what restores
780
- // writability; the id auto-returns when the host upgrades.
781
- //
782
- // P1-1 scope: that rejection exists only for the route reusing the builtin
783
- // catalog (chat slot + the builtin provider id). A custom go.routes.chat
784
- // name keeps its own api/baseURL and is never validated against the
785
- // runtime catalog, so its deletions follow the normal two-round path.
786
- const enforcesHostCatalog = planned.slot === 'chat' && planned.route === HOST_CATALOG_PROVIDER
787
- const hostSet = enforcesHostCatalog && deps.hostCatalogIds !== undefined
788
- ? new Set(deps.hostCatalogIds)
789
- : undefined
790
- const missing: Record<string, number> = { ...(prior?.missing ?? {}) }
791
- const finalModels = [...planned.models]
792
- for (const candidate of candidates) {
793
- const id = candidate.id!
794
- const hostUnknown = hostSet !== undefined && !hostSet.has(id)
795
- if (hostUnknown) {
796
- // Confirmed immediately: let the planner's exclusion stand — delete.
797
- delete missing[id]
798
- candidate.code = 'deleted'
799
- candidate.message = `model ${id} removed immediately: the host runtime catalog does not know it (its presence would make the host reject every mutate); it auto-returns after the host upgrades`
800
- continue
801
- }
802
- const seen = missing[id] ?? 0
803
- if (seen + 1 < confirmRemovals) {
804
- // Round 1 of 2 (or earlier for a larger threshold): keep the model.
805
- const currentModel = currentById.get(id)
806
- // A deletion candidate is by definition NOT in the desired set — never
807
- // add it to `desiredById`, or the counter-reset loop below would erase
808
- // the very counter we are setting here.
809
- if (currentModel !== undefined) finalModels.push(currentModel)
810
- missing[id] = seen + 1
811
- candidate.code = 'deletion-pending'
812
- candidate.message = `model ${id} absent (${seen + 1}/${confirmRemovals}); kept until confirmed`
813
- } else {
814
- // Confirmed: let the planner's exclusion stand — actually delete.
815
- delete missing[id]
816
- candidate.code = 'deleted'
817
- candidate.message = `model ${id} removed after ${confirmRemovals} consecutive absent rounds`
818
- }
819
- }
820
- // A model that came back into the DESIRED set resets its absence counter.
821
- // Must not iterate `finalModels`: a pending candidate was just re-added
822
- // there for this round and its counter must survive.
823
- for (const id of desiredById.keys()) {
824
- if (missing[id] !== undefined) delete missing[id]
825
- }
826
- const sortedFinal = sortedModels(finalModels)
827
-
828
- // H5 (fail-closed): refuse the route write when the FINAL models array
829
- // would still carry ids the host runtime catalog does not know — the host
830
- // rejects the whole mutate, so writing is guaranteed to fail while
831
- // pretending otherwise. Zero writes for this route; the report names the
832
- // ids and both actionable exits.
833
- if (hostSet !== undefined && !planned.unset) {
834
- const unknownIds = sortedFinal.filter((model) => !hostSet.has(model.id)).map((model) => model.id)
835
- if (unknownIds.length > 0) {
836
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'failed', reason: 'host-catalog-unknown-models' })
837
- result.failedRoutes.push({ route: planned.route, reason: 'host-catalog-unknown-models' })
838
- report.push({
839
- level: 'error',
840
- code: 'host-catalog-unknown-models',
841
- route: planned.route,
842
- slot: planned.slot,
843
- message: `route ${planned.route} not written: ${unknownIds.join(', ')} are not in the host runtime catalog and the host would reject the whole mutate — keep them on a custom route (with api/baseURL) or wait for the host upgrade; zero settings writes for this route`,
844
- })
845
- continue
846
- }
847
- }
848
-
849
- // --- Ledger to persist if this route's write succeeds ------------------
850
- const nextManaged: Record<string, GoManagedModel> = { ...(plan.nextOwnership[key]?.managed ?? {}) }
851
- // A pending candidate is still plugin-managed: keep it in the ledger so a
852
- // later round can finish the deletion (the planner dropped it already).
853
- for (const candidate of candidates) {
854
- if (candidate.code === 'deletion-pending' && candidate.id !== undefined) {
855
- const model = currentById.get(candidate.id)
856
- if (model !== undefined) nextManaged[candidate.id] = { hash: profileHash(model) }
857
- }
858
- }
859
- // First-round conservative claim (§6.2.4 / A3): with no prior ledger claim
860
- // the desired∩current id set, recording the hash of the value we write —
861
- // never claim ids outside the official desired set (qwen4-max / grok-4.7
862
- // stay user-owned until adopt). `adoptExisting` (design §14.1) explicitly
863
- // opts those pre-existing ids into the ledger; they still leave via the
864
- // two-round confirmation and the three deletion gates, never immediately.
865
- if (prior === undefined || deps.adoptExisting === true) {
866
- for (const desired of desiredProfiles) {
867
- if (currentById.has(desired.id)) {
868
- nextManaged[desired.id] = { hash: profileHash(desired) }
869
- }
870
- }
871
- if (deps.adoptExisting === true) {
872
- for (const model of current) {
873
- if (nextManaged[model.id] === undefined) {
874
- nextManaged[model.id] = { hash: profileHash(model) }
875
- }
876
- }
877
- }
878
- }
879
- const preManagedSnapshot = prior?.preManagedSnapshot !== undefined
880
- ? prior.preManagedSnapshot
881
- : current.map((model) => ({ ...model }))
882
- // §14.3 ownership: `preManagedSection`, `appliedAddedIds` (and any future
883
- // migration-period fields) are written ONLY by the migrate module. The go
884
- // writer may only read/inherit them — never generate, recompute, or clear
885
- // them. Spreading `prior` first carries every field the writer does NOT own
886
- // forward verbatim on EVERY round (including no-change and
887
- // deletion-candidate rounds), so the authoritative rollback snapshot keeps
888
- // its exact bytes until rollback removes it. Only the fields the writer
889
- // actually owns (routeFields / managed / preManagedSnapshot / missing) are
890
- // overridden below. This is a merge, never a replace.
891
- const nextEntry: GoOwnershipEntry = {
892
- ...prior,
893
- routeFields: plan.nextOwnership[key]?.routeFields ?? planned.fields,
894
- managed: nextManaged,
895
- preManagedSnapshot,
896
- }
897
- // `missing` is writer-owned: reflect this round exactly (drop the key once
898
- // the counter drains to empty, matching the previous behaviour).
899
- if (Object.keys(missing).length > 0) nextEntry.missing = missing
900
- else delete nextEntry.missing
901
-
902
- // --- Build + run the mutate (with one revision-conflict retry) ---------
903
- let built: RouteOps | undefined
904
- try {
905
- built = await buildRouteOps(planned, desc, sortedFinal, deps.overrideStorer)
906
- } catch (err) {
907
- if (isStoreLockTimeout(err)) {
908
- logger.warn('override resolve lock timeout for %s: %s', planned.route, errorText(err))
909
- recordLockTimeout(result, report, planned, err, 'override resolve')
910
- continue
911
- }
912
- const reason = 'store-unavailable'
913
- logger.warn('override resolve failed for %s: %s', planned.route, errorText(err))
914
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'failed', reason })
915
- result.failedRoutes.push({ route: planned.route, reason })
916
- continue
917
- }
918
-
919
- // B4/N1 window ①: re-read the descriptor IMMEDIATELY before any settings
920
- // mutate (or the no-change ledger commit) for this route. A revision moved
921
- // since our last validated write means settings changed underneath us —
922
- // the plan is stale, so abandon the whole round with zero writes. Our own
923
- // earlier mutate advances the document revision, so compare against the
924
- // rolling baseline (updated after each successful write), not the round's
925
- // original revision.
926
- let live: SettingsDescriptor | undefined
927
- if (expectedRevision !== undefined) {
928
- live = findLlmDescriptor(settings)
929
- if (live === undefined || live.revision !== currentExpectedRevision) {
930
- return abandonForSettingsChange(result, report, plan, currentExpectedRevision, live?.revision ?? -1)
931
- }
932
- }
933
-
934
- if (built === undefined) {
935
- const commit = await persistLedger(ownershipStore, key, planned.unset, nextEntry, logger, report, planned.route)
936
- if (commit.lockTimeout !== undefined) {
937
- // Lock failures keep their dedicated fail-closed semantics (unchanged).
938
- recordLockTimeout(result, report, planned, commit.lockTimeout, 'ledger commit')
939
- continue
940
- }
941
- // A non-lock ledger failure on a no-change path is still a real failure:
942
- // the round must not advertise a clean no-change. Data direction is safe
943
- // (the next round re-reads ownership from scratch), but surface it in
944
- // failedRoutes so the command reports `kind:'error'` (oldfox #1).
945
- if (!commit.committed) {
946
- result.failedRoutes.push({ route: planned.route, reason: 'ledger-write-failed' })
947
- result.routes.push({
948
- route: planned.route, slot: planned.slot, status: 'no-change', reason: 'ledger-write-failed',
949
- })
950
- } else {
951
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'no-change' })
952
- }
953
- continue
954
- }
955
-
956
- let failedReason: string | undefined
957
- // Settings mutate landing is tracked separately: it is added to
958
- // `writtenRoutes` only once the ledger commit also succeeds. A lock
959
- // timeout on the ledger must not leave the route counted as a success.
960
- let settingsLanded = false
961
- if (built.settingsOverrides !== undefined && deps.overrideStorer === undefined) {
962
- // Unsetting a settings key with no store copy is the v0.1.5 data-loss
963
- // shape — fail closed rather than drop the user's folded values.
964
- failedReason = 'store-unavailable'
965
- logger.warn('modelOverrides present but no models-store seam for %s', planned.route)
966
- } else {
967
- try {
968
- await stageOverrides(deps.overrideStorer, planned.route, built.settingsOverrides)
969
- } catch (err) {
970
- if (isStoreLockTimeout(err)) {
971
- logger.warn('override stage lock timeout for %s: %s', planned.route, errorText(err))
972
- recordLockTimeout(result, report, planned, err, 'override stage')
973
- continue
974
- }
975
- failedReason = 'store-unavailable'
976
- logger.warn('override stage failed for %s: %s', planned.route, errorText(err))
977
- }
978
- }
979
-
980
- // O1/C2: journal the intent BEFORE the only settings mutate. A journal is
981
- // kept on ANY failure after this point (mutate, ledger, record) so the next
982
- // round can reconcile it. It is deleted only on a fully accounted success.
983
- const jkey = deps.journalStore !== undefined && deps.profileKey !== undefined
984
- ? goJournalKey(deps.profileKey, planned.route, keyFingerprint)
985
- : undefined
986
- let journalWritten = false
987
- if (failedReason === undefined && jkey !== undefined) {
988
- journalWritten = await writeJournal(deps, jkey, {
989
- route: planned.route,
990
- models: built.models,
991
- entry: nextEntry,
992
- unset: planned.unset,
993
- expectedRevision: currentExpectedRevision,
994
- })
995
- if (!journalWritten) {
996
- // Fail closed: no journal means no way to re-account this write next
997
- // round. Refuse the settings mutate entirely (zero settings/ledger/
998
- // fingerprint writes for this route) with an identifiable reason.
999
- failedReason = 'journal-unavailable'
1000
- logger.warn('write-ahead journal unavailable for %s; refusing settings mutate (fail-closed)', planned.route)
1001
- report.push({
1002
- level: 'error',
1003
- code: 'journal-unavailable',
1004
- route: planned.route,
1005
- slot: planned.slot,
1006
- message: `route ${planned.route} not written: the write-ahead journal could not be persisted; zero settings writes (fail-closed)`,
1007
- })
1008
- }
1009
- }
1010
-
1011
- // O1/C2: re-run the freshness check AFTER the journal store write, so the
1012
- // extra store I/O never widens the window between validation and mutate.
1013
- // If a user edit landed while we journaled, discard the journal (no mutate
1014
- // has run) and abandon the whole round with zero writes.
1015
- if (journalWritten && expectedRevision !== undefined) {
1016
- const afterJournal = findLlmDescriptor(settings)
1017
- if (afterJournal === undefined || afterJournal.revision !== currentExpectedRevision) {
1018
- await deleteJournal(deps, jkey)
1019
- return abandonForSettingsChange(result, report, plan, currentExpectedRevision, afterJournal?.revision ?? -1)
1020
- }
1021
- }
1022
-
1023
- if (failedReason === undefined) {
1024
- try {
1025
- await settings.mutate('llm-pi-ai', built.ops, live?.revision ?? desc.revision)
1026
- settingsLanded = true
1027
- result.settingsLandedRoutes.push(planned.route)
1028
- // N1 residual window: the revision alone is not enough to establish the
1029
- // new baseline. A user edit landing between mutate() returning and this
1030
- // re-read bumps the revision too, so adopting it would make later routes
1031
- // treat a stale plan as fresh. Hash the content we EXPECT our ops to
1032
- // leave and compare it with what is actually present; only a match
1033
- // advances the rolling baseline. The write-ahead journal is deliberately
1034
- // kept on mismatch so the next round can still re-account our write.
1035
- if (expectedRevision !== undefined) {
1036
- const after = findLlmDescriptor(settings)
1037
- const expectedContent = fingerprintSection(expectedUserAfterOps(live?.user, built.ops))
1038
- if (after === undefined || fingerprintSection(after.user ?? {}) !== expectedContent) {
1039
- logger.warn('settings changed after our mutate for %s; abandoning round', planned.route)
1040
- return abandonForSettingsChange(result, report, plan, currentExpectedRevision, after?.revision ?? -1)
1041
- }
1042
- currentExpectedRevision = after.revision
1043
- }
1044
- } catch (err) {
1045
- if (!isConflictError(err)) {
1046
- failedReason = 'mutate-rejected'
1047
- logger.warn('mutate failed for %s: %s', planned.route, errorText(err))
1048
- } else if (expectedRevision !== undefined) {
1049
- // B4/N1: a conflict AFTER our freshness check can only be an external
1050
- // edit that landed in the narrow gap before the mutate. Retrying with
1051
- // the stale plan would delete the just-saved model — abandon the
1052
- // whole round instead (no ledger/fingerprint, next round re-plans).
1053
- // No mutate landed for this route; drop the journal so reconciliation
1054
- // does not re-account an abandoned plan on the next round.
1055
- await deleteJournal(deps, jkey)
1056
- const fresh = findLlmDescriptor(settings)
1057
- return abandonForSettingsChange(result, report, plan, currentExpectedRevision, fresh?.revision ?? -1)
1058
- } else {
1059
- // Legacy retry for direct unit writers that did not supply a
1060
- // round-level expectedRevision (production always supplies one).
1061
- // §14.7.5: re-run the second gate BEFORE the retry mutate. The live
1062
- // migration status may have flipped during the first attempt; the
1063
- // round-level decision and the first gate result are both stale now.
1064
- const retryGate = await canWriteDecision(deps, planned.route)
1065
- if (retryGate !== undefined && !retryGate.allow) {
1066
- skipByCanWrite(result, report, planned, retryGate)
1067
- continue
1068
- }
1069
- // SETTINGS_CONFLICT: re-read the revision, rebuild the ops against the
1070
- // fresh descriptor, and retry exactly once (existing writer style).
1071
- logger.info('SETTINGS_CONFLICT for %s; retrying once', planned.route)
1072
- failedReason = 'conflict-retry-failed'
1073
- try {
1074
- const fresh = findLlmDescriptor(settings)
1075
- if (fresh === undefined) throw new Error('llm-pi-ai namespace disappeared on retry')
1076
- const retryBuilt = await buildRouteOps(planned, fresh, sortedFinal, deps.overrideStorer)
1077
- if (retryBuilt === undefined) {
1078
- // Another writer already landed the exact target: no-op success.
1079
- failedReason = undefined
1080
- const retryCommit = await persistLedger(ownershipStore, key, planned.unset, nextEntry, logger, report, planned.route)
1081
- if (retryCommit.lockTimeout !== undefined) {
1082
- recordLockTimeout(result, report, planned, retryCommit.lockTimeout, 'ledger commit (conflict retry)')
1083
- continue
1084
- }
1085
- // Same honest failure accounting as the normal no-change path
1086
- // (oldfox #1): a non-lock ledger failure is a real failure.
1087
- if (!retryCommit.committed) {
1088
- result.failedRoutes.push({ route: planned.route, reason: 'ledger-write-failed' })
1089
- result.routes.push({
1090
- route: planned.route, slot: planned.slot, status: 'no-change', reason: 'ledger-write-failed',
1091
- })
1092
- } else {
1093
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'no-change' })
1094
- }
1095
- continue
1096
- }
1097
- // O1/C2: the retry may write a different models array; refresh the
1098
- // journal so reconciliation hashes the value actually written. A
1099
- // failed refresh is fail-closed too: mutating with the FIRST
1100
- // attempt's stale journal would give reconciliation a hash mismatch
1101
- // (journal-stale) and recreate the S1/S2/S3 window.
1102
- let retryJournalWritten = true
1103
- if (jkey !== undefined && journalWritten) {
1104
- retryJournalWritten = await writeJournal(deps, jkey, {
1105
- route: planned.route,
1106
- models: retryBuilt.models,
1107
- entry: nextEntry,
1108
- unset: planned.unset,
1109
- expectedRevision: currentExpectedRevision,
1110
- })
1111
- }
1112
- if (!retryJournalWritten) {
1113
- await deleteJournal(deps, jkey)
1114
- failedReason = 'journal-unavailable'
1115
- logger.warn('write-ahead journal unavailable on conflict retry for %s; refusing settings mutate (fail-closed)', planned.route)
1116
- report.push({
1117
- level: 'error',
1118
- code: 'journal-unavailable',
1119
- route: planned.route,
1120
- slot: planned.slot,
1121
- message: `route ${planned.route} not written: the write-ahead journal could not be refreshed on conflict retry; zero settings writes (fail-closed)`,
1122
- })
1123
- } else {
1124
- await stageOverrides(deps.overrideStorer, planned.route, retryBuilt.settingsOverrides)
1125
- await settings.mutate('llm-pi-ai', retryBuilt.ops, fresh.revision)
1126
- settingsLanded = true
1127
- result.settingsLandedRoutes.push(planned.route)
1128
- failedReason = undefined
1129
- }
1130
- } catch (retryErr) {
1131
- if (isStoreLockTimeout(retryErr)) {
1132
- recordLockTimeout(result, report, planned, retryErr, 'write (conflict retry)')
1133
- continue
1134
- }
1135
- logger.warn('conflict retry failed for %s: %s', planned.route, errorText(retryErr))
1136
- }
1137
- }
1138
- }
1139
- }
1140
-
1141
- if (failedReason !== undefined) {
1142
- result.routes.push({ route: planned.route, slot: planned.slot, status: 'failed', reason: failedReason })
1143
- result.failedRoutes.push({ route: planned.route, reason: failedReason })
1144
- report.push({
1145
- level: 'error',
1146
- code: 'write-failed',
1147
- route: planned.route,
1148
- slot: planned.slot,
1149
- message: `route ${planned.route} not written (${failedReason})`,
1150
- })
1151
- continue
1152
- }
1153
-
1154
- // §14.7.4: settings mutate + ledger commit both succeeded — only now
1155
- // re-persist the applied fingerprint (same store queue as the ledger), with
1156
- // the managed id set we just committed. Failed/no-change routes never get
1157
- // here, so a partial failure leaves their fingerprint untouched.
1158
- const commit = await persistLedger(ownershipStore, key, planned.unset, nextEntry, logger, report, planned.route, settingsLanded)
1159
- if (commit.lockTimeout !== undefined) {
1160
- // Settings may have landed, but without a committed ledger this round is
1161
- // NOT a success: report the actionable lock error and exclude the route
1162
- // from writtenRoutes (and from the fingerprint update).
1163
- recordLockTimeout(result, report, planned, commit.lockTimeout, 'ledger commit', settingsLanded)
1164
- if (settingsLanded) unaccounted.add(planned.route)
1165
- continue
1166
- }
1167
- if (!commit.committed) {
1168
- // O1-minimal: settings landed but the ledger did not. This is a real
1169
- // (non-lock) failure — surface it in failedRoutes so the command result
1170
- // is `kind:'error'` and the route is not advertised as a clean success.
1171
- result.failedRoutes.push({
1172
- route: planned.route,
1173
- reason: settingsLanded ? UNACCOUNTED_CODE : 'ledger-write-failed',
1174
- })
1175
- if (settingsLanded) unaccounted.add(planned.route)
1176
- }
1177
- if (commit.committed) {
1178
- const recordPersisted = await recordOwnWrite(
1179
- deps, planned.route, planned.unset ? [] : Object.keys(nextEntry.managed).sort(), report, planned.unset,
1180
- )
1181
- // C2: only a fully accounted write (settings + ledger + record) closes the
1182
- // journal. A failed record persist (S1b) keeps it so the next round's
1183
- // reconciliation re-persists the migration record and reopens the gate.
1184
- if (recordPersisted) await deleteJournal(deps, jkey)
1185
- }
1186
- if (settingsLanded) result.writtenRoutes.push(planned.route)
1187
- result.routes.push({
1188
- route: planned.route,
1189
- slot: planned.slot,
1190
- status: planned.unset ? 'unset' : 'wrote',
1191
- })
1192
- }
1193
-
1194
- // O1-minimal: never advertise an `added` model on a route that was skipped,
1195
- // failed, or written-but-unaccounted. The model was not claimed in the ledger,
1196
- // so the next round will treat it as user-owned (S1/S2 report-text trap).
1197
- const notClaimed = new Set([
1198
- ...result.routes.filter((r) => r.status === 'skipped' || r.status === 'failed').map((r) => r.route),
1199
- // oldfox #1: a no-change route whose ledger re-commit failed is in
1200
- // failedRoutes but keeps status 'no-change' (no settings were written).
1201
- // Its model was never claimed, so never advertise an `added` line for it.
1202
- ...result.failedRoutes.map((f) => f.route),
1203
- ...unaccounted,
1204
- ])
1205
- const honestReport = report.filter((entry) =>
1206
- !(entry.code === 'added' && entry.route !== undefined && notClaimed.has(entry.route)))
1207
- result.report = associateGoMoves(honestReport)
1208
- return result
1209
- }
1210
-
1211
- /** Commits the ledger; a lock timeout is returned with its original error (not degraded). */
1212
- async function persistLedger(
1213
- store: GoOwnershipStore,
1214
- key: string,
1215
- unset: boolean,
1216
- entry: GoOwnershipEntry,
1217
- logger: Logger,
1218
- report: GoPlanReportEntry[],
1219
- route: string,
1220
- settingsLanded = false,
1221
- ): Promise<LedgerCommitResult> {
1222
- try {
1223
- if (unset) await store.delete(key)
1224
- else await store.write(key, entry)
1225
- return { committed: true }
1226
- } catch (err) {
1227
- if (isStoreLockTimeout(err)) {
1228
- // Keep the original error (code / lockPath / actionable message) for the
1229
- // caller to surface verbatim — do NOT collapse it into a generic warning.
1230
- logger.warn('ownership store lock timeout for %s: %s', key, errorText(err))
1231
- return { committed: false, lockTimeout: err }
1232
- }
1233
- // A failed ledger write degrades to "no ledger" next round, which is the
1234
- // safe direction (never delete without a hash). But when settings already
1235
- // landed this is NOT a clean success: say so truthfully (O1-minimal).
1236
- logger.warn('ownership store write failed for %s: %s', key, errorText(err))
1237
- if (settingsLanded) {
1238
- report.push({
1239
- level: 'error',
1240
- code: UNACCOUNTED_CODE,
1241
- route,
1242
- message: `route ${route} ${UNACCOUNTED_ADVICE} (ledger write error: ${errorText(err)})`,
1243
- })
1244
- } else {
1245
- // No settings write preceded this commit (no-change path). The old
1246
- // "written but ownership ledger could not be persisted" was false —
1247
- // nothing was written here. State the real outcome (oldfox #1).
1248
- report.push({
1249
- level: 'error',
1250
- code: 'ledger-write-failed',
1251
- route,
1252
- message: `route ${route} ownership ledger could not be persisted; no settings writes were made in this no-change path (self-heals next round via a fresh ownership read; re-claim with \`/model-sync adopt go\` if needed)`,
1253
- })
1254
- }
1255
- return { committed: false }
1256
- }
1257
- }
1258
-
1259
- // ---------------------------------------------------------------------------
1260
- // moved association (P1a verification concern ③)
1261
- // ---------------------------------------------------------------------------
1262
-
1263
- /**
1264
- * Pair a removal on route A with an add of the same id on route B into one
1265
- * human-readable `moved` entry, so a consumer never reads a cross-slot move as
1266
- * an unrelated delete + add. A still-pending source removal is labelled as
1267
- * such (double confirmation), so the report stays honest.
1268
- */
1269
- export function associateGoMoves(report: readonly GoPlanReportEntry[]): GoPlanReportEntry[] {
1270
- const out = report.map((entry) => ({ ...entry }))
1271
- const removals: number[] = []
1272
- const adds: number[] = []
1273
- for (let i = 0; i < out.length; i++) {
1274
- const entry = out[i]
1275
- if (entry.id === undefined || entry.route === undefined) continue
1276
- if (entry.code === 'added') adds.push(i)
1277
- else if (entry.code === 'deletion-candidate' || entry.code === 'deletion-pending' || entry.code === 'deleted') removals.push(i)
1278
- }
1279
- const used = new Set<number>()
1280
- const moves: GoPlanReportEntry[] = []
1281
- for (const ri of removals) {
1282
- const removal = out[ri]
1283
- const addIndex = adds.find((ai) => !used.has(ai)
1284
- && out[ai].id === removal.id
1285
- && out[ai].route !== removal.route)
1286
- if (addIndex === undefined) continue
1287
- used.add(ri)
1288
- used.add(addIndex)
1289
- const added = out[addIndex]
1290
- const pending = removal.code === 'deletion-pending' || removal.code === 'deletion-candidate'
1291
- moves.push({
1292
- level: 'info',
1293
- code: 'moved',
1294
- id: removal.id,
1295
- route: removal.route,
1296
- slot: removal.slot,
1297
- message: `model ${removal.id} moved from ${removal.route} to ${added.route}${pending ? ' (source removal pending confirmation)' : ''}`,
1298
- })
1299
- }
1300
- return [...out.filter((_, i) => !used.has(i)), ...moves]
1301
- }