dsh-compaction-weave 0.0.0-stage → 0.3.3

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 (92) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +136 -0
  4. package/README.md +139 -2
  5. package/cordis.patch.yml +19 -0
  6. package/docs/architecture.md +84 -0
  7. package/docs/benchmarks/published-0.3.2-rc.1-tests.json +576 -0
  8. package/docs/benchmarks/rc2-documentation.json +41 -0
  9. package/docs/benchmarks/rc2-linux-tests.json +590 -0
  10. package/docs/benchmarks/rc2-live-and-cost.json +746 -0
  11. package/docs/benchmarks/rc3-host-compatibility.json +2314 -0
  12. package/docs/benchmarks/rc4-tests.json +617 -0
  13. package/docs/benchmarks/review35-compression.json +117 -0
  14. package/docs/benchmarks/v0.3.2-live-four-way.json +3495 -0
  15. package/docs/benchmarks/v0.3.2-tests.json +590 -0
  16. package/docs/configuration.md +131 -0
  17. package/docs/development.md +88 -0
  18. package/docs/en/architecture.md +75 -0
  19. package/docs/en/configuration.md +131 -0
  20. package/docs/en/development.md +86 -0
  21. package/docs/en/feedback.md +47 -0
  22. package/docs/en/principles.md +235 -0
  23. package/docs/en/testing.md +368 -0
  24. package/docs/en/troubleshooting.md +59 -0
  25. package/docs/feedback.md +47 -0
  26. package/docs/images/principles-context.en.svg +77 -0
  27. package/docs/images/principles-context.zh.svg +77 -0
  28. package/docs/images/principles-pipeline.en.svg +93 -0
  29. package/docs/images/principles-pipeline.zh.svg +93 -0
  30. package/docs/images/principles-recovery.en.svg +46 -0
  31. package/docs/images/principles-recovery.zh.svg +46 -0
  32. package/docs/principles.md +235 -0
  33. package/docs/test-results.json +634 -0
  34. package/docs/testing.md +358 -0
  35. package/docs/troubleshooting.md +59 -0
  36. package/lib/abort.js +13 -0
  37. package/lib/action-state.js +60 -0
  38. package/lib/atomic-replace.js +18 -0
  39. package/lib/attachments.js +76 -0
  40. package/lib/audit-reject.js +161 -0
  41. package/lib/audit.js +939 -0
  42. package/lib/cache-policy.js +71 -0
  43. package/lib/client.js +696 -0
  44. package/lib/command-compact.js +38 -0
  45. package/lib/command-heartbeat.js +61 -0
  46. package/lib/config.js +596 -0
  47. package/lib/constraint-scope.js +37 -0
  48. package/lib/continuation-budget.js +69 -0
  49. package/lib/continuation-pending.js +57 -0
  50. package/lib/continuation-progress.js +46 -0
  51. package/lib/continuation.js +287 -0
  52. package/lib/engine-entry.js +103 -0
  53. package/lib/engine.js +2485 -0
  54. package/lib/failure-diagnostics.js +220 -0
  55. package/lib/history-source.js +74 -0
  56. package/lib/history.js +712 -0
  57. package/lib/idle-compaction.js +64 -0
  58. package/lib/index.js +611 -0
  59. package/lib/instruction-source.js +163 -0
  60. package/lib/journal.js +164 -0
  61. package/lib/manual-error.js +179 -0
  62. package/lib/memory-policy.js +383 -0
  63. package/lib/meter.js +387 -0
  64. package/lib/observation-mask.js +390 -0
  65. package/lib/proactive.js +108 -0
  66. package/lib/progress-facts.js +347 -0
  67. package/lib/progress-state.js +30 -0
  68. package/lib/prompt.js +194 -0
  69. package/lib/reconstruct.js +72 -0
  70. package/lib/reference-input.js +107 -0
  71. package/lib/region.js +972 -0
  72. package/lib/source-provenance.js +58 -0
  73. package/lib/source-recovery.js +22 -0
  74. package/lib/source-refs.js +137 -0
  75. package/lib/state.js +46 -0
  76. package/lib/storage-path.js +42 -0
  77. package/lib/summary-budget.js +187 -0
  78. package/lib/summary-config.js +308 -0
  79. package/lib/summary-progress.js +56 -0
  80. package/lib/summary-retry.js +27 -0
  81. package/lib/summary-timeout.js +68 -0
  82. package/lib/summary.js +476 -0
  83. package/lib/tools.js +341 -0
  84. package/lib/transaction-host.js +252 -0
  85. package/lib/transaction.js +285 -0
  86. package/lib/validate.js +503 -0
  87. package/lib/version.js +3 -0
  88. package/lib/window.js +120 -0
  89. package/lib/work-report.js +55 -0
  90. package/locale/en.json +6 -0
  91. package/locale/zh.json +6 -0
  92. package/package.json +71 -4
@@ -0,0 +1,163 @@
1
+ // Structural channel and explicit XML quotation boundary resolution.
2
+ // Trusts only host event provenance (`sourceKind` / `role`) and explicit XML
3
+ // containers (`<untrusted_reference>`, `<quoted_text>`, etc.) instead of
4
+ // guessing natural-language citation prose.
5
+
6
+ import { copySourceLayout } from './source-refs.js';
7
+ import { isReferenceContextKind } from './source-provenance.js';
8
+
9
+ const boundaries = new WeakMap();
10
+ const blocksOf = (message) => (message?.blocks?.length ? message.blocks : [{ text: message?.text ?? '' }]);
11
+
12
+ const REFERENCE_TAG_RE = /<(\/?)(untrusted[-_]?reference|quoted[-_]?text|untrusted[-_]?text|reference|blockquote)(?:\s(?:[^>"']|"[^"]*"|'[^']*')*)?>/gi;
13
+ const VERIFIED_TAG_RE = /<\/?verified[-_]?user[-_]?message(?:\s(?:[^>"']|"[^"]*"|'[^']*')*)?>/gi;
14
+
15
+ function textRanges(text) {
16
+ const value = String(text ?? '');
17
+ const excluded = [];
18
+ const stack = [];
19
+ for (const match of value.matchAll(REFERENCE_TAG_RE)) {
20
+ const start = match.index;
21
+ const end = start + match[0].length;
22
+ const tag = match[2].toLowerCase().replace(/-/g, '_');
23
+ const isClosing = match[1] === '/';
24
+ const isSelfClosing = !isClosing && match[0].endsWith('/>');
25
+ if (isSelfClosing) {
26
+ if (stack.length === 0 && end > start) excluded.push({ start, end, reference: true });
27
+ continue;
28
+ }
29
+ if (!isClosing) {
30
+ stack.push({ tag, start });
31
+ continue;
32
+ }
33
+ if (stack.length > 0 && stack.at(-1).tag === tag) {
34
+ const opened = stack.pop();
35
+ if (stack.length === 0 && end > opened.start) {
36
+ excluded.push({ start: opened.start, end, reference: true });
37
+ }
38
+ } else if (stack.length > 0) {
39
+ // Malformed nesting inside an open reference tag fails closed through end of message.
40
+ break;
41
+ } else if (end > start) {
42
+ excluded.push({ start, end, reference: true });
43
+ }
44
+ }
45
+ if (stack.length > 0 && value.length > stack[0].start) {
46
+ excluded.push({ start: stack[0].start, end: value.length, reference: true });
47
+ }
48
+ for (const match of value.matchAll(VERIFIED_TAG_RE)) {
49
+ const start = match.index;
50
+ const end = start + match[0].length;
51
+ if (end > start) excluded.push({ start, end, reference: true });
52
+ }
53
+
54
+ excluded.sort((a, b) => a.start - b.start || b.end - a.end);
55
+ const merged = [];
56
+ for (const item of excluded) {
57
+ const prev = merged.at(-1);
58
+ if (prev && item.start <= prev.end) {
59
+ prev.end = Math.max(prev.end, item.end);
60
+ } else {
61
+ merged.push({ ...item });
62
+ }
63
+ }
64
+
65
+ const result = [];
66
+ let cursor = 0;
67
+ for (const range of merged) {
68
+ if (range.start > cursor) result.push({ start: cursor, end: range.start, reference: false });
69
+ result.push(range);
70
+ cursor = range.end;
71
+ }
72
+ if (cursor < value.length) result.push({ start: cursor, end: value.length, reference: false });
73
+ return result;
74
+ }
75
+
76
+ export function instructionRanges(message) {
77
+ if (boundaries.has(message)) return boundaries.get(message);
78
+ const blocks = blocksOf(message).map((b) => String(b.text ?? ''));
79
+ if (isReferenceContextKind(message?.sourceKind) || message?.role === 'tool') {
80
+ const refOnly = blocks.map((text) => (text.length > 0 ? [{ start: 0, end: text.length, reference: true }] : []));
81
+ boundaries.set(message, refOnly);
82
+ return refOnly;
83
+ }
84
+ const ranges = textRanges(blocks.join('\n'));
85
+ let offset = 0;
86
+ const result = blocks.map((text) => {
87
+ const selected = ranges
88
+ .filter((r) => r.start < offset + text.length && r.end > offset)
89
+ .map((r) => ({
90
+ start: Math.max(0, r.start - offset),
91
+ end: Math.min(text.length, r.end - offset),
92
+ reference: r.reference,
93
+ }));
94
+ offset += text.length + 1;
95
+ return selected;
96
+ });
97
+ boundaries.set(message, result);
98
+ return result;
99
+ }
100
+
101
+ export function instructionText(message) {
102
+ const blocks = blocksOf(message);
103
+ const ranges = instructionRanges(message);
104
+ return blocks
105
+ .flatMap((block, index) =>
106
+ ranges[index].filter((r) => !r.reference).map((r) => String(block.text ?? '').slice(r.start, r.end)),
107
+ )
108
+ .join('\n');
109
+ }
110
+
111
+ export function instructionSlices(message) {
112
+ const blocks = blocksOf(message);
113
+ const ranges = instructionRanges(message);
114
+ let offset = 0;
115
+ return blocks.flatMap((block, index) => {
116
+ const text = String(block.text ?? '');
117
+ const result = ranges[index]
118
+ .filter((r) => !r.reference)
119
+ .map((r) => ({ text: text.slice(r.start, r.end), start: offset + r.start }));
120
+ offset += text.length + 1;
121
+ return result;
122
+ });
123
+ }
124
+
125
+ export function referenceTexts(message) {
126
+ const blocks = blocksOf(message);
127
+ const ranges = instructionRanges(message);
128
+ return blocks
129
+ .flatMap((block, index) =>
130
+ ranges[index].filter((r) => r.reference).map((r) => String(block.text ?? '').slice(r.start, r.end)),
131
+ )
132
+ .filter((text) => text.trim());
133
+ }
134
+
135
+ export function copyInstructionBoundaries(original, selected) {
136
+ boundaries.set(selected, instructionRanges(original));
137
+ return copySourceLayout(original, selected);
138
+ }
139
+
140
+ export function projectInstructionBoundaries(selected, original, layout) {
141
+ const source = instructionRanges(original);
142
+ const projected = layout.blocks.map((block) => {
143
+ let offset = 0;
144
+ const ranges = [];
145
+ for (const part of block.parts) {
146
+ if (typeof part.space === 'string') {
147
+ offset += part.space.length;
148
+ continue;
149
+ }
150
+ for (const range of source[part.block] ?? []) {
151
+ const start = Math.max(part.start, range.start);
152
+ const end = Math.min(part.end, range.end);
153
+ if (end > start) {
154
+ ranges.push({ start: offset + start - part.start, end: offset + end - part.start, reference: range.reference });
155
+ }
156
+ }
157
+ offset += part.end - part.start;
158
+ }
159
+ return ranges;
160
+ });
161
+ boundaries.set(selected, projected);
162
+ return selected;
163
+ }
package/lib/journal.js ADDED
@@ -0,0 +1,164 @@
1
+ import {atomicReplaceSync,atomicReplace} from './atomic-replace.js';
2
+ import { sessionDirectory } from './storage-path.js';
3
+ // 持久事务日志:插件保存成功决策;原装宿主未决替换保留并阻断。
4
+ // started/committing 等阶段是未决事务,committed 是已持久成功决策。
5
+ // 清理失败不能抹掉决策,也不能把已成功事务误回滚;坏记录保留并阻断继续。
6
+
7
+ import { mkdir, readFile, readdir, rm, writeFile, open } from 'node:fs/promises';
8
+ import { mkdirSync, openSync, writeFileSync, fsyncSync, closeSync, unlinkSync } from 'node:fs';
9
+ import { dirname, join, resolve } from 'node:path';
10
+
11
+ const JOURNAL_DIR_NAME = 'journal';
12
+
13
+ function safeSegment(value) {
14
+ return String(value ?? 'unknown').replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120);
15
+ }
16
+
17
+ /**
18
+ * 压缩事务日志。
19
+ *
20
+ * started 记录首次发布边界;committing 保存原节点/投影快照及失败计数。
21
+ * replaced/closing 记录中间阶段;committed 只做清理,不再撤销成功结果。
22
+ */
23
+ export class CompactionJournal {
24
+ /** @param {{ root?: string|null }} [options] */
25
+ constructor(options = {}) {
26
+ this.root = options.root
27
+ ? resolve(options.root)
28
+ : join(process.cwd(), JOURNAL_DIR_NAME);
29
+ }
30
+
31
+ /** 由归档根目录推出日志根目录(两者共用 DSH_HOME 下的同一个 storage 目录)。 */
32
+ static alongside(archiveRoot) {
33
+ if (typeof archiveRoot !== 'string' || archiveRoot.length === 0) return new CompactionJournal({});
34
+ return new CompactionJournal({ root: join(dirname(archiveRoot), JOURNAL_DIR_NAME) });
35
+ }
36
+
37
+ dirFor(sessionId) {
38
+ return sessionDirectory(this.root, sessionId, 'journal');
39
+ }
40
+
41
+ fileFor(sessionId, compactionId) {
42
+ return join(this.dirFor(sessionId), `${safeSegment(compactionId)}.json`);
43
+ }
44
+
45
+ /**
46
+ * 记一笔"我要做/我正在做"。
47
+ *
48
+ * ⚠️ 写失败**必须抛**。日志写不进去时继续往下做,就等于放弃跨进程恢复:
49
+ * 崩溃之后没人知道这次压缩做到哪一步了。宁可这次不压,也不能留一个
50
+ * 谁也说不清的半成品事务。
51
+ *
52
+ * @param {{ sessionId: string, compactionId: string, phase: string, startSeq?: number, endSeq?: number, note?: string }} record
53
+ * @returns {Promise<string>} 日志文件路径
54
+ */
55
+ async record({ sessionId, compactionId, phase, startSeq, endSeq, note, snapshot, startEventSeq, failuresBefore, failureKind, atomic }) {
56
+ const dir = this.dirFor(sessionId);
57
+ await mkdir(dir, { recursive: true });
58
+ const file = this.fileFor(sessionId, compactionId);
59
+ const payload = {
60
+ kind: 'compaction-weave/journal',
61
+ version: 1,
62
+ sessionId,
63
+ compactionId,
64
+ phase,
65
+ ...(failuresBefore === undefined ? {} : { failuresBefore }),
66
+ ...(failureKind === undefined ? {} : { failureKind }),
67
+ ...(atomic === undefined ? {} : { atomic }),
68
+ ...(startEventSeq === undefined ? {} : { startEventSeq }),
69
+ ...(startSeq === undefined ? {} : { startSeq }),
70
+ ...(endSeq === undefined ? {} : { endSeq }),
71
+ ...(note === undefined ? {} : { note }),
72
+ ...(snapshot === undefined ? {} : { snapshot }),
73
+ at: new Date().toISOString(),
74
+ };
75
+ const temp = `${file}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
76
+ let handle;
77
+ try {
78
+ handle = await open(temp, 'wx'); await handle.writeFile(`${JSON.stringify(payload)}\n`, 'utf8');
79
+ await handle.sync(); await handle.close(); handle = null; await atomicReplace(temp, file);
80
+ } finally { if (handle) await handle.close().catch(() => {}); await rm(temp, { force: true }).catch(() => {}); }
81
+ return file;
82
+ }
83
+
84
+ // The short stock-host commit section must not yield between the durable
85
+ // decision and publication. The record has the same schema as record().
86
+ recordSync(record) {
87
+ const { file: ignored, corrupt: ignoredCorrupt, ...data } = record;
88
+ const file = this.fileFor(data.sessionId, data.compactionId);
89
+ mkdirSync(dirname(file), { recursive: true });
90
+ const temp = `${file}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
91
+ let fd;
92
+ try {
93
+ fd = openSync(temp, 'wx');
94
+ writeFileSync(fd, JSON.stringify({ ...data, kind: 'compaction-weave/journal', version: 1, at: new Date().toISOString() }) + '\n');
95
+ fsyncSync(fd); closeSync(fd); fd = undefined; atomicReplaceSync(temp, file);
96
+ } finally {
97
+ if (fd !== undefined) closeSync(fd);
98
+ try { unlinkSync(temp); } catch {}
99
+ }
100
+ return file;
101
+ }
102
+
103
+ /** 事务正常收尾后清掉痕迹。清失败不算致命 —— 下次启动最多多做一次幂等收尾。 */
104
+ async clear(sessionId, compactionId) {
105
+ try {
106
+ const file = this.fileFor(sessionId, compactionId);
107
+ await rm(file, { force: true });
108
+ // Once the journal is gone, no recovery can need these transaction files.
109
+ await rm(file + '.rollback', { force: true }).catch(() => {});
110
+ await rm(file + '.tail', { force: true }).catch(() => {});
111
+ return true;
112
+ } catch {
113
+ return false;
114
+ }
115
+ }
116
+
117
+ /**
118
+ * 列出某会话所有**没走完**的事务。
119
+ * 目录不存在 = 没有未完成事务(这是正常情况,不是错误)。
120
+ *
121
+ * @param {string} sessionId
122
+ * @returns {Promise<{compactionId: string, phase: string, startSeq?: number, endSeq?: number, at?: string, file: string, corrupt?: boolean}[]>}
123
+ */
124
+ async pending(sessionId) {
125
+ const dir = this.dirFor(sessionId);
126
+ let names;
127
+ try {
128
+ names = await readdir(dir);
129
+ } catch (error) {
130
+ if (error?.code === 'ENOENT') return [];
131
+ throw error;
132
+ }
133
+ const out = [];
134
+ for (const name of names) {
135
+ if (!name.endsWith('.json')) continue;
136
+ const file = join(dir, name);
137
+ const compactionId = name.slice(0, -'.json'.length);
138
+ try {
139
+ const raw = await readFile(file, 'utf8');
140
+ const record = JSON.parse(raw);
141
+ if (!record || record.kind !== 'compaction-weave/journal' || record.version !== 1 || record.sessionId !== sessionId || record.compactionId !== compactionId || (record.failureKind !== undefined && !['failed', 'cancelled', 'interrupted'].includes(record.failureKind)) || !['started', 'committing', 'replaced', 'closing', 'committed'].includes(record.phase)) {
142
+ out.push({ compactionId, phase: 'unknown', file, corrupt: true });
143
+ continue;
144
+ }
145
+ out.push({
146
+ compactionId: typeof record.compactionId === 'string' ? record.compactionId : compactionId,
147
+ phase: typeof record.phase === 'string' ? record.phase : 'unknown',
148
+ ...(record.failuresBefore === undefined ? {} : { failuresBefore: record.failuresBefore }),
149
+ ...(record.failureKind === undefined ? {} : { failureKind: record.failureKind }),
150
+ ...(record.atomic === undefined ? {} : { atomic: record.atomic }),
151
+ ...(record.startEventSeq === undefined ? {} : { startEventSeq: record.startEventSeq }),
152
+ ...(record.startSeq === undefined ? {} : { startSeq: record.startSeq }),
153
+ ...(record.endSeq === undefined ? {} : { endSeq: record.endSeq }),
154
+ ...(record.at === undefined ? {} : { at: record.at }),
155
+ ...(record.snapshot === undefined ? {} : { snapshot: record.snapshot }),
156
+ file,
157
+ });
158
+ } catch {
159
+ out.push({ compactionId, phase: 'unknown', file, corrupt: true });
160
+ }
161
+ }
162
+ return out;
163
+ }
164
+ }
@@ -0,0 +1,179 @@
1
+ // 手动 `/compact` 的错误协议。
2
+ //
3
+ // 宿主的 `dsh-command-compact` 只把 `ManualCompactionError` 翻译成人话,
4
+ // 其它任何 Error 都**原样 rethrow**(`dsh-command-compact/lib/index.js:65-72`):
5
+ //
6
+ // } catch (error) {
7
+ // if (invocation.signal.aborted) return { kind: 'error', text: 'Compaction cancelled.' };
8
+ // if (error instanceof ManualCompactionError) return expectedFailure(error);
9
+ // throw error;
10
+ // }
11
+ //
12
+ // 也就是说:抛普通 Error 不会变成"用户看到一句解释",而是变成命令层的未处理
13
+ // 异常。所以引擎在手动路径上抛出的每一个失败,都必须是**宿主那个类的实例**。
14
+ //
15
+ // ⚠️ 光"长得一样"没用。`instanceof` 只认同一个类对象,自己在本文件里再声明一个
16
+ // 同名同码的类,`error instanceof HostClass` 依然是 `false`,仍然会 rethrow。
17
+ // 唯一可靠的做法是拿到宿主模块导出的那个构造函数本身。
18
+ //
19
+ // 插件自己 `import('@deepseek-ai/dsh-compaction')` 解析不到(插件目录与 profile
20
+ // 目录都没有可用的 `node_modules`)。但宿主进程里有个现成的加载器:`ctx.loader`
21
+ // 由 `cordis-plugin-loader` 在启动时 `provide('loader', this)`,它的
22
+ // `import(name, getOuterStack)` 是以**加载器自身位置**为基准解析裸导入的
23
+ // (`cordis-plugin-loader/lib/index.js:214-228`),而那个位置就在宿主自己的
24
+ // `node_modules` 里 —— 宿主的 `dsh-command-compact` 正是这么拿到这个类的。
25
+ //
26
+ // 取不到时退回同形实现:至少 `code` 落在 `expectedFailure` 的六个分支内,
27
+ // 任何按 `code` 分类的消费方仍能读懂;只是 `instanceof` 这条路过不去。
28
+
29
+ /** 官方 `ManualCompactionErrorCode` 的封闭取值(`expectedFailure` 的六个分支)。 */
30
+ export const MANUAL_CODES = Object.freeze([
31
+ 'busy',
32
+ 'cancelled',
33
+ 'changed',
34
+ 'summary',
35
+ 'commit',
36
+ 'persistence',
37
+ ]);
38
+
39
+ /** 同形实现。字段顺序与官方一致:`code` 先声明,`name` 用类字段覆盖。 */
40
+ export class ManualCompactionError extends Error {
41
+ code;
42
+
43
+ name = 'ManualCompactionError';
44
+
45
+ constructor(code, message, options) {
46
+ super(message, options);
47
+ this.code = code;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * 通过宿主加载器取回**真正的** `ManualCompactionError` 构造函数。
53
+ *
54
+ * 全程 best-effort:任何一步不成立(没有 loader、加载器拒绝、导出表里没有这个
55
+ * 名字)都返回 `null`,由调用方退回同形实现。绝不因为拿不到类而让插件加载失败。
56
+ *
57
+ * @param {object} ctx
58
+ * @returns {Promise<Function|null>}
59
+ */
60
+ export async function loadHostManualErrorClass(ctx) {
61
+ const loader = typeof ctx?.get === 'function' ? ctx.get('loader') : undefined;
62
+ if (!loader || typeof loader.import !== 'function') return null;
63
+ try {
64
+ // 第二个参数是出错时取外层调用栈的回调,只在异常路径上被调用。
65
+ const mod = await loader.import('@deepseek-ai/dsh-compaction', () => '');
66
+ const ctor = mod?.ManualCompactionError;
67
+ return typeof ctor === 'function' ? ctor : null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ /** ctx → Promise<类|null>。每个 realm 只解析一次,失败也记住,避免每次失败都重试。 */
74
+ const HOST_CLASS_CACHE = new WeakMap();
75
+
76
+ /**
77
+ * 惰性取宿主类(带缓存)。
78
+ *
79
+ * 放在**抛错那一刻**才解析,而不是插件启动时:拿不到类不影响插件加载,
80
+ * 而失败路径本来就罕见,多一次 await 不构成性能问题。反过来,启动期解析一旦
81
+ * 遇到加载器尚未就绪,就会永久记住 `null`,手动命令的错误协议就再也修不回来。
82
+ */
83
+ export function hostManualErrorClass(ctx) {
84
+ if (!ctx || typeof ctx !== 'object') return Promise.resolve(null);
85
+ let pending = HOST_CLASS_CACHE.get(ctx);
86
+ if (pending === undefined) {
87
+ pending = loadHostManualErrorClass(ctx);
88
+ HOST_CLASS_CACHE.set(ctx, pending);
89
+ }
90
+ return pending;
91
+ }
92
+
93
+ export function isManualCompactionError(error) {
94
+ return Boolean(error) && error.name === 'ManualCompactionError' && MANUAL_CODES.includes(error.code);
95
+ }
96
+
97
+ /**
98
+ * 把引擎内部的细分错误码映射到官方六个码。
99
+ *
100
+ * 内部码比官方多(`SPAN_CHANGED`、`SUMMARY_NOT_SMALLER`、`SUMMARY_TIMEOUT`…),
101
+ * 直接抛出去会让 `expectedFailure` 的 `assertNever` 抛
102
+ * `TypeError: unknown manual compaction error code` —— 比原来的普通 Error 更糟。
103
+ */
104
+ export function toManualCode(code, stage) {
105
+ switch (code) {
106
+ case 'busy':
107
+ return 'busy';
108
+ case 'cancelled':
109
+ case 'ABORTED':
110
+ return 'cancelled';
111
+ case 'changed':
112
+ case 'SPAN_CHANGED':
113
+ return 'changed';
114
+ case 'commit':
115
+ return 'commit';
116
+ case 'persistence':
117
+ return 'persistence';
118
+ case 'summary':
119
+ case 'SUMMARY_NOT_SMALLER':
120
+ case 'SUMMARY_TIMEOUT':
121
+ case 'SUMMARY_ALL_FAILED':
122
+ case 'NO_SUMMARY_TARGET':
123
+ case 'MAX_TOKENS':
124
+ case 'UNSUPPORTED_CONTENT':
125
+ case 'CONTEXT_WINDOW_EXCEEDED':
126
+ // 归档失败发生在提交之前,但它的后果属于"摘要没能变成可用的替代品",
127
+ // 归到 `summary` 比 `commit` 更贴切:surface 一个字节都没动。
128
+ case 'ARCHIVE_FAILED':
129
+ // 约束审计拦下的三类同理 —— 都是"这份摘要不能用",surface 没动过。
130
+ // 真正的细分原因在 `cause` 里,用户从 `/compact` 的输出看不到码,
131
+ // 但日志和 `error.cause.code` 都保留着。
132
+ case 'CONSTRAINT_LOST':
133
+ case 'CONSTRAINT_POLARITY_LOST':
134
+ case 'AUDIT_UNAVAILABLE':
135
+ return 'summary';
136
+ default:
137
+ // 未知码按阶段归类:已经进到提交段 = commit,否则 = summary。
138
+ return stage === 'commit' ? 'commit' : 'summary';
139
+ }
140
+ }
141
+
142
+ /**
143
+ * 把手动压缩路径上的任意失败收敛成官方形状。
144
+ *
145
+ * 用一个统一出口而不是在每个 throw 点各写一遍:手动压缩要穿过
146
+ * `compactNow → _compactManual → _compactRegionCore → _compactSpan` 四层,
147
+ * 中间任何一层新增一个 throw,逐点改造时都会漏。
148
+ *
149
+ * 已经是正确形状的(比如别处抛进来的 ManualCompactionError)原样返回,
150
+ * 这样重试/递归路径上的错误不会被二次包装。
151
+ */
152
+ export function asManualError(error, stage) {
153
+ if (isManualCompactionError(error)) return error;
154
+ const code = toManualCode(error?.code, stage ?? error?.compactionStage);
155
+ const message = error?.message ?? String(error);
156
+ return new ManualCompactionError(code, message, { cause: error });
157
+ }
158
+
159
+ /**
160
+ * 优先产出**宿主类**的实例(这才是 `instanceof` 认的那个)。
161
+ *
162
+ * 取不到宿主类时退回 `asManualError` 的同形实现:`instanceof` 过不去,但
163
+ * `code` 仍落在官方六码内,比普通 Error 强。
164
+ *
165
+ * @param {object} ctx
166
+ * @param {unknown} error
167
+ * @param {string} [stage]
168
+ */
169
+ export async function asHostManualError(ctx, error, stage) {
170
+ const Host = await hostManualErrorClass(ctx);
171
+ if (!Host) return asManualError(error, stage);
172
+ // 已经是宿主实例:原样返回,避免重试/递归路径上二次包装。
173
+ if (error instanceof Host) return error;
174
+ const code = isManualCompactionError(error)
175
+ ? error.code
176
+ : toManualCode(error?.code, stage ?? error?.compactionStage);
177
+ const message = error?.message ?? String(error);
178
+ return new Host(code, message, { cause: error });
179
+ }