@suifei/dsh-ai-team 0.4.161 → 0.4.163

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.
@@ -1,1274 +1,1274 @@
1
- /**
2
- * 单项目账本写入器:append-only JSONL、分段、fsync、单写者锁、尾撕裂修复。
3
- *
4
- * 对应 03-架构设计报告 §6.5 / §6.6 / §8.1、附录 B §B.3.6:
5
- * - 一个 Project 一个 LedgerWriter;进程内 Promise 队列串行化写入。
6
- * - append 成功(默认 fsync 完成)后才更新内存 head;失败回滚到写前长度。
7
- * - 跨段 hash 链连续;打开时全量校验,尾部半行可截断修复并返回修复信息。
8
- * - 锁文件 `lock`:PID + host + startedAt + token,非 OS flock(ADR-11)。
9
- *
10
- * 同时提供 `openLedger()` 门面(供 host service 直接消费):
11
- * { append, appendMany, state, events, head, verify, repair, replay, close }
12
- * 门面在 append 成功之后才推进 state,失败不改变 state。
13
- */
14
-
15
- import fsDefault from 'node:fs';
16
- import os from 'node:os';
17
- import path from 'node:path';
18
- import { randomBytes } from 'node:crypto';
19
- import {
20
- GENESIS_HASH,
21
- HASH_PATTERN,
22
- MAX_EVENT_BYTES,
23
- EVENT_VERSION,
24
- LedgerError,
25
- canonicalJson,
26
- newEventId,
27
- sealEvent,
28
- serializeEvent,
29
- verifyChain,
30
- verifyEvent,
31
- } from './events.js';
32
- import { applyEvent, FOLD_STATE_VERSION, fold, initialState } from './fold.js';
33
- import { reportFail } from '../diaglog.js';
34
- import { loadCheckpoint, saveCheckpoint } from './checkpoint.js';
35
-
36
- export { LedgerError };
37
-
38
- /** 默认分段阈值(03 §6.5:32 MB 或 50,000 事件先到为准)。 */
39
- export const DEFAULT_SEGMENT_EVENTS = 50_000;
40
- export const DEFAULT_SEGMENT_BYTES = 32 * 1024 * 1024;
41
-
42
- export const SEGMENT_PATTERN = /^ledger-(\d{6})\.jsonl$/;
43
- export const LOCK_FILE = 'lock';
44
-
45
- /**
46
- * Grace period for an unreadable lock record. The lock file is created empty and
47
- * filled immediately after, so a 0-byte file is normal for a live writer; only
48
- * an unreadable record older than this counts as a crashed writer.
49
- */
50
- export const LOCK_WRITE_GRACE_MS = 10_000;
51
-
52
- const DRAFT_FIELDS = new Set([
53
- 'type',
54
- 'payload',
55
- 'actor',
56
- 'at',
57
- 'id',
58
- 'v',
59
- 'correlationId',
60
- 'causationId',
61
- 'projectId',
62
- ]);
63
-
64
- function formatSegmentName(index) {
65
- if (!Number.isSafeInteger(index) || index < 1 || index > 999_999) {
66
- throw new LedgerError('E_SEGMENT_INDEX', 'segment index is out of range', { index });
67
- }
68
- return `ledger-${String(index).padStart(6, '0')}.jsonl`;
69
- }
70
-
71
- function isProcessAlive(pid) {
72
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
73
- if (pid === process.pid) return true;
74
- try {
75
- process.kill(pid, 0);
76
- return true;
77
- } catch (error) {
78
- // EPERM 说明进程存在但无权限发信号;ESRCH 才是“不存在”。
79
- return error?.code === 'EPERM';
80
- }
81
- }
82
-
83
- /** 写一个 Buffer 到 fd,处理短写。 */
84
- function writeAll(fs, fd, buffer) {
85
- let offset = 0;
86
- while (offset < buffer.length) {
87
- const written = fs.writeSync(fd, buffer, offset, buffer.length - offset, null);
88
- if (!Number.isFinite(written) || written <= 0) {
89
- throw new Error('short write');
90
- }
91
- offset += written;
92
- }
93
- }
94
-
95
- /**
96
- * 每 Project 的账本写入器。
97
- *
98
- * 选项:
99
- * - segmentEvents / segmentBytes:分段阈值,测试可调小。
100
- * - fsync:默认 true;false 仅供测试/基准,生产路径必须为 true。
101
- * - lock:默认 true;false 仅供只读检查或测试替身。
102
- * - repairTail:open 时是否修复最后一行半行,默认 true。
103
- * - fs:可注入的 fs 实现(故障注入测试),默认 node:fs。
104
- * - clock:时间源,默认 Date.now。
105
- */
106
- export class LedgerWriter {
107
- constructor(options = {}) {
108
- const {
109
- dir,
110
- projectId,
111
- segmentEvents = DEFAULT_SEGMENT_EVENTS,
112
- segmentBytes = DEFAULT_SEGMENT_BYTES,
113
- fsync = true,
114
- lock = true,
115
- repairTail = true,
116
- fs = fsDefault,
117
- clock = Date.now,
118
- } = options;
119
-
120
- if (typeof dir !== 'string' || dir.length === 0) {
121
- throw new LedgerError('E_INVALID_OPTION', 'LedgerWriter requires a data directory');
122
- }
123
- if (typeof projectId !== 'string' || projectId.length === 0) {
124
- throw new LedgerError('E_INVALID_OPTION', 'LedgerWriter requires a projectId');
125
- }
126
- if (!Number.isSafeInteger(segmentEvents) || segmentEvents < 1) {
127
- throw new LedgerError('E_INVALID_OPTION', 'segmentEvents must be a positive integer');
128
- }
129
- if (!Number.isSafeInteger(segmentBytes) || segmentBytes < 1) {
130
- throw new LedgerError('E_INVALID_OPTION', 'segmentBytes must be a positive integer');
131
- }
132
- if (typeof clock !== 'function') {
133
- throw new LedgerError('E_INVALID_OPTION', 'clock must be a function');
134
- }
135
-
136
- this.dir = path.resolve(dir);
137
- this.projectId = projectId;
138
- this.segmentEvents = segmentEvents;
139
- this.segmentBytes = segmentBytes;
140
- this.fsync = fsync !== false;
141
- this.useLock = lock !== false;
142
- this.repairTailOnOpen = repairTail !== false;
143
- this._fs = fs;
144
- this._clock = clock;
145
- this._lockToken = randomBytes(8).toString('hex');
146
-
147
- this._opened = false;
148
- this._closed = false;
149
- this._head = { seq: 0, hash: GENESIS_HASH };
150
- this._eventCount = 0;
151
- this._current = null;
152
- this._segments = [];
153
- this._segmentCounts = new Map();
154
- this._hashes = new Map();
155
- this._ids = new Set();
156
- this._repairs = [];
157
- this._openResult = null;
158
- this._queue = Promise.resolve();
159
- // 回滚失败后置为非空:本句柄不可继续写,必须 close + open 重新扫描。
160
- this._poisoned = null;
161
- }
162
-
163
- get head() {
164
- return { ...this._head };
165
- }
166
-
167
- get eventCount() {
168
- return this._eventCount;
169
- }
170
-
171
- get opened() {
172
- return this._opened && !this._closed;
173
- }
174
-
175
- get closed() {
176
- return this._closed;
177
- }
178
-
179
- get repairs() {
180
- return [...this._repairs];
181
- }
182
-
183
- /**
184
- * 打开账本:加锁 → 全量校验 → 尾撕裂修复 → 打开当前段。
185
- * @returns {{projectId:string,segments:string[],eventCount:number,head:{seq:number,hash:string},repair:object|null,repairs:object[]}}
186
- */
187
- open() {
188
- if (this._opened && !this._closed) return this._openResult;
189
- this._resetForOpen();
190
-
191
- try {
192
- this._fs.mkdirSync(this.dir, { recursive: true });
193
- } catch (error) {
194
- throw new LedgerError('E_STORAGE', `cannot create ledger directory: ${error.message}`, {
195
- sysCode: error.code ?? null,
196
- });
197
- }
198
-
199
- const repairs = [];
200
- this._poisoned = null;
201
- try {
202
- if (this.useLock) this._acquireLock(repairs);
203
- const scan = this._scan({ repairTail: this.repairTailOnOpen });
204
- this._adoptScan(scan);
205
- if (scan.repair) repairs.push(scan.repair);
206
-
207
- if (scan.segments.length === 0) {
208
- this._current = {
209
- index: 1,
210
- name: formatSegmentName(1),
211
- path: path.join(this.dir, formatSegmentName(1)),
212
- fd: null,
213
- size: 0,
214
- count: 0,
215
- };
216
- } else {
217
- const last = scan.segments[scan.segments.length - 1];
218
- const fd = this._fs.openSync(last.path, 'a');
219
- this._current = {
220
- ...last,
221
- fd,
222
- size: this._fs.statSync(last.path).size,
223
- count: scan.counts.get(last.index) ?? 0,
224
- };
225
- }
226
-
227
- this._opened = true;
228
- this._closed = false;
229
- this._repairs = repairs;
230
- this._openResult = {
231
- projectId: this.projectId,
232
- segments: scan.segments.map((segment) => segment.name),
233
- eventCount: this._eventCount,
234
- head: { ...this._head },
235
- repair: scan.repair,
236
- repairs: [...repairs],
237
- };
238
- return this._openResult;
239
- } catch (error) {
240
- try {
241
- if (this._current?.fd !== null && this._current?.fd !== undefined) {
242
- this._fs.closeSync(this._current.fd);
243
- }
244
- } catch {
245
- // 打开失败时只尽力清理。
246
- }
247
- this._current = null;
248
- try {
249
- if (this.useLock) this._releaseLock();
250
- } catch {
251
- // 锁清理失败不能掩盖真正的打开错误。
252
- }
253
- throw error;
254
- }
255
- }
256
-
257
- /**
258
- * 追加单条事件。返回 sealed event(含 seq / hash / prevHash)。
259
- * Promise 在写入(以及默认 fsync)完成后 resolve;失败则文件回滚、head 不变。
260
- */
261
- append(draft, options) {
262
- return this.appendMany([draft], options).then((events) => events[0]);
263
- }
264
-
265
- /**
266
- * 组提交:一批事件共享一次 fsync;任一失败整批回滚。
267
- * @param {object[]} drafts
268
- * @param {{expectedHeadSeq?: number}} [options]
269
- * @returns {Promise<object[]>} sealed events
270
- */
271
- appendMany(drafts, { expectedHeadSeq } = {}) {
272
- if (!Array.isArray(drafts)) {
273
- return Promise.reject(new LedgerError('E_EVENT_INVALID', 'appendMany expects an array'));
274
- }
275
- if (drafts.length === 0) return Promise.resolve([]);
276
- // 回滚失败过:本句柄的历史不再可信(可能已有半截写入留在段内),
277
- // 继续接单会把后续事件追加到未知状态之后。要求 close + open 重新扫描。
278
- if (this._poisoned !== null && this._poisoned !== undefined) {
279
- return Promise.reject(new LedgerError('E_LEDGER_POISONED',
280
- `ledger writer is unusable after a failed rollback (${this._poisoned}); close and open it again`, {
281
- rollbackError: this._poisoned,
282
- }));
283
- }
284
- return this._enqueue(() => {
285
- if (expectedHeadSeq !== undefined && this._head.seq !== expectedHeadSeq) {
286
- throw new LedgerError('E_LEDGER_HEAD_CHANGED', 'ledger advanced before append', {
287
- expected: expectedHeadSeq, actual: this._head.seq,
288
- });
289
- }
290
- return this._appendBatch(drafts);
291
- });
292
- }
293
-
294
- /**
295
- * 读取全部事件并校验 hash 链 / seq / projectId。
296
- * 未 open 的只读句柄默认修复尾部半行(open 会自动修复;已 open 的句柄
297
- * 默认只读,需要再次修复时显式传 repairTail:true)。
298
- */
299
- readAll(options = {}) {
300
- const repairTail = options.repairTail ?? !this._opened;
301
- const scan = this._scan({ repairTail });
302
- if (this._opened && scan.repair) {
303
- this._adoptScan(scan);
304
- this._syncCurrentFromScan(scan);
305
- this._openResult = {
306
- ...this._openResult,
307
- segments: scan.segments.map((segment) => segment.name),
308
- eventCount: this._eventCount,
309
- head: { ...this._head },
310
- repair: scan.repair ?? this._openResult?.repair ?? null,
311
- };
312
- }
313
- return scan.events;
314
- }
315
-
316
- /**
317
- * 重放:读取全部事件,从 fromSeq(含)开始对 state 调 apply。
318
- * 用于 checkpoint 之后的 tail replay。
319
- */
320
- replay(initialStateValue, apply, options = {}) {
321
- if (typeof apply !== 'function') {
322
- throw new LedgerError('E_INVALID_OPTION', 'replay requires an apply(state,event) function');
323
- }
324
- const fromSeq = options.fromSeq ?? 1;
325
- if (!Number.isSafeInteger(fromSeq) || fromSeq < 1) {
326
- throw new LedgerError('E_INVALID_OPTION', 'fromSeq must be a positive integer');
327
- }
328
- if (fromSeq > this._head.seq + 1) {
329
- throw new LedgerError('E_FROM_SEQ_FUTURE', 'fromSeq is beyond the ledger head', {
330
- fromSeq,
331
- headSeq: this._head.seq,
332
- });
333
- }
334
-
335
- const events = this.readAll({ repairTail: false });
336
- let state = initialStateValue;
337
- for (const event of events) {
338
- if (event.seq >= fromSeq) state = apply(state, event);
339
- }
340
- return state;
341
- }
342
-
343
- /** seq 对应事件的 hash;seq=0 返回创世 hash。 */
344
- hashAt(seq) {
345
- if (seq === 0) return GENESIS_HASH;
346
- return this._hashes.get(seq);
347
- }
348
-
349
- /** 再次扫描账本,修复尾部半行,并让内存索引追平。 */
350
- repair() {
351
- if (!this._opened || this._closed) {
352
- throw new LedgerError('E_LEDGER_CLOSED', 'ledger is not open');
353
- }
354
- const wasPoisoned = this._poisoned;
355
- const scan = this._scan({ repairTail: true });
356
- this._adoptScan(scan);
357
- this._syncCurrentFromScan(scan);
358
- // repair 会按磁盘真相重建 head/ids/segments,因此 poison(回滚失败留下的
359
- // 不一致内存态)在此刻已经不再成立。不解除的话,错误信息里建议的
360
- // 「close and open it again」在生产代码里没有任何调用点,writer 只能等重启。
361
- this._poisoned = null;
362
- if (scan.repair) this._repairs.push(scan.repair);
363
- this._openResult = {
364
- ...this._openResult,
365
- segments: scan.segments.map((segment) => segment.name),
366
- eventCount: this._eventCount,
367
- head: { ...this._head },
368
- repair: scan.repair ?? this._openResult?.repair ?? null,
369
- repairs: [...this._repairs],
370
- };
371
- return {
372
- repair: scan.repair,
373
- repairs: [...this._repairs],
374
- head: { ...this._head },
375
- eventCount: this._eventCount,
376
- segments: scan.segments.map((segment) => segment.name),
377
- recoveredFromPoison: wasPoisoned !== null && wasPoisoned !== undefined,
378
- ...(wasPoisoned === null || wasPoisoned === undefined ? {} : { poisonError: wasPoisoned }),
379
- };
380
- }
381
-
382
- /** 账本统计(文件列表 + 当前 head)。 */
383
- stats() {
384
- return {
385
- projectId: this.projectId,
386
- eventCount: this._eventCount,
387
- head: { ...this._head },
388
- segments: this._segments.map((segment) => ({
389
- ...segment,
390
- bytes: this._fs.statSync(segment.path).size,
391
- })),
392
- };
393
- }
394
-
395
- /** 关闭写句柄并释放锁;已提交事件保持不变。 */
396
- close() {
397
- if (this._closed) return;
398
- this._closed = true;
399
- this._opened = false;
400
- if (this._current?.fd !== null && this._current?.fd !== undefined) {
401
- try {
402
- this._fs.closeSync(this._current.fd);
403
- } catch {
404
- // close 失败不改变已落盘事实。
405
- }
406
- this._current = { ...this._current, fd: null };
407
- }
408
- if (this.useLock) this._releaseLock();
409
- this._queue = Promise.resolve();
410
- }
411
-
412
- _resetForOpen() {
413
- if (!this._closed) return;
414
- this._closed = false;
415
- this._opened = false;
416
- this._current = null;
417
- this._segments = [];
418
- this._segmentCounts = new Map();
419
- this._hashes = new Map();
420
- this._ids = new Set();
421
- this._repairs = [];
422
- this._openResult = null;
423
- }
424
-
425
- _enqueue(job) {
426
- if (!this._opened || this._closed) {
427
- return Promise.reject(new LedgerError('E_LEDGER_CLOSED', 'ledger is not open'));
428
- }
429
- const run = this._queue.then(job, job);
430
- this._queue = run.then(
431
- () => undefined,
432
- () => undefined,
433
- );
434
- return run;
435
- }
436
-
437
- _appendBatch(drafts) {
438
- if (this._closed) throw new LedgerError('E_LEDGER_CLOSED', 'ledger is closed');
439
- // poison 必须在**队列内**复核:appendMany 入口的检查发生在入队之前,
440
- // 同一 tick 内并发提交的两个批次会同时通过入口检查,先失败的那个把
441
- // writer 置为 poisoned 后,后一个已经排在队列里,仍会按旧 head 算出重复
442
- // seq 写进新段——账本此后永久打不开。
443
- if (this._poisoned !== null && this._poisoned !== undefined) {
444
- throw new LedgerError('E_LEDGER_POISONED',
445
- `ledger writer is unusable after a failed rollback (${this._poisoned}); close and open it again`, {
446
- rollbackError: this._poisoned,
447
- });
448
- }
449
-
450
- const plans = [];
451
- // 批内查重只用临时小集合;全局查重直接查 _ids(O(1)),避免每次
452
- // append 全量拷贝已存事件集合带来的平方级开销。
453
- const seenIds = new Set();
454
- const hasId = (id) => seenIds.has(id) || this._ids.has(id);
455
- let seq = this._head.seq;
456
- let prevHash = this._head.hash;
457
-
458
- for (const draft of drafts) {
459
- if (draft === null || typeof draft !== 'object' || Array.isArray(draft)) {
460
- throw new LedgerError('E_EVENT_INVALID', 'each draft must be a plain object');
461
- }
462
- for (const key of Object.keys(draft)) {
463
- if (!DRAFT_FIELDS.has(key)) {
464
- throw new LedgerError('E_EVENT_FIELD', `draft has unknown field "${key}"`, { field: key });
465
- }
466
- }
467
- if (typeof draft.type !== 'string' || draft.type.length === 0) {
468
- throw new LedgerError('E_EVENT_INVALID', 'draft.type must be a non-empty string');
469
- }
470
- if (draft.projectId !== undefined && draft.projectId !== this.projectId) {
471
- throw new LedgerError('E_EVENT_PROJECT', 'draft.projectId does not match this ledger', {
472
- expected: this.projectId,
473
- actual: draft.projectId,
474
- });
475
- }
476
- if (draft.id !== undefined && typeof draft.id !== 'string') {
477
- throw new LedgerError('E_EVENT_ID', 'draft.id must be a string when present');
478
- }
479
-
480
- const at = draft.at ?? this._clock();
481
- const id = draft.id ?? newEventId(at);
482
- if (hasId(id)) {
483
- throw new LedgerError('E_DUPLICATE_ID', 'event id already exists in this ledger', { id });
484
- }
485
- seenIds.add(id);
486
-
487
- let event;
488
- try {
489
- event = sealEvent({
490
- v: draft.v ?? EVENT_VERSION,
491
- id,
492
- projectId: this.projectId,
493
- seq: seq + 1,
494
- type: draft.type,
495
- at,
496
- actor: draft.actor,
497
- correlationId: draft.correlationId,
498
- causationId: draft.causationId,
499
- payload: draft.payload,
500
- prevHash,
501
- });
502
- } catch (error) {
503
- if (error instanceof LedgerError) throw error;
504
- throw new LedgerError('E_EVENT_INVALID', `cannot seal event: ${error.message}`, {
505
- cause: error.message,
506
- });
507
- }
508
-
509
- const line = Buffer.from(serializeEvent(event), 'utf8');
510
- if (line.length > MAX_EVENT_BYTES) {
511
- throw new LedgerError('E_EVENT_TOO_LARGE', 'event exceeds the 256 KB limit', {
512
- bytes: line.length,
513
- limit: MAX_EVENT_BYTES,
514
- seq: event.seq,
515
- });
516
- }
517
- plans.push({ event, line });
518
- seq = event.seq;
519
- prevHash = event.hash;
520
- }
521
-
522
- const origin = { ...this._current };
523
- const counts = new Map(this._segmentCounts);
524
- const created = [];
525
- let segIndex = this._current.index;
526
- let segPath = this._current.path;
527
- let segName = this._current.name;
528
- let segFd = this._current.fd;
529
- let segSize = this._current.size;
530
- let segCount = this._current.count;
531
-
532
- try {
533
- for (const plan of plans) {
534
- const needRoll =
535
- segFd === null ||
536
- (segCount > 0 &&
537
- (segCount >= this.segmentEvents || segSize + plan.line.length > this.segmentBytes));
538
- if (needRoll) {
539
- if (segFd !== null) {
540
- // 落盘后再关闭旧段:closeSync 不保证刷盘,若旧段尾部整行
541
- // 只留在 OS 缓冲而崩溃丢失,新段首行的 prevHash/seq 将与
542
- // 截断后的旧段尾对不上,哈希链断裂且无法修复。
543
- if (this.fsync) this._fs.fsyncSync(segFd);
544
- this._fs.closeSync(segFd);
545
- }
546
- // 段号 = 磁盘上已存在段的最大编号 + 1(全新账本的第一段是 000001)。
547
- // 不能从 origin.index 推导:回滚失败会留下 fd=null 的当前段,
548
- // 而 origin.index 是「下一个待用编号」,据此新建会复用已存在的段号。
549
- const lastIndex = Math.max(
550
- created.length > 0 ? created[created.length - 1].index : 0,
551
- this._lastSegmentIndexOnDisk(),
552
- );
553
- segIndex = lastIndex + 1;
554
- segName = formatSegmentName(segIndex);
555
- segPath = path.join(this.dir, segName);
556
- segFd = this._fs.openSync(segPath, 'ax');
557
- segSize = 0;
558
- segCount = 0;
559
- created.push({ index: segIndex, name: segName, path: segPath });
560
- }
561
- writeAll(this._fs, segFd, plan.line);
562
- segSize += plan.line.length;
563
- segCount += 1;
564
- counts.set(segIndex, segCount);
565
- }
566
-
567
- if (this.fsync) this._fs.fsyncSync(segFd);
568
- } catch (writeError) {
569
- const rollbackError = this._rollback(origin, created, segFd);
570
- if (rollbackError) this._poisoned = rollbackError;
571
- if (writeError instanceof LedgerError) {
572
- if (rollbackError) writeError.details = { ...writeError.details, rollbackError };
573
- throw writeError;
574
- }
575
- throw new LedgerError('E_STORAGE', `ledger append failed: ${writeError.message}`, {
576
- sysCode: writeError.code ?? null,
577
- ...(rollbackError ? { rollbackError } : {}),
578
- });
579
- }
580
-
581
- this._current = {
582
- index: segIndex,
583
- name: segName,
584
- path: segPath,
585
- fd: segFd,
586
- size: segSize,
587
- count: segCount,
588
- };
589
- this._segmentCounts = counts;
590
- this._head = { seq, hash: prevHash };
591
- this._eventCount += plans.length;
592
- for (const segment of created) this._segments.push(segment);
593
- for (const plan of plans) {
594
- this._hashes.set(plan.event.seq, plan.event.hash);
595
- this._ids.add(plan.event.id);
596
- }
597
- return plans.map((plan) => plan.event);
598
- }
599
-
600
- /**
601
- * 回滚本批次写入:删除新建段,把原段 ftruncate 回写前长度。
602
- * 返回错误描述(尽力而为,不抛出,避免掩盖原始写失败)。
603
- */
604
- _rollback(origin, created, segFd) {
605
- let problem = null;
606
- if (segFd !== null && segFd !== undefined) {
607
- try {
608
- this._fs.closeSync(segFd);
609
- } catch (error) {
610
- problem = `close: ${error.message}`;
611
- }
612
- }
613
- for (let index = created.length - 1; index >= 0; index -= 1) {
614
- try {
615
- this._fs.unlinkSync(created[index].path);
616
- } catch (error) {
617
- problem = problem ?? `unlink: ${error.message}`;
618
- }
619
- }
620
-
621
- if (origin.fd !== null && origin.fd !== undefined) {
622
- try {
623
- // Windows 上 O_APPEND 句柄不能 ftruncate(EPERM),必须用 r+ 打开截断,
624
- // 成功后再用 a 重新打开为追加句柄。
625
- const truncateFd = this._fs.openSync(origin.path, 'r+');
626
- try {
627
- this._fs.ftruncateSync(truncateFd, origin.size);
628
- try {
629
- this._fs.fsyncSync(truncateFd);
630
- } catch {
631
- // fsync 本身失败时 truncate 已经是当前能做到的最好回滚。
632
- }
633
- } finally {
634
- this._fs.closeSync(truncateFd);
635
- }
636
- const fd = this._fs.openSync(origin.path, 'a');
637
- this._current = { ...origin, fd, size: origin.size, count: origin.count };
638
- } catch (error) {
639
- problem = problem ?? `truncate: ${error.message}`;
640
- this._current = { ...origin, fd: null };
641
- }
642
- } else {
643
- this._current = { ...origin, fd: null, size: 0, count: 0 };
644
- }
645
- return problem;
646
- }
647
-
648
- _adoptScan(scan) {
649
- this._segments = scan.segments;
650
- this._segmentCounts = new Map(scan.counts);
651
- this._hashes = new Map(scan.events.map((event) => [event.seq, event.hash]));
652
- this._ids = new Set(scan.events.map((event) => event.id));
653
- this._head = { ...scan.head };
654
- this._eventCount = scan.events.length;
655
- }
656
-
657
- _syncCurrentFromScan(scan) {
658
- if (scan.segments.length === 0) {
659
- // 空账本:**不要**预创建段文件——空段会被扫描当成可修复的尾段删掉,
660
- // 段号就跳到 2 了。fd 留空,首次 append 会按需创建 000001。
661
- this._current = {
662
- index: 1,
663
- name: formatSegmentName(1),
664
- path: path.join(this.dir, formatSegmentName(1)),
665
- fd: null,
666
- size: 0,
667
- count: 0,
668
- };
669
- return;
670
- }
671
- const last = scan.segments[scan.segments.length - 1];
672
- const reuseFd = this._current?.path === last.path ? this._current.fd : null;
673
- this._current = {
674
- ...last,
675
- fd: reuseFd,
676
- size: this._fs.statSync(last.path).size,
677
- count: scan.counts.get(last.index) ?? 0,
678
- };
679
- this._reopenCurrent();
680
- }
681
-
682
- /** Re-open the current segment for append when the rollback left no usable fd. */
683
- _reopenCurrent() {
684
- if (this._current === null || this._current.fd !== null) return;
685
- try {
686
- this._current = {
687
- ...this._current,
688
- fd: this._fs.openSync(this._current.path, 'a'),
689
- };
690
- } catch {
691
- // 段文件可能已被回滚删除;保持 fd=null,append 会按磁盘最大段号新建。
692
- this._current = { ...this._current, fd: null };
693
- }
694
- }
695
-
696
- /** Highest segment index that actually exists on disk (0 when the dir is empty). */
697
- _lastSegmentIndexOnDisk() {
698
- let max = 0;
699
- for (const segment of this._listSegments()) {
700
- if (segment.index > max) max = segment.index;
701
- }
702
- return max;
703
- }
704
-
705
- _listSegments() {
706
- let entries;
707
- try {
708
- entries = this._fs.readdirSync(this.dir, { withFileTypes: true });
709
- } catch (error) {
710
- if (error.code === 'ENOENT') return [];
711
- throw error;
712
- }
713
-
714
- const found = [];
715
- for (const entry of entries) {
716
- const name = typeof entry === 'string' ? entry : entry.name;
717
- const match = SEGMENT_PATTERN.exec(name);
718
- if (!match) continue;
719
- found.push({
720
- index: Number.parseInt(match[1], 10),
721
- name,
722
- path: path.join(this.dir, name),
723
- });
724
- }
725
- found.sort((left, right) => left.index - right.index);
726
-
727
- if (found.length === 0) return [];
728
- if (found[0].index !== 1) {
729
- throw new LedgerError('E_LEDGER_CORRUPT', 'ledger is missing segment 1', {
730
- reason: 'missing-segment',
731
- expected: 1,
732
- actual: found[0].index,
733
- });
734
- }
735
- for (let index = 0; index < found.length; index += 1) {
736
- if (found[index].index !== index + 1) {
737
- throw new LedgerError('E_LEDGER_CORRUPT', 'ledger segments are not contiguous', {
738
- reason: 'segment-gap',
739
- expected: index + 1,
740
- actual: found[index].index,
741
- });
742
- }
743
- }
744
- return found;
745
- }
746
-
747
- _scan(options = {}) {
748
- const repairTail = options.repairTail === true;
749
- const segments = this._listSegments();
750
- const events = [];
751
- const counts = new Map();
752
- const seenIds = new Set();
753
- let prevHash = GENESIS_HASH;
754
- let expectedSeq = 1;
755
- let repair = null;
756
-
757
- for (let index = 0; index < segments.length; index += 1) {
758
- const segment = segments[index];
759
- const isLast = index === segments.length - 1;
760
- const buffer = this._fs.readFileSync(segment.path);
761
-
762
- if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) {
763
- throw new LedgerError('E_LEDGER_CORRUPT', 'ledger segment must not start with a UTF-8 BOM', {
764
- reason: 'bom',
765
- file: segment.name,
766
- });
767
- }
768
-
769
- let chunk = buffer;
770
- let truncatedBytes = 0;
771
- if (isLast && buffer.length > 0 && buffer[buffer.length - 1] !== 0x0a) {
772
- if (!repairTail) {
773
- throw new LedgerError('E_LEDGER_TORN_TAIL', 'ledger has an incomplete last line', {
774
- file: segment.name,
775
- bytes: buffer.length,
776
- });
777
- }
778
- const cut = buffer.lastIndexOf(0x0a) + 1;
779
- truncatedBytes = buffer.length - cut;
780
- chunk = buffer.subarray(0, cut);
781
- }
782
-
783
- const text = chunk.toString('utf8');
784
- let lines = text.length === 0 ? [] : text.split('\n');
785
- if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
786
-
787
- for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
788
- const line = lines[lineIndex];
789
- if (line.trim() === '') {
790
- throw new LedgerError('E_LEDGER_CORRUPT', 'ledger contains an empty line', {
791
- reason: 'empty-line',
792
- file: segment.name,
793
- line: lineIndex + 1,
794
- });
795
- }
796
- let event;
797
- try {
798
- event = JSON.parse(line);
799
- } catch (error) {
800
- throw new LedgerError('E_LEDGER_CORRUPT', 'ledger line is not valid JSON', {
801
- reason: 'invalid-json',
802
- file: segment.name,
803
- line: lineIndex + 1,
804
- cause: error.message,
805
- });
806
- }
807
- const result = verifyEvent(event, {
808
- expectedSeq,
809
- expectedPrevHash: prevHash,
810
- projectId: this.projectId,
811
- });
812
- if (!result.ok) {
813
- const code = result.code === 'E_SEQ_GAP' ? 'E_SEQ_GAP' : 'E_LEDGER_CORRUPT';
814
- throw new LedgerError(code, `ledger verification failed: ${result.message}`, {
815
- file: segment.name,
816
- line: lineIndex + 1,
817
- ...result,
818
- });
819
- }
820
- // 事件 id 是外部引用的唯一键:append 路径保证不重复,但双写者/外部
821
- // 合并/手工修复都可能造出重复 id。载入时静默折叠会让引用产生歧义,
822
- // 因此在这里按损坏账本处理(open 与 verify 都会报出来)。
823
- if (seenIds.has(event.id)) {
824
- throw new LedgerError('E_LEDGER_CORRUPT', 'ledger contains a duplicate event id', {
825
- reason: 'duplicate-id',
826
- file: segment.name,
827
- line: lineIndex + 1,
828
- id: event.id,
829
- });
830
- }
831
- seenIds.add(event.id);
832
- events.push(event);
833
- prevHash = event.hash;
834
- expectedSeq += 1;
835
- }
836
-
837
- counts.set(segment.index, lines.length);
838
-
839
- if (truncatedBytes > 0) {
840
- // 先完成本段全部行校验,确认不是中间损坏,再截断尾部半行。
841
- const fd = this._fs.openSync(segment.path, 'r+');
842
- try {
843
- this._fs.ftruncateSync(fd, buffer.length - truncatedBytes);
844
- this._fs.fsyncSync(fd);
845
- } finally {
846
- this._fs.closeSync(fd);
847
- }
848
- repair = {
849
- kind: 'torn-tail',
850
- file: segment.name,
851
- truncatedBytes,
852
- recoveredSeq: expectedSeq - 1,
853
- recoveredHash: prevHash,
854
- };
855
- }
856
- }
857
-
858
- return {
859
- events,
860
- counts,
861
- segments,
862
- head: { seq: expectedSeq - 1, hash: prevHash },
863
- repair,
864
- };
865
- }
866
-
867
- _acquireLock(repairs) {
868
- const lockPath = path.join(this.dir, LOCK_FILE);
869
- const takeoverPath = `${lockPath}.takeover`;
870
-
871
- for (let attempt = 0; attempt < 2; attempt += 1) {
872
- try {
873
- const fd = this._fs.openSync(lockPath, 'wx');
874
- try {
875
- const payload = {
876
- pid: process.pid,
877
- host: os.hostname(),
878
- startedAt: this._clock(),
879
- token: this._lockToken,
880
- };
881
- writeAll(this._fs, fd, Buffer.from(`${canonicalJson(payload)}\n`, 'utf8'));
882
- this._fs.fsyncSync(fd);
883
- } finally {
884
- this._fs.closeSync(fd);
885
- }
886
- return;
887
- } catch (error) {
888
- if (error.code !== 'EEXIST') {
889
- throw new LedgerError('E_STORAGE', `cannot create ledger lock: ${error.message}`, {
890
- sysCode: error.code ?? null,
891
- });
892
- }
893
-
894
- const existing = this._readLock(lockPath);
895
- // 锁在 fopen 与读取之间消失:没有锁可接管,直接重试创建。
896
- if (existing.error === 'missing') continue;
897
- if (!this._isStaleLock(existing.data, lockPath)) {
898
- throw new LedgerError('E_LOCKED', 'project ledger is locked by another writer', {
899
- pid: existing.data?.pid ?? null,
900
- host: existing.data?.host ?? null,
901
- startedAt: existing.data?.startedAt ?? null,
902
- });
903
- }
904
- if (attempt === 1) {
905
- throw new LedgerError('E_LOCKED', 'project ledger lock could not be taken over', {
906
- pid: existing.data?.pid ?? null,
907
- });
908
- }
909
- // 单赢家接管:只有成功创建 takeover 标记的进程可以删除陈旧锁。
910
- // 否则两个进程会各自"读到陈旧 → unlink → 新建",把对方的活锁删掉。
911
- // 标记必须带所有者且可判陈旧:否则一次崩溃(或 unlink 失败)留下的
912
- // 空标记会让该项目**永久** E_LOCKED,只能手工删文件才能恢复。
913
- let held = false;
914
- for (let markerAttempt = 0; markerAttempt < 2 && !held; markerAttempt += 1) {
915
- try {
916
- const marker = this._fs.openSync(takeoverPath, 'wx');
917
- try {
918
- writeAll(this._fs, marker, Buffer.from(`${canonicalJson({ pid: process.pid, startedAt: this._clock() })}\n`, 'utf8'));
919
- } finally {
920
- this._fs.closeSync(marker);
921
- }
922
- held = true;
923
- } catch (markerError) {
924
- if (markerError.code !== 'EEXIST') {
925
- throw new LedgerError('E_LOCKED', `cannot create ledger takeover marker: ${markerError.message}`, {
926
- pid: existing.data?.pid ?? null,
927
- sysCode: markerError.code ?? null,
928
- });
929
- }
930
- // 陈旧标记(创建者已死或超时)直接回收,避免永久卡死。
931
- if (this._lockRecordAge(takeoverPath) > LOCK_WRITE_GRACE_MS) {
932
- try { this._fs.unlinkSync(takeoverPath); } catch { /* someone else reclaimed it */ }
933
- continue;
934
- }
935
- throw new LedgerError('E_LOCKED', 'another writer is taking over the ledger lock', {
936
- pid: existing.data?.pid ?? null,
937
- });
938
- }
939
- }
940
- if (!held) {
941
- throw new LedgerError('E_LOCKED', 'ledger takeover marker could not be acquired', {});
942
- }
943
- try {
944
- // 标记生效后重新读取:原主可能已经写完(或已被别人接管成新锁)。
945
- const fresh = this._readLock(lockPath);
946
- if (fresh.error !== 'missing' && !this._isStaleLock(fresh.data, lockPath)) {
947
- throw new LedgerError('E_LOCKED', 'ledger lock was refreshed by its owner during takeover', {
948
- pid: fresh.data?.pid ?? null,
949
- });
950
- }
951
- try {
952
- this._fs.unlinkSync(lockPath);
953
- } catch (unlinkError) {
954
- if (unlinkError.code !== 'ENOENT') {
955
- throw new LedgerError('E_LOCKED', `cannot remove stale ledger lock: ${unlinkError.message}`);
956
- }
957
- }
958
- repairs.push({
959
- kind: 'stale-lock',
960
- pid: existing.data?.pid ?? null,
961
- host: existing.data?.host ?? null,
962
- startedAt: existing.data?.startedAt ?? null,
963
- reason: existing.error ?? 'owner-not-running',
964
- });
965
- } finally {
966
- try {
967
- this._fs.unlinkSync(takeoverPath);
968
- } catch (markerCleanupError) {
969
- // 不静默:残留标记会被陈旧回收逻辑接管,但要在日志里留痕。
970
- if (markerCleanupError.code !== 'ENOENT') {
971
- reportFail('ledger.takeover.marker.fail', { projectId: this.projectId, takeoverPath }, `[ai-team] ledger takeover marker could not be removed (${takeoverPath}): ${markerCleanupError.message}`);
972
- }
973
- }
974
- }
975
- }
976
- }
977
- throw new LedgerError('E_LOCKED', 'project ledger lock could not be acquired', {});
978
- }
979
-
980
- _readLock(lockPath) {
981
- try {
982
- const text = this._fs.readFileSync(lockPath, 'utf8');
983
- const data = JSON.parse(text);
984
- if (data === null || typeof data !== 'object') {
985
- return { data: null, error: 'invalid-lock-record' };
986
- }
987
- return { data, error: null };
988
- } catch (error) {
989
- if (error.code === 'ENOENT') return { data: null, error: 'missing' };
990
- return { data: null, error: error.name === 'SyntaxError' ? 'invalid-json' : error.message };
991
- }
992
- }
993
-
994
- /** Age of the on-disk lock record in ms; Infinity when it cannot be stat'd. */
995
- _lockRecordAge(lockPath) {
996
- try {
997
- return this._clock() - this._fs.statSync(lockPath).mtimeMs;
998
- } catch {
999
- return Number.POSITIVE_INFINITY;
1000
- }
1001
- }
1002
-
1003
- _isStaleLock(data, lockPath) {
1004
- if (!data || !Number.isSafeInteger(data.pid) || data.pid <= 0) {
1005
- // 锁创建与写入 payload 之间文件是 0 字节:无条件判陈旧会让并发进程
1006
- // 接管一个仍然活着的锁。给写入一个宽限期,超时后才认为是崩溃残留。
1007
- return this._lockRecordAge(lockPath) > LOCK_WRITE_GRACE_MS;
1008
- }
1009
- // 不同主机共享目录:无法用本机 PID 判断,保守视为仍持有。
1010
- if (typeof data.host === 'string' && data.host.length > 0 && data.host !== os.hostname()) {
1011
- return false;
1012
- }
1013
- return !isProcessAlive(data.pid);
1014
- }
1015
-
1016
- _releaseLock() {
1017
- const lockPath = path.join(this.dir, LOCK_FILE);
1018
- try {
1019
- const text = this._fs.readFileSync(lockPath, 'utf8');
1020
- const data = JSON.parse(text);
1021
- if (data?.token !== this._lockToken) return;
1022
- this._fs.unlinkSync(lockPath);
1023
- } catch {
1024
- // 锁已不存在或已不是自己的:不要误删别人的锁。
1025
- }
1026
- }
1027
- }
1028
-
1029
- /**
1030
- * 稳定门面:打开账本、重放当前状态,并保证 append 成功后才推进 state。
1031
- *
1032
- * @param {object} options 透传 LedgerWriter 选项:dir/projectId/fsync/segmentBytes/segmentEvents/lock/fs/clock
1033
- * @returns {{
1034
- * projectId: string,
1035
- * writer: LedgerWriter,
1036
- * state: object,
1037
- * events: object[],
1038
- * head: {seq:number,hash:string},
1039
- * append: (draft:object)=>Promise<object>,
1040
- * appendMany: (drafts:object[])=>Promise<object[]>,
1041
- * readAll: (options?:object)=>object[],
1042
- * replay: (state?:object)=>object,
1043
- * verify: ()=>object,
1044
- * repair: ()=>object,
1045
- * close: ()=>void
1046
- * }}
1047
- */
1048
- export function openLedger(options = {}) {
1049
- const writer = new LedgerWriter(options);
1050
- const opened = writer.open();
1051
- // checkpoint 命中且账本与检查点齐平时,跳过全量 readAll(boot 的大头):
1052
- // state 直接取自检查点,events 惰性化(首次访问才读盘,append 只增新事件)。
1053
- // 尾部存在时才需要一次 readAll 来续放投影。
1054
- const checkpointOptions = options.checkpoint ?? null;
1055
- const checkpointDir = checkpointOptions?.dir ?? writer.dir;
1056
- const stateVersion = checkpointOptions?.stateVersion ?? FOLD_STATE_VERSION;
1057
- let state;
1058
- let recovery = null;
1059
- let events = null;
1060
- const ensureEvents = () => {
1061
- if (events === null) events = writer.readAll({ repairTail: false });
1062
- return events;
1063
- };
1064
- if (checkpointOptions) {
1065
- const loaded = loadCheckpoint(checkpointDir, {
1066
- stateVersion,
1067
- hashAt: (seq) => writer.hashAt(seq),
1068
- });
1069
- if (loaded.checkpoint && loaded.checkpoint.lastSeq === writer.head.seq) {
1070
- // 齐平:零尾放,账本事件列表不进内存。
1071
- state = loaded.checkpoint.state;
1072
- recovery = {
1073
- source: loaded.source,
1074
- fromSeq: loaded.checkpoint.lastSeq + 1,
1075
- tailReplayed: 0,
1076
- errors: loaded.errors,
1077
- };
1078
- } else {
1079
- const fromSeq = loaded.checkpoint ? loaded.checkpoint.lastSeq + 1 : 1;
1080
- state = loaded.checkpoint ? loaded.checkpoint.state : initialState();
1081
- const all = ensureEvents();
1082
- for (const event of all) {
1083
- if (event.seq >= fromSeq) Object.assign(state, applyEvent(state, event));
1084
- }
1085
- recovery = {
1086
- source: loaded.source ?? 'replay',
1087
- fromSeq,
1088
- tailReplayed: Math.max(0, writer.head.seq - fromSeq + 1),
1089
- errors: loaded.errors,
1090
- };
1091
- }
1092
- } else {
1093
- events = writer.readAll({ repairTail: false });
1094
- state = fold(events);
1095
- }
1096
-
1097
- let onEvent = typeof options.onEvent === 'function' ? options.onEvent : null;
1098
- // 检查点节奏:boot 后落一次地板,之后每 saveEvery 次追加落一次,close
1099
- // 前必落——崩溃窗口最多丢 saveEvery 个事件的投影进度(账本本体无损)。
1100
- const saveEvery = Number.isSafeInteger(checkpointOptions?.saveEvery)
1101
- ? Math.max(50, checkpointOptions.saveEvery)
1102
- : 500;
1103
- let eventsSinceCheckpoint = 0;
1104
- const saveCheckpointNow = () => {
1105
- if (!checkpointOptions) return null;
1106
- try {
1107
- // 水位取"fold 已应用前缀"而非 writer.head:跨调用交错下(B 批次可在
1108
- // A 的 facade 续体推进 state 之前提交),head 可能领先 state——按
1109
- // head 落盘会持久化一个 state 落后于 lastSeq 的检查点,崩溃重开时
1110
- // 零尾放静默吞掉投影。state.lastSeq/lastHash 由 advance() 逐事件
1111
- // 维护,永远 ≤ head,尾放从其 +1 重放天然自洽。
1112
- return saveCheckpoint(
1113
- checkpointDir,
1114
- { stateVersion, lastSeq: state.lastSeq, lastHash: state.lastHash, state },
1115
- { hashAt: (seq) => writer.hashAt(seq) },
1116
- );
1117
- } catch (error) {
1118
- // 检查点保存失败绝不影响追加,但必须可见:静默失败会让检查点
1119
- // 名存实亡(boot 退化为全量重放而无人知晓)。
1120
- reportFail('checkpoint.save.fail', { projectId: writer.projectId }, `[ai-team] ledger ${writer.projectId} checkpoint save failed: ${error?.message ?? error}`);
1121
- return { error: error.message ?? String(error) };
1122
- }
1123
- };
1124
- if (checkpointOptions) {
1125
- const saved = saveCheckpointNow();
1126
- recovery.saved = saved && !saved.error ? saved.path : (saved?.error ?? null);
1127
- }
1128
- const ledger = {
1129
- projectId: writer.projectId,
1130
- writer,
1131
- state,
1132
- /** 账本事件全列表(checkpoint 模式下惰性读盘,append 持续追加)。 */
1133
- get events() {
1134
- return ensureEvents();
1135
- },
1136
- opened,
1137
- get onEvent() {
1138
- return onEvent;
1139
- },
1140
- set onEvent(handler) {
1141
- onEvent = typeof handler === 'function' ? handler : null;
1142
- },
1143
- get head() {
1144
- return { ...writer.head };
1145
- },
1146
- get headSeq() {
1147
- return writer.head.seq;
1148
- },
1149
- async append(draft, options) {
1150
- // 先齐平 events:checkpoint 齐平启动时 events 还是 null,若等 append 之后再
1151
- // readAll,刚写入的事件会被读出来、再被 push 一次(重复)。
1152
- const list = ensureEvents();
1153
- const event = await writer.append(draft, options);
1154
- // 只有 append 成功(含 fsync)后才推进内存状态。
1155
- Object.assign(state, applyEvent(state, event));
1156
- list.push(event);
1157
- try {
1158
- onEvent?.(event);
1159
- } catch {
1160
- /* a projection listener must never break the append */
1161
- }
1162
- if (checkpointOptions) {
1163
- eventsSinceCheckpoint += 1;
1164
- if (eventsSinceCheckpoint >= saveEvery) {
1165
- eventsSinceCheckpoint = 0;
1166
- saveCheckpointNow();
1167
- }
1168
- }
1169
- return event;
1170
- },
1171
- async appendMany(drafts) {
1172
- const list = ensureEvents();
1173
- const appended = await writer.appendMany(drafts);
1174
- let next = state;
1175
- for (const event of appended) {
1176
- next = applyEvent(next, event);
1177
- list.push(event);
1178
- }
1179
- Object.assign(state, next);
1180
- for (const event of appended) {
1181
- try {
1182
- onEvent?.(event);
1183
- } catch {
1184
- /* a projection listener must never break the append */
1185
- }
1186
- }
1187
- if (checkpointOptions) {
1188
- eventsSinceCheckpoint += appended.length;
1189
- if (eventsSinceCheckpoint >= saveEvery) {
1190
- eventsSinceCheckpoint = 0;
1191
- saveCheckpointNow();
1192
- }
1193
- }
1194
- return appended;
1195
- },
1196
- /** boot 时检查点恢复方式:'primary'/'backup'/'replay' 与尾放区间。 */
1197
- get recovery() {
1198
- return recovery;
1199
- },
1200
- readAll(readOptions = {}) {
1201
- return writer.readAll(readOptions);
1202
- },
1203
- replay(from = initialState()) {
1204
- return writer.replay(from, applyEvent);
1205
- },
1206
- verify() {
1207
- try {
1208
- const all = writer.readAll({ repairTail: false });
1209
- const chain = verifyChain(all, { projectId: writer.projectId });
1210
- return {
1211
- ok: chain.ok,
1212
- eventCount: all.length,
1213
- head: writer.head,
1214
- error: chain.ok
1215
- ? null
1216
- : {
1217
- code: chain.code,
1218
- message: chain.message,
1219
- details: chain.details ?? {},
1220
- index: chain.index,
1221
- },
1222
- };
1223
- } catch (error) {
1224
- return {
1225
- ok: false,
1226
- eventCount: null,
1227
- head: writer.head,
1228
- error: {
1229
- code: error.code ?? 'E_LEDGER_CORRUPT',
1230
- message: error.message,
1231
- details: error.details ?? {},
1232
- },
1233
- };
1234
- }
1235
- },
1236
- repair() {
1237
- const result = writer.repair();
1238
- // writer 层修的是段文件;门面这一层的 state/events 必须跟着**重折**。
1239
- // 只返回 writer 的结果会让 state.lastSeq 停在修复前的水位:下一次 append
1240
- // 之后 state.lastSeq 直接跳到新 head,中间那段事件永远不进投影,而
1241
- // checkpoint 的零尾放会把这条缺口永久固化。
1242
- // 从磁盘重读而不是用缓存:缓存里可能正是修复前那份含撕裂批次的列表。
1243
- events = writer.readAll({ repairTail: false });
1244
- state = fold(events);
1245
- eventsSinceCheckpoint = 0;
1246
- if (checkpointOptions) saveCheckpointNow();
1247
- // 恢复区间与缺口:一次失败的 appendMany 可能把「前缀」留在盘上,光说
1248
- // 「修好了」不够——运维需要知道接受到了哪个 seq、有没有洞。
1249
- const gaps = [];
1250
- for (let index = 0; index < events.length; index += 1) {
1251
- if (events[index]?.seq !== index + 1) {
1252
- gaps.push({ at: index, seq: events[index]?.seq ?? null });
1253
- if (gaps.length >= 20) break;
1254
- }
1255
- }
1256
- return {
1257
- ...result,
1258
- refolded: true,
1259
- events: events.length,
1260
- stateLastSeq: state.lastSeq ?? null,
1261
- acceptedRange: events.length === 0
1262
- ? null
1263
- : { from: events[0].seq ?? null, to: events[events.length - 1].seq ?? null },
1264
- seqGaps: gaps,
1265
- };
1266
- },
1267
- close() {
1268
- if (checkpointOptions) saveCheckpointNow();
1269
- writer.close();
1270
- },
1271
- };
1272
-
1273
- return ledger;
1274
- }
1
+ /**
2
+ * 单项目账本写入器:append-only JSONL、分段、fsync、单写者锁、尾撕裂修复。
3
+ *
4
+ * 对应 03-架构设计报告 §6.5 / §6.6 / §8.1、附录 B §B.3.6:
5
+ * - 一个 Project 一个 LedgerWriter;进程内 Promise 队列串行化写入。
6
+ * - append 成功(默认 fsync 完成)后才更新内存 head;失败回滚到写前长度。
7
+ * - 跨段 hash 链连续;打开时全量校验,尾部半行可截断修复并返回修复信息。
8
+ * - 锁文件 `lock`:PID + host + startedAt + token,非 OS flock(ADR-11)。
9
+ *
10
+ * 同时提供 `openLedger()` 门面(供 host service 直接消费):
11
+ * { append, appendMany, state, events, head, verify, repair, replay, close }
12
+ * 门面在 append 成功之后才推进 state,失败不改变 state。
13
+ */
14
+
15
+ import fsDefault from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ import { randomBytes } from 'node:crypto';
19
+ import {
20
+ GENESIS_HASH,
21
+ HASH_PATTERN,
22
+ MAX_EVENT_BYTES,
23
+ EVENT_VERSION,
24
+ LedgerError,
25
+ canonicalJson,
26
+ newEventId,
27
+ sealEvent,
28
+ serializeEvent,
29
+ verifyChain,
30
+ verifyEvent,
31
+ } from './events.js';
32
+ import { applyEvent, FOLD_STATE_VERSION, fold, initialState } from './fold.js';
33
+ import { reportFail } from '../diaglog.js';
34
+ import { loadCheckpoint, saveCheckpoint } from './checkpoint.js';
35
+
36
+ export { LedgerError };
37
+
38
+ /** 默认分段阈值(03 §6.5:32 MB 或 50,000 事件先到为准)。 */
39
+ export const DEFAULT_SEGMENT_EVENTS = 50_000;
40
+ export const DEFAULT_SEGMENT_BYTES = 32 * 1024 * 1024;
41
+
42
+ export const SEGMENT_PATTERN = /^ledger-(\d{6})\.jsonl$/;
43
+ export const LOCK_FILE = 'lock';
44
+
45
+ /**
46
+ * Grace period for an unreadable lock record. The lock file is created empty and
47
+ * filled immediately after, so a 0-byte file is normal for a live writer; only
48
+ * an unreadable record older than this counts as a crashed writer.
49
+ */
50
+ export const LOCK_WRITE_GRACE_MS = 10_000;
51
+
52
+ const DRAFT_FIELDS = new Set([
53
+ 'type',
54
+ 'payload',
55
+ 'actor',
56
+ 'at',
57
+ 'id',
58
+ 'v',
59
+ 'correlationId',
60
+ 'causationId',
61
+ 'projectId',
62
+ ]);
63
+
64
+ function formatSegmentName(index) {
65
+ if (!Number.isSafeInteger(index) || index < 1 || index > 999_999) {
66
+ throw new LedgerError('E_SEGMENT_INDEX', 'segment index is out of range', { index });
67
+ }
68
+ return `ledger-${String(index).padStart(6, '0')}.jsonl`;
69
+ }
70
+
71
+ function isProcessAlive(pid) {
72
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
73
+ if (pid === process.pid) return true;
74
+ try {
75
+ process.kill(pid, 0);
76
+ return true;
77
+ } catch (error) {
78
+ // EPERM 说明进程存在但无权限发信号;ESRCH 才是“不存在”。
79
+ return error?.code === 'EPERM';
80
+ }
81
+ }
82
+
83
+ /** 写一个 Buffer 到 fd,处理短写。 */
84
+ function writeAll(fs, fd, buffer) {
85
+ let offset = 0;
86
+ while (offset < buffer.length) {
87
+ const written = fs.writeSync(fd, buffer, offset, buffer.length - offset, null);
88
+ if (!Number.isFinite(written) || written <= 0) {
89
+ throw new Error('short write');
90
+ }
91
+ offset += written;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * 每 Project 的账本写入器。
97
+ *
98
+ * 选项:
99
+ * - segmentEvents / segmentBytes:分段阈值,测试可调小。
100
+ * - fsync:默认 true;false 仅供测试/基准,生产路径必须为 true。
101
+ * - lock:默认 true;false 仅供只读检查或测试替身。
102
+ * - repairTail:open 时是否修复最后一行半行,默认 true。
103
+ * - fs:可注入的 fs 实现(故障注入测试),默认 node:fs。
104
+ * - clock:时间源,默认 Date.now。
105
+ */
106
+ export class LedgerWriter {
107
+ constructor(options = {}) {
108
+ const {
109
+ dir,
110
+ projectId,
111
+ segmentEvents = DEFAULT_SEGMENT_EVENTS,
112
+ segmentBytes = DEFAULT_SEGMENT_BYTES,
113
+ fsync = true,
114
+ lock = true,
115
+ repairTail = true,
116
+ fs = fsDefault,
117
+ clock = Date.now,
118
+ } = options;
119
+
120
+ if (typeof dir !== 'string' || dir.length === 0) {
121
+ throw new LedgerError('E_INVALID_OPTION', 'LedgerWriter requires a data directory');
122
+ }
123
+ if (typeof projectId !== 'string' || projectId.length === 0) {
124
+ throw new LedgerError('E_INVALID_OPTION', 'LedgerWriter requires a projectId');
125
+ }
126
+ if (!Number.isSafeInteger(segmentEvents) || segmentEvents < 1) {
127
+ throw new LedgerError('E_INVALID_OPTION', 'segmentEvents must be a positive integer');
128
+ }
129
+ if (!Number.isSafeInteger(segmentBytes) || segmentBytes < 1) {
130
+ throw new LedgerError('E_INVALID_OPTION', 'segmentBytes must be a positive integer');
131
+ }
132
+ if (typeof clock !== 'function') {
133
+ throw new LedgerError('E_INVALID_OPTION', 'clock must be a function');
134
+ }
135
+
136
+ this.dir = path.resolve(dir);
137
+ this.projectId = projectId;
138
+ this.segmentEvents = segmentEvents;
139
+ this.segmentBytes = segmentBytes;
140
+ this.fsync = fsync !== false;
141
+ this.useLock = lock !== false;
142
+ this.repairTailOnOpen = repairTail !== false;
143
+ this._fs = fs;
144
+ this._clock = clock;
145
+ this._lockToken = randomBytes(8).toString('hex');
146
+
147
+ this._opened = false;
148
+ this._closed = false;
149
+ this._head = { seq: 0, hash: GENESIS_HASH };
150
+ this._eventCount = 0;
151
+ this._current = null;
152
+ this._segments = [];
153
+ this._segmentCounts = new Map();
154
+ this._hashes = new Map();
155
+ this._ids = new Set();
156
+ this._repairs = [];
157
+ this._openResult = null;
158
+ this._queue = Promise.resolve();
159
+ // 回滚失败后置为非空:本句柄不可继续写,必须 close + open 重新扫描。
160
+ this._poisoned = null;
161
+ }
162
+
163
+ get head() {
164
+ return { ...this._head };
165
+ }
166
+
167
+ get eventCount() {
168
+ return this._eventCount;
169
+ }
170
+
171
+ get opened() {
172
+ return this._opened && !this._closed;
173
+ }
174
+
175
+ get closed() {
176
+ return this._closed;
177
+ }
178
+
179
+ get repairs() {
180
+ return [...this._repairs];
181
+ }
182
+
183
+ /**
184
+ * 打开账本:加锁 → 全量校验 → 尾撕裂修复 → 打开当前段。
185
+ * @returns {{projectId:string,segments:string[],eventCount:number,head:{seq:number,hash:string},repair:object|null,repairs:object[]}}
186
+ */
187
+ open() {
188
+ if (this._opened && !this._closed) return this._openResult;
189
+ this._resetForOpen();
190
+
191
+ try {
192
+ this._fs.mkdirSync(this.dir, { recursive: true });
193
+ } catch (error) {
194
+ throw new LedgerError('E_STORAGE', `cannot create ledger directory: ${error.message}`, {
195
+ sysCode: error.code ?? null,
196
+ });
197
+ }
198
+
199
+ const repairs = [];
200
+ this._poisoned = null;
201
+ try {
202
+ if (this.useLock) this._acquireLock(repairs);
203
+ const scan = this._scan({ repairTail: this.repairTailOnOpen });
204
+ this._adoptScan(scan);
205
+ if (scan.repair) repairs.push(scan.repair);
206
+
207
+ if (scan.segments.length === 0) {
208
+ this._current = {
209
+ index: 1,
210
+ name: formatSegmentName(1),
211
+ path: path.join(this.dir, formatSegmentName(1)),
212
+ fd: null,
213
+ size: 0,
214
+ count: 0,
215
+ };
216
+ } else {
217
+ const last = scan.segments[scan.segments.length - 1];
218
+ const fd = this._fs.openSync(last.path, 'a');
219
+ this._current = {
220
+ ...last,
221
+ fd,
222
+ size: this._fs.statSync(last.path).size,
223
+ count: scan.counts.get(last.index) ?? 0,
224
+ };
225
+ }
226
+
227
+ this._opened = true;
228
+ this._closed = false;
229
+ this._repairs = repairs;
230
+ this._openResult = {
231
+ projectId: this.projectId,
232
+ segments: scan.segments.map((segment) => segment.name),
233
+ eventCount: this._eventCount,
234
+ head: { ...this._head },
235
+ repair: scan.repair,
236
+ repairs: [...repairs],
237
+ };
238
+ return this._openResult;
239
+ } catch (error) {
240
+ try {
241
+ if (this._current?.fd !== null && this._current?.fd !== undefined) {
242
+ this._fs.closeSync(this._current.fd);
243
+ }
244
+ } catch {
245
+ // 打开失败时只尽力清理。
246
+ }
247
+ this._current = null;
248
+ try {
249
+ if (this.useLock) this._releaseLock();
250
+ } catch {
251
+ // 锁清理失败不能掩盖真正的打开错误。
252
+ }
253
+ throw error;
254
+ }
255
+ }
256
+
257
+ /**
258
+ * 追加单条事件。返回 sealed event(含 seq / hash / prevHash)。
259
+ * Promise 在写入(以及默认 fsync)完成后 resolve;失败则文件回滚、head 不变。
260
+ */
261
+ append(draft, options) {
262
+ return this.appendMany([draft], options).then((events) => events[0]);
263
+ }
264
+
265
+ /**
266
+ * 组提交:一批事件共享一次 fsync;任一失败整批回滚。
267
+ * @param {object[]} drafts
268
+ * @param {{expectedHeadSeq?: number}} [options]
269
+ * @returns {Promise<object[]>} sealed events
270
+ */
271
+ appendMany(drafts, { expectedHeadSeq } = {}) {
272
+ if (!Array.isArray(drafts)) {
273
+ return Promise.reject(new LedgerError('E_EVENT_INVALID', 'appendMany expects an array'));
274
+ }
275
+ if (drafts.length === 0) return Promise.resolve([]);
276
+ // 回滚失败过:本句柄的历史不再可信(可能已有半截写入留在段内),
277
+ // 继续接单会把后续事件追加到未知状态之后。要求 close + open 重新扫描。
278
+ if (this._poisoned !== null && this._poisoned !== undefined) {
279
+ return Promise.reject(new LedgerError('E_LEDGER_POISONED',
280
+ `ledger writer is unusable after a failed rollback (${this._poisoned}); close and open it again`, {
281
+ rollbackError: this._poisoned,
282
+ }));
283
+ }
284
+ return this._enqueue(() => {
285
+ if (expectedHeadSeq !== undefined && this._head.seq !== expectedHeadSeq) {
286
+ throw new LedgerError('E_LEDGER_HEAD_CHANGED', 'ledger advanced before append', {
287
+ expected: expectedHeadSeq, actual: this._head.seq,
288
+ });
289
+ }
290
+ return this._appendBatch(drafts);
291
+ });
292
+ }
293
+
294
+ /**
295
+ * 读取全部事件并校验 hash 链 / seq / projectId。
296
+ * 未 open 的只读句柄默认修复尾部半行(open 会自动修复;已 open 的句柄
297
+ * 默认只读,需要再次修复时显式传 repairTail:true)。
298
+ */
299
+ readAll(options = {}) {
300
+ const repairTail = options.repairTail ?? !this._opened;
301
+ const scan = this._scan({ repairTail });
302
+ if (this._opened && scan.repair) {
303
+ this._adoptScan(scan);
304
+ this._syncCurrentFromScan(scan);
305
+ this._openResult = {
306
+ ...this._openResult,
307
+ segments: scan.segments.map((segment) => segment.name),
308
+ eventCount: this._eventCount,
309
+ head: { ...this._head },
310
+ repair: scan.repair ?? this._openResult?.repair ?? null,
311
+ };
312
+ }
313
+ return scan.events;
314
+ }
315
+
316
+ /**
317
+ * 重放:读取全部事件,从 fromSeq(含)开始对 state 调 apply。
318
+ * 用于 checkpoint 之后的 tail replay。
319
+ */
320
+ replay(initialStateValue, apply, options = {}) {
321
+ if (typeof apply !== 'function') {
322
+ throw new LedgerError('E_INVALID_OPTION', 'replay requires an apply(state,event) function');
323
+ }
324
+ const fromSeq = options.fromSeq ?? 1;
325
+ if (!Number.isSafeInteger(fromSeq) || fromSeq < 1) {
326
+ throw new LedgerError('E_INVALID_OPTION', 'fromSeq must be a positive integer');
327
+ }
328
+ if (fromSeq > this._head.seq + 1) {
329
+ throw new LedgerError('E_FROM_SEQ_FUTURE', 'fromSeq is beyond the ledger head', {
330
+ fromSeq,
331
+ headSeq: this._head.seq,
332
+ });
333
+ }
334
+
335
+ const events = this.readAll({ repairTail: false });
336
+ let state = initialStateValue;
337
+ for (const event of events) {
338
+ if (event.seq >= fromSeq) state = apply(state, event);
339
+ }
340
+ return state;
341
+ }
342
+
343
+ /** seq 对应事件的 hash;seq=0 返回创世 hash。 */
344
+ hashAt(seq) {
345
+ if (seq === 0) return GENESIS_HASH;
346
+ return this._hashes.get(seq);
347
+ }
348
+
349
+ /** 再次扫描账本,修复尾部半行,并让内存索引追平。 */
350
+ repair() {
351
+ if (!this._opened || this._closed) {
352
+ throw new LedgerError('E_LEDGER_CLOSED', 'ledger is not open');
353
+ }
354
+ const wasPoisoned = this._poisoned;
355
+ const scan = this._scan({ repairTail: true });
356
+ this._adoptScan(scan);
357
+ this._syncCurrentFromScan(scan);
358
+ // repair 会按磁盘真相重建 head/ids/segments,因此 poison(回滚失败留下的
359
+ // 不一致内存态)在此刻已经不再成立。不解除的话,错误信息里建议的
360
+ // 「close and open it again」在生产代码里没有任何调用点,writer 只能等重启。
361
+ this._poisoned = null;
362
+ if (scan.repair) this._repairs.push(scan.repair);
363
+ this._openResult = {
364
+ ...this._openResult,
365
+ segments: scan.segments.map((segment) => segment.name),
366
+ eventCount: this._eventCount,
367
+ head: { ...this._head },
368
+ repair: scan.repair ?? this._openResult?.repair ?? null,
369
+ repairs: [...this._repairs],
370
+ };
371
+ return {
372
+ repair: scan.repair,
373
+ repairs: [...this._repairs],
374
+ head: { ...this._head },
375
+ eventCount: this._eventCount,
376
+ segments: scan.segments.map((segment) => segment.name),
377
+ recoveredFromPoison: wasPoisoned !== null && wasPoisoned !== undefined,
378
+ ...(wasPoisoned === null || wasPoisoned === undefined ? {} : { poisonError: wasPoisoned }),
379
+ };
380
+ }
381
+
382
+ /** 账本统计(文件列表 + 当前 head)。 */
383
+ stats() {
384
+ return {
385
+ projectId: this.projectId,
386
+ eventCount: this._eventCount,
387
+ head: { ...this._head },
388
+ segments: this._segments.map((segment) => ({
389
+ ...segment,
390
+ bytes: this._fs.statSync(segment.path).size,
391
+ })),
392
+ };
393
+ }
394
+
395
+ /** 关闭写句柄并释放锁;已提交事件保持不变。 */
396
+ close() {
397
+ if (this._closed) return;
398
+ this._closed = true;
399
+ this._opened = false;
400
+ if (this._current?.fd !== null && this._current?.fd !== undefined) {
401
+ try {
402
+ this._fs.closeSync(this._current.fd);
403
+ } catch {
404
+ // close 失败不改变已落盘事实。
405
+ }
406
+ this._current = { ...this._current, fd: null };
407
+ }
408
+ if (this.useLock) this._releaseLock();
409
+ this._queue = Promise.resolve();
410
+ }
411
+
412
+ _resetForOpen() {
413
+ if (!this._closed) return;
414
+ this._closed = false;
415
+ this._opened = false;
416
+ this._current = null;
417
+ this._segments = [];
418
+ this._segmentCounts = new Map();
419
+ this._hashes = new Map();
420
+ this._ids = new Set();
421
+ this._repairs = [];
422
+ this._openResult = null;
423
+ }
424
+
425
+ _enqueue(job) {
426
+ if (!this._opened || this._closed) {
427
+ return Promise.reject(new LedgerError('E_LEDGER_CLOSED', 'ledger is not open'));
428
+ }
429
+ const run = this._queue.then(job, job);
430
+ this._queue = run.then(
431
+ () => undefined,
432
+ () => undefined,
433
+ );
434
+ return run;
435
+ }
436
+
437
+ _appendBatch(drafts) {
438
+ if (this._closed) throw new LedgerError('E_LEDGER_CLOSED', 'ledger is closed');
439
+ // poison 必须在**队列内**复核:appendMany 入口的检查发生在入队之前,
440
+ // 同一 tick 内并发提交的两个批次会同时通过入口检查,先失败的那个把
441
+ // writer 置为 poisoned 后,后一个已经排在队列里,仍会按旧 head 算出重复
442
+ // seq 写进新段——账本此后永久打不开。
443
+ if (this._poisoned !== null && this._poisoned !== undefined) {
444
+ throw new LedgerError('E_LEDGER_POISONED',
445
+ `ledger writer is unusable after a failed rollback (${this._poisoned}); close and open it again`, {
446
+ rollbackError: this._poisoned,
447
+ });
448
+ }
449
+
450
+ const plans = [];
451
+ // 批内查重只用临时小集合;全局查重直接查 _ids(O(1)),避免每次
452
+ // append 全量拷贝已存事件集合带来的平方级开销。
453
+ const seenIds = new Set();
454
+ const hasId = (id) => seenIds.has(id) || this._ids.has(id);
455
+ let seq = this._head.seq;
456
+ let prevHash = this._head.hash;
457
+
458
+ for (const draft of drafts) {
459
+ if (draft === null || typeof draft !== 'object' || Array.isArray(draft)) {
460
+ throw new LedgerError('E_EVENT_INVALID', 'each draft must be a plain object');
461
+ }
462
+ for (const key of Object.keys(draft)) {
463
+ if (!DRAFT_FIELDS.has(key)) {
464
+ throw new LedgerError('E_EVENT_FIELD', `draft has unknown field "${key}"`, { field: key });
465
+ }
466
+ }
467
+ if (typeof draft.type !== 'string' || draft.type.length === 0) {
468
+ throw new LedgerError('E_EVENT_INVALID', 'draft.type must be a non-empty string');
469
+ }
470
+ if (draft.projectId !== undefined && draft.projectId !== this.projectId) {
471
+ throw new LedgerError('E_EVENT_PROJECT', 'draft.projectId does not match this ledger', {
472
+ expected: this.projectId,
473
+ actual: draft.projectId,
474
+ });
475
+ }
476
+ if (draft.id !== undefined && typeof draft.id !== 'string') {
477
+ throw new LedgerError('E_EVENT_ID', 'draft.id must be a string when present');
478
+ }
479
+
480
+ const at = draft.at ?? this._clock();
481
+ const id = draft.id ?? newEventId(at);
482
+ if (hasId(id)) {
483
+ throw new LedgerError('E_DUPLICATE_ID', 'event id already exists in this ledger', { id });
484
+ }
485
+ seenIds.add(id);
486
+
487
+ let event;
488
+ try {
489
+ event = sealEvent({
490
+ v: draft.v ?? EVENT_VERSION,
491
+ id,
492
+ projectId: this.projectId,
493
+ seq: seq + 1,
494
+ type: draft.type,
495
+ at,
496
+ actor: draft.actor,
497
+ correlationId: draft.correlationId,
498
+ causationId: draft.causationId,
499
+ payload: draft.payload,
500
+ prevHash,
501
+ });
502
+ } catch (error) {
503
+ if (error instanceof LedgerError) throw error;
504
+ throw new LedgerError('E_EVENT_INVALID', `cannot seal event: ${error.message}`, {
505
+ cause: error.message,
506
+ });
507
+ }
508
+
509
+ const line = Buffer.from(serializeEvent(event), 'utf8');
510
+ if (line.length > MAX_EVENT_BYTES) {
511
+ throw new LedgerError('E_EVENT_TOO_LARGE', 'event exceeds the 256 KB limit', {
512
+ bytes: line.length,
513
+ limit: MAX_EVENT_BYTES,
514
+ seq: event.seq,
515
+ });
516
+ }
517
+ plans.push({ event, line });
518
+ seq = event.seq;
519
+ prevHash = event.hash;
520
+ }
521
+
522
+ const origin = { ...this._current };
523
+ const counts = new Map(this._segmentCounts);
524
+ const created = [];
525
+ let segIndex = this._current.index;
526
+ let segPath = this._current.path;
527
+ let segName = this._current.name;
528
+ let segFd = this._current.fd;
529
+ let segSize = this._current.size;
530
+ let segCount = this._current.count;
531
+
532
+ try {
533
+ for (const plan of plans) {
534
+ const needRoll =
535
+ segFd === null ||
536
+ (segCount > 0 &&
537
+ (segCount >= this.segmentEvents || segSize + plan.line.length > this.segmentBytes));
538
+ if (needRoll) {
539
+ if (segFd !== null) {
540
+ // 落盘后再关闭旧段:closeSync 不保证刷盘,若旧段尾部整行
541
+ // 只留在 OS 缓冲而崩溃丢失,新段首行的 prevHash/seq 将与
542
+ // 截断后的旧段尾对不上,哈希链断裂且无法修复。
543
+ if (this.fsync) this._fs.fsyncSync(segFd);
544
+ this._fs.closeSync(segFd);
545
+ }
546
+ // 段号 = 磁盘上已存在段的最大编号 + 1(全新账本的第一段是 000001)。
547
+ // 不能从 origin.index 推导:回滚失败会留下 fd=null 的当前段,
548
+ // 而 origin.index 是「下一个待用编号」,据此新建会复用已存在的段号。
549
+ const lastIndex = Math.max(
550
+ created.length > 0 ? created[created.length - 1].index : 0,
551
+ this._lastSegmentIndexOnDisk(),
552
+ );
553
+ segIndex = lastIndex + 1;
554
+ segName = formatSegmentName(segIndex);
555
+ segPath = path.join(this.dir, segName);
556
+ segFd = this._fs.openSync(segPath, 'ax');
557
+ segSize = 0;
558
+ segCount = 0;
559
+ created.push({ index: segIndex, name: segName, path: segPath });
560
+ }
561
+ writeAll(this._fs, segFd, plan.line);
562
+ segSize += plan.line.length;
563
+ segCount += 1;
564
+ counts.set(segIndex, segCount);
565
+ }
566
+
567
+ if (this.fsync) this._fs.fsyncSync(segFd);
568
+ } catch (writeError) {
569
+ const rollbackError = this._rollback(origin, created, segFd);
570
+ if (rollbackError) this._poisoned = rollbackError;
571
+ if (writeError instanceof LedgerError) {
572
+ if (rollbackError) writeError.details = { ...writeError.details, rollbackError };
573
+ throw writeError;
574
+ }
575
+ throw new LedgerError('E_STORAGE', `ledger append failed: ${writeError.message}`, {
576
+ sysCode: writeError.code ?? null,
577
+ ...(rollbackError ? { rollbackError } : {}),
578
+ });
579
+ }
580
+
581
+ this._current = {
582
+ index: segIndex,
583
+ name: segName,
584
+ path: segPath,
585
+ fd: segFd,
586
+ size: segSize,
587
+ count: segCount,
588
+ };
589
+ this._segmentCounts = counts;
590
+ this._head = { seq, hash: prevHash };
591
+ this._eventCount += plans.length;
592
+ for (const segment of created) this._segments.push(segment);
593
+ for (const plan of plans) {
594
+ this._hashes.set(plan.event.seq, plan.event.hash);
595
+ this._ids.add(plan.event.id);
596
+ }
597
+ return plans.map((plan) => plan.event);
598
+ }
599
+
600
+ /**
601
+ * 回滚本批次写入:删除新建段,把原段 ftruncate 回写前长度。
602
+ * 返回错误描述(尽力而为,不抛出,避免掩盖原始写失败)。
603
+ */
604
+ _rollback(origin, created, segFd) {
605
+ let problem = null;
606
+ if (segFd !== null && segFd !== undefined) {
607
+ try {
608
+ this._fs.closeSync(segFd);
609
+ } catch (error) {
610
+ problem = `close: ${error.message}`;
611
+ }
612
+ }
613
+ for (let index = created.length - 1; index >= 0; index -= 1) {
614
+ try {
615
+ this._fs.unlinkSync(created[index].path);
616
+ } catch (error) {
617
+ problem = problem ?? `unlink: ${error.message}`;
618
+ }
619
+ }
620
+
621
+ if (origin.fd !== null && origin.fd !== undefined) {
622
+ try {
623
+ // Windows 上 O_APPEND 句柄不能 ftruncate(EPERM),必须用 r+ 打开截断,
624
+ // 成功后再用 a 重新打开为追加句柄。
625
+ const truncateFd = this._fs.openSync(origin.path, 'r+');
626
+ try {
627
+ this._fs.ftruncateSync(truncateFd, origin.size);
628
+ try {
629
+ this._fs.fsyncSync(truncateFd);
630
+ } catch {
631
+ // fsync 本身失败时 truncate 已经是当前能做到的最好回滚。
632
+ }
633
+ } finally {
634
+ this._fs.closeSync(truncateFd);
635
+ }
636
+ const fd = this._fs.openSync(origin.path, 'a');
637
+ this._current = { ...origin, fd, size: origin.size, count: origin.count };
638
+ } catch (error) {
639
+ problem = problem ?? `truncate: ${error.message}`;
640
+ this._current = { ...origin, fd: null };
641
+ }
642
+ } else {
643
+ this._current = { ...origin, fd: null, size: 0, count: 0 };
644
+ }
645
+ return problem;
646
+ }
647
+
648
+ _adoptScan(scan) {
649
+ this._segments = scan.segments;
650
+ this._segmentCounts = new Map(scan.counts);
651
+ this._hashes = new Map(scan.events.map((event) => [event.seq, event.hash]));
652
+ this._ids = new Set(scan.events.map((event) => event.id));
653
+ this._head = { ...scan.head };
654
+ this._eventCount = scan.events.length;
655
+ }
656
+
657
+ _syncCurrentFromScan(scan) {
658
+ if (scan.segments.length === 0) {
659
+ // 空账本:**不要**预创建段文件——空段会被扫描当成可修复的尾段删掉,
660
+ // 段号就跳到 2 了。fd 留空,首次 append 会按需创建 000001。
661
+ this._current = {
662
+ index: 1,
663
+ name: formatSegmentName(1),
664
+ path: path.join(this.dir, formatSegmentName(1)),
665
+ fd: null,
666
+ size: 0,
667
+ count: 0,
668
+ };
669
+ return;
670
+ }
671
+ const last = scan.segments[scan.segments.length - 1];
672
+ const reuseFd = this._current?.path === last.path ? this._current.fd : null;
673
+ this._current = {
674
+ ...last,
675
+ fd: reuseFd,
676
+ size: this._fs.statSync(last.path).size,
677
+ count: scan.counts.get(last.index) ?? 0,
678
+ };
679
+ this._reopenCurrent();
680
+ }
681
+
682
+ /** Re-open the current segment for append when the rollback left no usable fd. */
683
+ _reopenCurrent() {
684
+ if (this._current === null || this._current.fd !== null) return;
685
+ try {
686
+ this._current = {
687
+ ...this._current,
688
+ fd: this._fs.openSync(this._current.path, 'a'),
689
+ };
690
+ } catch {
691
+ // 段文件可能已被回滚删除;保持 fd=null,append 会按磁盘最大段号新建。
692
+ this._current = { ...this._current, fd: null };
693
+ }
694
+ }
695
+
696
+ /** Highest segment index that actually exists on disk (0 when the dir is empty). */
697
+ _lastSegmentIndexOnDisk() {
698
+ let max = 0;
699
+ for (const segment of this._listSegments()) {
700
+ if (segment.index > max) max = segment.index;
701
+ }
702
+ return max;
703
+ }
704
+
705
+ _listSegments() {
706
+ let entries;
707
+ try {
708
+ entries = this._fs.readdirSync(this.dir, { withFileTypes: true });
709
+ } catch (error) {
710
+ if (error.code === 'ENOENT') return [];
711
+ throw error;
712
+ }
713
+
714
+ const found = [];
715
+ for (const entry of entries) {
716
+ const name = typeof entry === 'string' ? entry : entry.name;
717
+ const match = SEGMENT_PATTERN.exec(name);
718
+ if (!match) continue;
719
+ found.push({
720
+ index: Number.parseInt(match[1], 10),
721
+ name,
722
+ path: path.join(this.dir, name),
723
+ });
724
+ }
725
+ found.sort((left, right) => left.index - right.index);
726
+
727
+ if (found.length === 0) return [];
728
+ if (found[0].index !== 1) {
729
+ throw new LedgerError('E_LEDGER_CORRUPT', 'ledger is missing segment 1', {
730
+ reason: 'missing-segment',
731
+ expected: 1,
732
+ actual: found[0].index,
733
+ });
734
+ }
735
+ for (let index = 0; index < found.length; index += 1) {
736
+ if (found[index].index !== index + 1) {
737
+ throw new LedgerError('E_LEDGER_CORRUPT', 'ledger segments are not contiguous', {
738
+ reason: 'segment-gap',
739
+ expected: index + 1,
740
+ actual: found[index].index,
741
+ });
742
+ }
743
+ }
744
+ return found;
745
+ }
746
+
747
+ _scan(options = {}) {
748
+ const repairTail = options.repairTail === true;
749
+ const segments = this._listSegments();
750
+ const events = [];
751
+ const counts = new Map();
752
+ const seenIds = new Set();
753
+ let prevHash = GENESIS_HASH;
754
+ let expectedSeq = 1;
755
+ let repair = null;
756
+
757
+ for (let index = 0; index < segments.length; index += 1) {
758
+ const segment = segments[index];
759
+ const isLast = index === segments.length - 1;
760
+ const buffer = this._fs.readFileSync(segment.path);
761
+
762
+ if (buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf) {
763
+ throw new LedgerError('E_LEDGER_CORRUPT', 'ledger segment must not start with a UTF-8 BOM', {
764
+ reason: 'bom',
765
+ file: segment.name,
766
+ });
767
+ }
768
+
769
+ let chunk = buffer;
770
+ let truncatedBytes = 0;
771
+ if (isLast && buffer.length > 0 && buffer[buffer.length - 1] !== 0x0a) {
772
+ if (!repairTail) {
773
+ throw new LedgerError('E_LEDGER_TORN_TAIL', 'ledger has an incomplete last line', {
774
+ file: segment.name,
775
+ bytes: buffer.length,
776
+ });
777
+ }
778
+ const cut = buffer.lastIndexOf(0x0a) + 1;
779
+ truncatedBytes = buffer.length - cut;
780
+ chunk = buffer.subarray(0, cut);
781
+ }
782
+
783
+ const text = chunk.toString('utf8');
784
+ let lines = text.length === 0 ? [] : text.split('\n');
785
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
786
+
787
+ for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
788
+ const line = lines[lineIndex];
789
+ if (line.trim() === '') {
790
+ throw new LedgerError('E_LEDGER_CORRUPT', 'ledger contains an empty line', {
791
+ reason: 'empty-line',
792
+ file: segment.name,
793
+ line: lineIndex + 1,
794
+ });
795
+ }
796
+ let event;
797
+ try {
798
+ event = JSON.parse(line);
799
+ } catch (error) {
800
+ throw new LedgerError('E_LEDGER_CORRUPT', 'ledger line is not valid JSON', {
801
+ reason: 'invalid-json',
802
+ file: segment.name,
803
+ line: lineIndex + 1,
804
+ cause: error.message,
805
+ });
806
+ }
807
+ const result = verifyEvent(event, {
808
+ expectedSeq,
809
+ expectedPrevHash: prevHash,
810
+ projectId: this.projectId,
811
+ });
812
+ if (!result.ok) {
813
+ const code = result.code === 'E_SEQ_GAP' ? 'E_SEQ_GAP' : 'E_LEDGER_CORRUPT';
814
+ throw new LedgerError(code, `ledger verification failed: ${result.message}`, {
815
+ file: segment.name,
816
+ line: lineIndex + 1,
817
+ ...result,
818
+ });
819
+ }
820
+ // 事件 id 是外部引用的唯一键:append 路径保证不重复,但双写者/外部
821
+ // 合并/手工修复都可能造出重复 id。载入时静默折叠会让引用产生歧义,
822
+ // 因此在这里按损坏账本处理(open 与 verify 都会报出来)。
823
+ if (seenIds.has(event.id)) {
824
+ throw new LedgerError('E_LEDGER_CORRUPT', 'ledger contains a duplicate event id', {
825
+ reason: 'duplicate-id',
826
+ file: segment.name,
827
+ line: lineIndex + 1,
828
+ id: event.id,
829
+ });
830
+ }
831
+ seenIds.add(event.id);
832
+ events.push(event);
833
+ prevHash = event.hash;
834
+ expectedSeq += 1;
835
+ }
836
+
837
+ counts.set(segment.index, lines.length);
838
+
839
+ if (truncatedBytes > 0) {
840
+ // 先完成本段全部行校验,确认不是中间损坏,再截断尾部半行。
841
+ const fd = this._fs.openSync(segment.path, 'r+');
842
+ try {
843
+ this._fs.ftruncateSync(fd, buffer.length - truncatedBytes);
844
+ this._fs.fsyncSync(fd);
845
+ } finally {
846
+ this._fs.closeSync(fd);
847
+ }
848
+ repair = {
849
+ kind: 'torn-tail',
850
+ file: segment.name,
851
+ truncatedBytes,
852
+ recoveredSeq: expectedSeq - 1,
853
+ recoveredHash: prevHash,
854
+ };
855
+ }
856
+ }
857
+
858
+ return {
859
+ events,
860
+ counts,
861
+ segments,
862
+ head: { seq: expectedSeq - 1, hash: prevHash },
863
+ repair,
864
+ };
865
+ }
866
+
867
+ _acquireLock(repairs) {
868
+ const lockPath = path.join(this.dir, LOCK_FILE);
869
+ const takeoverPath = `${lockPath}.takeover`;
870
+
871
+ for (let attempt = 0; attempt < 2; attempt += 1) {
872
+ try {
873
+ const fd = this._fs.openSync(lockPath, 'wx');
874
+ try {
875
+ const payload = {
876
+ pid: process.pid,
877
+ host: os.hostname(),
878
+ startedAt: this._clock(),
879
+ token: this._lockToken,
880
+ };
881
+ writeAll(this._fs, fd, Buffer.from(`${canonicalJson(payload)}\n`, 'utf8'));
882
+ this._fs.fsyncSync(fd);
883
+ } finally {
884
+ this._fs.closeSync(fd);
885
+ }
886
+ return;
887
+ } catch (error) {
888
+ if (error.code !== 'EEXIST') {
889
+ throw new LedgerError('E_STORAGE', `cannot create ledger lock: ${error.message}`, {
890
+ sysCode: error.code ?? null,
891
+ });
892
+ }
893
+
894
+ const existing = this._readLock(lockPath);
895
+ // 锁在 fopen 与读取之间消失:没有锁可接管,直接重试创建。
896
+ if (existing.error === 'missing') continue;
897
+ if (!this._isStaleLock(existing.data, lockPath)) {
898
+ throw new LedgerError('E_LOCKED', 'project ledger is locked by another writer', {
899
+ pid: existing.data?.pid ?? null,
900
+ host: existing.data?.host ?? null,
901
+ startedAt: existing.data?.startedAt ?? null,
902
+ });
903
+ }
904
+ if (attempt === 1) {
905
+ throw new LedgerError('E_LOCKED', 'project ledger lock could not be taken over', {
906
+ pid: existing.data?.pid ?? null,
907
+ });
908
+ }
909
+ // 单赢家接管:只有成功创建 takeover 标记的进程可以删除陈旧锁。
910
+ // 否则两个进程会各自"读到陈旧 → unlink → 新建",把对方的活锁删掉。
911
+ // 标记必须带所有者且可判陈旧:否则一次崩溃(或 unlink 失败)留下的
912
+ // 空标记会让该项目**永久** E_LOCKED,只能手工删文件才能恢复。
913
+ let held = false;
914
+ for (let markerAttempt = 0; markerAttempt < 2 && !held; markerAttempt += 1) {
915
+ try {
916
+ const marker = this._fs.openSync(takeoverPath, 'wx');
917
+ try {
918
+ writeAll(this._fs, marker, Buffer.from(`${canonicalJson({ pid: process.pid, startedAt: this._clock() })}\n`, 'utf8'));
919
+ } finally {
920
+ this._fs.closeSync(marker);
921
+ }
922
+ held = true;
923
+ } catch (markerError) {
924
+ if (markerError.code !== 'EEXIST') {
925
+ throw new LedgerError('E_LOCKED', `cannot create ledger takeover marker: ${markerError.message}`, {
926
+ pid: existing.data?.pid ?? null,
927
+ sysCode: markerError.code ?? null,
928
+ });
929
+ }
930
+ // 陈旧标记(创建者已死或超时)直接回收,避免永久卡死。
931
+ if (this._lockRecordAge(takeoverPath) > LOCK_WRITE_GRACE_MS) {
932
+ try { this._fs.unlinkSync(takeoverPath); } catch { /* someone else reclaimed it */ }
933
+ continue;
934
+ }
935
+ throw new LedgerError('E_LOCKED', 'another writer is taking over the ledger lock', {
936
+ pid: existing.data?.pid ?? null,
937
+ });
938
+ }
939
+ }
940
+ if (!held) {
941
+ throw new LedgerError('E_LOCKED', 'ledger takeover marker could not be acquired', {});
942
+ }
943
+ try {
944
+ // 标记生效后重新读取:原主可能已经写完(或已被别人接管成新锁)。
945
+ const fresh = this._readLock(lockPath);
946
+ if (fresh.error !== 'missing' && !this._isStaleLock(fresh.data, lockPath)) {
947
+ throw new LedgerError('E_LOCKED', 'ledger lock was refreshed by its owner during takeover', {
948
+ pid: fresh.data?.pid ?? null,
949
+ });
950
+ }
951
+ try {
952
+ this._fs.unlinkSync(lockPath);
953
+ } catch (unlinkError) {
954
+ if (unlinkError.code !== 'ENOENT') {
955
+ throw new LedgerError('E_LOCKED', `cannot remove stale ledger lock: ${unlinkError.message}`);
956
+ }
957
+ }
958
+ repairs.push({
959
+ kind: 'stale-lock',
960
+ pid: existing.data?.pid ?? null,
961
+ host: existing.data?.host ?? null,
962
+ startedAt: existing.data?.startedAt ?? null,
963
+ reason: existing.error ?? 'owner-not-running',
964
+ });
965
+ } finally {
966
+ try {
967
+ this._fs.unlinkSync(takeoverPath);
968
+ } catch (markerCleanupError) {
969
+ // 不静默:残留标记会被陈旧回收逻辑接管,但要在日志里留痕。
970
+ if (markerCleanupError.code !== 'ENOENT') {
971
+ reportFail('ledger.takeover.marker.fail', { projectId: this.projectId, takeoverPath }, `[ai-team] ledger takeover marker could not be removed (${takeoverPath}): ${markerCleanupError.message}`);
972
+ }
973
+ }
974
+ }
975
+ }
976
+ }
977
+ throw new LedgerError('E_LOCKED', 'project ledger lock could not be acquired', {});
978
+ }
979
+
980
+ _readLock(lockPath) {
981
+ try {
982
+ const text = this._fs.readFileSync(lockPath, 'utf8');
983
+ const data = JSON.parse(text);
984
+ if (data === null || typeof data !== 'object') {
985
+ return { data: null, error: 'invalid-lock-record' };
986
+ }
987
+ return { data, error: null };
988
+ } catch (error) {
989
+ if (error.code === 'ENOENT') return { data: null, error: 'missing' };
990
+ return { data: null, error: error.name === 'SyntaxError' ? 'invalid-json' : error.message };
991
+ }
992
+ }
993
+
994
+ /** Age of the on-disk lock record in ms; Infinity when it cannot be stat'd. */
995
+ _lockRecordAge(lockPath) {
996
+ try {
997
+ return this._clock() - this._fs.statSync(lockPath).mtimeMs;
998
+ } catch {
999
+ return Number.POSITIVE_INFINITY;
1000
+ }
1001
+ }
1002
+
1003
+ _isStaleLock(data, lockPath) {
1004
+ if (!data || !Number.isSafeInteger(data.pid) || data.pid <= 0) {
1005
+ // 锁创建与写入 payload 之间文件是 0 字节:无条件判陈旧会让并发进程
1006
+ // 接管一个仍然活着的锁。给写入一个宽限期,超时后才认为是崩溃残留。
1007
+ return this._lockRecordAge(lockPath) > LOCK_WRITE_GRACE_MS;
1008
+ }
1009
+ // 不同主机共享目录:无法用本机 PID 判断,保守视为仍持有。
1010
+ if (typeof data.host === 'string' && data.host.length > 0 && data.host !== os.hostname()) {
1011
+ return false;
1012
+ }
1013
+ return !isProcessAlive(data.pid);
1014
+ }
1015
+
1016
+ _releaseLock() {
1017
+ const lockPath = path.join(this.dir, LOCK_FILE);
1018
+ try {
1019
+ const text = this._fs.readFileSync(lockPath, 'utf8');
1020
+ const data = JSON.parse(text);
1021
+ if (data?.token !== this._lockToken) return;
1022
+ this._fs.unlinkSync(lockPath);
1023
+ } catch {
1024
+ // 锁已不存在或已不是自己的:不要误删别人的锁。
1025
+ }
1026
+ }
1027
+ }
1028
+
1029
+ /**
1030
+ * 稳定门面:打开账本、重放当前状态,并保证 append 成功后才推进 state。
1031
+ *
1032
+ * @param {object} options 透传 LedgerWriter 选项:dir/projectId/fsync/segmentBytes/segmentEvents/lock/fs/clock
1033
+ * @returns {{
1034
+ * projectId: string,
1035
+ * writer: LedgerWriter,
1036
+ * state: object,
1037
+ * events: object[],
1038
+ * head: {seq:number,hash:string},
1039
+ * append: (draft:object)=>Promise<object>,
1040
+ * appendMany: (drafts:object[])=>Promise<object[]>,
1041
+ * readAll: (options?:object)=>object[],
1042
+ * replay: (state?:object)=>object,
1043
+ * verify: ()=>object,
1044
+ * repair: ()=>object,
1045
+ * close: ()=>void
1046
+ * }}
1047
+ */
1048
+ export function openLedger(options = {}) {
1049
+ const writer = new LedgerWriter(options);
1050
+ const opened = writer.open();
1051
+ // checkpoint 命中且账本与检查点齐平时,跳过全量 readAll(boot 的大头):
1052
+ // state 直接取自检查点,events 惰性化(首次访问才读盘,append 只增新事件)。
1053
+ // 尾部存在时才需要一次 readAll 来续放投影。
1054
+ const checkpointOptions = options.checkpoint ?? null;
1055
+ const checkpointDir = checkpointOptions?.dir ?? writer.dir;
1056
+ const stateVersion = checkpointOptions?.stateVersion ?? FOLD_STATE_VERSION;
1057
+ let state;
1058
+ let recovery = null;
1059
+ let events = null;
1060
+ const ensureEvents = () => {
1061
+ if (events === null) events = writer.readAll({ repairTail: false });
1062
+ return events;
1063
+ };
1064
+ if (checkpointOptions) {
1065
+ const loaded = loadCheckpoint(checkpointDir, {
1066
+ stateVersion,
1067
+ hashAt: (seq) => writer.hashAt(seq),
1068
+ });
1069
+ if (loaded.checkpoint && loaded.checkpoint.lastSeq === writer.head.seq) {
1070
+ // 齐平:零尾放,账本事件列表不进内存。
1071
+ state = loaded.checkpoint.state;
1072
+ recovery = {
1073
+ source: loaded.source,
1074
+ fromSeq: loaded.checkpoint.lastSeq + 1,
1075
+ tailReplayed: 0,
1076
+ errors: loaded.errors,
1077
+ };
1078
+ } else {
1079
+ const fromSeq = loaded.checkpoint ? loaded.checkpoint.lastSeq + 1 : 1;
1080
+ state = loaded.checkpoint ? loaded.checkpoint.state : initialState();
1081
+ const all = ensureEvents();
1082
+ for (const event of all) {
1083
+ if (event.seq >= fromSeq) Object.assign(state, applyEvent(state, event));
1084
+ }
1085
+ recovery = {
1086
+ source: loaded.source ?? 'replay',
1087
+ fromSeq,
1088
+ tailReplayed: Math.max(0, writer.head.seq - fromSeq + 1),
1089
+ errors: loaded.errors,
1090
+ };
1091
+ }
1092
+ } else {
1093
+ events = writer.readAll({ repairTail: false });
1094
+ state = fold(events);
1095
+ }
1096
+
1097
+ let onEvent = typeof options.onEvent === 'function' ? options.onEvent : null;
1098
+ // 检查点节奏:boot 后落一次地板,之后每 saveEvery 次追加落一次,close
1099
+ // 前必落——崩溃窗口最多丢 saveEvery 个事件的投影进度(账本本体无损)。
1100
+ const saveEvery = Number.isSafeInteger(checkpointOptions?.saveEvery)
1101
+ ? Math.max(50, checkpointOptions.saveEvery)
1102
+ : 500;
1103
+ let eventsSinceCheckpoint = 0;
1104
+ const saveCheckpointNow = () => {
1105
+ if (!checkpointOptions) return null;
1106
+ try {
1107
+ // 水位取"fold 已应用前缀"而非 writer.head:跨调用交错下(B 批次可在
1108
+ // A 的 facade 续体推进 state 之前提交),head 可能领先 state——按
1109
+ // head 落盘会持久化一个 state 落后于 lastSeq 的检查点,崩溃重开时
1110
+ // 零尾放静默吞掉投影。state.lastSeq/lastHash 由 advance() 逐事件
1111
+ // 维护,永远 ≤ head,尾放从其 +1 重放天然自洽。
1112
+ return saveCheckpoint(
1113
+ checkpointDir,
1114
+ { stateVersion, lastSeq: state.lastSeq, lastHash: state.lastHash, state },
1115
+ { hashAt: (seq) => writer.hashAt(seq) },
1116
+ );
1117
+ } catch (error) {
1118
+ // 检查点保存失败绝不影响追加,但必须可见:静默失败会让检查点
1119
+ // 名存实亡(boot 退化为全量重放而无人知晓)。
1120
+ reportFail('checkpoint.save.fail', { projectId: writer.projectId }, `[ai-team] ledger ${writer.projectId} checkpoint save failed: ${error?.message ?? error}`);
1121
+ return { error: error.message ?? String(error) };
1122
+ }
1123
+ };
1124
+ if (checkpointOptions) {
1125
+ const saved = saveCheckpointNow();
1126
+ recovery.saved = saved && !saved.error ? saved.path : (saved?.error ?? null);
1127
+ }
1128
+ const ledger = {
1129
+ projectId: writer.projectId,
1130
+ writer,
1131
+ state,
1132
+ /** 账本事件全列表(checkpoint 模式下惰性读盘,append 持续追加)。 */
1133
+ get events() {
1134
+ return ensureEvents();
1135
+ },
1136
+ opened,
1137
+ get onEvent() {
1138
+ return onEvent;
1139
+ },
1140
+ set onEvent(handler) {
1141
+ onEvent = typeof handler === 'function' ? handler : null;
1142
+ },
1143
+ get head() {
1144
+ return { ...writer.head };
1145
+ },
1146
+ get headSeq() {
1147
+ return writer.head.seq;
1148
+ },
1149
+ async append(draft, options) {
1150
+ // 先齐平 events:checkpoint 齐平启动时 events 还是 null,若等 append 之后再
1151
+ // readAll,刚写入的事件会被读出来、再被 push 一次(重复)。
1152
+ const list = ensureEvents();
1153
+ const event = await writer.append(draft, options);
1154
+ // 只有 append 成功(含 fsync)后才推进内存状态。
1155
+ Object.assign(state, applyEvent(state, event));
1156
+ list.push(event);
1157
+ try {
1158
+ onEvent?.(event);
1159
+ } catch {
1160
+ /* a projection listener must never break the append */
1161
+ }
1162
+ if (checkpointOptions) {
1163
+ eventsSinceCheckpoint += 1;
1164
+ if (eventsSinceCheckpoint >= saveEvery) {
1165
+ eventsSinceCheckpoint = 0;
1166
+ saveCheckpointNow();
1167
+ }
1168
+ }
1169
+ return event;
1170
+ },
1171
+ async appendMany(drafts) {
1172
+ const list = ensureEvents();
1173
+ const appended = await writer.appendMany(drafts);
1174
+ let next = state;
1175
+ for (const event of appended) {
1176
+ next = applyEvent(next, event);
1177
+ list.push(event);
1178
+ }
1179
+ Object.assign(state, next);
1180
+ for (const event of appended) {
1181
+ try {
1182
+ onEvent?.(event);
1183
+ } catch {
1184
+ /* a projection listener must never break the append */
1185
+ }
1186
+ }
1187
+ if (checkpointOptions) {
1188
+ eventsSinceCheckpoint += appended.length;
1189
+ if (eventsSinceCheckpoint >= saveEvery) {
1190
+ eventsSinceCheckpoint = 0;
1191
+ saveCheckpointNow();
1192
+ }
1193
+ }
1194
+ return appended;
1195
+ },
1196
+ /** boot 时检查点恢复方式:'primary'/'backup'/'replay' 与尾放区间。 */
1197
+ get recovery() {
1198
+ return recovery;
1199
+ },
1200
+ readAll(readOptions = {}) {
1201
+ return writer.readAll(readOptions);
1202
+ },
1203
+ replay(from = initialState()) {
1204
+ return writer.replay(from, applyEvent);
1205
+ },
1206
+ verify() {
1207
+ try {
1208
+ const all = writer.readAll({ repairTail: false });
1209
+ const chain = verifyChain(all, { projectId: writer.projectId });
1210
+ return {
1211
+ ok: chain.ok,
1212
+ eventCount: all.length,
1213
+ head: writer.head,
1214
+ error: chain.ok
1215
+ ? null
1216
+ : {
1217
+ code: chain.code,
1218
+ message: chain.message,
1219
+ details: chain.details ?? {},
1220
+ index: chain.index,
1221
+ },
1222
+ };
1223
+ } catch (error) {
1224
+ return {
1225
+ ok: false,
1226
+ eventCount: null,
1227
+ head: writer.head,
1228
+ error: {
1229
+ code: error.code ?? 'E_LEDGER_CORRUPT',
1230
+ message: error.message,
1231
+ details: error.details ?? {},
1232
+ },
1233
+ };
1234
+ }
1235
+ },
1236
+ repair() {
1237
+ const result = writer.repair();
1238
+ // writer 层修的是段文件;门面这一层的 state/events 必须跟着**重折**。
1239
+ // 只返回 writer 的结果会让 state.lastSeq 停在修复前的水位:下一次 append
1240
+ // 之后 state.lastSeq 直接跳到新 head,中间那段事件永远不进投影,而
1241
+ // checkpoint 的零尾放会把这条缺口永久固化。
1242
+ // 从磁盘重读而不是用缓存:缓存里可能正是修复前那份含撕裂批次的列表。
1243
+ events = writer.readAll({ repairTail: false });
1244
+ state = fold(events);
1245
+ eventsSinceCheckpoint = 0;
1246
+ if (checkpointOptions) saveCheckpointNow();
1247
+ // 恢复区间与缺口:一次失败的 appendMany 可能把「前缀」留在盘上,光说
1248
+ // 「修好了」不够——运维需要知道接受到了哪个 seq、有没有洞。
1249
+ const gaps = [];
1250
+ for (let index = 0; index < events.length; index += 1) {
1251
+ if (events[index]?.seq !== index + 1) {
1252
+ gaps.push({ at: index, seq: events[index]?.seq ?? null });
1253
+ if (gaps.length >= 20) break;
1254
+ }
1255
+ }
1256
+ return {
1257
+ ...result,
1258
+ refolded: true,
1259
+ events: events.length,
1260
+ stateLastSeq: state.lastSeq ?? null,
1261
+ acceptedRange: events.length === 0
1262
+ ? null
1263
+ : { from: events[0].seq ?? null, to: events[events.length - 1].seq ?? null },
1264
+ seqGaps: gaps,
1265
+ };
1266
+ },
1267
+ close() {
1268
+ if (checkpointOptions) saveCheckpointNow();
1269
+ writer.close();
1270
+ },
1271
+ };
1272
+
1273
+ return ledger;
1274
+ }