@jjh32456/longlive 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +108 -1
  2. package/QUICKSTART.md +7 -7
  3. package/README.en.md +13 -1
  4. package/README.md +26 -8
  5. package/SPEC.md +6 -5
  6. package/build-info.json +143 -73
  7. package/cordis.patch.yml +2 -0
  8. package/docs/ARCHITECTURE.md +6 -3
  9. package/docs/CONFIG.md +25 -1
  10. package/docs/FAQ.md +2 -2
  11. package/docs/FEATURES.md +125 -2
  12. package/docs/INDEX-FRESHNESS.md +8 -1
  13. package/docs/OPERATIONS.md +63 -2
  14. package/docs/QUICKSTART.md +2 -2
  15. package/docs/README.en.md +1 -1
  16. package/docs/TROUBLESHOOTING.md +1 -1
  17. package/package.json +10 -2
  18. package/scripts/assert-install.mjs +124 -0
  19. package/scripts/backlog-report.mjs +98 -0
  20. package/scripts/install-230.mjs +787 -0
  21. package/scripts/lib/eng-common.mjs +428 -0
  22. package/scripts/rebuild-index.mjs +148 -0
  23. package/scripts/restore-drill.mjs +351 -0
  24. package/scripts/run-autoresolve.mjs +123 -0
  25. package/scripts/watchdog-230.mjs +379 -0
  26. package/src/config.js +7 -0
  27. package/src/features.js +35 -0
  28. package/src/gate/action-gate.js +545 -0
  29. package/src/memory/backup-retention.mjs +823 -0
  30. package/src/memory/cards.js +73 -12
  31. package/src/memory/conflict-scan.mjs +356 -0
  32. package/src/memory/conflicts.js +202 -9
  33. package/src/memory/consolidate.js +537 -35
  34. package/src/memory/decay.js +133 -19
  35. package/src/memory/event-index.js +62 -4
  36. package/src/memory/forget-scheduler.mjs +303 -0
  37. package/src/memory/forget-v2.js +94 -8
  38. package/src/memory/index-cache.mjs +216 -0
  39. package/src/memory/index.js +179 -16
  40. package/src/memory/lock.js +53 -12
  41. package/src/memory/maintenance.js +295 -19
  42. package/src/memory/recall-feedback.mjs +159 -17
  43. package/src/memory/recall-v2.js +5 -3
  44. package/src/memory/recall.js +10 -4
  45. package/src/memory/state.js +446 -38
  46. package/src/memory/task-state.mjs +569 -0
  47. package/src/recall/brain.mjs +55 -6
  48. package/src/recall/continuity-volatile.mjs +195 -1
  49. package/src/recall/index.js +8 -0
  50. package/src/tools.js +141 -21
  51. package/src/ui/routes-readonly.js +63 -5
@@ -22,6 +22,14 @@ import {
22
22
  } from './state.js';
23
23
  import { PROCEDURES_DIR, scanProcedures } from './procedure.js';
24
24
  import { getIndexFreshness } from './index-freshness.js';
25
+ import {
26
+ cacheRowToCard,
27
+ cardToCacheRow,
28
+ getHash,
29
+ loadIndexCache,
30
+ planIndexScan,
31
+ saveIndexCache,
32
+ } from './index-cache.mjs';
25
33
 
26
34
  export const BEGIN_GENERATED = '<!-- BEGIN GENERATED -->';
27
35
  export const END_GENERATED = '<!-- END GENERATED -->';
@@ -29,6 +37,11 @@ export const INDEX_FILE = 'INDEX.md';
29
37
  export const PROCEDURES_HEADING = `### 程序性(${PROCEDURES_DIR}/)`;
30
38
 
31
39
  const SCAN_DIRS = ['topics', 'journal'];
40
+ /**
41
+ * 召回面扫描目录:卡片面 + procedures(程序卡)。索引面(memoryIndex)仍用
42
+ * SCAN_DIRS,procedures 由 scanProcedures 单独计入「程序性」表,避免重复计数。
43
+ */
44
+ export const RECALL_SCAN_DIRS = Object.freeze(['topics', 'journal', PROCEDURES_DIR]);
32
45
  export const RAW_DIRS = ['raw', 'topics/raw'];
33
46
  export const RAW_INDEX_POLICY = 'excluded-by-default';
34
47
  export const RAW_OPT_IN_FIELD = 'index';
@@ -141,6 +154,24 @@ function resolveReadCardArgs(first, second) {
141
154
  return { root, abs };
142
155
  }
143
156
 
157
+ /** 程序卡 trigger 是动作词数组(`[发布, 部署]`),也兼容裸字符串(`发布`)。 */
158
+ function procedureTriggerTags(value) {
159
+ if (Array.isArray(value)) return value.map((item) => collapse(item)).filter(Boolean);
160
+ let text = collapse(value);
161
+ if (!text) return [];
162
+ // parseFrontmatter 不解析内联数组,extras.trigger 可能是整段 `[发布, publish, npm]` 字符串。
163
+ text = text.replace(/^\[/, '').replace(/\]$/, '');
164
+ return text.split(',').map((item) => item.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
165
+ }
166
+
167
+ function mergeProcedureTags(existing, trigger) {
168
+ const merged = Array.isArray(existing) ? existing.map((item) => collapse(item)).filter(Boolean) : [];
169
+ for (const tag of procedureTriggerTags(trigger)) {
170
+ if (!merged.some((item) => item.toLowerCase() === tag.toLowerCase())) merged.push(tag);
171
+ }
172
+ return merged;
173
+ }
174
+
144
175
  /**
145
176
  * 读一张卡:frontmatter + 正文。正文按 C 召回面口径带 body(≤1,200 码点,
146
177
  * 超长 bodyTruncated:true,另给 bodyChars);local_only / 隐私卡正文与摘要一律
@@ -152,7 +183,11 @@ export function readCard(first, second) {
152
183
  const text = fs.readFileSync(abs, 'utf8');
153
184
  const parsed = parseFrontmatter(text);
154
185
  const rel = relFromAbs(abs, root);
155
- const title = collapse(parsed.fields.title || firstHeading(parsed.body) || path.basename(abs, '.md')) || '(无题)';
186
+ // 程序卡(procedures/)frontmatter 用 name / trigger,没有 title / tags:
187
+ // 把 name 映射成 title、trigger 映射成 tags,否则召回打分吃不到标题 +5 / tags +3。
188
+ const isProcedure = rel.replace(/\\/g, '/').startsWith(`${PROCEDURES_DIR}/`);
189
+ const title = collapse(parsed.fields.title || parsed.extras?.name || firstHeading(parsed.body) || path.basename(abs, '.md')) || '(无题)';
190
+ const tags = isProcedure ? mergeProcedureTags(parsed.fields.tags, parsed.extras?.trigger) : parsed.fields.tags;
156
191
  const rawBody = String(parsed.body ?? '').trim();
157
192
  const localOnly = truthyFlag(parsed.fields.local_only) || truthyFlag(parsed.extras?.local_only);
158
193
  const bodyChars = Array.from(rawBody).length;
@@ -170,8 +205,9 @@ export function readCard(first, second) {
170
205
  title,
171
206
  summary: localOnly ? CARD_BODY_HIDDEN : firstSummaryLine(parsed.body),
172
207
  legacy: parsed.legacy,
173
- fields: parsed.fields,
208
+ fields: isProcedure ? { ...parsed.fields, tags } : parsed.fields,
174
209
  extras: parsed.extras ?? {},
210
+ ...(isProcedure ? { procedure: true } : {}),
175
211
  body,
176
212
  bodyChars: localOnly ? 0 : Array.from(body).length,
177
213
  bodyTruncated,
@@ -187,24 +223,80 @@ function shouldSkipScanRel(rel) {
187
223
  return false;
188
224
  }
189
225
 
190
- /** All cards under `topics/` (incl. `topics/auto/`) and `journal/`, archive excluded. */
191
- export function scanCards(root) {
192
- const cards = [];
193
- for (const dir of SCAN_DIRS) {
226
+ /** 扫描面文件清单(abs):topics/(含 topics/auto/)与 journal/,archive 除外。 */
227
+ export function scanFileList(root, dirs = SCAN_DIRS) {
228
+ const out = [];
229
+ const list = Array.isArray(dirs) && dirs.length > 0 ? dirs : SCAN_DIRS;
230
+ for (const dir of list) {
194
231
  for (const abs of listMarkdownFiles(root, dir)) {
195
232
  const rel = relativePath(root, abs);
196
233
  if (shouldSkipScanRel(rel)) continue;
197
- cards.push(readCard(root, abs));
234
+ out.push(abs);
198
235
  }
199
236
  }
200
- cards.sort((left, right) => {
237
+ return out;
238
+ }
239
+
240
+ function sortCards(cards) {
241
+ return cards.sort((left, right) => {
201
242
  if (right.fields.salience !== left.fields.salience) return right.fields.salience - left.fields.salience;
202
243
  const leftUsed = left.fields.last_used ?? '';
203
244
  const rightUsed = right.fields.last_used ?? '';
204
245
  if (rightUsed !== leftUsed) return rightUsed.localeCompare(leftUsed);
205
246
  return left.rel.localeCompare(right.rel);
206
247
  });
207
- return cards;
248
+ }
249
+
250
+ /** All cards under `topics/` (incl. `topics/auto/`) and `journal/`, archive excluded. */
251
+ export function scanCards(root, options = {}) {
252
+ const cards = scanFileList(root, options?.dirs).map((abs) => readCard(root, abs));
253
+ return sortCards(cards);
254
+ }
255
+
256
+ /**
257
+ * mtime 预筛版扫描:未变化的卡直接用缓存里的行,不 open / 不 read / 不解析。
258
+ * 返回 {cards, stats, entries, dataThroughMs};stats 让调用端(和测试)能看到
259
+ * 这一轮到底读了几张、复用了几张、删掉几张。
260
+ */
261
+ export function scanCardsWithCache(root, options = {}) {
262
+ const dirs = Array.isArray(options?.dirs) && options.dirs.length > 0 ? options.dirs : SCAN_DIRS;
263
+ const full = options?.full === true;
264
+ const cache = options?.cache === null ? null : (options?.cache ?? loadIndexCache(root));
265
+ const files = scanFileList(root, dirs);
266
+ const plan = planIndexScan({ root, files, cache, full });
267
+ const cards = [];
268
+ for (const item of plan.read) {
269
+ const card = readCard(root, item.abs);
270
+ cards.push(card);
271
+ plan.entries[item.rel] = {
272
+ mtimeMs: item.signature.mtimeMs,
273
+ ctimeMs: item.signature.ctimeMs,
274
+ size: item.signature.size,
275
+ chunkAtMs: item.signature.mtimeMs,
276
+ row: cardToCacheRow(card),
277
+ };
278
+ plan.dataThroughMs = Math.max(plan.dataThroughMs, item.signature.mtimeMs);
279
+ }
280
+ for (const rel of plan.reused) {
281
+ const entry = plan.entries[rel];
282
+ if (!entry || !entry.row) continue;
283
+ cards.push(cacheRowToCard(entry.row));
284
+ }
285
+ return {
286
+ cards: sortCards(cards),
287
+ entries: plan.entries,
288
+ dataThroughMs: plan.dataThroughMs,
289
+ stats: {
290
+ filesScanned: files.length,
291
+ filesRead: plan.read.length,
292
+ filesReused: plan.reused.length,
293
+ filesRemoved: plan.removed.length,
294
+ removed: plan.removed,
295
+ cacheHit: full === false && plan.read.length === 0 && plan.reused.length > 0,
296
+ // ③ chunk 级时间戳:dataThroughAt 是这些 chunk mtime 的最大值。
297
+ dataThroughAt: plan.dataThroughMs > 0 ? new Date(plan.dataThroughMs).toISOString() : null,
298
+ },
299
+ };
208
300
  }
209
301
 
210
302
  function cell(value) {
@@ -317,7 +409,12 @@ export function memoryIndex(args = {}, config = {}) {
317
409
  const root = memoryRootFromConfig(config);
318
410
  const now = config.now instanceof Date ? config.now : new Date();
319
411
  const apply = args.apply === true;
320
- const core = scanCards(root);
412
+ const full = args.full === true;
413
+ const scanned = scanCardsWithCache(root, {
414
+ full,
415
+ cache: args.cache === null ? null : args.cache,
416
+ });
417
+ const core = scanned.cards;
321
418
  const { cards: procedures, invalid: invalidCards } = scanProcedures(root);
322
419
  const cards = [...core, ...procedures.map((card) => ({ ...card, procedure: true }))];
323
420
  const rawPolicy = scanRawPolicy(root);
@@ -335,6 +432,8 @@ export function memoryIndex(args = {}, config = {}) {
335
432
  // A generated timestamp alone is not a content change; capture/ifChanged must
336
433
  // not rewrite/back up INDEX.md on every turn just because time moved.
337
434
  const contentChanged = withoutGeneratedStamp(before) !== withoutGeneratedStamp(after);
435
+ // ④ 页面自算 hash 与 getHash:这里算出来的就是 state/缓存里记的那个 hash。
436
+ const pageHash = getHash(after);
338
437
  const base = {
339
438
  root,
340
439
  indexPath,
@@ -346,6 +445,8 @@ export function memoryIndex(args = {}, config = {}) {
346
445
  ...counts,
347
446
  changed,
348
447
  contentChanged,
448
+ indexHash: pageHash,
449
+ scan: scanned.stats,
349
450
  generated: section,
350
451
  };
351
452
 
@@ -361,26 +462,60 @@ export function memoryIndex(args = {}, config = {}) {
361
462
  message:
362
463
  `dry-run:扫描到 ${cards.length} 张卡(legacy ${legacy},程序性 ${procedures.length}` +
363
464
  `${invalid > 0 ? `,坏卡 ${invalid}` : ''});raw 策略=${rawPolicy.policy}` +
465
+ `;读取 ${scanned.stats.filesRead} / 复用 ${scanned.stats.filesReused} / 移除 ${scanned.stats.filesRemoved}` +
364
466
  `→ ${changed ? 'INDEX.md 会变化' : 'INDEX.md 已是最新'};加 apply:true 才落盘`,
365
467
  };
366
468
  }
367
469
 
368
- if (args.ifChanged === true && !contentChanged) {
470
+ // F5(记忆索引幂等):默认只在“生成段内容真的变了”时才重写 INDEX.md。
471
+ // 只看自动生成的时间戳会每次都换 sha、每次都堆一份备份;`ifChanged:false`
472
+ // 仍可强制重写(供需要刷新戳的显式场景用)。
473
+ const ifChanged = args.ifChanged !== false;
474
+ if (ifChanged && !contentChanged) {
475
+ // F5(记忆索引幂等):apply 已执行,但 INDEX.md 本来就没有内容变化 —— 不重写文件、
476
+ // 不新增 INDEX 备份(只更新时间戳会换 sha、每次都堆一份备份,这是 RT 审计的 F5)。
477
+ //
478
+ // 兼容语义(2.2 起就有的约定):applied 表示“这次 apply 请求被受理并执行”,
479
+ // 不代表“必然重写了文件”;是否真的动盘看 changed / contentChanged / status。
480
+ //
481
+ // N8:即使不重写 INDEX,“当前内容已复核为最新”也必须推进 indexBuiltAt。否则 capture
482
+ // 每轮的正常写入会被 indexLagMs 误判成索引落后,>5 分钟后健康度假性变 stale。
369
483
  updateState(root, {
484
+ indexBuiltAt: now.toISOString(),
370
485
  indexLastRefreshAt: now.toISOString(),
486
+ // ③ 即使内容没变也要把 dataThrough 记成真实 chunk 时间(卡片 mtime),
487
+ // 不是“这一轮扫描的开始时间”,否则新鲜度 lag 会假性增长。
488
+ indexDataAt: scanned.stats.dataThroughAt ?? now.toISOString(),
489
+ indexHash: pageHash,
371
490
  indexFreshness: 'fresh',
372
491
  indexLastError: null,
373
492
  }, { now });
493
+ persistCache(root, scanned, { full, now });
494
+ // 手动 apply 即使没写盘也要在 audit.log 留账,否则「我跑过重建没有」无从审计。
495
+ appendAudit(root, {
496
+ action: 'memory_index',
497
+ object: INDEX_FILE,
498
+ result:
499
+ `cards=${cards.length} legacy=${legacy} procedures=${procedures.length} invalid=${invalid} ` +
500
+ `raw=${rawPolicy.policy} unchanged=1 hash=${pageHash.slice(0, 16)} ` +
501
+ `read=${scanned.stats.filesRead} reused=${scanned.stats.filesReused} removed=${scanned.stats.filesRemoved}`,
502
+ now,
503
+ });
374
504
  const freshness = getIndexFreshness({ memoryRoot: root, now });
375
505
  return {
376
506
  ...base,
377
507
  ok: true,
378
508
  status: 'unchanged',
379
509
  dryRun: false,
380
- applied: false,
510
+ applied: true,
511
+ // 盘上的 INDEX.md 没有被改写:幂等判据就报 false;生成戳本会变不代表内容变了。
512
+ changed: false,
513
+ stateWritten: true,
381
514
  freshness,
382
515
  indexBuiltAt: freshness.generatedAt,
383
- message: `INDEX.md 已是最新(${cards.length} 行),未重写。`,
516
+ message:
517
+ `INDEX.md 已是最新(${cards.length} 行),未重写、未新增备份(幂等);` +
518
+ `本轮读取 ${scanned.stats.filesRead} / 复用 ${scanned.stats.filesReused} 个文件,新鲜度记账已刷新。`,
384
519
  };
385
520
  }
386
521
 
@@ -389,18 +524,28 @@ export function memoryIndex(args = {}, config = {}) {
389
524
  if (readBack !== after) {
390
525
  throw memoryError('E_INDEX_VERIFY', `INDEX.md 写入后读回不一致:${indexPath}`);
391
526
  }
527
+ const readBackHash = getHash(readBack);
528
+ if (readBackHash !== pageHash) {
529
+ throw memoryError('E_INDEX_HASH_VERIFY', `INDEX.md 读回 hash 与写入前不一致:${pageHash} != ${readBackHash}`);
530
+ }
531
+ const dataThroughAt = scanned.stats.dataThroughAt ?? now.toISOString();
392
532
  updateState(root, {
393
533
  indexBuiltAt: now.toISOString(),
394
- indexDataAt: now.toISOString(),
534
+ indexDataAt: dataThroughAt,
535
+ indexHash: readBackHash,
395
536
  indexFreshness: 'fresh',
396
537
  indexLagMs: 0,
397
538
  indexLastRefreshAt: now.toISOString(),
398
539
  indexLastError: null,
399
540
  }, { now });
541
+ persistCache(root, scanned, { full, now });
400
542
  appendAudit(root, {
401
543
  action: 'memory_index',
402
544
  object: INDEX_FILE,
403
- result: `cards=${cards.length} legacy=${legacy} procedures=${procedures.length} invalid=${invalid} raw=${rawPolicy.policy} changed=${changed}`,
545
+ result:
546
+ `cards=${cards.length} legacy=${legacy} procedures=${procedures.length} invalid=${invalid} ` +
547
+ `raw=${rawPolicy.policy} changed=${changed} hash=${readBackHash.slice(0, 16)} ` +
548
+ `read=${scanned.stats.filesRead} reused=${scanned.stats.filesReused} removed=${scanned.stats.filesRemoved}`,
404
549
  now,
405
550
  });
406
551
  const freshness = getIndexFreshness({ memoryRoot: root, now });
@@ -417,10 +562,28 @@ export function memoryIndex(args = {}, config = {}) {
417
562
  indexBuiltAt: now.toISOString(),
418
563
  message:
419
564
  `已重建 INDEX.md:${cards.length} 行(legacy ${legacy},程序性 ${procedures.length}` +
420
- `${invalid > 0 ? `,坏卡 ${invalid}` : ''}),备份 ${write.backupRel ?? '(首次创建,无旧文件)'}`,
565
+ `${invalid > 0 ? `,坏卡 ${invalid}` : ''}),读取 ${scanned.stats.filesRead} / 复用 ${scanned.stats.filesReused} 个文件` +
566
+ `,备份 ${write.backupRel ?? '(首次创建,无旧文件)'}`,
421
567
  };
422
568
  }
423
569
 
570
+ /**
571
+ * 缓存落盘失败不致命:索引本体已经写好,缓存只是下一次提速的附件。
572
+ * 返回 {saved, error},调用端保留在 scan 里即可。
573
+ */
574
+ function persistCache(root, scanned, { full, now }) {
575
+ try {
576
+ saveIndexCache(root, {
577
+ entries: scanned.entries,
578
+ builtAt: (now instanceof Date ? now : new Date()).toISOString(),
579
+ full,
580
+ });
581
+ return { saved: true };
582
+ } catch (error) {
583
+ return { saved: false, error: error?.message ?? String(error) };
584
+ }
585
+ }
586
+
424
587
  /** Read the generated region of an INDEX.md text, or null when absent. */
425
588
  export function extractGeneratedSection(text) {
426
589
  const source = String(text ?? '');
@@ -36,17 +36,50 @@ function nowMs(now) {
36
36
  return value instanceof Date ? value.getTime() : Number(value);
37
37
  }
38
38
 
39
+ /**
40
+ * Cross-platform synchronous sleep. `Atomics.wait` on a fresh SharedArrayBuffer
41
+ * works on the main thread in Node (unlike browsers) and needs no dependency.
42
+ */
43
+ export function sleepSync(ms) {
44
+ const value = Number(ms);
45
+ if (!Number.isFinite(value) || value <= 0) return 0;
46
+ const cell = new Int32Array(new SharedArrayBuffer(4));
47
+ Atomics.wait(cell, 0, 0, Math.ceil(value));
48
+ return Math.ceil(value);
49
+ }
50
+
39
51
  /**
40
52
  * Acquire a lease. Returns { ok:true, holder, acquiredAt, expiresAt, staleTakenOver }
41
- * or throws LockError E_LOCKED with the current holder.
53
+ * or throws LockError:
54
+ * * `E_LOCKED` — an active lease is held elsewhere and no waiting was asked for;
55
+ * * `E_LOCK_TIMEOUT`— waiting was requested (`waitTimeoutMs`) and the deadline passed.
56
+ *
57
+ * 2.3.0: optional bounded wait. `waitTimeoutMs` (default 0 = old fail-fast path) and
58
+ * `retryMs` (default 25) make a contended lease retry instead of failing the
59
+ * read-modify-write immediately; the deadline uses the real wall clock so an
60
+ * injected `now` cannot make the wait loop spin forever.
42
61
  */
62
+ export const DEFAULT_LOCK_RETRY_MS = 25;
63
+ export const DEFAULT_LOCK_WAIT_TIMEOUT_MS = 0;
64
+
43
65
  export function acquireLease(lockFile, options = {}) {
44
66
  const file = path.resolve(String(lockFile));
45
67
  const holder = typeof options.holder === 'string' && options.holder !== '' ? options.holder : `pid-${process.pid}`;
46
68
  const ttlMs = Number.isInteger(options.ttlMs) && options.ttlMs > 0 ? options.ttlMs : DEFAULT_LOCK_TTL_MS;
47
69
  const now = options.now;
70
+ const waitTimeoutMs = Number.isFinite(options.waitTimeoutMs) && options.waitTimeoutMs > 0
71
+ ? Number(options.waitTimeoutMs)
72
+ : DEFAULT_LOCK_WAIT_TIMEOUT_MS;
73
+ const retryMs = Number.isFinite(options.retryMs) && options.retryMs >= 0
74
+ ? Number(options.retryMs)
75
+ : DEFAULT_LOCK_RETRY_MS;
76
+ const deadline = Date.now() + waitTimeoutMs;
77
+ const startedAt = Date.now();
48
78
  fs.mkdirSync(path.dirname(file), { recursive: true });
49
- for (let attempt = 0; attempt < 2; attempt += 1) {
79
+ let staleTakeovers = 0;
80
+ let attempts = 0;
81
+ for (;;) {
82
+ attempts += 1;
50
83
  const acquiredAt = nowMs(now);
51
84
  const lease = { holder, pid: process.pid, acquiredAt, expiresAt: acquiredAt + ttlMs };
52
85
  try {
@@ -56,31 +89,39 @@ export function acquireLease(lockFile, options = {}) {
56
89
  } finally {
57
90
  fs.closeSync(fd);
58
91
  }
59
- return { ok: true, holder, acquiredAt, expiresAt: lease.expiresAt, lockFile: file, staleTakenOver: attempt > 0 };
92
+ return { ok: true, holder, acquiredAt, expiresAt: lease.expiresAt, lockFile: file, staleTakenOver: staleTakeovers > 0, attempts };
60
93
  } catch (error) {
61
94
  if (error?.code !== 'EEXIST') throw new LockError('E_LOCK_IO', `无法创建锁文件:${error?.message ?? error}`);
62
95
  const current = readLease(file);
63
96
  const currentAt = Number(current?.expiresAt ?? 0);
64
97
  if (current && current.holder === holder) {
65
- return { ok: true, holder, acquiredAt: Number(current.acquiredAt) || acquiredAt, expiresAt: currentAt, lockFile: file, alreadyHeld: true };
98
+ return { ok: true, holder, acquiredAt: Number(current.acquiredAt) || acquiredAt, expiresAt: currentAt, lockFile: file, alreadyHeld: true, attempts };
66
99
  }
67
100
  if (!current || !Number.isFinite(currentAt) || currentAt < nowMs(now)) {
68
- // stale / corrupt lease: take it over exactly once
101
+ // stale / corrupt lease: take it over, but never loop forever on a
102
+ // lease that keeps being re-created by a racing contender.
103
+ if (staleTakeovers >= 3) {
104
+ throw new LockError('E_LOCKED', '写锁竞争失败(stale takeover 多次被抢先)', { attempts });
105
+ }
106
+ staleTakeovers += 1;
69
107
  try {
70
108
  fs.rmSync(file, { force: true });
71
109
  } catch {
72
- /* raced with another taker; loop retries once */
110
+ /* raced with another taker; loop retries */
73
111
  }
74
112
  continue;
75
113
  }
76
- throw new LockError('E_LOCKED', `写锁被 ${current.holder} 持有(pid=${current.pid})`, {
77
- holder: current.holder,
78
- pid: current.pid,
79
- expiresAt: currentAt,
80
- });
114
+ const detail = { holder: current.holder, pid: current.pid, expiresAt: currentAt, attempts };
115
+ if (Date.now() < deadline) {
116
+ sleepSync(retryMs);
117
+ continue;
118
+ }
119
+ if (waitTimeoutMs > 0) {
120
+ throw new LockError('E_LOCK_TIMEOUT', `等待写锁超时(${Date.now() - startedAt}ms):被 ${current.holder} 持有(pid=${current.pid})`, detail);
121
+ }
122
+ throw new LockError('E_LOCKED', `写锁被 ${current.holder} 持有(pid=${current.pid})`, detail);
81
123
  }
82
124
  }
83
- throw new LockError('E_LOCKED', '写锁竞争失败(stale takeover 两次均被抢先)');
84
125
  }
85
126
 
86
127
  /** Release only if the recorded holder matches (never steal someone else's lease). */