@aiwayds/dsh-model-sync 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +9 -4
- package/README.zh-CN.md +9 -4
- package/lib/builtin-catalog-snapshot.d.ts +5 -1
- package/lib/builtin-catalog-snapshot.js +13 -10
- package/lib/builtin-catalog-snapshot.js.map +1 -1
- package/lib/index.d.ts +366 -0
- package/lib/index.js +729 -13
- package/lib/index.js.map +1 -1
- package/lib/opencode-go-diagnose.d.ts +74 -0
- package/lib/opencode-go-diagnose.js +146 -0
- package/lib/opencode-go-diagnose.js.map +1 -0
- package/lib/opencode-go-grouping.d.ts +29 -0
- package/lib/opencode-go-grouping.js +77 -0
- package/lib/opencode-go-grouping.js.map +1 -0
- package/lib/opencode-go-journal.d.ts +110 -0
- package/lib/opencode-go-journal.js +406 -0
- package/lib/opencode-go-journal.js.map +1 -0
- package/lib/opencode-go-migrate.d.ts +343 -0
- package/lib/opencode-go-migrate.js +1300 -0
- package/lib/opencode-go-migrate.js.map +1 -0
- package/lib/opencode-go-migration.d.ts +227 -0
- package/lib/opencode-go-migration.js +384 -0
- package/lib/opencode-go-migration.js.map +1 -0
- package/lib/opencode-go-planner.d.ts +153 -0
- package/lib/opencode-go-planner.js +339 -0
- package/lib/opencode-go-planner.js.map +1 -0
- package/lib/opencode-go-profile.d.ts +57 -0
- package/lib/opencode-go-profile.js +103 -0
- package/lib/opencode-go-profile.js.map +1 -0
- package/lib/opencode-go-scheduler.d.ts +128 -0
- package/lib/opencode-go-scheduler.js +241 -0
- package/lib/opencode-go-scheduler.js.map +1 -0
- package/lib/opencode-go-source.d.ts +117 -0
- package/lib/opencode-go-source.js +331 -0
- package/lib/opencode-go-source.js.map +1 -0
- package/lib/opencode-go-store.d.ts +18 -0
- package/lib/opencode-go-store.js +68 -0
- package/lib/opencode-go-store.js.map +1 -0
- package/lib/opencode-go-sync.d.ts +94 -0
- package/lib/opencode-go-sync.js +364 -0
- package/lib/opencode-go-sync.js.map +1 -0
- package/lib/opencode-go-writer.d.ts +132 -0
- package/lib/opencode-go-writer.js +966 -0
- package/lib/opencode-go-writer.js.map +1 -0
- package/lib/provider-native.d.ts +3 -1
- package/lib/provider-native.js +4 -2
- package/lib/provider-native.js.map +1 -1
- package/lib/remote-catalog.d.ts +37 -0
- package/lib/remote-catalog.js +261 -3
- package/lib/remote-catalog.js.map +1 -1
- package/package.json +18 -18
- package/src/builtin-catalog-snapshot.ts +18 -11
- package/src/index.ts +873 -12
- package/src/opencode-go-diagnose.ts +222 -0
- package/src/opencode-go-grouping.ts +97 -0
- package/src/opencode-go-journal.ts +458 -0
- package/src/opencode-go-migrate.ts +1694 -0
- package/src/opencode-go-migration.ts +552 -0
- package/src/opencode-go-planner.ts +505 -0
- package/src/opencode-go-profile.ts +114 -0
- package/src/opencode-go-scheduler.ts +315 -0
- package/src/opencode-go-source.ts +424 -0
- package/src/opencode-go-store.ts +73 -0
- package/src/opencode-go-sync.ts +503 -0
- package/src/opencode-go-writer.ts +1189 -0
- package/src/provider-native.ts +3 -1
- package/src/remote-catalog.ts +293 -3
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
// O1/C2: write-ahead journal + next-round reconciliation. The go writer's real
|
|
2
|
+
// order is `settings.mutate` → ownership ledger → migration record. A crash (or
|
|
3
|
+
// a store write failure) between those steps leaves settings AHEAD of the two
|
|
4
|
+
// store records: on the next round the route looks user-owned, the migration
|
|
5
|
+
// gate can close forever (S1), a new model is never claimed (S2), and rollback
|
|
6
|
+
// refuses with hash-mismatch (S3). No settings rollback is attempted (the
|
|
7
|
+
// cross-process lock does not cover settings.mutate); instead this module
|
|
8
|
+
// records the intended write BEFORE the mutate and reconciles it on the next
|
|
9
|
+
// round, converging on the hash of the value actually present in settings.
|
|
10
|
+
//
|
|
11
|
+
// Wire format: one opaque slot per route in the SAME ~/.dsh/models-store.json
|
|
12
|
+
// (same queue / atomic temp+rename as the ledger and migration record):
|
|
13
|
+
// `<profileKey>#<route>#<keyFingerprint>#journal` -> GoWriteJournal
|
|
14
|
+
// Four '#'-separated parts. `isUnscopedStoreKey` only classifies TWO-part keys
|
|
15
|
+
// as unscoped legacy slots, so a journal key is never reported/claimed as a
|
|
16
|
+
// foreign legacy record. The profile and fingerprint are BOTH stamped inside
|
|
17
|
+
// the payload and validated on read, so a rotated key or another profile's
|
|
18
|
+
// journal is discarded instead of being replayed onto the wrong ledger slot.
|
|
19
|
+
//
|
|
20
|
+
// Reconciliation is store/record-only: it NEVER calls settings.mutate. If the
|
|
21
|
+
// present value's content hash equals the recorded post-write hash, our write
|
|
22
|
+
// is intact and the ledger + migration record are re-committed; otherwise the
|
|
23
|
+
// user changed the value and the journal is dropped (their value is kept).
|
|
24
|
+
|
|
25
|
+
import { createHash } from 'node:crypto'
|
|
26
|
+
import { goOwnershipKey, type GoOwnershipEntry } from './opencode-go-planner.ts'
|
|
27
|
+
import type { GoOwnershipStore } from './opencode-go-writer.ts'
|
|
28
|
+
import { loadModelsStore, type ModelsStoreAccessor } from './remote-catalog.ts'
|
|
29
|
+
import type { SettingsModelProfile } from './translate.ts'
|
|
30
|
+
import type { Logger, SettingsDescriptor, SettingsService } from './writer.ts'
|
|
31
|
+
|
|
32
|
+
const JOURNAL_TAIL = 'journal'
|
|
33
|
+
const JOURNAL_VERSION = 1
|
|
34
|
+
|
|
35
|
+
export interface GoWriteJournal {
|
|
36
|
+
version: typeof JOURNAL_VERSION
|
|
37
|
+
/** Profile scope stamped at write time; must match the reconciling profile. */
|
|
38
|
+
profileKey: string
|
|
39
|
+
route: string
|
|
40
|
+
/** Credential fingerprint stamped at write time; must match the current key. */
|
|
41
|
+
keyFingerprint: string
|
|
42
|
+
/** Ledger-managed ids this write was about to commit (sorted). */
|
|
43
|
+
modelIds: string[]
|
|
44
|
+
/** sha256 of the sorted models array we were about to write. */
|
|
45
|
+
contentHash: string
|
|
46
|
+
/** Host settings revision the mutate was issued against (diagnostic only). */
|
|
47
|
+
expectedRevision?: number
|
|
48
|
+
/** True for a whole-route unset (reconciliation deletes the ledger slot). */
|
|
49
|
+
unset: boolean
|
|
50
|
+
/** Exact ledger entry to re-commit when not unset. */
|
|
51
|
+
entry?: GoOwnershipEntry
|
|
52
|
+
/** Write timestamp (injected clock in tests). */
|
|
53
|
+
at: number
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface JournalReadResult {
|
|
57
|
+
journal?: GoWriteJournal
|
|
58
|
+
/** Slot existed but could not be parsed — treat as "no journal" + warn. */
|
|
59
|
+
parseError?: string
|
|
60
|
+
/**
|
|
61
|
+
* The slot held a primitive/null (not an object at all). Such a value can
|
|
62
|
+
* never carry a journal; reconciliation warns AND cleans it (after the
|
|
63
|
+
* key-shape/profile check), unlike a plain parse error on an object slot.
|
|
64
|
+
*/
|
|
65
|
+
rawTypeCorrupt?: boolean
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface GoJournalStore {
|
|
69
|
+
read(key: string): Promise<JournalReadResult>
|
|
70
|
+
write(key: string, journal: GoWriteJournal): Promise<void>
|
|
71
|
+
delete(key: string): Promise<void>
|
|
72
|
+
/** All journal slots belonging to this profile (any key fingerprint). */
|
|
73
|
+
list(profileKey: string): Promise<string[]>
|
|
74
|
+
/** Delete every journal slot of this profile; returns the number removed. */
|
|
75
|
+
clearProfile(profileKey: string): Promise<number>
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Four-part journal slot: `<profile>#<route>#<keyFingerprint>#journal`. */
|
|
79
|
+
export function goJournalKey(profileKey: string, route: string, keyFingerprint: string): string {
|
|
80
|
+
return `${profileKey}#${goOwnershipKey(route, keyFingerprint)}#${JOURNAL_TAIL}`
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* True for a syntactically journal-shaped slot of the given profile. We match
|
|
85
|
+
* the profile PREFIX and the `#journal` TAIL rather than a fixed part count: a
|
|
86
|
+
* profile name may itself contain '#', and the payload's profile/fingerprint
|
|
87
|
+
* stamps are validated independently on read.
|
|
88
|
+
*/
|
|
89
|
+
export function isJournalKey(key: string, profileKey: string): boolean {
|
|
90
|
+
const prefix = `${profileKey}#`
|
|
91
|
+
const tail = `#${JOURNAL_TAIL}`
|
|
92
|
+
if (!key.startsWith(prefix) || !key.endsWith(tail)) return false
|
|
93
|
+
const middle = key.slice(prefix.length, -tail.length)
|
|
94
|
+
return middle.length > 0 && middle.includes('#')
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function canonicalize(value: unknown): unknown {
|
|
98
|
+
if (Array.isArray(value)) return value.map(canonicalize)
|
|
99
|
+
if (isRecord(value)) {
|
|
100
|
+
const out: Record<string, unknown> = {}
|
|
101
|
+
for (const key of Object.keys(value).sort()) out[key] = canonicalize(value[key])
|
|
102
|
+
return out
|
|
103
|
+
}
|
|
104
|
+
return value
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Stable content hash of a route's models array. The writer calls this on the
|
|
109
|
+
* exact array it hands to settings.mutate; reconciliation calls it on the raw
|
|
110
|
+
* models read back from settings. Sorting by id + recursively canonical field
|
|
111
|
+
* order makes the two agree regardless of key insertion or array order.
|
|
112
|
+
*/
|
|
113
|
+
export function journalContentHash(models: readonly SettingsModelProfile[]): string {
|
|
114
|
+
// oldfox #5: localeCompare is host/locale-dependent, so the same models array
|
|
115
|
+
// could hash differently on two machines sharing a store → `journal-stale`
|
|
116
|
+
// false positives. JS string `<` compares UTF-16 code units (deterministic
|
|
117
|
+
// byte/codepoint order for these ASCII ids), making the hash locale-proof.
|
|
118
|
+
const stable = [...models]
|
|
119
|
+
.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
|
120
|
+
.map((model) => canonicalize(model))
|
|
121
|
+
return createHash('sha256').update(JSON.stringify(stable)).digest('hex')
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function errorText(err: unknown): string {
|
|
125
|
+
const message = (err as { message?: unknown } | null | undefined)?.message
|
|
126
|
+
return typeof message === 'string' ? message : String(err)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
130
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Defensive bound against a corrupt/hostile journal carrying an oversized
|
|
135
|
+
* entry. Legitimate ledgers are far smaller; this only rejects absurd arrays
|
|
136
|
+
* before they are copied into an in-memory ledger.
|
|
137
|
+
*/
|
|
138
|
+
const MAX_LEDGER_ENTRIES = 100_000
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* oldfox #4: `entry` is the exact object reconciliation re-commits to the
|
|
142
|
+
* ownership ledger, so a malformed one must never enter it. parseJournal used
|
|
143
|
+
* to accept any object here; validate the real GoOwnershipEntry shape instead:
|
|
144
|
+
* the required `managed` id→{hash} map plus every optional field's type. On
|
|
145
|
+
* failure the whole slot is treated as an unparseable journal (warn + clean),
|
|
146
|
+
* never reconciled.
|
|
147
|
+
*/
|
|
148
|
+
function isValidOwnershipEntry(value: unknown): value is GoOwnershipEntry {
|
|
149
|
+
if (!isRecord(value)) return false
|
|
150
|
+
const managed = value.managed
|
|
151
|
+
if (!isRecord(managed)) return false
|
|
152
|
+
const ids = Object.keys(managed)
|
|
153
|
+
if (ids.length > MAX_LEDGER_ENTRIES) return false
|
|
154
|
+
for (const id of ids) {
|
|
155
|
+
if (id.length === 0) return false
|
|
156
|
+
const owner = managed[id]
|
|
157
|
+
if (!isRecord(owner) || typeof owner.hash !== 'string' || owner.hash.length === 0) return false
|
|
158
|
+
}
|
|
159
|
+
if (value.routeFields !== undefined && !isRecord(value.routeFields)) return false
|
|
160
|
+
if (value.preManagedSnapshot !== undefined) {
|
|
161
|
+
if (!Array.isArray(value.preManagedSnapshot) || value.preManagedSnapshot.length > MAX_LEDGER_ENTRIES) return false
|
|
162
|
+
if (value.preManagedSnapshot.some((m) => !isRecord(m) || typeof m.id !== 'string')) return false
|
|
163
|
+
}
|
|
164
|
+
if (value.preManagedSection !== undefined
|
|
165
|
+
&& value.preManagedSection !== null && !isRecord(value.preManagedSection)) return false
|
|
166
|
+
if (value.appliedAddedIds !== undefined) {
|
|
167
|
+
if (!Array.isArray(value.appliedAddedIds) || value.appliedAddedIds.length > MAX_LEDGER_ENTRIES) return false
|
|
168
|
+
if (value.appliedAddedIds.some((id) => typeof id !== 'string')) return false
|
|
169
|
+
}
|
|
170
|
+
if (value.missing !== undefined) {
|
|
171
|
+
if (!isRecord(value.missing)) return false
|
|
172
|
+
const missingIds = Object.keys(value.missing)
|
|
173
|
+
if (missingIds.length > MAX_LEDGER_ENTRIES) return false
|
|
174
|
+
for (const id of missingIds) {
|
|
175
|
+
const count = value.missing[id]
|
|
176
|
+
if (typeof count !== 'number' || !Number.isFinite(count)) return false
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return true
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Strict parse: any missing/mistyped field is a parse failure, never a journal. */
|
|
183
|
+
export function parseJournal(raw: unknown): { journal?: GoWriteJournal; error?: string } {
|
|
184
|
+
if (!isRecord(raw)) return { error: 'journal slot is not an object' }
|
|
185
|
+
if (raw.version !== JOURNAL_VERSION) return { error: `unsupported journal version ${String(raw.version)}` }
|
|
186
|
+
if (typeof raw.profileKey !== 'string' || raw.profileKey.length === 0) return { error: 'journal has no profileKey' }
|
|
187
|
+
if (typeof raw.route !== 'string' || raw.route.length === 0) return { error: 'journal has no route' }
|
|
188
|
+
if (typeof raw.keyFingerprint !== 'string' || raw.keyFingerprint.length === 0) return { error: 'journal has no keyFingerprint' }
|
|
189
|
+
if (!Array.isArray(raw.modelIds) || raw.modelIds.some((id) => typeof id !== 'string')) {
|
|
190
|
+
return { error: 'journal has invalid modelIds' }
|
|
191
|
+
}
|
|
192
|
+
if (typeof raw.contentHash !== 'string' || raw.contentHash.length === 0) return { error: 'journal has no contentHash' }
|
|
193
|
+
if (typeof raw.unset !== 'boolean') return { error: 'journal has no unset flag' }
|
|
194
|
+
if (!raw.unset && raw.entry === undefined) return { error: 'journal has no ledger entry' }
|
|
195
|
+
if (typeof raw.at !== 'number' || !Number.isFinite(raw.at)) return { error: 'journal has invalid timestamp' }
|
|
196
|
+
const journal: GoWriteJournal = {
|
|
197
|
+
version: JOURNAL_VERSION,
|
|
198
|
+
profileKey: raw.profileKey,
|
|
199
|
+
route: raw.route,
|
|
200
|
+
keyFingerprint: raw.keyFingerprint,
|
|
201
|
+
modelIds: [...raw.modelIds] as string[],
|
|
202
|
+
contentHash: raw.contentHash,
|
|
203
|
+
unset: raw.unset,
|
|
204
|
+
at: raw.at,
|
|
205
|
+
}
|
|
206
|
+
if (typeof raw.expectedRevision === 'number') journal.expectedRevision = raw.expectedRevision
|
|
207
|
+
// Validate whenever an entry is present (also on unset journals, where a
|
|
208
|
+
// stale malformed entry must not survive into a later re-commit).
|
|
209
|
+
if (raw.entry !== undefined) {
|
|
210
|
+
if (!isValidOwnershipEntry(raw.entry)) return { error: 'journal has invalid ledger entry' }
|
|
211
|
+
journal.entry = raw.entry
|
|
212
|
+
}
|
|
213
|
+
return { journal }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** File-backed journal store built on the same atomic queue as the ledger. */
|
|
217
|
+
export function createFileJournalStore(accessor: ModelsStoreAccessor): GoJournalStore {
|
|
218
|
+
return {
|
|
219
|
+
async read(key) {
|
|
220
|
+
let raw: unknown
|
|
221
|
+
try {
|
|
222
|
+
raw = await accessor.readRaw(key)
|
|
223
|
+
} catch (err) {
|
|
224
|
+
return { parseError: `journal read failed: ${errorText(err)}` }
|
|
225
|
+
}
|
|
226
|
+
if (raw === undefined) return {}
|
|
227
|
+
if (!isRecord(raw)) {
|
|
228
|
+
// A primitive/null slot is not "no journal" — it is corruption that
|
|
229
|
+
// can never carry a valid journal. Flag it so reconciliation warns and
|
|
230
|
+
// cleans it under the key-shape/profile safety check.
|
|
231
|
+
return {
|
|
232
|
+
parseError: `journal slot held a non-object value (${raw === null ? 'null' : typeof raw})`,
|
|
233
|
+
rawTypeCorrupt: true,
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
const parsed = parseJournal(raw)
|
|
237
|
+
return parsed.journal !== undefined
|
|
238
|
+
? { journal: parsed.journal }
|
|
239
|
+
: { parseError: parsed.error ?? 'unknown journal parse failure' }
|
|
240
|
+
},
|
|
241
|
+
async write(key, journal) {
|
|
242
|
+
await accessor.writeRaw(key, journal as unknown as Record<string, unknown>)
|
|
243
|
+
},
|
|
244
|
+
async delete(key) {
|
|
245
|
+
await accessor.deleteRaw(key)
|
|
246
|
+
},
|
|
247
|
+
async list(profileKey) {
|
|
248
|
+
// Do NOT swallow enumeration failures. An unreadable store must reach
|
|
249
|
+
// reconcileJournals' try/catch and surface `journal-list-failed`, not be
|
|
250
|
+
// mistaken for "no journals this round".
|
|
251
|
+
return (await accessor.listRawKeys()).filter((key) => isJournalKey(key, profileKey))
|
|
252
|
+
},
|
|
253
|
+
async clearProfile(profileKey) {
|
|
254
|
+
const keys = await this.list(profileKey)
|
|
255
|
+
let deleted = 0
|
|
256
|
+
for (const key of keys) {
|
|
257
|
+
try {
|
|
258
|
+
await accessor.deleteRaw(key)
|
|
259
|
+
deleted += 1
|
|
260
|
+
} catch {
|
|
261
|
+
// Best effort: a surviving slot is re-validated (and discarded) by
|
|
262
|
+
// the next reconciliation, never replayed blindly.
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return deleted
|
|
266
|
+
},
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function createModelsStoreJournalStore(storePath?: string): GoJournalStore {
|
|
271
|
+
return createFileJournalStore(loadModelsStore(storePath))
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---------------------------------------------------------------------------
|
|
275
|
+
// Reconciliation (called once per round, BEFORE the migration gate)
|
|
276
|
+
// ---------------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
export interface JournalNotice {
|
|
279
|
+
code: 'journal-reconciled' | 'journal-stale' | 'journal-orphan'
|
|
280
|
+
| 'journal-unparseable' | 'journal-reconcile-failed' | 'journal-list-failed'
|
|
281
|
+
// oldfox #2: the descriptor-unavailable branch is a distinct condition from
|
|
282
|
+
// a store enumeration failure. Sharing `journal-list-failed` misled
|
|
283
|
+
// machine consumers into reporting a list error when nothing was listed.
|
|
284
|
+
| 'journal-descriptor-unavailable'
|
|
285
|
+
level: 'info' | 'warn' | 'error'
|
|
286
|
+
key: string
|
|
287
|
+
message: string
|
|
288
|
+
/** True for a primitive/null slot (vs an object that merely failed parsing). */
|
|
289
|
+
rawTypeCorrupt?: boolean
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export interface ReconcileResult {
|
|
293
|
+
reconciled: string[]
|
|
294
|
+
discarded: string[]
|
|
295
|
+
notices: JournalNotice[]
|
|
296
|
+
lines: string[]
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export interface ReconcileDeps {
|
|
300
|
+
journalStore: GoJournalStore
|
|
301
|
+
ownershipStore: GoOwnershipStore
|
|
302
|
+
settings: SettingsService | undefined
|
|
303
|
+
profileKey: string
|
|
304
|
+
keyFingerprint: string
|
|
305
|
+
logger: Logger
|
|
306
|
+
/** Same callback the writer uses after a healthy own-write: re-persist the
|
|
307
|
+
* migration record. Store/record only — never touches settings. */
|
|
308
|
+
onRecord?: (route: string, managedIds: string[]) => Promise<void> | void
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function rawModels(desc: SettingsDescriptor | undefined, route: string): SettingsModelProfile[] {
|
|
312
|
+
const providers = desc?.user?.providers as Record<string, unknown> | undefined
|
|
313
|
+
if (providers === undefined) return []
|
|
314
|
+
const data = providers[route]
|
|
315
|
+
if (data === null || typeof data !== 'object' || Array.isArray(data)) return []
|
|
316
|
+
const models = (data as Record<string, unknown>).models
|
|
317
|
+
return Array.isArray(models) ? models as SettingsModelProfile[] : []
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Reconcile every journal of this profile against the value actually present
|
|
322
|
+
* in settings. Outcomes:
|
|
323
|
+
* hash equal → re-commit ledger + migration record, delete journal;
|
|
324
|
+
* hash differs → the user edited the value: discard journal, keep their value;
|
|
325
|
+
* wrong scope → orphan (profile/key rotation): discard journal;
|
|
326
|
+
* parse fail → treat as no journal, warn, discard;
|
|
327
|
+
* raw-type slot → warn (journal-unparseable + rawTypeCorrupt flag) and clean
|
|
328
|
+
* it after a journal-key / profile safety check;
|
|
329
|
+
* store fail → keep journal for the next round, never block the round.
|
|
330
|
+
*/
|
|
331
|
+
export async function reconcileJournals(deps: ReconcileDeps): Promise<ReconcileResult> {
|
|
332
|
+
const result: ReconcileResult = { reconciled: [], discarded: [], notices: [], lines: [] }
|
|
333
|
+
const notice = (entry: JournalNotice): void => {
|
|
334
|
+
result.notices.push(entry)
|
|
335
|
+
result.lines.push(` [${entry.level}] ${entry.code} ${entry.key}: ${entry.message}`)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
let keys: string[]
|
|
339
|
+
try {
|
|
340
|
+
keys = await deps.journalStore.list(deps.profileKey)
|
|
341
|
+
} catch (err) {
|
|
342
|
+
const key = `profile:${deps.profileKey}`
|
|
343
|
+
deps.logger.warn('journal list failed for %s: %s', deps.profileKey, errorText(err))
|
|
344
|
+
notice({
|
|
345
|
+
code: 'journal-list-failed', level: 'warn', key,
|
|
346
|
+
message: `could not list write-ahead journals (${errorText(err)}); reconciliation skipped this round`,
|
|
347
|
+
})
|
|
348
|
+
return result
|
|
349
|
+
}
|
|
350
|
+
if (keys.length === 0) return result
|
|
351
|
+
|
|
352
|
+
const desc = deps.settings?.describe().find((entry) => entry.ns === 'llm-pi-ai')
|
|
353
|
+
if (desc === undefined) {
|
|
354
|
+
// Cannot verify the present hash — keep every journal, never guess.
|
|
355
|
+
// This is NOT a list failure: enumeration succeeded. Use a dedicated code
|
|
356
|
+
// so automation can tell the two apart (oldfox #2). Text stays accurate:
|
|
357
|
+
// journals are kept, not discarded.
|
|
358
|
+
notice({
|
|
359
|
+
code: 'journal-descriptor-unavailable', level: 'warn', key: `profile:${deps.profileKey}`,
|
|
360
|
+
message: 'llm-pi-ai descriptor unavailable; journals kept for a later round (reconciliation deferred, no list error)',
|
|
361
|
+
})
|
|
362
|
+
return result
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
for (const key of keys) {
|
|
366
|
+
let read: JournalReadResult
|
|
367
|
+
try {
|
|
368
|
+
read = await deps.journalStore.read(key)
|
|
369
|
+
} catch (err) {
|
|
370
|
+
deps.logger.warn('journal read failed for %s: %s', key, errorText(err))
|
|
371
|
+
notice({ code: 'journal-unparseable', level: 'warn', key, message: `read failed (${errorText(err)}); journal kept` })
|
|
372
|
+
continue
|
|
373
|
+
}
|
|
374
|
+
if (read.parseError !== undefined) {
|
|
375
|
+
deps.logger.warn('unparseable journal %s: %s', key, read.parseError)
|
|
376
|
+
if (read.rawTypeCorrupt === true) {
|
|
377
|
+
// A primitive/null slot can never carry a valid journal. Same warn code
|
|
378
|
+
// as an object-shape parse failure, but flagged and explicitly worded so
|
|
379
|
+
// the raw-type case is recognizable. Clean it ONLY after re-confirming
|
|
380
|
+
// the slot is a journal-shaped key of THIS profile — never touch a
|
|
381
|
+
// foreign or non-journal key that happens to hold a primitive.
|
|
382
|
+
notice({
|
|
383
|
+
code: 'journal-unparseable', level: 'warn', key, rawTypeCorrupt: true,
|
|
384
|
+
message: `${read.parseError}; raw-type corruption (cannot carry a journal) — slot discarded and cleaned`,
|
|
385
|
+
})
|
|
386
|
+
if (isJournalKey(key, deps.profileKey)) {
|
|
387
|
+
try { await deps.journalStore.delete(key) } catch { /* best effort */ }
|
|
388
|
+
}
|
|
389
|
+
} else {
|
|
390
|
+
notice({ code: 'journal-unparseable', level: 'warn', key, message: `${read.parseError}; journal discarded (treated as no journal)` })
|
|
391
|
+
try { await deps.journalStore.delete(key) } catch { /* best effort */ }
|
|
392
|
+
}
|
|
393
|
+
result.discarded.push(key)
|
|
394
|
+
continue
|
|
395
|
+
}
|
|
396
|
+
const journal = read.journal
|
|
397
|
+
if (journal === undefined) continue
|
|
398
|
+
|
|
399
|
+
const expectedKey = goJournalKey(deps.profileKey, journal.route, journal.keyFingerprint)
|
|
400
|
+
if (journal.profileKey !== deps.profileKey || journal.keyFingerprint !== deps.keyFingerprint
|
|
401
|
+
|| key !== expectedKey) {
|
|
402
|
+
deps.logger.warn('orphan journal %s (profile=%s key=%s)', key, journal.profileKey, journal.keyFingerprint)
|
|
403
|
+
notice({
|
|
404
|
+
code: 'journal-orphan', level: 'warn', key,
|
|
405
|
+
message: `profile/key fingerprint mismatch (profile=${journal.profileKey}, key=${journal.keyFingerprint}); discarded, never replayed`,
|
|
406
|
+
})
|
|
407
|
+
try { await deps.journalStore.delete(key) } catch { /* best effort */ }
|
|
408
|
+
result.discarded.push(key)
|
|
409
|
+
continue
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
const currentHash = journalContentHash(rawModels(desc, journal.route))
|
|
413
|
+
if (currentHash !== journal.contentHash) {
|
|
414
|
+
deps.logger.warn('stale journal %s: current settings hash differs', key)
|
|
415
|
+
notice({
|
|
416
|
+
code: 'journal-stale', level: 'warn', key,
|
|
417
|
+
message: `current settings differ from the recorded write hash; journal discarded and the user's value kept`,
|
|
418
|
+
})
|
|
419
|
+
try { await deps.journalStore.delete(key) } catch { /* best effort */ }
|
|
420
|
+
result.discarded.push(key)
|
|
421
|
+
continue
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
try {
|
|
425
|
+
const ledgerKey = goOwnershipKey(journal.route, deps.keyFingerprint)
|
|
426
|
+
if (journal.unset || journal.entry === undefined) {
|
|
427
|
+
await deps.ownershipStore.delete(ledgerKey)
|
|
428
|
+
} else {
|
|
429
|
+
await deps.ownershipStore.write(ledgerKey, journal.entry)
|
|
430
|
+
}
|
|
431
|
+
if (deps.onRecord !== undefined) {
|
|
432
|
+
await deps.onRecord(journal.route, [...journal.modelIds].sort())
|
|
433
|
+
}
|
|
434
|
+
await deps.journalStore.delete(key)
|
|
435
|
+
result.reconciled.push(journal.route)
|
|
436
|
+
notice({
|
|
437
|
+
code: 'journal-reconciled', level: 'info', key,
|
|
438
|
+
message: `present value matches the recorded write; ownership ledger + migration record re-committed`,
|
|
439
|
+
})
|
|
440
|
+
} catch (err) {
|
|
441
|
+
// Keep the journal so a later round retries. Never block the round: the
|
|
442
|
+
// user's settings are untouched by reconciliation by construction.
|
|
443
|
+
deps.logger.warn('journal reconciliation failed for %s: %s', key, errorText(err))
|
|
444
|
+
notice({
|
|
445
|
+
code: 'journal-reconcile-failed', level: 'warn', key,
|
|
446
|
+
message: `ledger/record re-commit failed (${errorText(err)}); journal kept for the next round`,
|
|
447
|
+
})
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
return result
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** One-line summary prepended to the round report when anything reconciled. */
|
|
455
|
+
export function formatReconcileSummary(result: ReconcileResult): string {
|
|
456
|
+
if (result.reconciled.length === 0 && result.discarded.length === 0 && result.notices.length === 0) return ''
|
|
457
|
+
return `opencode-go: journal reconciliation: ${result.reconciled.length} re-committed, ${result.discarded.length} discarded`
|
|
458
|
+
}
|