@kabxx/dsh-message-revision 0.0.0-stage → 0.1.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.
@@ -0,0 +1,484 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { lstat, open, readFile, realpath, rename, unlink } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join } from 'node:path';
4
+ import {
5
+ cleanRewriteDebris, clearFailedCommitMarker, forgetRewriteJournal, hasPendingRewrite, listRewriteDebris, markRewriteCommitted,
6
+ matchJournalRevision, prepareRewriteJournal, readRewriteJournals, readRewriteOriginal, restoreWithdrawnChildren,
7
+ retireRewriteJournal, stageWithdrawnChildren,
8
+ } from './rewrite-journal.js';
9
+ import { promisify } from 'node:util';
10
+ import { constants, zstdCompress, zstdDecompress } from 'node:zlib';
11
+
12
+ const compress = promisify(zstdCompress);
13
+ const decompress = promisify(zstdDecompress);
14
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
15
+ const maxBytes = 256 * 1024 * 1024;
16
+ const logName = /^session\.v4\.jsonl(?:\.zstd)?$/u;
17
+
18
+ export class RevisionError extends Error {
19
+ constructor(message, options) {
20
+ super(message, options);
21
+ this.name = 'RevisionError';
22
+ }
23
+ }
24
+
25
+ function requireRevision(condition, message) {
26
+ if (!condition) throw new RevisionError(message);
27
+ }
28
+
29
+ /** Find the beginning of the turn and the existing next-turn queue entry. */
30
+ export function planRevision(events, messageId, inheritedCount = 0) {
31
+ const queues = { 'next-turn': [], 'next-step': [] };
32
+ let turn;
33
+ let selected;
34
+ let checkpoint;
35
+ const inputCopies = [];
36
+ for (const [index, event] of events.entries()) {
37
+ requireRevision(event.seq === index, '会话日志的事件顺序不完整。');
38
+ const data = event.data;
39
+ if (event.type === 'agent/inbox/spliced') {
40
+ const queue = queues[data.target];
41
+ const count = data.removedCount ?? 0;
42
+ requireRevision(queue && Number.isSafeInteger(data.start) && data.start >= 0
43
+ && Number.isSafeInteger(count) && count >= 0 && data.start + count <= queue.length
44
+ && Array.isArray(data.inserted), '无法安全复原会话的消息队列。');
45
+ const inserted = data.inserted.map((message, offset) => ({ message, index, offset }));
46
+ for (const item of inserted) if (item.message.id === messageId) inputCopies.push(item);
47
+ queue.splice(data.start, count, ...inserted);
48
+ } else if (event.type === 'turn/start') {
49
+ requireRevision(turn === undefined, '会话日志中存在未关闭的回合。');
50
+ turn = {
51
+ index,
52
+ number: data.turn,
53
+ input: queues['next-turn'][0],
54
+ queuedCount: queues['next-turn'].length,
55
+ hasSteering: queues['next-step'].length > 0,
56
+ };
57
+ } else if (event.type === 'turn/end') {
58
+ requireRevision(turn?.number === data.turn, '会话日志的回合边界不完整。');
59
+ turn = undefined;
60
+ } else if (event.type === 'user/message' && data?.id === messageId && data.source?.kind === 'user') {
61
+ requireRevision(selected === undefined, '日志中找到了重复的用户消息。');
62
+ selected = event;
63
+ checkpoint = turn;
64
+ }
65
+ }
66
+ requireRevision(turn === undefined, '回复生成中,请先停止或等待完成。');
67
+ requireRevision(selected && checkpoint?.input?.message.id === messageId
68
+ && checkpoint.index > inheritedCount && checkpoint.input.index >= inheritedCount
69
+ && !checkpoint.hasSteering && checkpoint.queuedCount === 1,
70
+ '此消息没有可独立回退的对话轮次。');
71
+ requireRevision(queues['next-turn'].length === 0 && queues['next-step'].length === 0,
72
+ '会话仍有排队消息,请等队列清空后再试。');
73
+ const retainedInputs = inputCopies.filter(item => item.index < checkpoint.index);
74
+ requireRevision(retainedInputs.every(item => item.index >= inheritedCount && item.message.source?.kind === 'user'),
75
+ '无法替换继承历史中的同一条消息。');
76
+ return {
77
+ cut: checkpoint.index,
78
+ retainedInputs,
79
+ time: events[checkpoint.index].time,
80
+ message: checkpoint.input.message,
81
+ };
82
+ }
83
+
84
+ export function isRevisionAttachment(block) {
85
+ return (block?.type === 'image' || block?.type === 'file') && typeof block.attachment === 'object' && block.attachment !== null;
86
+ }
87
+
88
+ export function retainedRevisionAttachments(message, removed = []) {
89
+ requireRevision(Array.isArray(message.content), '无法读取该消息正文。');
90
+ for (const index of removed) {
91
+ requireRevision(isRevisionAttachment(message.content[index]), '无法确认待移除的附件。');
92
+ }
93
+ const ignored = new Set(removed);
94
+ return message.content.filter((block, index) => isRevisionAttachment(block) && !ignored.has(index));
95
+ }
96
+
97
+ export function revisionTextParts(message) {
98
+ return message.content.filter(block => block.type === 'text').map(block => block.text);
99
+ }
100
+
101
+ export function resolveRevisionText(message, { text, textParts }) {
102
+ const original = revisionTextParts(message);
103
+ if (textParts !== undefined) {
104
+ requireRevision(Array.isArray(textParts) && original.length > 1 && textParts.length === original.length
105
+ && textParts.every(part => typeof part === 'string') && textParts.join('') === text,
106
+ '分段正文与原消息不匹配,请重新打开编辑框。');
107
+ return textParts;
108
+ }
109
+ if (text === original.join('')) return original;
110
+ requireRevision(original.length <= 1, '此消息包含多段正文,请使用分段编辑。');
111
+ return [text];
112
+ }
113
+
114
+ function rewriteMessage(message, input, removed, added) {
115
+ const retained = retainedRevisionAttachments(message, removed);
116
+ const textParts = resolveRevisionText(message, input);
117
+ requireRevision(input.text.trim() !== '' || retained.length > 0 || added.length > 0, '请输入消息内容或至少保留一个附件。');
118
+ const ignored = new Set(removed);
119
+ const content = [];
120
+ let part = 0;
121
+ for (const [index, block] of message.content.entries()) {
122
+ if (block.type === 'text') {
123
+ const replacement = textParts[part++];
124
+ if (replacement === block.text) content.push(block);
125
+ else if (replacement !== '') content.push({ ...block, text: replacement });
126
+ } else if (!ignored.has(index)) {
127
+ content.push(block);
128
+ }
129
+ }
130
+ if (part === 0 && input.text.trim() !== '') content.unshift({ type: 'text', text: input.text });
131
+ return { ...message, content: [...content, ...added] };
132
+ }
133
+
134
+ function validateText(text) {
135
+ requireRevision(typeof text === 'string' && text.length <= 200_000,
136
+ '消息内容无效,最多支持 200,000 个字符。');
137
+ }
138
+
139
+ function checkLocation(snapshot) {
140
+ const path = snapshot?.location?.path;
141
+ requireRevision(snapshot?.location?.kind === 'jsonl' && typeof path === 'string'
142
+ && isAbsolute(path) && logName.test(basename(path)), '当前会话存储格式不支持编辑。');
143
+ return path;
144
+ }
145
+
146
+ async function checkArtifact(path) {
147
+ const identity = await lstat(path, { bigint: true });
148
+ requireRevision(identity.isFile() && !identity.isSymbolicLink() && await realpath(path) === path,
149
+ '会话日志路径异常。');
150
+ requireRevision(identity.size <= maxBytes, '会话日志超出大小上限,无法编辑。');
151
+ return identity;
152
+ }
153
+
154
+ async function openLocked(persistence, sessionId, snapshot) {
155
+ const path = checkLocation(snapshot);
156
+ const identity = await checkArtifact(path);
157
+ const handle = await persistence.open(sessionId, 'write');
158
+ try {
159
+ const current = await persistence.stat(sessionId);
160
+ requireRevision(handle.header.id === sessionId && checkLocation(current) === path
161
+ && current.revision === snapshot.revision, '会话状态已变更,请刷新后重试。');
162
+ const { events } = await handle.read(0);
163
+ return { handle, path, identity, events, snapshot: current };
164
+ } catch (error) {
165
+ await handle.close();
166
+ throw error;
167
+ }
168
+ }
169
+
170
+ async function encodeReplacement(source, plan, message, controls, restoredCatalog) {
171
+ const compressed = source.path.endsWith('.zstd');
172
+ const raw = await readFile(source.path);
173
+ const decoded = compressed ? await decompress(raw, { maxOutputLength: maxBytes }) : raw;
174
+ const lines = utf8.decode(decoded).split('\n');
175
+ requireRevision(lines.pop() === '' && lines.length === source.events.length + 1,
176
+ '会话日志不完整,已取消编辑。');
177
+ const header = JSON.parse(lines[0]);
178
+ requireRevision(header.type === 'session' && header.version === 4 && header.id === source.handle.header.id,
179
+ '会话日志文件头不匹配。');
180
+ const prefix = lines.slice(1, plan.cut + 1);
181
+ // A previous edit may have canceled the original queue occurrence and
182
+ // enqueued the same message again. Keep native splice semantics and replace
183
+ // the content in every retained occurrence of this specific user input.
184
+ for (const { index, offset } of plan.retainedInputs) {
185
+ const encodedInput = JSON.parse(prefix[index]);
186
+ const occurrence = encodedInput.data?.inserted?.[offset];
187
+ requireRevision(encodedInput.seq === index && encodedInput.type === 'agent/inbox/spliced'
188
+ && occurrence?.id === message.id && occurrence.source?.kind === 'user', '无法定位原消息的入队记录。');
189
+ encodedInput.data.inserted[offset] = { ...occurrence, content: message.content };
190
+ prefix[index] = JSON.stringify(encodedInput);
191
+ }
192
+ for (const event of restoredCatalog) {
193
+ prefix.push(JSON.stringify({ ...event, seq: prefix.length, time: plan.time }));
194
+ }
195
+ for (const control of controls) {
196
+ prefix.push(JSON.stringify({ type: control.type, seq: prefix.length, time: Date.now(), data: control.data }));
197
+ }
198
+ const headerBytes = Buffer.from(`${lines[0]}\n`);
199
+ const eventBytes = Buffer.from(`${prefix.join('\n')}\n`);
200
+ if (!compressed) return { original: raw, buffers: [headerBytes, eventBytes], retained: prefix.length };
201
+ const options = { params: { [constants.ZSTD_c_checksumFlag]: 1 } };
202
+ const buffers = await Promise.all([compress(headerBytes, options), compress(eventBytes, options)]);
203
+ return { original: raw, buffers, retained: prefix.length };
204
+ }
205
+
206
+ function catalogEntries(events) {
207
+ return events.filter(event => event.type === 'subagent/catalog');
208
+ }
209
+
210
+ function verifyCatalogBirth(event) {
211
+ const { childId, childCreatedAt, mode } = event.data;
212
+ requireRevision(typeof childId === 'string' && childId.length > 0
213
+ && ['continuable', 'one-shot', 'unknown', 'external'].includes(mode)
214
+ && Number.isSafeInteger(childCreatedAt) && childCreatedAt >= 0 && childCreatedAt <= event.time,
215
+ '无法确认子会话的登记或创建时间。');
216
+ }
217
+
218
+ /** Native migration can append an older child's creation fact at the log tail. */
219
+ export function splitChildCatalog(catalog, { cut, time }) {
220
+ const retained = [];
221
+ const withdrawn = [];
222
+ const seen = new Set();
223
+ for (const event of catalog) {
224
+ verifyCatalogBirth(event);
225
+ const { childId, childCreatedAt } = event.data;
226
+ requireRevision(!seen.has(childId), '子会话登记重复,无法安全判断归属。');
227
+ seen.add(childId);
228
+ if (event.seq < cut) {
229
+ requireRevision(childCreatedAt <= time, '子会话的创建时间与会话顺序不一致。');
230
+ retained.push(event);
231
+ } else {
232
+ requireRevision(childCreatedAt !== time, '子会话的创建时间与改写点重合,无法安全判定归属。');
233
+ (childCreatedAt < time ? retained : withdrawn).push(event);
234
+ }
235
+ }
236
+ return { retained, withdrawn };
237
+ }
238
+
239
+ function verifyChildHeader(header, parent, { childId, childCreatedAt }) {
240
+ requireRevision(header.id === childId && header.parentSession === parent.handle.header.id
241
+ && header.origin === 'subagent' && header.createdAt === childCreatedAt,
242
+ '子会话的实际归属或创建时间与登记不匹配。');
243
+ }
244
+
245
+ async function collectChildTree(persistence, parent, catalog, cutoff, locked, seen) {
246
+ for (const event of catalog) {
247
+ verifyCatalogBirth(event);
248
+ const { childId, childCreatedAt, mode } = event.data;
249
+ requireRevision(!seen.has(childId) && mode !== 'external', '无法安全核对子会话树。');
250
+ seen.add(childId);
251
+ requireRevision(childCreatedAt >= parent.handle.header.createdAt, '子会话早于其父会话,无法确认创建顺序。');
252
+ const snapshot = await persistence.stat(childId);
253
+ requireRevision(snapshot, '子会话记录不可用,无法核对其历史与后代。');
254
+ verifyChildHeader(snapshot.header, parent, event.data);
255
+
256
+ // The native writer lock makes the entire traversed subtree stable until the
257
+ // parent commits. It also catches descendants that are live or opening.
258
+ let child;
259
+ try {
260
+ child = await openLocked(persistence, childId, snapshot);
261
+ } catch (error) {
262
+ if (error.name === 'SessionAlreadyOwnedError') {
263
+ throw new RevisionError('关联的子智能体会话或其后代仍处于打开状态,请关闭后重试。', { cause: error });
264
+ }
265
+ throw error;
266
+ }
267
+ locked.push(child);
268
+ verifyChildHeader(child.handle.header, parent, event.data);
269
+ const ownEvents = child.events.slice(child.handle.inheritedEventCount);
270
+ if (cutoff !== undefined) {
271
+ requireRevision(childCreatedAt < cutoff && ownEvents.every(item => item.time < cutoff),
272
+ '保留的子智能体会话或其后代跨过改写点,无法编辑此消息。');
273
+ let inTurn = false;
274
+ for (const item of ownEvents) {
275
+ if (item.type === 'turn/start') inTurn = true;
276
+ if (item.type === 'turn/end') inTurn = false;
277
+ }
278
+ requireRevision(!inTurn, '保留的子智能体会话或其后代存在未关闭的回合。');
279
+ }
280
+ await collectChildTree(persistence, child, catalogEntries(ownEvents), cutoff, locked, seen);
281
+ }
282
+ }
283
+
284
+ async function checkUnchanged(entry) {
285
+ const now = await checkArtifact(entry.path);
286
+ const initial = entry.identity;
287
+ requireRevision(now.dev === initial.dev && now.ino === initial.ino && now.size === initial.size
288
+ && now.mtimeNs === initial.mtimeNs && now.ctimeNs === initial.ctimeNs,
289
+ '日志文件已变化,未继续替换。');
290
+ }
291
+
292
+ async function replaceArtifact(source, buffers, beforeReplace, onPublished, staging = dirname(source.path)) {
293
+ const directory = dirname(source.path);
294
+ const stage = join(staging, `.message-revision-${randomUUID()}.tmp`);
295
+ let pending = false;
296
+ try {
297
+ const file = await open(stage, 'wx', Number(source.identity.mode & 0o777n));
298
+ pending = true;
299
+ try {
300
+ for (const bytes of buffers) await file.writeFile(bytes);
301
+ await file.sync();
302
+ } finally {
303
+ await file.close();
304
+ }
305
+ await checkUnchanged(source);
306
+ await beforeReplace?.();
307
+ await checkUnchanged(source);
308
+ await rename(stage, source.path);
309
+ pending = false;
310
+ onPublished?.();
311
+ if (process.platform !== 'win32') {
312
+ const parent = await open(directory, 'r');
313
+ try { await parent.sync(); } finally { await parent.close(); }
314
+ }
315
+ } finally {
316
+ if (pending) await unlink(stage);
317
+ }
318
+ }
319
+
320
+ function isProvisionalOpenEvent(event) {
321
+ // A failed initializer may have persisted settings or other native events.
322
+ // A turn or an accepted human input could belong to a different operation.
323
+ const { data } = event;
324
+ if (event.type === 'turn/start' || event.type === 'step/start'
325
+ || (event.type === 'user/message' && data.source?.kind === 'user')) return false;
326
+ if (event.type !== 'agent/inbox/spliced') return true;
327
+ return (data.removedCount ?? 0) === 0
328
+ ? data.inserted?.every(message => message.source?.kind !== 'user' && message.source?.kind !== 'retry')
329
+ : data.target === 'next-turn' && data.start === 0 && data.removedCount === 1
330
+ && data.inserted?.length === 0 && data.outcome === 'canceled';
331
+ }
332
+
333
+ async function recoverRewrite(source, journal, { canRollback, beforeCommit } = {}) {
334
+ if (journal.committed) return;
335
+ const revision = await matchJournalRevision(journal);
336
+ requireRevision((canRollback?.() ?? true) && revision !== 'conflict',
337
+ '会话已变化,无法自动恢复上次编辑。');
338
+ if (revision === 'original') {
339
+ await restoreWithdrawnChildren(journal);
340
+ return;
341
+ }
342
+ const retained = journal.intent.candidate.records;
343
+ requireRevision(source.events.length >= retained && source.events.slice(retained).every(isProvisionalOpenEvent),
344
+ '更新后的会话已有新增内容,无法自动回滚。');
345
+ const original = await readRewriteOriginal(journal);
346
+ await replaceArtifact(source, [original], async () => {
347
+ await beforeCommit?.([journal.intent.parentId, ...journal.intent.children.map(child => child.id)]);
348
+ await restoreWithdrawnChildren(journal);
349
+ }, undefined, journal.directory);
350
+ }
351
+
352
+ /** Recover transactions left by a previous Host before admitting new rewrites. */
353
+ export async function recoverStoredSessions(persistence, { beforeCommit, canRollback, onError } = {}) {
354
+ for (const snapshot of await persistence.list()) {
355
+ const { id } = snapshot.header;
356
+ try {
357
+ const journals = await readRewriteJournals(snapshot);
358
+ if (snapshot.location?.kind !== 'jsonl' || !isAbsolute(snapshot.location.path)) continue;
359
+ const { preparations, retired } = await listRewriteDebris(snapshot.location.path);
360
+ if (journals.length > 0 || preparations.length > 0) {
361
+ const source = await openLocked(persistence, id, snapshot);
362
+ try {
363
+ // The journal may have been retired between scanning and claiming the lock.
364
+ for (const journal of await readRewriteJournals(source.snapshot)) {
365
+ await recoverRewrite(source, journal, { beforeCommit, canRollback: () => canRollback?.(id) ?? true });
366
+ await retireRewriteJournal(journal);
367
+ }
368
+ await cleanRewriteDebris((await listRewriteDebris(source.path)).preparations);
369
+ } finally {
370
+ await source.handle.close();
371
+ }
372
+ }
373
+ await cleanRewriteDebris(retired);
374
+ } catch (error) {
375
+ onError?.(id, error);
376
+ }
377
+ }
378
+ }
379
+
380
+ export async function assertNoPendingRewrite(snapshot) {
381
+ if (snapshot?.location?.kind === 'jsonl') {
382
+ requireRevision(!await hasPendingRewrite(checkLocation(snapshot)), '上次编辑尚未完成恢复,请检查运行日志。');
383
+ }
384
+ }
385
+
386
+ /** Publish provisionally, then let DSH open the same ID before discarding any old data. */
387
+ export async function rewriteStoredSession(persistence, {
388
+ sessionId, messageId, text, textParts, expectedRevision, removedAttachments = [],
389
+ }, { beforeCommit, verifyReload, canRollback, closeFailedReload, afterCommit, onCleanupError, addedAttachments = [], controls = [] } = {}) {
390
+ validateText(text);
391
+ const snapshot = await persistence.stat(sessionId);
392
+ requireRevision(expectedRevision === undefined || snapshot?.revision === expectedRevision,
393
+ '会话状态已变更,请重新打开编辑框。');
394
+ const source = await openLocked(persistence, sessionId, snapshot);
395
+ const retainedChildren = [];
396
+ const withdrawnChildren = [];
397
+ let journal;
398
+ let published = false;
399
+ let committed = false;
400
+ let markerFailed = false;
401
+ let handlesClosed = false;
402
+ async function releaseHandles() {
403
+ if (handlesClosed) return;
404
+ handlesClosed = true;
405
+ const results = await Promise.allSettled([
406
+ ...retainedChildren.map(child => child.handle.close()),
407
+ ...withdrawnChildren.map(child => child.handle.close()),
408
+ source.handle.close(),
409
+ ]);
410
+ const failure = results.find(result => result.status === 'rejected');
411
+ if (failure) throw failure.reason;
412
+ }
413
+ try {
414
+ await assertNoPendingRewrite(source.snapshot);
415
+ requireRevision(source.handle.header.origin !== 'subagent', '子智能体会话不支持直接编辑,请在主会话中操作。');
416
+ const plan = planRevision(source.events, messageId, source.handle.inheritedEventCount);
417
+ const catalog = catalogEntries(source.events).filter(event => event.seq >= source.handle.inheritedEventCount);
418
+ const { retained, withdrawn } = splitChildCatalog(catalog, plan);
419
+ const seen = new Set([sessionId]);
420
+ await collectChildTree(persistence, source, retained, plan.time, retainedChildren, seen);
421
+ await collectChildTree(persistence, source, withdrawn, undefined, withdrawnChildren, seen);
422
+ requireRevision(withdrawnChildren.length === 0 || process.platform !== 'win32',
423
+ '当前系统不支持清理关联的子智能体会话。');
424
+ const message = rewriteMessage(plan.message, { text, textParts }, removedAttachments, addedAttachments);
425
+ const replacement = await encodeReplacement(source, plan, message, controls, retained.filter(event => event.seq >= plan.cut));
426
+ const removedChildren = withdrawnChildren.map(child => child.handle.header.id);
427
+ for (const child of [...retainedChildren, ...withdrawnChildren]) await checkUnchanged(child);
428
+ await beforeCommit?.([sessionId, ...removedChildren]);
429
+ journal = await prepareRewriteJournal(source, withdrawnChildren, replacement);
430
+ await replaceArtifact(source, replacement.buffers, async () => {
431
+ for (const child of [...retainedChildren, ...withdrawnChildren]) await checkUnchanged(child);
432
+ await stageWithdrawnChildren(journal);
433
+ }, () => { published = true; }, journal.directory);
434
+ await releaseHandles();
435
+ await verifyReload?.();
436
+ try {
437
+ await markRewriteCommitted(journal);
438
+ } catch (error) {
439
+ markerFailed = true;
440
+ throw error;
441
+ }
442
+ committed = true;
443
+ const result = { messageId, removedChildren };
444
+ try {
445
+ await afterCommit?.(result);
446
+ } finally {
447
+ // Dispatch happens first. Cleanup cannot turn a saved edit into a failed
448
+ // request, and startup will retry committed or partially retired journals.
449
+ try {
450
+ await retireRewriteJournal(journal);
451
+ } catch (error) {
452
+ result.cleanupWarning = true;
453
+ onCleanupError?.(error);
454
+ }
455
+ }
456
+ return result;
457
+ } catch (error) {
458
+ if (committed || !journal) throw error;
459
+ try {
460
+ if (published) {
461
+ await releaseHandles();
462
+ if (markerFailed) await closeFailedReload?.();
463
+ const current = await openLocked(persistence, sessionId, await persistence.stat(sessionId));
464
+ try {
465
+ requireRevision(current.path === source.path && (canRollback?.() ?? true), '无法确认候选会话已释放。');
466
+ if (markerFailed) await clearFailedCommitMarker(journal);
467
+ await recoverRewrite(current, journal, { canRollback, beforeCommit });
468
+ } finally {
469
+ await current.handle.close();
470
+ }
471
+ } else {
472
+ await restoreWithdrawnChildren(journal);
473
+ }
474
+ await retireRewriteJournal(journal);
475
+ } catch (rollbackError) {
476
+ throw new Error('编辑回滚失败,请刷新后检查会话。', { cause: rollbackError });
477
+ }
478
+ if (published) throw new RevisionError('无法加载更新后的会话,已恢复原记录。', { cause: error });
479
+ throw error;
480
+ } finally {
481
+ forgetRewriteJournal(journal);
482
+ await releaseHandles();
483
+ }
484
+ }