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