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