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