@aiwayds/dsh-model-sync 0.12.1 → 0.13.0

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