@dsh-plus/lifeboat 0.1.7 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -256,6 +256,16 @@ function installLlmFallback(ctx, deps) {
256
256
  * 官方预留的逃生门:用户层支持 id 定向 disabled,覆盖 bundle 层 insert。
257
257
  * 写入纪律:先备份、幂等(已禁用跳过)、原子落盘(tmp + rename),失败抛错由调用方告警,
258
258
  * 绝不写半个文件、绝不改动既有条目内容。
259
+ *
260
+ * 2026-08-30 事故教训(保险丝必须先于负载可靠):
261
+ * 1. 并发写竞争:多个插件同一毫秒 FAILED → 多路 appendDisable 共享固定 tmp 名
262
+ * → rename ENOENT / 读改写丢更新。修复:进程内按文件串行化(promise 链锁)
263
+ * + tmp 名带 pid/随机后缀。
264
+ * 2. YAML 带错仍强行 stringify:parseDocument 对语法错误不抛而收集进
265
+ * doc.errors,后续 toString 抛 "Document with errors cannot be stringified"
266
+ * → 隔离永远写不进去。修复:写前校验 doc.errors;文件已坏时走重建通道
267
+ * (备份坏文件 → 容错打捞既有 disabled 条目 → 重写干净文档),
268
+ * 隔离落盘优先于保留坏文件。
259
269
  * @module lifeboat/patch-file
260
270
  */
261
271
  /** 条目(含 insert 子列表)中是否已有针对 targetId 的 disabled 覆盖。 */
@@ -266,66 +276,116 @@ function hasDisable(entries, targetId) {
266
276
  }
267
277
  return false;
268
278
  }
279
+ /** 顶层条目中已禁用的 id 列表(不含 insert 子列表;用户层 disabled 语义只在顶层)。 */
280
+ function listDisabled(entries) {
281
+ const out = [];
282
+ for (const entry of entries) if (typeof entry.id === "string" && entry.disabled === true) out.push(entry.id);
283
+ return out;
284
+ }
285
+ /** 进程内按文件串行化:并发隔离写同一 patch 文件时消除读改写竞争。 */
286
+ const fileLocks = /* @__PURE__ */ new Map();
287
+ function withFileLock(file, fn) {
288
+ const next = (fileLocks.get(file) ?? Promise.resolve()).then(fn, fn);
289
+ fileLocks.set(file, next.catch(() => {}));
290
+ return next;
291
+ }
292
+ /** 唯一 tmp 名(并发/重入不留共享路径),rename 原子落盘。 */
293
+ async function atomicWrite(patchFile, content) {
294
+ const tmp = `${patchFile}.lifeboat.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`;
295
+ await writeFile(tmp, content, "utf-8");
296
+ await rename(tmp, patchFile);
297
+ }
298
+ /**
299
+ * 容错打捞坏 YAML 文本中既有的顶层 disabled 条目(best-effort):
300
+ * `- id: <name>` 与同条块内的 `disabled: true` 配对即认定。
301
+ * 坏文件里可能躺着此前已隔离的插件——重建时漏掉它们等于重新放行故障插件。
302
+ */
303
+ function salvageDisabled(text) {
304
+ const out = [];
305
+ for (const match of text.matchAll(/-\s+id:\s*(\S+)([^\0]*?)(?=\n\s*-\s+id:|$)/g)) {
306
+ const id = match[1];
307
+ const block = match[2] ?? "";
308
+ if (id !== void 0 && /\bdisabled:\s*true\b/.test(block)) out.push(id);
309
+ }
310
+ return out;
311
+ }
312
+ /**
313
+ * 重建通道:原文件 YAML 已坏(doc.errors 非空)时的隔离写入。
314
+ * 备份坏文件(保留现场)→ 打捞既有 disabled → 重写干净文档。
315
+ * 即使目标已在打捞集中也照样重写——坏文件对 loader 等于不存在,
316
+ * 修复文件本身与写入禁用同等重要;返回值仅报告目标集合是否变化。
317
+ */
318
+ async function appendDisableRebuild(patchFile, text, targetId) {
319
+ const salvaged = salvageDisabled(text);
320
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g, "-");
321
+ await copyFile(patchFile, `${patchFile}.broken-${stamp}.bak`);
322
+ const entries = (salvaged.includes(targetId) ? salvaged : [...salvaged, targetId]).map((id) => `- id: ${id}\n disabled: true`);
323
+ await atomicWrite(patchFile, [
324
+ "# 本文件由 lifeboat 重建:原文件存在 YAML 语法错误,无法安全改写。",
325
+ `# 原件已备份为同目录 .broken-${stamp}.bak,请人工合并残留自定义条目。`,
326
+ ...entries,
327
+ ""
328
+ ].join("\n"));
329
+ return !salvaged.includes(targetId);
330
+ }
269
331
  /**
270
332
  * 向 patch 文件追加一条禁用覆盖;返回是否实际写入(已存在禁用则跳过)。
333
+ * 原文件 YAML 已坏时转重建通道(隔离落盘优先,原件备份待人工合并)。
271
334
  * @throws 文件不可读/顶层不是数组/落盘失败——调用方负责告警。
272
335
  */
273
336
  async function appendDisable(patchFile, targetId) {
274
- const text = await readFile(patchFile, "utf-8");
275
- const doc = parseDocument(text);
276
- const root = doc.toJS();
277
- if (!Array.isArray(root)) throw new Error(`patch 文件顶层不是数组: ${patchFile}`);
278
- if (hasDisable(root, targetId)) return false;
279
- await copyFile(patchFile, `${patchFile}.lifeboat.bak`);
280
- doc.add({
281
- id: targetId,
282
- disabled: true
337
+ return withFileLock(patchFile, async () => {
338
+ const text = await readFile(patchFile, "utf-8");
339
+ const doc = parseDocument(text);
340
+ if (doc.errors.length > 0) return appendDisableRebuild(patchFile, text, targetId);
341
+ const root = doc.toJS();
342
+ if (!Array.isArray(root)) throw new Error(`patch 文件顶层不是数组: ${patchFile}`);
343
+ if (hasDisable(root, targetId)) return false;
344
+ await copyFile(patchFile, `${patchFile}.lifeboat.bak`);
345
+ doc.add({
346
+ id: targetId,
347
+ disabled: true
348
+ });
349
+ await atomicWrite(patchFile, doc.toString());
350
+ return true;
283
351
  });
284
- const tmp = `${patchFile}.lifeboat.tmp`;
285
- await writeFile(tmp, doc.toString(), "utf-8");
286
- await rename(tmp, patchFile);
287
- return true;
288
- }
289
- /** 顶层条目中已禁用的 id 列表(不含 insert 子列表;用户层 disabled 语义只在顶层)。 */
290
- function listDisabled(entries) {
291
- const out = [];
292
- for (const entry of entries) if (typeof entry.id === "string" && entry.disabled === true) out.push(entry.id);
293
- return out;
294
352
  }
295
353
  /**
296
354
  * 从 patch 文件移除针对 targetId 的禁用覆盖(恢复插件);返回是否实际写入。
297
355
  * 只移除「id 定向且 disabled: true」的行,其余内容(注释经 yaml 文档保留、
298
356
  * 其他条目)原样不动;无该覆盖时幂等返回 false。
299
- * @throws 文件不可读/顶层不是数组/落盘失败——调用方负责告警。
357
+ * 原文件 YAML 已坏时不猜测改写,抛错指引人工处理(恢复操作有使用者在场)。
358
+ * @throws 文件不可读/顶层不是数组/YAML 语法错误/落盘失败——调用方负责告警。
300
359
  */
301
360
  async function removeDisable(patchFile, targetId) {
302
- const text = await readFile(patchFile, "utf-8");
303
- const doc = parseDocument(text);
304
- const root = doc.toJS();
305
- if (!Array.isArray(root)) throw new Error(`patch 文件顶层不是数组: ${patchFile}`);
306
- let removed = false;
307
- const items = doc.contents;
308
- if (items?.items !== void 0 && Array.isArray(items.items)) {
309
- const headComment = items.items[0]?.commentBefore;
310
- doc.contents.items = items.items.filter((item) => {
311
- const value = item.toJS?.(doc);
312
- if (value !== void 0 && typeof value === "object" && value.id === targetId && value.disabled === true) {
313
- removed = true;
314
- return false;
361
+ return withFileLock(patchFile, async () => {
362
+ const text = await readFile(patchFile, "utf-8");
363
+ const doc = parseDocument(text);
364
+ if (doc.errors.length > 0) throw new Error(`patch 文件存在 YAML 语法错误,请人工修复后重试: ${patchFile}`);
365
+ const root = doc.toJS();
366
+ if (!Array.isArray(root)) throw new Error(`patch 文件顶层不是数组: ${patchFile}`);
367
+ let removed = false;
368
+ const items = doc.contents;
369
+ if (items?.items !== void 0 && Array.isArray(items.items)) {
370
+ const headComment = items.items[0]?.commentBefore;
371
+ doc.contents.items = items.items.filter((item) => {
372
+ const value = item.toJS?.(doc);
373
+ if (value !== void 0 && typeof value === "object" && value.id === targetId && value.disabled === true) {
374
+ removed = true;
375
+ return false;
376
+ }
377
+ return true;
378
+ });
379
+ if (removed && headComment !== void 0 && doc.contents.items.length > 0) {
380
+ const next = doc.contents.items[0];
381
+ if (next.commentBefore === void 0) next.commentBefore = headComment;
315
382
  }
316
- return true;
317
- });
318
- if (removed && headComment !== void 0 && doc.contents.items.length > 0) {
319
- const next = doc.contents.items[0];
320
- if (next.commentBefore === void 0) next.commentBefore = headComment;
321
383
  }
322
- }
323
- if (!removed) return false;
324
- await copyFile(patchFile, `${patchFile}.lifeboat.bak`);
325
- const tmp = `${patchFile}.lifeboat.tmp`;
326
- await writeFile(tmp, doc.toString(), "utf-8");
327
- await rename(tmp, patchFile);
328
- return true;
384
+ if (!removed) return false;
385
+ await copyFile(patchFile, `${patchFile}.lifeboat.bak`);
386
+ await atomicWrite(patchFile, doc.toString());
387
+ return true;
388
+ });
329
389
  }
330
390
  //#endregion
331
391
  //#region src/quarantine.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-plus/lifeboat",
3
- "version": "0.1.7",
3
+ "version": "0.2.0",
4
4
  "description": "dsh-plus service plugin: 故障救生艇——兄弟插件崩溃时自动隔离(写用户 patch 层禁用),llm-pi 缺席时把其配置临时翻译为官方 llm-pi-ai 路由,恢复后自动还原",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
package/src/patch-file.ts CHANGED
@@ -3,6 +3,16 @@
3
3
  * 官方预留的逃生门:用户层支持 id 定向 disabled,覆盖 bundle 层 insert。
4
4
  * 写入纪律:先备份、幂等(已禁用跳过)、原子落盘(tmp + rename),失败抛错由调用方告警,
5
5
  * 绝不写半个文件、绝不改动既有条目内容。
6
+ *
7
+ * 2026-08-30 事故教训(保险丝必须先于负载可靠):
8
+ * 1. 并发写竞争:多个插件同一毫秒 FAILED → 多路 appendDisable 共享固定 tmp 名
9
+ * → rename ENOENT / 读改写丢更新。修复:进程内按文件串行化(promise 链锁)
10
+ * + tmp 名带 pid/随机后缀。
11
+ * 2. YAML 带错仍强行 stringify:parseDocument 对语法错误不抛而收集进
12
+ * doc.errors,后续 toString 抛 "Document with errors cannot be stringified"
13
+ * → 隔离永远写不进去。修复:写前校验 doc.errors;文件已坏时走重建通道
14
+ * (备份坏文件 → 容错打捞既有 disabled 条目 → 重写干净文档),
15
+ * 隔离落盘优先于保留坏文件。
6
16
  * @module lifeboat/patch-file
7
17
  */
8
18
  import { copyFile, readFile, rename, writeFile } from 'node:fs/promises'
@@ -26,24 +36,6 @@ export function hasDisable(entries: PatchEntry[], targetId: string): boolean {
26
36
  return false
27
37
  }
28
38
 
29
- /**
30
- * 向 patch 文件追加一条禁用覆盖;返回是否实际写入(已存在禁用则跳过)。
31
- * @throws 文件不可读/顶层不是数组/落盘失败——调用方负责告警。
32
- */
33
- export async function appendDisable(patchFile: string, targetId: string): Promise<boolean> {
34
- const text = await readFile(patchFile, 'utf-8')
35
- const doc = parseDocument(text)
36
- const root = doc.toJS() as unknown
37
- if (!Array.isArray(root)) throw new Error(`patch 文件顶层不是数组: ${patchFile}`)
38
- if (hasDisable(root as PatchEntry[], targetId)) return false
39
- await copyFile(patchFile, `${patchFile}.lifeboat.bak`)
40
- doc.add({ id: targetId, disabled: true })
41
- const tmp = `${patchFile}.lifeboat.tmp`
42
- await writeFile(tmp, doc.toString(), 'utf-8')
43
- await rename(tmp, patchFile)
44
- return true
45
- }
46
-
47
39
  /** 顶层条目中已禁用的 id 列表(不含 insert 子列表;用户层 disabled 语义只在顶层)。 */
48
40
  export function listDisabled(entries: PatchEntry[]): string[] {
49
41
  const out: string[] = []
@@ -53,47 +45,133 @@ export function listDisabled(entries: PatchEntry[]): string[] {
53
45
  return out
54
46
  }
55
47
 
48
+ /** 进程内按文件串行化:并发隔离写同一 patch 文件时消除读改写竞争。 */
49
+ const fileLocks = new Map<string, Promise<unknown>>()
50
+
51
+ function withFileLock<T>(file: string, fn: () => Promise<T>): Promise<T> {
52
+ const prev = fileLocks.get(file) ?? Promise.resolve()
53
+ const next = prev.then(fn, fn)
54
+ fileLocks.set(
55
+ file,
56
+ next.catch(() => {}),
57
+ )
58
+ return next
59
+ }
60
+
61
+ /** 唯一 tmp 名(并发/重入不留共享路径),rename 原子落盘。 */
62
+ async function atomicWrite(patchFile: string, content: string): Promise<void> {
63
+ const tmp = `${patchFile}.lifeboat.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`
64
+ await writeFile(tmp, content, 'utf-8')
65
+ await rename(tmp, patchFile)
66
+ }
67
+
68
+ /**
69
+ * 容错打捞坏 YAML 文本中既有的顶层 disabled 条目(best-effort):
70
+ * `- id: <name>` 与同条块内的 `disabled: true` 配对即认定。
71
+ * 坏文件里可能躺着此前已隔离的插件——重建时漏掉它们等于重新放行故障插件。
72
+ */
73
+ export function salvageDisabled(text: string): string[] {
74
+ const out: string[] = []
75
+ const blockRe = /-\s+id:\s*(\S+)([^\0]*?)(?=\n\s*-\s+id:|$)/g
76
+ for (const match of text.matchAll(blockRe)) {
77
+ const id = match[1]
78
+ const block = match[2] ?? ''
79
+ if (id !== undefined && /\bdisabled:\s*true\b/.test(block)) out.push(id)
80
+ }
81
+ return out
82
+ }
83
+
84
+ /**
85
+ * 重建通道:原文件 YAML 已坏(doc.errors 非空)时的隔离写入。
86
+ * 备份坏文件(保留现场)→ 打捞既有 disabled → 重写干净文档。
87
+ * 即使目标已在打捞集中也照样重写——坏文件对 loader 等于不存在,
88
+ * 修复文件本身与写入禁用同等重要;返回值仅报告目标集合是否变化。
89
+ */
90
+ async function appendDisableRebuild(
91
+ patchFile: string,
92
+ text: string,
93
+ targetId: string,
94
+ ): Promise<boolean> {
95
+ const salvaged = salvageDisabled(text)
96
+ const stamp = new Date().toISOString().replaceAll(/[:.]/g, '-')
97
+ await copyFile(patchFile, `${patchFile}.broken-${stamp}.bak`)
98
+ const ids = salvaged.includes(targetId) ? salvaged : [...salvaged, targetId]
99
+ const entries = ids.map((id) => `- id: ${id}\n disabled: true`)
100
+ const content = [
101
+ '# 本文件由 lifeboat 重建:原文件存在 YAML 语法错误,无法安全改写。',
102
+ `# 原件已备份为同目录 .broken-${stamp}.bak,请人工合并残留自定义条目。`,
103
+ ...entries,
104
+ '',
105
+ ].join('\n')
106
+ await atomicWrite(patchFile, content)
107
+ return !salvaged.includes(targetId)
108
+ }
109
+
110
+ /**
111
+ * 向 patch 文件追加一条禁用覆盖;返回是否实际写入(已存在禁用则跳过)。
112
+ * 原文件 YAML 已坏时转重建通道(隔离落盘优先,原件备份待人工合并)。
113
+ * @throws 文件不可读/顶层不是数组/落盘失败——调用方负责告警。
114
+ */
115
+ export async function appendDisable(patchFile: string, targetId: string): Promise<boolean> {
116
+ return withFileLock(patchFile, async () => {
117
+ const text = await readFile(patchFile, 'utf-8')
118
+ const doc = parseDocument(text)
119
+ if (doc.errors.length > 0) return appendDisableRebuild(patchFile, text, targetId)
120
+ const root = doc.toJS() as unknown
121
+ if (!Array.isArray(root)) throw new Error(`patch 文件顶层不是数组: ${patchFile}`)
122
+ if (hasDisable(root as PatchEntry[], targetId)) return false
123
+ await copyFile(patchFile, `${patchFile}.lifeboat.bak`)
124
+ doc.add({ id: targetId, disabled: true })
125
+ await atomicWrite(patchFile, doc.toString())
126
+ return true
127
+ })
128
+ }
129
+
56
130
  /**
57
131
  * 从 patch 文件移除针对 targetId 的禁用覆盖(恢复插件);返回是否实际写入。
58
132
  * 只移除「id 定向且 disabled: true」的行,其余内容(注释经 yaml 文档保留、
59
133
  * 其他条目)原样不动;无该覆盖时幂等返回 false。
60
- * @throws 文件不可读/顶层不是数组/落盘失败——调用方负责告警。
134
+ * 原文件 YAML 已坏时不猜测改写,抛错指引人工处理(恢复操作有使用者在场)。
135
+ * @throws 文件不可读/顶层不是数组/YAML 语法错误/落盘失败——调用方负责告警。
61
136
  */
62
137
  export async function removeDisable(patchFile: string, targetId: string): Promise<boolean> {
63
- const text = await readFile(patchFile, 'utf-8')
64
- const doc = parseDocument(text)
65
- const root = doc.toJS() as unknown
66
- if (!Array.isArray(root)) throw new Error(`patch 文件顶层不是数组: ${patchFile}`)
67
- let removed = false
68
- const items = doc.contents
69
- if (items?.items !== undefined && Array.isArray(items.items)) {
70
- // 头注释挂在首个条目的 commentBefore 上:被移除项若为首项,注释迁移给
71
- // 新的首项,避免整文件头注释丢失。
72
- const headComment = (items.items[0] as unknown as { commentBefore?: string })?.commentBefore
73
- doc.contents.items = items.items.filter((item) => {
74
- const value = (item as unknown as { toJS?(doc: unknown): unknown }).toJS?.(doc) as
75
- | PatchEntry
76
- | undefined
77
- if (
78
- value !== undefined &&
79
- typeof value === 'object' &&
80
- value.id === targetId &&
81
- value.disabled === true
82
- ) {
83
- removed = true
84
- return false
138
+ return withFileLock(patchFile, async () => {
139
+ const text = await readFile(patchFile, 'utf-8')
140
+ const doc = parseDocument(text)
141
+ if (doc.errors.length > 0) {
142
+ throw new Error(`patch 文件存在 YAML 语法错误,请人工修复后重试: ${patchFile}`)
143
+ }
144
+ const root = doc.toJS() as unknown
145
+ if (!Array.isArray(root)) throw new Error(`patch 文件顶层不是数组: ${patchFile}`)
146
+ let removed = false
147
+ const items = doc.contents
148
+ if (items?.items !== undefined && Array.isArray(items.items)) {
149
+ // 头注释挂在首个条目的 commentBefore 上:被移除项若为首项,注释迁移给
150
+ // 新的首项,避免整文件头注释丢失。
151
+ const headComment = (items.items[0] as unknown as { commentBefore?: string })?.commentBefore
152
+ doc.contents.items = items.items.filter((item) => {
153
+ const value = (item as unknown as { toJS?(doc: unknown): unknown }).toJS?.(doc) as
154
+ | PatchEntry
155
+ | undefined
156
+ if (
157
+ value !== undefined &&
158
+ typeof value === 'object' &&
159
+ value.id === targetId &&
160
+ value.disabled === true
161
+ ) {
162
+ removed = true
163
+ return false
164
+ }
165
+ return true
166
+ })
167
+ if (removed && headComment !== undefined && doc.contents.items.length > 0) {
168
+ const next = doc.contents.items[0] as unknown as { commentBefore?: string }
169
+ if (next.commentBefore === undefined) next.commentBefore = headComment
85
170
  }
86
- return true
87
- })
88
- if (removed && headComment !== undefined && doc.contents.items.length > 0) {
89
- const next = doc.contents.items[0] as unknown as { commentBefore?: string }
90
- if (next.commentBefore === undefined) next.commentBefore = headComment
91
171
  }
92
- }
93
- if (!removed) return false
94
- await copyFile(patchFile, `${patchFile}.lifeboat.bak`)
95
- const tmp = `${patchFile}.lifeboat.tmp`
96
- await writeFile(tmp, doc.toString(), 'utf-8')
97
- await rename(tmp, patchFile)
98
- return true
172
+ if (!removed) return false
173
+ await copyFile(patchFile, `${patchFile}.lifeboat.bak`)
174
+ await atomicWrite(patchFile, doc.toString())
175
+ return true
176
+ })
99
177
  }