@asd2233996/dsh-auto-context 0.0.0-stage → 1.15.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/LICENSE +21 -0
- package/README.en.md +113 -0
- package/README.md +250 -2
- package/cordis.patch.yml +23 -0
- package/docs/product-introduction.md +282 -0
- package/docs/structured-kb-notes.md +179 -0
- package/lib/actions.js +2758 -0
- package/lib/extract.js +1647 -0
- package/lib/graph.js +1628 -0
- package/lib/groups.js +307 -0
- package/lib/impl.js +170 -0
- package/lib/index.js +43 -0
- package/lib/kb-tools.js +384 -0
- package/lib/kb.js +254 -0
- package/lib/kg-archive.js +1042 -0
- package/lib/kg-store.js +1427 -0
- package/lib/recall.js +62 -0
- package/lib/scan.js +2537 -0
- package/lib/segments.js +660 -0
- package/lib/store.js +365 -0
- package/lib/util.js +64 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +87 -4
package/lib/scan.js
ADDED
|
@@ -0,0 +1,2537 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* context-manager — 一次性 AI 分析模块。
|
|
3
|
+
*
|
|
4
|
+
* 职责只有一件事:对「即将发给云端的对话历史」切出来的卡片做一次批量分类,
|
|
5
|
+
* 给每张卡片生成 分类(category)/ 短标题(title)/ 简介(summary),
|
|
6
|
+
* 供后台自动精简按重要度丢弃过时卡片(本插件没有用户界面)。
|
|
7
|
+
*
|
|
8
|
+
* 设计要点:
|
|
9
|
+
*
|
|
10
|
+
* 1. **纯函数优先**:哈希、归一化、分批、prompt、解析、兜底全部是不碰 IO 的
|
|
11
|
+
* 纯函数;唯一的副作用是主入口 `scanCards` 通过参数注入的 `llm.stream`
|
|
12
|
+
* 发请求。模块绝不访问 Cordis 的 `ctx`,因此可以在 `node --test` 里用假
|
|
13
|
+
* llm 完整覆盖,宿主 lib/impl.js 只负责把真实的 `ctx.llm` 传进来。
|
|
14
|
+
*
|
|
15
|
+
* 2. **绝不拖垮宿主**:单批超时/模型报错/输出坏 JSON 只记 `lastError` 并让
|
|
16
|
+
* 该批卡片走确定性兜底(`fallbackAnalysis`),整次扫描永远 resolve;
|
|
17
|
+
* 唯一的例外是调用方主动 abort——那种情况按约定抛出取消错误,让上层能
|
|
18
|
+
* 区分「用户取消」与「分析失败」。
|
|
19
|
+
*
|
|
20
|
+
* 3. **省钱**:`cardHash` 是内容指纹,调用方持久化的 cache 命中(hash 相同)
|
|
21
|
+
* 就直接复用,不再花钱请求;一次扫描最多处理 `maxCardsPerPass` 张卡片。
|
|
22
|
+
*
|
|
23
|
+
* 4. **防御式解析**:模型输出经常带 ```json 围栏、前后解释文字、对象包装、
|
|
24
|
+
* 字段名大小写差异,甚至有超长/空字段;解析器逐层降级,永远返回结构化
|
|
25
|
+
* 结果而不是抛错。
|
|
26
|
+
*
|
|
27
|
+
* 独立测试:`node --test tests/scan.test.mjs`。
|
|
28
|
+
* @module context-manager/scan
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { createHash } from 'node:crypto'
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 分类词表:`id` 是稳定机器码(写进缓存与解析结果),`label` 是中文展示名
|
|
35
|
+
* (prompt 里给模型看,日志/工具输出里给 AI 与人类读)。`noise` 明确表示
|
|
36
|
+
* 「闲聊/废话」,是自动精简优先丢弃的一类。
|
|
37
|
+
*/
|
|
38
|
+
export const CATEGORIES = [
|
|
39
|
+
{ id: 'goal', label: '需求与目标' },
|
|
40
|
+
{ id: 'decision', label: '决策与约束' },
|
|
41
|
+
{ id: 'code', label: '代码修改' },
|
|
42
|
+
{ id: 'tooling', label: '工具过程' },
|
|
43
|
+
{ id: 'research', label: '探索与调研' },
|
|
44
|
+
{ id: 'error', label: '错误与修复' },
|
|
45
|
+
{ id: 'verify', label: '验证与测试' },
|
|
46
|
+
{ id: 'noise', label: '闲聊与废话' },
|
|
47
|
+
{ id: 'other', label: '其他' },
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
/** 出现的顺序也是 prompt 里给模型列举的顺序,保持稳定。 */
|
|
51
|
+
const CATEGORY_IDS = CATEGORIES.map(category => category.id)
|
|
52
|
+
|
|
53
|
+
/** 合法分类 id 集合(解析时 O(1) 校验)。 */
|
|
54
|
+
const CATEGORY_ID_SET = new Set(CATEGORY_IDS)
|
|
55
|
+
|
|
56
|
+
/** id → 中文展示名。 */
|
|
57
|
+
const CATEGORY_LABEL_BY_ID = new Map(CATEGORIES.map(category => [category.id, category.label]))
|
|
58
|
+
|
|
59
|
+
/** 中文展示名 → id(模型偶尔会输出中文分类名,尽量接住)。 */
|
|
60
|
+
const CATEGORY_ID_BY_LABEL = new Map(CATEGORIES.map(category => [category.label, category.id]))
|
|
61
|
+
|
|
62
|
+
/** 兜底分类的常见英文同义写法(模型不按词表输出时的降级映射)。 */
|
|
63
|
+
const CATEGORY_ALIASES = new Map([
|
|
64
|
+
['codechange', 'code'],
|
|
65
|
+
['codechanges', 'code'],
|
|
66
|
+
['coding', 'code'],
|
|
67
|
+
['refactor', 'code'],
|
|
68
|
+
['tool', 'tooling'],
|
|
69
|
+
['tools', 'tooling'],
|
|
70
|
+
['tooluse', 'tooling'],
|
|
71
|
+
['toolcall', 'tooling'],
|
|
72
|
+
['bug', 'error'],
|
|
73
|
+
['bugs', 'error'],
|
|
74
|
+
['bugfix', 'error'],
|
|
75
|
+
['fix', 'error'],
|
|
76
|
+
['errorfix', 'error'],
|
|
77
|
+
['test', 'verify'],
|
|
78
|
+
['tests', 'verify'],
|
|
79
|
+
['testing', 'verify'],
|
|
80
|
+
['verification', 'verify'],
|
|
81
|
+
['explore', 'research'],
|
|
82
|
+
['exploration', 'research'],
|
|
83
|
+
['requirement', 'goal'],
|
|
84
|
+
['requirements', 'goal'],
|
|
85
|
+
['objective', 'goal'],
|
|
86
|
+
['chat', 'noise'],
|
|
87
|
+
['chitchat', 'noise'],
|
|
88
|
+
])
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 默认扫描配置。宿主可以只覆盖其中几项;`scanCards` 内部会把缺省项补齐,
|
|
92
|
+
* 并对非法值(负数/NaN/字符串等)退回默认值。
|
|
93
|
+
*/
|
|
94
|
+
export const DEFAULT_SCAN_CONFIG = {
|
|
95
|
+
batchSize: 20, // 每批卡片数
|
|
96
|
+
maxTokens: 1600, // 单批模型输出上限
|
|
97
|
+
previewChars: 700, // 每张卡片送进 prompt 的预览字符数上限
|
|
98
|
+
temperature: 0.2,
|
|
99
|
+
timeoutMs: 90_000, // 单批超时
|
|
100
|
+
maxConcurrentBatches: 1, // 默认串行:同一 session 的网关通常只允许单并发流
|
|
101
|
+
maxCardsPerPass: 400, // 单次扫描最多处理的卡片数(防止超大会话一次烧太多)
|
|
102
|
+
retries: 2, // 每批失败后的重试次数(不含首次尝试)
|
|
103
|
+
retryDelayMs: 1500, // 重试退避基数:第 n 次重试前等待 retryDelayMs * 2^(n-1)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* importance 词表:这张卡片值不值得长期保留。
|
|
108
|
+
* - `important`:项目结构 / 关键约束 / 关键决策 / 用户需求 / 交付结论,必须长期保留;
|
|
109
|
+
* - `keep`:一般实现过程 / 工具输出 / 探索记录,可以保留;
|
|
110
|
+
* - `noisy`:**仅限**时间戳、系统提醒、重复确认、纯闲聊等无用的元信息。
|
|
111
|
+
*
|
|
112
|
+
* 产品硬规则:用户提出的请求 / 需求 / 反馈,以及最新一轮的卡片,绝不能标 `noisy`
|
|
113
|
+
*(宁可标 `keep`);绝不能把「用户当前想做什么」当成可以被丢弃的噪音。
|
|
114
|
+
*/
|
|
115
|
+
export const IMPORTANCES = [
|
|
116
|
+
{ id: 'important', label: '必须保留' },
|
|
117
|
+
{ id: 'keep', label: '一般过程' },
|
|
118
|
+
{ id: 'noisy', label: '建议丢弃' },
|
|
119
|
+
]
|
|
120
|
+
|
|
121
|
+
/** 合法 importance id 集合。 */
|
|
122
|
+
const IMPORTANCE_ID_SET = new Set(IMPORTANCES.map(importance => importance.id))
|
|
123
|
+
|
|
124
|
+
/** 中文展示名 → id(模型偶尔直接用中文说明,尽量接住)。 */
|
|
125
|
+
const IMPORTANCE_ID_BY_LABEL = new Map(IMPORTANCES.map(importance => [importance.label, importance.id]))
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* importanceKind 词表:重要度的「种类」,让用户一眼看出这张卡为什么重要/为什么可精简。
|
|
129
|
+
* 顺序与宿主 lib/actions.js 的 IMPORTANCE_KINDS、client 的 i18n 词表保持一致;
|
|
130
|
+
* 前 5 类是「重要种类」,按硬规则必须 important。
|
|
131
|
+
*/
|
|
132
|
+
export const IMPORTANCE_KINDS = [
|
|
133
|
+
{ id: 'directive', label: '整体指示' },
|
|
134
|
+
{ id: 'constraint', label: '关键约束' },
|
|
135
|
+
{ id: 'architecture', label: '项目结构' },
|
|
136
|
+
{ id: 'decision', label: '关键决策' },
|
|
137
|
+
{ id: 'deliverable', label: '交付结论' },
|
|
138
|
+
{ id: 'feedback', label: '用户需求/反馈' },
|
|
139
|
+
{ id: 'process', label: '实现过程' },
|
|
140
|
+
{ id: 'tool', label: '工具输出' },
|
|
141
|
+
{ id: 'noise', label: '无用信息' },
|
|
142
|
+
]
|
|
143
|
+
|
|
144
|
+
/** 合法 importanceKind id 集合。 */
|
|
145
|
+
const IMPORTANCE_KIND_SET = new Set(IMPORTANCE_KINDS.map(kind => kind.id))
|
|
146
|
+
|
|
147
|
+
/** 必须 important 的种类(directive/constraint/architecture/decision/deliverable)。 */
|
|
148
|
+
const IMPORTANT_KINDS = new Set(['directive', 'constraint', 'architecture', 'decision', 'deliverable'])
|
|
149
|
+
|
|
150
|
+
/** 中文展示名 → id(模型偶尔直接输出中文标签,尽量接住)。 */
|
|
151
|
+
const IMPORTANCE_KIND_ID_BY_LABEL = new Map(IMPORTANCE_KINDS.map(kind => [kind.label, kind.id]))
|
|
152
|
+
IMPORTANCE_KIND_ID_BY_LABEL.set('用户需求', 'feedback')
|
|
153
|
+
IMPORTANCE_KIND_ID_BY_LABEL.set('用户反馈', 'feedback')
|
|
154
|
+
IMPORTANCE_KIND_ID_BY_LABEL.set('噪音', 'noise')
|
|
155
|
+
|
|
156
|
+
/** importanceReason 的字符上限(模型输出与兜底都按这个收紧)。 */
|
|
157
|
+
const IMPORTANCE_REASON_MAX_CHARS = 24
|
|
158
|
+
|
|
159
|
+
/** 缺省/兜底 reason:AI 只给了 kind、没给理由时用它补齐(≤24 字)。 */
|
|
160
|
+
const KIND_REASON = {
|
|
161
|
+
directive: '用户对整个项目的初始指示',
|
|
162
|
+
constraint: '关键约束/规则',
|
|
163
|
+
architecture: '项目结构/架构信息',
|
|
164
|
+
decision: '关键决策/方案取舍',
|
|
165
|
+
deliverable: '交付结论/验收结果',
|
|
166
|
+
feedback: '用户需求或反馈',
|
|
167
|
+
process: '实现过程,可精简',
|
|
168
|
+
tool: '工具输出,可精简',
|
|
169
|
+
noise: '时间戳/系统提醒,无业务信息',
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 兜底 importance 的常见同义写法(模型不按词表输出时的降级映射)。 */
|
|
173
|
+
const IMPORTANCE_ALIASES = new Map([
|
|
174
|
+
['high', 'important'],
|
|
175
|
+
['must', 'important'],
|
|
176
|
+
['critical', 'important'],
|
|
177
|
+
['required', 'important'],
|
|
178
|
+
['essential', 'important'],
|
|
179
|
+
['normal', 'keep'],
|
|
180
|
+
['medium', 'keep'],
|
|
181
|
+
['default', 'keep'],
|
|
182
|
+
['low', 'noisy'],
|
|
183
|
+
['noise', 'noisy'],
|
|
184
|
+
['discard', 'noisy'],
|
|
185
|
+
['drop', 'noisy'],
|
|
186
|
+
['skip', 'noisy'],
|
|
187
|
+
['trivial', 'noisy'],
|
|
188
|
+
])
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
/** 模型输出里 title 的字符上限(按 code point)。 */
|
|
192
|
+
const TITLE_MAX_CHARS = 14
|
|
193
|
+
|
|
194
|
+
/** 模型输出里 summary 的字符上限(按 code point)。 */
|
|
195
|
+
const SUMMARY_MAX_CHARS = 48
|
|
196
|
+
|
|
197
|
+
/** `cardHash` 返回的 16 进制前缀长度(64 bit,缓存指纹足够)。 */
|
|
198
|
+
const HASH_HEX_CHARS = 16
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Prompt / 分析语义的版本常量。
|
|
202
|
+
*
|
|
203
|
+
* 只要它变化,`cardHash` 前缀随之变化,旧 analysis 缓存一次性失效并重新分析;
|
|
204
|
+
* 之后同一版本内保持稳定命中。**不要把 prompt 文案本身塞进哈希**——文案微调不应
|
|
205
|
+
* 导致全量重新分析,只有语义变了(v12 新增 importanceKind/importanceReason)才升版本。
|
|
206
|
+
*/
|
|
207
|
+
export const PROMPT_VERSION = 'v4.1'
|
|
208
|
+
|
|
209
|
+
/** 哈希命名空间:包含 PROMPT_VERSION,版本升级即令旧缓存自然失效(v4 → v4.1)。 */
|
|
210
|
+
const HASH_NAMESPACE = `context-manager/scan/${PROMPT_VERSION}`
|
|
211
|
+
|
|
212
|
+
/** 预览被截断时的显式标记(prompt 里让模型知道内容不完整)。 */
|
|
213
|
+
const TRUNCATED_MARK = '…(已截断)'
|
|
214
|
+
|
|
215
|
+
/** 归一化后工具名列表最多保留几个(prompt 展示用)。 */
|
|
216
|
+
const TOOL_NAME_LIMIT = 10
|
|
217
|
+
|
|
218
|
+
/** 计算哈希时工具名列表的上限(比展示更宽松,覆盖绝大多数真实卡片)。 */
|
|
219
|
+
const HASH_TOOL_NAME_LIMIT = 64
|
|
220
|
+
|
|
221
|
+
/** 单个工具名的字符上限(防御异常长的模型/工具名)。 */
|
|
222
|
+
const TOOL_NAME_MAX_CHARS = 48
|
|
223
|
+
|
|
224
|
+
/** 卡片自带 title 的存储上限(只是防止畸形数据撑爆内存/哈希)。 */
|
|
225
|
+
const TITLE_STORE_MAX_CHARS = 200
|
|
226
|
+
|
|
227
|
+
/** 计算哈希时预览文本的硬上限(正常卡片远小于此值)。 */
|
|
228
|
+
const HASH_PREVIEW_MAX_CHARS = 1_000_000
|
|
229
|
+
|
|
230
|
+
/** kind 的展示名(prompt 里给模型看的人类可读说明)。 */
|
|
231
|
+
const KIND_LABELS = {
|
|
232
|
+
user: '用户消息',
|
|
233
|
+
assistant: '助手回复',
|
|
234
|
+
group: '阶段分组',
|
|
235
|
+
context: '上下文/工具结果',
|
|
236
|
+
developer: '开发者/系统指令',
|
|
237
|
+
system: '系统提示',
|
|
238
|
+
tool: '工具调用或结果',
|
|
239
|
+
'tool-call': '工具调用',
|
|
240
|
+
'tool-result': '工具结果',
|
|
241
|
+
unknown: '未知类型',
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** 摘要兜底句的引导语:不同分类给用户不同的「要不要保留」提示。 */
|
|
245
|
+
const SUMMARY_LEAD_BY_CATEGORY = {
|
|
246
|
+
goal: '用户提出的需求/目标',
|
|
247
|
+
decision: '包含决策或约束',
|
|
248
|
+
code: '涉及代码修改',
|
|
249
|
+
tooling: '工具调用或执行过程',
|
|
250
|
+
research: '探索或调研内容',
|
|
251
|
+
error: '包含错误与修复信息',
|
|
252
|
+
verify: '包含验证或测试信息',
|
|
253
|
+
noise: '闲聊内容,可优先考虑丢弃',
|
|
254
|
+
other: '上下文片段',
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** 兜底分类:错误/修复类关键词(错误优先于其它分类)。 */
|
|
258
|
+
const ERROR_PATTERN = /(?:error|errors|exception|traceback|failed|failure|stderr|报错|错误|失败|异常|崩溃|故障|修复)/iu
|
|
259
|
+
|
|
260
|
+
/** 兜底分类:验证/测试类关键词。 */
|
|
261
|
+
const VERIFY_PATTERN = /(?:test|tests|testing|verify|verified|assert|expect|通过|测试|验证|校验|回归|单测|断言)/iu
|
|
262
|
+
|
|
263
|
+
/** 兜底分类:代码修改类关键词。 */
|
|
264
|
+
const CODE_PATTERN = /(?:```|@@|\bdiff\b|\bpatch\b|apply_patch|write_file|edit_file|replace|修改|实现|重构|函数|接口|代码)/iu
|
|
265
|
+
|
|
266
|
+
/** 兜底分类:探索/调研类关键词。 */
|
|
267
|
+
const RESEARCH_PATTERN = /(?:搜索|检索|调研|查阅|阅读|查找|了解|grep|search|read_file|web_search|web_fetch|research|explore|文档)/iu
|
|
268
|
+
|
|
269
|
+
/** 兜底分类:决策/约束类关键词。 */
|
|
270
|
+
const DECISION_PATTERN = /(?:决定|决策|方案|约束|约定|必须|禁止|原则|取舍|权衡|选择|要求)/u
|
|
271
|
+
|
|
272
|
+
/** 纯确认/寒暄词:折叠分隔符后整段只由这些词组成时,才算「纯确认噪音」。 */
|
|
273
|
+
const CONFIRMATION_WORD_PATTERN = /^(?:okay|ok|好的|好|收到|了解|明白|谢谢|感谢|可以|行|嗯|哦|是的|对|没问题|辛苦|👍|👌)+$/iu
|
|
274
|
+
|
|
275
|
+
/** 纯确认判定上限:折叠后 ≤20 个字符(更长的寒暄串不当作纯确认,避免误伤)。 */
|
|
276
|
+
const CONFIRMATION_MAX_CHARS = 20
|
|
277
|
+
|
|
278
|
+
/** 请求/问题语义阻断词:出现即不得判纯确认(继续/请/帮/改/做/为什么…)。 */
|
|
279
|
+
const CONFIRMATION_REQUEST_BLOCKER_PATTERN = /(?:继续|请|帮|改|做|为什么|怎么|如何|需要|不要|别|停止|开始|实现|修复|添加|删除|调整|补充|看看)/u
|
|
280
|
+
|
|
281
|
+
/** 纯确认折叠用分隔符:空白 / 中英文标点 / 连接符。 */
|
|
282
|
+
const CONFIRMATION_SEPARATOR_PATTERN = /[\s,,.。!!??;;::、~~…·\-—"'“”‘’()()\[\]【】《》<>]+/gu
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* 判断一段文本是否为「纯确认/寒暄」:折叠空白、去掉标点/emoji 变体后,
|
|
286
|
+
* 长度 ≤20 且整体由确认词(好/好的/收到/了解/明白/谢谢/感谢/OK/okay/可以/行/嗯/👍/👌…)
|
|
287
|
+
* 组成;只要含继续/请/帮/改/做/为什么等请求语义,就一律不算(不得判 noise)。
|
|
288
|
+
* @param {unknown} text - 预览/标题文本。
|
|
289
|
+
* @returns {boolean} 是否纯确认。
|
|
290
|
+
*/
|
|
291
|
+
function isPureConfirmationText(text) {
|
|
292
|
+
if (typeof text !== 'string') return false
|
|
293
|
+
const trimmed = cleanInline(text)
|
|
294
|
+
if (trimmed === '') return false
|
|
295
|
+
if (CONFIRMATION_REQUEST_BLOCKER_PATTERN.test(trimmed)) return false
|
|
296
|
+
const compact = trimmed.replace(CONFIRMATION_SEPARATOR_PATTERN, '').replace(/\uFE0F/gu, '')
|
|
297
|
+
if (compact === '') return false
|
|
298
|
+
if (Array.from(compact).length > CONFIRMATION_MAX_CHARS) return false
|
|
299
|
+
return CONFIRMATION_WORD_PATTERN.test(compact)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** 兜底 importance:系统噪音/时间戳特征(体量小且命中这些词时建议丢弃)。 */
|
|
303
|
+
const NOISY_SIGNAL_PATTERN = /(?:Time sampled|system-reminder|系统提醒|时间戳|自动提醒|定时提醒|重复确认|已自动忽略|rewrite the todo)/iu
|
|
304
|
+
|
|
305
|
+
/** 兜底 importance:用户请求/反馈语义(命中时绝不允许回落到 noisy,宁可 keep)。 */
|
|
306
|
+
const USER_REQUEST_PATTERN = /(?:需求|要求|请求|请|帮我|帮忙|麻烦|现在|目前|我们|反馈|希望|需要|修复|改成|调整|补充|please|feedback|request)/iu
|
|
307
|
+
|
|
308
|
+
/** 兜底 importance:项目结构/关键约束/关键决策/交付结论类关键词(命中可判 important)。 */
|
|
309
|
+
const IMPORTANT_HINT_PATTERN = /(?:需求|要求|约束|结构|决策|方案|目标|必须|禁止|约定|规范|架构|交付|结论|关键|项目结构|项目约束|不能|不要|务必)/u
|
|
310
|
+
|
|
311
|
+
/** 兜底 importanceKind:关键约束 / 规则 / 技术原则 / 禁止事项。 */
|
|
312
|
+
const CONSTRAINT_KIND_PATTERN = /(?:约束|规则|必须|禁止|原则|规范|约定|技术原则|不能|不要|务必)/u
|
|
313
|
+
|
|
314
|
+
/** 兜底 importanceKind:项目结构 / 架构 / 关键组成 / 目录模块。 */
|
|
315
|
+
const ARCHITECTURE_KIND_PATTERN = /(?:结构|架构|目录|模块|组成|组件|分层|代码组织|项目结构)/u
|
|
316
|
+
|
|
317
|
+
/** 兜底 importanceKind:关键决策 / 方案取舍。 */
|
|
318
|
+
const DECISION_KIND_PATTERN = /(?:决策|决定|方案|取舍|权衡|选择|采用)/u
|
|
319
|
+
|
|
320
|
+
/** 兜底 importanceKind:交付结论 / 验收结果 / 最终答复。 */
|
|
321
|
+
const DELIVERABLE_KIND_PATTERN = /(?:交付|完成|验收|结论|最终答复|最终版本|定稿)/u
|
|
322
|
+
|
|
323
|
+
/** 兜底 importanceKind:用户对整个项目的整体指示 / 目标(需配合用户请求上下文,避免误判)。 */
|
|
324
|
+
const DIRECTIVE_KIND_PATTERN = /(?:整体指示|整体目标|整体要求|整体任务|整体约束|整个项目|项目整体|项目目标|项目要求|核心目标|主要目标|目标)/u
|
|
325
|
+
|
|
326
|
+
/** 兜底 importanceKind:工具输出 / 读取结果 / 命令过程。 */
|
|
327
|
+
const TOOL_KIND_PATTERN = /(?:shell|bash|terminal|终端|命令行|命令输出|文件内容|读取结果|工具输出|工具返回|stdout|stderr|read_file|write_file|list_dir|grep|find)/iu
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* v13 后处理:交付/验证结论的强特征(在 title + summary 里命中即视为交付结论)。
|
|
331
|
+
*
|
|
332
|
+
* 真实误判样本(task-24验证全绿报告 / v8自动分析与详情增强 / v11规则型重要度交付 /
|
|
333
|
+
* v12交付总结)说明:交付/验收总结的措辞经常“看起来像过程”,但这必须是
|
|
334
|
+
* deliverable/important,否则用户最需要的结论会被当成可精简过程。
|
|
335
|
+
*/
|
|
336
|
+
const DELIVERABLE_STRONG_PATTERN = /(?:全绿|验收|交付|已安装|安装生效|已生效|通过全部|全部通过|测试通过|完成汇报|交付总结|验收报告|结论[::]|已上线|已发布)/u
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* v13 后处理:过程强特征。出现这些词说明卡片主要是等待/调度/读取/修改/检索/探索,
|
|
340
|
+
* 不得被误升为 deliverable(防止「等待交付」「调度任务」这类卡被抬成交付结论)。
|
|
341
|
+
*/
|
|
342
|
+
const PROCESS_STRONG_PATTERN = /(?:等待|调度|读取|修改|检索|探索|派发|轮询|排队|重试)/u
|
|
343
|
+
|
|
344
|
+
/** v13 理由具体化:各 kind 的理由前缀(生成「交付结论:{title}」这类具体理由)。 */
|
|
345
|
+
const REASON_PREFIX_BY_KIND = {
|
|
346
|
+
directive: '用户整体指示',
|
|
347
|
+
constraint: '关键约束',
|
|
348
|
+
architecture: '项目结构',
|
|
349
|
+
decision: '关键决策',
|
|
350
|
+
deliverable: '交付结论',
|
|
351
|
+
feedback: '用户需求/反馈',
|
|
352
|
+
process: '实现过程',
|
|
353
|
+
tool: '工具输出',
|
|
354
|
+
noise: '无用元信息',
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* 通用/模板化理由黑名单:这些没有引用任何任务或对象,prompt v4.1 明确禁止,
|
|
359
|
+
* 后处理会替换成「{种类前缀}:{title}」形式的具体理由。
|
|
360
|
+
*/
|
|
361
|
+
const GENERIC_REASONS = new Set([
|
|
362
|
+
'实现过程,可精简', '工具输出,可精简', '实现过程', '工具过程', '工具输出',
|
|
363
|
+
'上下文片段', '用户需求或反馈', '用户需求', '关键约束', '项目结构', '关键决策',
|
|
364
|
+
'交付结论', '时间戳/系统提醒,无业务信息', '时间戳/系统提醒,可丢弃',
|
|
365
|
+
'噪音', '无用信息', '一般过程', '其他', '可精简',
|
|
366
|
+
])
|
|
367
|
+
|
|
368
|
+
/** 常见 JSON 包装键(值应是结果数组)。 */
|
|
369
|
+
const RESULT_ARRAY_KEYS = ['results', 'cards', 'items', 'analyses', 'analysis', 'data', 'list', 'output', 'entries']
|
|
370
|
+
|
|
371
|
+
/** 解析结果条目时的字段别名(大小写/下划线/连字符由 normalizeFieldKey 抹平)。 */
|
|
372
|
+
const ID_KEYS = ['id', 'cardid', 'card', 'key', 'identity']
|
|
373
|
+
const CATEGORY_KEYS = ['category', 'cat', '分类']
|
|
374
|
+
const TITLE_KEYS = ['title', 'shorttitle', 'name', 'heading', '标题']
|
|
375
|
+
const SUMMARY_KEYS = ['summary', 'desc', 'description', 'brief', 'intro', '简介', '摘要']
|
|
376
|
+
const IMPORTANCE_KEYS = ['importance', 'importancelevel', 'importantlevel', '重要度', '重要性']
|
|
377
|
+
const IMPORTANCE_KIND_KEYS = ['importancekind', 'importancetype', 'kind', '种类', '类型']
|
|
378
|
+
const IMPORTANCE_REASON_KEYS = ['importancereason', 'reason', '理由', '原因']
|
|
379
|
+
|
|
380
|
+
/* -------------------------------------------------------------------------- */
|
|
381
|
+
/* 通用小工具 */
|
|
382
|
+
/* -------------------------------------------------------------------------- */
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* 是不是「普通对象」(排除 null / 数组;函数按对象处理)。
|
|
386
|
+
* @param {unknown} value - 任意值。
|
|
387
|
+
* @returns {boolean} 判断结果。
|
|
388
|
+
*/
|
|
389
|
+
function isRecord(value) {
|
|
390
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* 把任意异常转成一行可读文本(绝不抛出)。
|
|
395
|
+
* @param {unknown} error - 任意异常。
|
|
396
|
+
* @returns {string} 文本。
|
|
397
|
+
*/
|
|
398
|
+
function toErrorMessage(error) {
|
|
399
|
+
if (error instanceof Error) return error.message === '' ? error.name : error.message
|
|
400
|
+
try {
|
|
401
|
+
return String(error)
|
|
402
|
+
} catch {
|
|
403
|
+
return '未知错误'
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* 把文本压成一行:换行/制表符/连续空白都折叠为单个空格(用于 title/summary)。
|
|
409
|
+
* @param {unknown} value - 任意值。
|
|
410
|
+
* @returns {string} 规范化后的一行文本。
|
|
411
|
+
*/
|
|
412
|
+
function cleanInline(value) {
|
|
413
|
+
if (typeof value !== 'string') return ''
|
|
414
|
+
return value.replace(/\s+/gu, ' ').trim()
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* 找到「按 code point 截断到 maxChars」时的字符下标(不拆分代理对)。
|
|
419
|
+
* @param {string} text - 文本。
|
|
420
|
+
* @param {number} maxChars - 最大 code point 数。
|
|
421
|
+
* @returns {number} 可安全 slice 的 UTF-16 下标。
|
|
422
|
+
*/
|
|
423
|
+
function codePointCutIndex(text, maxChars) {
|
|
424
|
+
if (maxChars <= 0) return 0
|
|
425
|
+
let count = 0
|
|
426
|
+
let index = 0
|
|
427
|
+
while (index < text.length && count < maxChars) {
|
|
428
|
+
const code = text.codePointAt(index)
|
|
429
|
+
index += code !== undefined && code > 0xffff ? 2 : 1
|
|
430
|
+
count += 1
|
|
431
|
+
}
|
|
432
|
+
return index
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* 按 code point 截断(不加省略号)。用于模型输出字段的硬上限。
|
|
437
|
+
* @param {string} text - 文本。
|
|
438
|
+
* @param {number} maxChars - 最大 code point 数。
|
|
439
|
+
* @returns {string} 截断结果。
|
|
440
|
+
*/
|
|
441
|
+
function truncateCodePoints(text, maxChars) {
|
|
442
|
+
if (typeof text !== 'string' || text === '') return ''
|
|
443
|
+
if (maxChars <= 0) return ''
|
|
444
|
+
const cut = codePointCutIndex(text, maxChars)
|
|
445
|
+
return cut >= text.length ? text : text.slice(0, cut)
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* 截断卡片预览,超长时追加「…(已截断)」标记(让模型知道自己看到的不是全文)。
|
|
450
|
+
* @param {string} text - 预览文本。
|
|
451
|
+
* @param {number} maxChars - 预览字符上限。
|
|
452
|
+
* @returns {string} 截断结果。
|
|
453
|
+
*/
|
|
454
|
+
function truncatePreview(text, maxChars) {
|
|
455
|
+
if (typeof text !== 'string' || text === '') return ''
|
|
456
|
+
if (maxChars <= 0) return TRUNCATED_MARK
|
|
457
|
+
const cut = codePointCutIndex(text, maxChars)
|
|
458
|
+
return cut >= text.length ? text : `${text.slice(0, cut)}${TRUNCATED_MARK}`
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* 依次取第一个非空字符串(数字会安全转成字符串)。
|
|
463
|
+
* @param {...unknown} values - 候选值。
|
|
464
|
+
* @returns {string} 结果(没有则空串)。
|
|
465
|
+
*/
|
|
466
|
+
function pickString(...values) {
|
|
467
|
+
for (const value of values) {
|
|
468
|
+
if (typeof value === 'string' && value.trim() !== '') return value
|
|
469
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
|
470
|
+
}
|
|
471
|
+
return ''
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* 读取一个非负整数(支持数字与数字字符串),非法返回 null。
|
|
476
|
+
* @param {unknown} value - 原始值。
|
|
477
|
+
* @returns {number | null} 整数或 null。
|
|
478
|
+
*/
|
|
479
|
+
function readNonNegativeInt(value) {
|
|
480
|
+
let number = NaN
|
|
481
|
+
if (typeof value === 'number') number = value
|
|
482
|
+
else if (typeof value === 'string' && value.trim() !== '') number = Number(value)
|
|
483
|
+
if (!Number.isFinite(number) || number < 0) return null
|
|
484
|
+
return Math.round(number)
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* config 里读正整数:非法/缺失时回退默认值。
|
|
489
|
+
* @param {unknown} value - 原始值。
|
|
490
|
+
* @param {number} fallback - 默认值。
|
|
491
|
+
* @returns {number} 合法正整数。
|
|
492
|
+
*/
|
|
493
|
+
function readPositiveInt(value, fallback) {
|
|
494
|
+
const number = typeof value === 'number' ? value : NaN
|
|
495
|
+
return Number.isFinite(number) && number >= 1 ? Math.floor(number) : fallback
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* config 里读非负整数(0 合法,用于 retries / retryDelayMs);非法/缺失回退默认值。
|
|
500
|
+
* @param {unknown} value - 原始值。
|
|
501
|
+
* @param {number} fallback - 默认值。
|
|
502
|
+
* @returns {number} 合法非负整数。
|
|
503
|
+
*/
|
|
504
|
+
function readNonNegativeConfigInt(value, fallback) {
|
|
505
|
+
const number = typeof value === 'number' ? value : NaN
|
|
506
|
+
return Number.isFinite(number) && number >= 0 ? Math.floor(number) : fallback
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* config 里读闭区间数字:非法/缺失时回退默认值。
|
|
511
|
+
* @param {unknown} value - 原始值。
|
|
512
|
+
* @param {number} fallback - 默认值。
|
|
513
|
+
* @param {number} min - 下界。
|
|
514
|
+
* @param {number} max - 上界。
|
|
515
|
+
* @returns {number} 合法数字。
|
|
516
|
+
*/
|
|
517
|
+
function readBoundedNumber(value, fallback, min, max) {
|
|
518
|
+
const number = typeof value === 'number' ? value : NaN
|
|
519
|
+
return Number.isFinite(number) && number >= min && number <= max ? number : fallback
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* 合并用户配置与默认配置,逐项校验非法值。
|
|
524
|
+
* @param {unknown} config - 调用方传入的部分配置。
|
|
525
|
+
* @returns {typeof DEFAULT_SCAN_CONFIG} 完整且合法的配置。
|
|
526
|
+
*/
|
|
527
|
+
function resolveScanConfig(config) {
|
|
528
|
+
const source = isRecord(config) ? config : {}
|
|
529
|
+
return {
|
|
530
|
+
batchSize: readPositiveInt(source.batchSize, DEFAULT_SCAN_CONFIG.batchSize),
|
|
531
|
+
maxTokens: readPositiveInt(source.maxTokens, DEFAULT_SCAN_CONFIG.maxTokens),
|
|
532
|
+
previewChars: readPositiveInt(source.previewChars, DEFAULT_SCAN_CONFIG.previewChars),
|
|
533
|
+
temperature: readBoundedNumber(source.temperature, DEFAULT_SCAN_CONFIG.temperature, 0, 2),
|
|
534
|
+
timeoutMs: readPositiveInt(source.timeoutMs, DEFAULT_SCAN_CONFIG.timeoutMs),
|
|
535
|
+
maxConcurrentBatches: readPositiveInt(source.maxConcurrentBatches, DEFAULT_SCAN_CONFIG.maxConcurrentBatches),
|
|
536
|
+
maxCardsPerPass: readPositiveInt(source.maxCardsPerPass, DEFAULT_SCAN_CONFIG.maxCardsPerPass),
|
|
537
|
+
retries: readNonNegativeConfigInt(source.retries, DEFAULT_SCAN_CONFIG.retries),
|
|
538
|
+
retryDelayMs: readNonNegativeConfigInt(source.retryDelayMs, DEFAULT_SCAN_CONFIG.retryDelayMs),
|
|
539
|
+
// 分类是短 JSON 输出:宿主会显式关掉 reasoning(默认空 = 不设置,跟随路由默认)。
|
|
540
|
+
reasoningEffort: typeof source.reasoningEffort === 'string' && source.reasoningEffort.trim() !== ''
|
|
541
|
+
? source.reasoningEffort.trim()
|
|
542
|
+
: '',
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/* -------------------------------------------------------------------------- */
|
|
547
|
+
/* 卡片归一化 */
|
|
548
|
+
/* -------------------------------------------------------------------------- */
|
|
549
|
+
|
|
550
|
+
/** kind → role 的推导(宿主没给 role 时用)。 */
|
|
551
|
+
function roleForKind(kind) {
|
|
552
|
+
if (typeof kind !== 'string' || kind === '') return ''
|
|
553
|
+
if (kind === 'user' || kind === 'human') return 'user'
|
|
554
|
+
if (kind === 'assistant' || kind === 'ai' || kind === 'model') return 'assistant'
|
|
555
|
+
if (kind === 'developer' || kind === 'system') return 'developer'
|
|
556
|
+
if (kind === 'context' || kind === 'tool-result' || kind === 'tool-result-block') return 'context'
|
|
557
|
+
if (kind.startsWith('tool')) return 'tool'
|
|
558
|
+
return ''
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** role → kind 的推导(宿主没给 kind 时用)。 */
|
|
562
|
+
function kindForRole(role) {
|
|
563
|
+
if (typeof role !== 'string' || role === '') return 'unknown'
|
|
564
|
+
if (role === 'user' || role === 'human') return 'user'
|
|
565
|
+
if (role === 'assistant' || role === 'ai' || role === 'model') return 'assistant'
|
|
566
|
+
if (role === 'tool') return 'tool'
|
|
567
|
+
if (role === 'system') return 'system'
|
|
568
|
+
if (role === 'developer') return 'developer'
|
|
569
|
+
if (role === 'context') return 'context'
|
|
570
|
+
return 'unknown'
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* 读取卡片 id(字符串化;缺失返回空串,由调用方跳过)。
|
|
575
|
+
* @param {Record<string, unknown>} card - 卡片。
|
|
576
|
+
* @returns {string} id。
|
|
577
|
+
*/
|
|
578
|
+
function readCardId(card) {
|
|
579
|
+
const value = card.id ?? card.cardId ?? card.card_id ?? card.key
|
|
580
|
+
if (typeof value === 'string') return value.trim()
|
|
581
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(Math.round(value))
|
|
582
|
+
return ''
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* 读取卡片 kind(小写;缺失时尝试从 role 推导)。
|
|
587
|
+
* @param {Record<string, unknown>} card - 卡片。
|
|
588
|
+
* @returns {string} kind。
|
|
589
|
+
*/
|
|
590
|
+
function readCardKind(card) {
|
|
591
|
+
const raw = cleanInline(pickString(card.kind, card.type, card.blockType, card.cardType, card.segmentKind)).toLowerCase()
|
|
592
|
+
if (raw !== '') return raw
|
|
593
|
+
const role = cleanInline(pickString(card.role, card.messageRole)).toLowerCase()
|
|
594
|
+
return role !== '' ? kindForRole(role) : 'unknown'
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* 读取卡片 role(小写;缺失时尝试从 kind 推导)。
|
|
599
|
+
* @param {Record<string, unknown>} card - 卡片。
|
|
600
|
+
* @param {string} kind - 已解析的 kind。
|
|
601
|
+
* @returns {string} role(可能为空串)。
|
|
602
|
+
*/
|
|
603
|
+
function readCardRole(card, kind) {
|
|
604
|
+
const raw = cleanInline(pickString(card.role, card.messageRole)).toLowerCase()
|
|
605
|
+
return raw !== '' ? raw : roleForKind(kind)
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* 读取工具名列表:容忍「字符串 / 字符串数组 / {name} 对象数组 / 工具 schema 数组」。
|
|
610
|
+
* @param {Record<string, unknown>} card - 卡片。
|
|
611
|
+
* @param {number} limit - 最多保留几个。
|
|
612
|
+
* @returns {string[]} 去重后的工具名。
|
|
613
|
+
*/
|
|
614
|
+
function readToolNames(card, limit) {
|
|
615
|
+
const names = []
|
|
616
|
+
/**
|
|
617
|
+
* 收集一个候选值里的工具名(深度可控:数组/对象最多展开一层)。
|
|
618
|
+
* @param {unknown} value - 候选值。
|
|
619
|
+
*/
|
|
620
|
+
const collect = value => {
|
|
621
|
+
if (typeof value === 'string') {
|
|
622
|
+
for (const part of value.split(/[,,、;;|]+/u)) append(part)
|
|
623
|
+
return
|
|
624
|
+
}
|
|
625
|
+
if (Array.isArray(value)) {
|
|
626
|
+
for (const item of value) collect(item)
|
|
627
|
+
return
|
|
628
|
+
}
|
|
629
|
+
if (isRecord(value)) {
|
|
630
|
+
append(pickString(value.name, value.toolName, value.tool_name))
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* 追加一个工具名(去重 + 截断)。
|
|
635
|
+
* @param {string} raw - 原始工具名。
|
|
636
|
+
*/
|
|
637
|
+
const append = raw => {
|
|
638
|
+
const name = truncateCodePoints(cleanInline(raw), TOOL_NAME_MAX_CHARS)
|
|
639
|
+
if (name === '' || names.includes(name)) return
|
|
640
|
+
names.push(name)
|
|
641
|
+
}
|
|
642
|
+
collect(card.toolNames ?? card.tool_names ?? card.toolnames)
|
|
643
|
+
collect(card.tools)
|
|
644
|
+
collect(card.toolCalls ?? card.tool_calls)
|
|
645
|
+
collect(card.toolName ?? card.tool_name)
|
|
646
|
+
return names.slice(0, limit)
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* 把卡片的 `content`(可能是块数组)压平成文本。
|
|
651
|
+
* @param {unknown} value - 内容候选值。
|
|
652
|
+
* @returns {string} 文本。
|
|
653
|
+
*/
|
|
654
|
+
function flattenContent(value) {
|
|
655
|
+
if (typeof value === 'string') return value
|
|
656
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
|
|
657
|
+
if (Array.isArray(value)) {
|
|
658
|
+
const parts = []
|
|
659
|
+
for (const item of value) {
|
|
660
|
+
if (typeof item === 'string') {
|
|
661
|
+
if (item !== '') parts.push(item)
|
|
662
|
+
continue
|
|
663
|
+
}
|
|
664
|
+
if (isRecord(item) && typeof item.text === 'string' && item.text !== '') parts.push(item.text)
|
|
665
|
+
}
|
|
666
|
+
return parts.join('\n')
|
|
667
|
+
}
|
|
668
|
+
if (isRecord(value) && typeof value.text === 'string') return value.text
|
|
669
|
+
return ''
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* 读取卡片的原始预览文本(未截断、未清洗,保留换行)。
|
|
674
|
+
* @param {Record<string, unknown>} card - 卡片。
|
|
675
|
+
* @returns {string} 预览文本。
|
|
676
|
+
*/
|
|
677
|
+
function readPreviewText(card) {
|
|
678
|
+
for (const candidate of [card.preview, card.text, card.body, card.snippet, card.excerpt, card.content]) {
|
|
679
|
+
const text = flattenContent(candidate)
|
|
680
|
+
if (text.trim() !== '') return text
|
|
681
|
+
}
|
|
682
|
+
return ''
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* 把一张卡片归一化成送进 prompt 的最小信息集(不含原始全文,避免 prompt 失控)。
|
|
687
|
+
*
|
|
688
|
+
* 归一化是「防御式」的:卡片字段缺失、类型不对、预览超长都不会抛错,只会退化成
|
|
689
|
+
* 合理的空值/截断值。宿主只需保证一张卡片至少带 `id` 与一段可读文本,其余字段
|
|
690
|
+
* (kind / role / turn / tokens / unitCount / title / toolNames)有就用、没有就省略。
|
|
691
|
+
*
|
|
692
|
+
* v2 卡片是「按轮次的语义阶段分组」:`kind: 'group'`、`role: 'mixed'`,
|
|
693
|
+
* `unitCount` 表示这个分组包含多少个原始步骤。
|
|
694
|
+
*
|
|
695
|
+
* @param {unknown} card - 卡片对象(见模块文档;字段缺失可容忍)。
|
|
696
|
+
* @param {unknown} [config] - 部分扫描配置(目前只用到 previewChars)。
|
|
697
|
+
* @returns {{ id: string, kind: string, role: string, turn: number | null, tokens: number | null, unitCount: number | null, title: string, toolNames: string[], preview: string }}
|
|
698
|
+
*/
|
|
699
|
+
export function normalizeCardForScan(card, config = DEFAULT_SCAN_CONFIG) {
|
|
700
|
+
const raw = isRecord(card) ? card : {}
|
|
701
|
+
const settings = resolveScanConfig(config)
|
|
702
|
+
const kind = readCardKind(raw)
|
|
703
|
+
return {
|
|
704
|
+
id: readCardId(raw),
|
|
705
|
+
kind,
|
|
706
|
+
role: readCardRole(raw, kind),
|
|
707
|
+
turn: readNonNegativeInt(raw.turn ?? raw.turnIndex),
|
|
708
|
+
tokens: readNonNegativeInt(raw.tokens ?? raw.tokenCount ?? raw.tokenEstimate),
|
|
709
|
+
unitCount: readNonNegativeInt(raw.unitCount ?? raw.unit_count),
|
|
710
|
+
title: truncateCodePoints(cleanInline(pickString(raw.title, raw.name)), TITLE_STORE_MAX_CHARS),
|
|
711
|
+
toolNames: readToolNames(raw, TOOL_NAME_LIMIT),
|
|
712
|
+
preview: truncatePreview(readPreviewText(raw), settings.previewChars),
|
|
713
|
+
// 规则提示(由宿主/actions 传入):包含最早用户请求 / 包含用户请求。
|
|
714
|
+
firstUserRequest: raw.firstUserRequest === true,
|
|
715
|
+
hasUserRequest: raw.hasUserRequest === true,
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/* -------------------------------------------------------------------------- */
|
|
720
|
+
/* 缓存指纹 */
|
|
721
|
+
/* -------------------------------------------------------------------------- */
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* 计算一张卡片的内容指纹:内容没变就稳定命中缓存,不再重复花钱分析。
|
|
725
|
+
*
|
|
726
|
+
* 指纹只由「会影响分析结果」的字段组成(kind / role / turn / tokens / unitCount /
|
|
727
|
+
* title / 工具名 / 预览全文),刻意不含 id 与时间戳:同一段内容即使换了个 id 也
|
|
728
|
+
* 不影响分析结论。每个字段都带长度前缀,避免简单拼接产生的歧义冲突。
|
|
729
|
+
*
|
|
730
|
+
* @param {unknown} card - 卡片对象。
|
|
731
|
+
* @returns {string} 16 位 16 进制 sha1 前缀。
|
|
732
|
+
*/
|
|
733
|
+
export function cardHash(card) {
|
|
734
|
+
const raw = isRecord(card) ? card : {}
|
|
735
|
+
const kind = readCardKind(raw)
|
|
736
|
+
const role = readCardRole(raw, kind)
|
|
737
|
+
const preview = readPreviewText(raw)
|
|
738
|
+
const hash = createHash('sha1')
|
|
739
|
+
const parts = [
|
|
740
|
+
HASH_NAMESPACE,
|
|
741
|
+
kind,
|
|
742
|
+
role,
|
|
743
|
+
readNonNegativeInt(raw.turn ?? raw.turnIndex) === null ? '' : String(readNonNegativeInt(raw.turn ?? raw.turnIndex)),
|
|
744
|
+
readNonNegativeInt(raw.tokens ?? raw.tokenCount ?? raw.tokenEstimate) === null
|
|
745
|
+
? ''
|
|
746
|
+
: String(readNonNegativeInt(raw.tokens ?? raw.tokenCount ?? raw.tokenEstimate)),
|
|
747
|
+
readNonNegativeInt(raw.unitCount ?? raw.unit_count) === null
|
|
748
|
+
? ''
|
|
749
|
+
: String(readNonNegativeInt(raw.unitCount ?? raw.unit_count)),
|
|
750
|
+
truncateCodePoints(cleanInline(pickString(raw.title, raw.name)), TITLE_STORE_MAX_CHARS),
|
|
751
|
+
readToolNames(raw, HASH_TOOL_NAME_LIMIT).join('\u0001'),
|
|
752
|
+
// 规则提示会影响重要度判断,必须参与缓存指纹(旧缓存一次失效后保持稳定)。
|
|
753
|
+
raw.firstUserRequest === true ? 'first-user-request' : '',
|
|
754
|
+
raw.hasUserRequest === true ? 'has-user-request' : '',
|
|
755
|
+
preview.length > HASH_PREVIEW_MAX_CHARS ? preview.slice(0, HASH_PREVIEW_MAX_CHARS) : preview,
|
|
756
|
+
]
|
|
757
|
+
for (const part of parts) {
|
|
758
|
+
const text = typeof part === 'string' ? part : String(part)
|
|
759
|
+
hash.update(String(text.length))
|
|
760
|
+
hash.update(':')
|
|
761
|
+
hash.update(text)
|
|
762
|
+
hash.update('\u0000')
|
|
763
|
+
}
|
|
764
|
+
return hash.digest('hex').slice(0, HASH_HEX_CHARS)
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/* -------------------------------------------------------------------------- */
|
|
768
|
+
/* 分批 */
|
|
769
|
+
/* -------------------------------------------------------------------------- */
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* 把卡片数组切成批:保持原顺序、每批不超过 batchSize、最多处理 maxCardsPerPass 张。
|
|
773
|
+
* 返回的是新数组(入参不被修改),批内仍引用原卡片对象。
|
|
774
|
+
*
|
|
775
|
+
* @param {unknown} cards - 卡片数组。
|
|
776
|
+
* @param {unknown} [config] - 部分扫描配置(batchSize / maxCardsPerPass)。
|
|
777
|
+
* @returns {unknown[][]} 批次数组。
|
|
778
|
+
*/
|
|
779
|
+
export function buildScanBatches(cards, config = DEFAULT_SCAN_CONFIG) {
|
|
780
|
+
const settings = resolveScanConfig(config)
|
|
781
|
+
const list = Array.isArray(cards) ? cards.filter(card => isRecord(card)) : []
|
|
782
|
+
const limited = list.slice(0, settings.maxCardsPerPass)
|
|
783
|
+
const batches = []
|
|
784
|
+
for (let index = 0; index < limited.length; index += settings.batchSize) {
|
|
785
|
+
batches.push(limited.slice(index, index + settings.batchSize))
|
|
786
|
+
}
|
|
787
|
+
return batches
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/* -------------------------------------------------------------------------- */
|
|
791
|
+
/* Prompt */
|
|
792
|
+
/* -------------------------------------------------------------------------- */
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* 取 kind 的中文说明(未知 kind 用原文兜底)。
|
|
796
|
+
* @param {string} kind - 归一化后的 kind。
|
|
797
|
+
* @returns {string} 中文说明。
|
|
798
|
+
*/
|
|
799
|
+
function kindLabelOf(kind) {
|
|
800
|
+
if (kind === '') return KIND_LABELS.unknown
|
|
801
|
+
return KIND_LABELS[kind] ?? kind
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* 构造单批分析 prompt(一个中文 user 文本,要求模型只输出 JSON 数组)。
|
|
806
|
+
*
|
|
807
|
+
* v2 的卡片语义是「按轮次分组的语义阶段」:每张卡是一轮对话中的一个阶段分组,
|
|
808
|
+
* `unitCount` 表示它包含多少个原始步骤。prompt 里逐张列出:id / kind / role /
|
|
809
|
+
* turn / tokens / unitCount / 工具名 / 已有标题 / 内容预览;预览长度由
|
|
810
|
+
* config.previewChars 控制,超长内容带「…(已截断)」标记。
|
|
811
|
+
*
|
|
812
|
+
* @param {unknown} batch - 一批卡片(buildScanBatches 的元素)。
|
|
813
|
+
* @param {unknown} [config] - 部分扫描配置(previewChars 等)。
|
|
814
|
+
* @returns {string} prompt 文本。
|
|
815
|
+
*/
|
|
816
|
+
export function buildScanPrompt(batch, config = DEFAULT_SCAN_CONFIG) {
|
|
817
|
+
const settings = resolveScanConfig(config)
|
|
818
|
+
const cards = Array.isArray(batch) ? batch : []
|
|
819
|
+
const normalized = cards.map(card => normalizeCardForScan(card, settings))
|
|
820
|
+
const lines = []
|
|
821
|
+
|
|
822
|
+
lines.push('你是上下文管理器(Context Manager)的分类引擎。用户会把「即将发给云端模型」的对话历史按轮次切成「语义阶段分组卡」:每张卡是一轮对话中的一个语义阶段分组,unitCount 表示它包含多少个原始步骤。用户会依据你的结果决定丢弃哪些卡片、保留哪些卡片。你的任务是对每一张分组卡生成:分类(category)、短标题(title)、一句话简介(summary)、重要度(importance)、重要度种类(importanceKind)、重要度理由(importanceReason)。')
|
|
823
|
+
lines.push('')
|
|
824
|
+
lines.push('输出要求(必须严格遵守):')
|
|
825
|
+
lines.push('1. 只输出一个严格的 JSON 数组,不要 Markdown 代码围栏,不要任何解释、前后缀或多余文字。')
|
|
826
|
+
lines.push('2. 数组元素必须与下面给出的卡片一一对应:id 必须原样照抄,不能遗漏、不能重复、不能新增。')
|
|
827
|
+
lines.push('3. 每个元素的格式必须是:{"id":"卡片id","category":"goal","title":"不超过14个字的短标题","summary":"不超过48个字的一句话简介","importance":"keep","importanceKind":"process","importanceReason":"不超过24个字的中文理由"}')
|
|
828
|
+
lines.push('4. category 只能取以下 9 个值之一(括号外是机器码,括号内是中文含义):')
|
|
829
|
+
for (const category of CATEGORIES) lines.push(` - "${category.id}":${category.label}`)
|
|
830
|
+
lines.push('5. importance 只能取以下 3 个值之一(硬性规则,必须严格遵守):')
|
|
831
|
+
lines.push(' - "important":项目结构、关键约束、关键决策、用户需求、交付结论等必须长期保留的信息')
|
|
832
|
+
lines.push(' - "keep":一般实现过程、工具输出、探索记录等可以保留的内容')
|
|
833
|
+
lines.push(' - "noisy":仅限时间戳、系统提醒、重复确认、纯闲聊等无用的元信息;其他情况一律不要用 "noisy"')
|
|
834
|
+
lines.push(' 硬性约束:用户提出的请求 / 需求 / 反馈,以及最新一轮对话中的卡片,绝不能标为 "noisy"(拿不准就标 "keep")。只要卡片包含用户的真实意图、指令、问题或反馈,就至少是 "keep";只有纯粹的时间戳、系统提醒、重复确认或闲聊才允许 "noisy"。')
|
|
835
|
+
lines.push(' 最高优先级规则:卡片里若包含用户最初对**整个项目/整体任务**的指示(“这个项目要做什么”“整体要求/目标/约束”),或下方标注了「首条用户请求: 是」,必须标为 "important",即使这张卡很长、混有时间戳/系统提醒/工具过程,也绝不能标 "keep" 或 "noisy"。这是用户最不希望被精简掉的信息。')
|
|
836
|
+
lines.push(' 次高优先级:下方标注「包含用户请求: 是」的卡片不得标为 "noisy";若其中的用户请求较长或含需求/约束/目标,应标 "important"。')
|
|
837
|
+
lines.push('6. importanceKind 只能取以下 9 个值之一,用来说明「这张卡为什么重要 / 为什么可以精简」(括号内是判定标准,必须严格遵守):')
|
|
838
|
+
lines.push(' - "directive":用户对整个项目「要做什么」的整体指示 / 目标(最高优先,必须标 importance="important")')
|
|
839
|
+
lines.push(' - "constraint":关键约束 / 规则 / 技术原则 / 禁止事项(必须标 importance="important")')
|
|
840
|
+
lines.push(' - "architecture":项目结构 / 架构 / 关键组成 / 目录模块(必须标 importance="important")')
|
|
841
|
+
lines.push(' - "decision":关键决策 / 方案取舍(必须标 importance="important")')
|
|
842
|
+
lines.push(' - "deliverable":交付结论 / 验收结果 / 最终答复 / 交付总结 / 验收报告(必须标 importance="important")。判定细则:“测试全绿 / 验收通过 / 已交付 / 已安装生效 / 通过全部 / 测试通过 / 完成汇报 / 交付总结 / 验收报告 / 结论:”这类验证或交付结论文本,即使叙述看起来像过程,也必须标 "deliverable"')
|
|
843
|
+
lines.push(' - "feedback":用户需求 / 反馈(至少标 "keep";重要则标 "important";绝不能标 "noisy")')
|
|
844
|
+
lines.push(' - "process":实现 / 调试 / 探索过程(不得标 importance="important")')
|
|
845
|
+
lines.push(' - "tool":工具输出 / 读取结果(不得标 importance="important")')
|
|
846
|
+
lines.push(' - "noise":时间戳 / 系统提醒 / 重复确认(不得标 importance="important",可以标 "noisy")')
|
|
847
|
+
lines.push(' 硬性一致性要求:importanceKind 为 directive/constraint/architecture/decision/deliverable 时,importance 必须是 "important";为 process/tool/noise 时不得是 "important";为 feedback 时绝不能是 "noisy"。')
|
|
848
|
+
lines.push(' 派发/分工细则:给子代理派任务、拆分团队工作——有关键取舍 / 方案选择时标 "decision",纯执行调度标 "process";不要因为出现“任务 / 派发”就标 "deliverable"。')
|
|
849
|
+
lines.push(' 用户短指令细则:用户说“继续 / 继续改进 / 按这个方向做 / 重申整体目标”等——针对整体项目方向的标 "directive",针对单次改动的标 "feedback";importance 至少 "keep",绝不能 "noisy"。')
|
|
850
|
+
lines.push('7. importanceReason 是 ≤24 个字的中文短理由,必须具体:引用这张卡在讲什么任务 / 对象,并说明为什么重要或为什么可以精简;不能为空。')
|
|
851
|
+
lines.push(' 禁止只写“实现过程,可精简”“工具输出,可精简”“用户需求”这类不引用任何对象的通用文案。交付类写成“交付结论:{任务名}”(例如“交付结论:v12 交付总结:种类/分区/人工纠正”),过程类写成“实现过程:{任务名}”,约束类写成“关键约束:{具体约束}”,验证类写成“验证结论:{通过项}”。')
|
|
852
|
+
lines.push('8. 所有 title 与 summary 都必须使用简体中文,不能为空,不能包含换行;title 概括这一阶段整体在干什么(便于用户一眼分辨),summary 说明其中包含哪些关键信息、是否值得保留(便于用户决定是否丢弃)。')
|
|
853
|
+
lines.push('9. 一张分组卡代表若干步骤的整体语义,请从整体概括,不要只描述第一个步骤;分类拿不准时选 "other",重要度拿不准时选 "keep",importanceKind 拿不准时选 "process";不要编造卡片里不存在的 id。')
|
|
854
|
+
lines.push('')
|
|
855
|
+
lines.push(`卡片共 ${normalized.length} 张:`)
|
|
856
|
+
|
|
857
|
+
for (let index = 0; index < normalized.length; index += 1) {
|
|
858
|
+
const card = normalized[index]
|
|
859
|
+
lines.push('')
|
|
860
|
+
lines.push(`--- 卡片 ${index + 1} / ${normalized.length} ---`)
|
|
861
|
+
lines.push(`id: ${card.id === '' ? '(缺失)' : card.id}`)
|
|
862
|
+
lines.push(`kind: ${card.kind === '' ? 'unknown' : card.kind}(${kindLabelOf(card.kind)})`)
|
|
863
|
+
lines.push(`role: ${card.role === '' ? '未知' : card.role}`)
|
|
864
|
+
lines.push(`turn: ${card.turn === null ? '未知' : String(card.turn)}`)
|
|
865
|
+
lines.push(`tokens: ${card.tokens === null ? '未知' : String(card.tokens)}`)
|
|
866
|
+
lines.push(`unitCount: ${card.unitCount === null ? '未知' : String(card.unitCount)}`)
|
|
867
|
+
lines.push(`工具: ${card.toolNames.length === 0 ? '(无)' : card.toolNames.join(', ')}`)
|
|
868
|
+
lines.push(`首条用户请求: ${card.firstUserRequest === true ? '是(这张卡包含项目整体指示,必须 important)' : '否'}`)
|
|
869
|
+
lines.push(`包含用户请求: ${card.hasUserRequest === true ? '是' : '否'}`)
|
|
870
|
+
if (card.title !== '') lines.push(`已有标题: ${card.title}`)
|
|
871
|
+
lines.push('内容预览:')
|
|
872
|
+
lines.push(card.preview === '' ? '(无预览内容)' : card.preview)
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
lines.push('')
|
|
876
|
+
lines.push(`请现在输出包含 ${normalized.length} 个元素的 JSON 数组,元素顺序与上面的卡片顺序一致,id 必须完全一致:`)
|
|
877
|
+
return lines.join('\n')
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/* -------------------------------------------------------------------------- */
|
|
881
|
+
/* 解析模型输出 */
|
|
882
|
+
/* -------------------------------------------------------------------------- */
|
|
883
|
+
|
|
884
|
+
/**
|
|
885
|
+
* 归一化字段名:大小写、空格、下划线、连字符都不敏感。
|
|
886
|
+
* @param {string} key - 原始字段名。
|
|
887
|
+
* @returns {string} 归一化后的字段名。
|
|
888
|
+
*/
|
|
889
|
+
function normalizeFieldKey(key) {
|
|
890
|
+
return String(key).toLowerCase().replace(/[\s_-]+/gu, '')
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* 按别名读取条目字段(大小写不敏感;取第一个命中的别名)。
|
|
895
|
+
* @param {Record<string, unknown>} record - 模型输出的一条结果。
|
|
896
|
+
* @param {string[]} keys - 字段别名(优先顺序)。
|
|
897
|
+
* @returns {unknown} 字段值。
|
|
898
|
+
*/
|
|
899
|
+
function readFieldValue(record, keys) {
|
|
900
|
+
const normalized = new Map()
|
|
901
|
+
for (const [key, value] of Object.entries(record)) {
|
|
902
|
+
const canonical = normalizeFieldKey(key)
|
|
903
|
+
if (!normalized.has(canonical)) normalized.set(canonical, value)
|
|
904
|
+
}
|
|
905
|
+
for (const key of keys) {
|
|
906
|
+
const canonical = normalizeFieldKey(key)
|
|
907
|
+
if (normalized.has(canonical)) return normalized.get(canonical)
|
|
908
|
+
}
|
|
909
|
+
return undefined
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/**
|
|
913
|
+
* 读取条目 id(字符串化;缺失返回空串)。
|
|
914
|
+
* @param {Record<string, unknown>} record - 模型输出的一条结果。
|
|
915
|
+
* @returns {string} id。
|
|
916
|
+
*/
|
|
917
|
+
function readEntryId(record) {
|
|
918
|
+
const value = readFieldValue(record, ID_KEYS)
|
|
919
|
+
if (typeof value === 'string') return value.trim()
|
|
920
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(Math.round(value))
|
|
921
|
+
return ''
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/**
|
|
925
|
+
* 读取并清洗条目里的 title/summary:折叠空白 + 按 code point 截断;空值返回空串。
|
|
926
|
+
* @param {Record<string, unknown>} record - 模型输出的一条结果。
|
|
927
|
+
* @param {string[]} keys - 字段别名。
|
|
928
|
+
* @param {number} maxChars - 字符上限。
|
|
929
|
+
* @returns {string} 清洗后的文本。
|
|
930
|
+
*/
|
|
931
|
+
function readEntryText(record, keys, maxChars) {
|
|
932
|
+
const value = readFieldValue(record, keys)
|
|
933
|
+
if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') return ''
|
|
934
|
+
const text = cleanInline(String(value))
|
|
935
|
+
if (text === '') return ''
|
|
936
|
+
return truncateCodePoints(text, maxChars)
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* 把模型给的分类映射到合法 id:非法值一律降级为 'other';中文分类名也能接住。
|
|
941
|
+
* @param {unknown} value - 模型输出里的 category。
|
|
942
|
+
* @returns {string} 合法分类 id。
|
|
943
|
+
*/
|
|
944
|
+
function normalizeCategoryId(value) {
|
|
945
|
+
if (typeof value !== 'string') return 'other'
|
|
946
|
+
const text = value.trim()
|
|
947
|
+
if (text === '') return 'other'
|
|
948
|
+
const lower = text.toLowerCase()
|
|
949
|
+
if (CATEGORY_ID_SET.has(lower)) return lower
|
|
950
|
+
if (CATEGORY_ID_BY_LABEL.has(text)) return CATEGORY_ID_BY_LABEL.get(text)
|
|
951
|
+
const compact = lower.replace(/[\s_-]+/gu, '')
|
|
952
|
+
if (CATEGORY_ID_SET.has(compact)) return compact
|
|
953
|
+
if (CATEGORY_ALIASES.has(compact)) return CATEGORY_ALIASES.get(compact)
|
|
954
|
+
return 'other'
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* 把模型给的 importance 映射到合法 id:非法值一律降级为 'keep';中文/同义写法也能接住。
|
|
959
|
+
* @param {unknown} value - 模型输出里的 importance。
|
|
960
|
+
* @returns {'important' | 'keep' | 'noisy'} 合法 importance。
|
|
961
|
+
*/
|
|
962
|
+
function normalizeImportance(value) {
|
|
963
|
+
if (typeof value !== 'string') return 'keep'
|
|
964
|
+
const text = value.trim()
|
|
965
|
+
if (text === '') return 'keep'
|
|
966
|
+
const lower = text.toLowerCase()
|
|
967
|
+
if (IMPORTANCE_ID_SET.has(lower)) return lower
|
|
968
|
+
if (IMPORTANCE_ID_BY_LABEL.has(text)) return IMPORTANCE_ID_BY_LABEL.get(text)
|
|
969
|
+
if (IMPORTANCE_ALIASES.has(lower)) return IMPORTANCE_ALIASES.get(lower)
|
|
970
|
+
return 'keep'
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
/**
|
|
974
|
+
* 把模型给的 importanceKind 映射到合法 id:非法/缺失 → null(由上层用 fallback 或
|
|
975
|
+
* 按 importance 推断,绝不抛错)。大小写、下划线、中文标签都能接住。
|
|
976
|
+
* @param {unknown} value - 模型输出里的 importanceKind。
|
|
977
|
+
* @returns {string | null} 合法种类 id 或 null。
|
|
978
|
+
*/
|
|
979
|
+
function normalizeImportanceKind(value) {
|
|
980
|
+
if (typeof value !== 'string') return null
|
|
981
|
+
const text = value.trim()
|
|
982
|
+
if (text === '') return null
|
|
983
|
+
const lower = text.toLowerCase()
|
|
984
|
+
if (IMPORTANCE_KIND_SET.has(lower)) return lower
|
|
985
|
+
if (IMPORTANCE_KIND_ID_BY_LABEL.has(text)) return IMPORTANCE_KIND_ID_BY_LABEL.get(text)
|
|
986
|
+
const compact = lower.replace(/[\s_-]+/gu, '')
|
|
987
|
+
if (IMPORTANCE_KIND_SET.has(compact)) return compact
|
|
988
|
+
return null
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
/**
|
|
992
|
+
* 把模型给的 importanceReason 归一化:折叠空白 + 按 code point 截断到 24 字;
|
|
993
|
+
* 非法/空 → 空串(由上层补默认 reason)。
|
|
994
|
+
* @param {unknown} value - 模型输出里的 importanceReason。
|
|
995
|
+
* @returns {string} 清洗后的短理由(可能为空串)。
|
|
996
|
+
*/
|
|
997
|
+
function normalizeImportanceReason(value) {
|
|
998
|
+
if (typeof value !== 'string') return ''
|
|
999
|
+
return truncateCodePoints(cleanInline(value), IMPORTANCE_REASON_MAX_CHARS)
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/**
|
|
1003
|
+
* 按 importance 反推一个兜底种类(只有 AI 缺失 kind 且拿不到卡片上下文时才会用到)。
|
|
1004
|
+
* @param {'important'|'keep'|'noisy'} importance - 已归一化的重要度。
|
|
1005
|
+
* @returns {string} 合法 kind。
|
|
1006
|
+
*/
|
|
1007
|
+
function inferImportanceKindFromImportance(importance) {
|
|
1008
|
+
if (importance === 'noisy') return 'noise'
|
|
1009
|
+
if (importance === 'important') return 'feedback'
|
|
1010
|
+
return 'process'
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* AI 没给合法 importanceKind 时的推断:优先信任 fallback 给出的「有信息量」种类;
|
|
1015
|
+
* 若 fallback 只能给出默认的 process,则按 AI 的 importance 反推,避免把 AI 明确
|
|
1016
|
+
* 判为 important 的信息降级:important → feedback(feedback 允许 important),
|
|
1017
|
+
* noisy → noise。
|
|
1018
|
+
* @param {'important'|'keep'|'noisy'} importance - AI 给的重要度(已归一化)。
|
|
1019
|
+
* @param {string} fallbackKind - 确定性兜底推断出的种类。
|
|
1020
|
+
* @returns {string} 推断出的合法种类。
|
|
1021
|
+
*/
|
|
1022
|
+
function inferImportanceKindForAi(importance, fallbackKind) {
|
|
1023
|
+
if (fallbackKind !== 'process') return fallbackKind
|
|
1024
|
+
if (importance === 'important') return 'feedback'
|
|
1025
|
+
if (importance === 'noisy') return 'noise'
|
|
1026
|
+
return 'process'
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* 让 importance 与 importanceKind 满足硬规则(与宿主 actions.js 的 enrich 逻辑一致):
|
|
1031
|
+
* - 重要种类(directive/constraint/architecture/decision/deliverable)→ 必须 important;
|
|
1032
|
+
* - feedback → 不得 noisy(降级 keep);
|
|
1033
|
+
* - process/tool/noise → 不得 important(降级 keep)。
|
|
1034
|
+
* @param {unknown} importance - 模型给的重要度(可非法)。
|
|
1035
|
+
* @param {string | null} kind - 已归一化的种类。
|
|
1036
|
+
* @returns {'important'|'keep'|'noisy'} 修正后的重要度。
|
|
1037
|
+
*/
|
|
1038
|
+
function reconcileImportance(importance, kind) {
|
|
1039
|
+
const normalized = normalizeImportance(importance)
|
|
1040
|
+
if (kind === null || kind === undefined) return normalized
|
|
1041
|
+
if (IMPORTANT_KINDS.has(kind)) return 'important'
|
|
1042
|
+
if (kind === 'feedback') return normalized === 'noisy' ? 'keep' : normalized
|
|
1043
|
+
return normalized === 'important' ? 'keep' : normalized
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* 去掉 JSON 里「对象/数组末尾多余的逗号」(字符串内部的逗号不动)。
|
|
1048
|
+
* 模型偶尔会输出 `[{"id":"a",},]` 这种非标准 JSON。
|
|
1049
|
+
* @param {string} text - 原始 JSON 文本。
|
|
1050
|
+
* @returns {string} 修复后的文本。
|
|
1051
|
+
*/
|
|
1052
|
+
function stripTrailingCommas(text) {
|
|
1053
|
+
let out = ''
|
|
1054
|
+
let inString = false
|
|
1055
|
+
let escaped = false
|
|
1056
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
1057
|
+
const char = text[index]
|
|
1058
|
+
if (inString) {
|
|
1059
|
+
out += char
|
|
1060
|
+
if (escaped) escaped = false
|
|
1061
|
+
else if (char === '\\') escaped = true
|
|
1062
|
+
else if (char === '"') inString = false
|
|
1063
|
+
continue
|
|
1064
|
+
}
|
|
1065
|
+
if (char === '"') {
|
|
1066
|
+
inString = true
|
|
1067
|
+
out += char
|
|
1068
|
+
continue
|
|
1069
|
+
}
|
|
1070
|
+
if (char === ',') {
|
|
1071
|
+
let next = index + 1
|
|
1072
|
+
while (next < text.length && /\s/u.test(text[next])) next += 1
|
|
1073
|
+
if (text[next] === ']' || text[next] === '}') continue
|
|
1074
|
+
}
|
|
1075
|
+
out += char
|
|
1076
|
+
}
|
|
1077
|
+
return out
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/**
|
|
1081
|
+
* 单次 JSON.parse(失败则试一次「去掉尾逗号」的修复版)。
|
|
1082
|
+
* @param {string} candidate - JSON 候选文本。
|
|
1083
|
+
* @returns {unknown} 解析结果;失败返回 undefined。
|
|
1084
|
+
*/
|
|
1085
|
+
function tryParseJson(candidate) {
|
|
1086
|
+
try {
|
|
1087
|
+
return JSON.parse(candidate)
|
|
1088
|
+
} catch {
|
|
1089
|
+
/* 继续尝试修复版 */
|
|
1090
|
+
}
|
|
1091
|
+
try {
|
|
1092
|
+
return JSON.parse(stripTrailingCommas(candidate))
|
|
1093
|
+
} catch {
|
|
1094
|
+
return undefined
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* 判断一个对象是否「像一条分析结果」(用于接住裸对象的单条输出)。
|
|
1100
|
+
* @param {Record<string, unknown>} record - 候选对象。
|
|
1101
|
+
* @returns {boolean} 判断结果。
|
|
1102
|
+
*/
|
|
1103
|
+
function looksLikeAnalysisEntry(record) {
|
|
1104
|
+
return readEntryId(record) !== '' || readFieldValue(record, TITLE_KEYS) !== undefined
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/**
|
|
1108
|
+
* 把解析出来的 JSON 值强制拉平成「结果数组」:数组直接用;对象则找 results 之类的
|
|
1109
|
+
* 包装数组,或把单条结果对象包成数组;都不是就返回 null。
|
|
1110
|
+
* @param {unknown} parsed - JSON.parse 的结果。
|
|
1111
|
+
* @param {number} [depth] - 递归深度(防御异常嵌套)。
|
|
1112
|
+
* @returns {unknown[] | null} 结果数组或 null。
|
|
1113
|
+
*/
|
|
1114
|
+
function coerceItems(parsed, depth = 0) {
|
|
1115
|
+
if (Array.isArray(parsed)) return parsed
|
|
1116
|
+
if (!isRecord(parsed)) return null
|
|
1117
|
+
for (const key of RESULT_ARRAY_KEYS) {
|
|
1118
|
+
const value = parsed[key]
|
|
1119
|
+
if (Array.isArray(value)) return value
|
|
1120
|
+
}
|
|
1121
|
+
for (const value of Object.values(parsed)) {
|
|
1122
|
+
if (Array.isArray(value) && value.length > 0) return value
|
|
1123
|
+
}
|
|
1124
|
+
if (depth < 3) {
|
|
1125
|
+
for (const value of Object.values(parsed)) {
|
|
1126
|
+
if (isRecord(value)) {
|
|
1127
|
+
const nested = coerceItems(value, depth + 1)
|
|
1128
|
+
if (nested !== null) return nested
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
if (looksLikeAnalysisEntry(parsed)) return [parsed]
|
|
1133
|
+
return null
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/**
|
|
1137
|
+
* 从模型输出里提取结果数组:容忍 ```json 围栏、前后解释文字、对象包装、单对象。
|
|
1138
|
+
* @param {unknown} text - 模型原始输出。
|
|
1139
|
+
* @returns {unknown[] | null} 结果数组或 null(完全解析不出来)。
|
|
1140
|
+
*/
|
|
1141
|
+
function extractAnalyses(text) {
|
|
1142
|
+
if (typeof text !== 'string') return null
|
|
1143
|
+
const cleaned = text.replace(/^\uFEFF/u, '').trim()
|
|
1144
|
+
if (cleaned === '') return null
|
|
1145
|
+
|
|
1146
|
+
const candidates = [cleaned]
|
|
1147
|
+
|
|
1148
|
+
// 1) Markdown 代码围栏(```json / ``` 都认)。
|
|
1149
|
+
const fencePattern = /```[^\n`]*\n?([\s\S]*?)```/gu
|
|
1150
|
+
let match
|
|
1151
|
+
while ((match = fencePattern.exec(cleaned)) !== null) {
|
|
1152
|
+
const body = match[1].trim()
|
|
1153
|
+
if (body !== '') candidates.push(body)
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
// 2) 前后带解释文字:截取第一个 '[' 到最后一个 ']',或第一个 '{' 到最后一个 '}'。
|
|
1157
|
+
const arrayStart = cleaned.indexOf('[')
|
|
1158
|
+
const arrayEnd = cleaned.lastIndexOf(']')
|
|
1159
|
+
if (arrayStart >= 0 && arrayEnd > arrayStart) candidates.push(cleaned.slice(arrayStart, arrayEnd + 1))
|
|
1160
|
+
const objectStart = cleaned.indexOf('{')
|
|
1161
|
+
const objectEnd = cleaned.lastIndexOf('}')
|
|
1162
|
+
if (objectStart >= 0 && objectEnd > objectStart) candidates.push(cleaned.slice(objectStart, objectEnd + 1))
|
|
1163
|
+
|
|
1164
|
+
for (const candidate of candidates) {
|
|
1165
|
+
const items = coerceItems(tryParseJson(candidate))
|
|
1166
|
+
if (items !== null) return items
|
|
1167
|
+
}
|
|
1168
|
+
// 5) 输在被 maxTokens 截断时(数组没闭合):逐个抢救完整的 {...} 对象,
|
|
1169
|
+
// 至少保住已完整生成的那部分卡片,剩余由调用方兜底。
|
|
1170
|
+
const salvaged = salvageCompleteObjects(cleaned)
|
|
1171
|
+
if (salvaged.length > 0) return salvaged
|
|
1172
|
+
return null
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
/**
|
|
1176
|
+
* 从可能被截断的文本里抢救完整的 JSON 对象(按括号配平、跳过字符串内部)。
|
|
1177
|
+
* @param {string} text - 模型原始输出。
|
|
1178
|
+
* @returns {unknown[]} 可解析的对象数组(保持出现顺序)。
|
|
1179
|
+
*/
|
|
1180
|
+
function salvageCompleteObjects(text) {
|
|
1181
|
+
const objects = []
|
|
1182
|
+
let depth = 0
|
|
1183
|
+
let start = -1
|
|
1184
|
+
let inString = false
|
|
1185
|
+
let escaped = false
|
|
1186
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
1187
|
+
const char = text[index]
|
|
1188
|
+
if (inString) {
|
|
1189
|
+
if (escaped) escaped = false
|
|
1190
|
+
else if (char === '\\') escaped = true
|
|
1191
|
+
else if (char === '"') inString = false
|
|
1192
|
+
continue
|
|
1193
|
+
}
|
|
1194
|
+
if (char === '"') {
|
|
1195
|
+
inString = true
|
|
1196
|
+
continue
|
|
1197
|
+
}
|
|
1198
|
+
if (char === '{') {
|
|
1199
|
+
if (depth === 0) start = index
|
|
1200
|
+
depth += 1
|
|
1201
|
+
continue
|
|
1202
|
+
}
|
|
1203
|
+
if (char === '}') {
|
|
1204
|
+
if (depth === 0) continue
|
|
1205
|
+
depth -= 1
|
|
1206
|
+
if (depth === 0 && start >= 0) {
|
|
1207
|
+
const parsed = tryParseJson(text.slice(start, index + 1))
|
|
1208
|
+
if (isRecord(parsed)) objects.push(parsed)
|
|
1209
|
+
start = -1
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
return objects
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
/**
|
|
1217
|
+
* 解析模型输出,得到「有效结果 + 需要兜底的 id 列表」。
|
|
1218
|
+
*
|
|
1219
|
+
* 容错规则:
|
|
1220
|
+
* - 裸 JSON 数组、```json 围栏、前后解释文字、{ results: [...] } 包装、单对象都能解析;
|
|
1221
|
+
* - 字段名大小写/下划线/连字符不敏感;
|
|
1222
|
+
* - category 非法 → 'other';importance 非法/缺失 → 'keep';
|
|
1223
|
+
* - importanceKind 非法/缺失 → null(由上层用 fallback 或按 importance 推断);
|
|
1224
|
+
* - importanceReason 非法/空 → '',超长截断到 24 个字符;
|
|
1225
|
+
* - title 截断到 14 个字符、summary 截断到 48 个字符(按 code point);
|
|
1226
|
+
* - 换行/多余空白折叠成单个空格;
|
|
1227
|
+
* - title 或 summary 为空 → 该条目无效(对应 id 进 invalid,由调用方兜底);
|
|
1228
|
+
* - 未知 id、重复 id → 忽略;
|
|
1229
|
+
* - expectedIds 里没拿到有效结果的 id → 进 invalid(顺序与 expectedIds 一致)。
|
|
1230
|
+
*
|
|
1231
|
+
* 注意:这里不修正 importance 与 importanceKind 的一致性(上层 buildAnalysisEntry /
|
|
1232
|
+
* 宿主 enrich 会按硬规则统一修正),只负责容错解析。
|
|
1233
|
+
*
|
|
1234
|
+
* @param {unknown} text - 模型原始输出。
|
|
1235
|
+
* @param {unknown} expectedIds - 本批期望出现的卡片 id 数组。
|
|
1236
|
+
* @returns {{ results: Array<{ id: string, category: string, title: string, summary: string, importance: 'important'|'keep'|'noisy', importanceKind: string | null, importanceReason: string }>, invalid: string[] }}
|
|
1237
|
+
*/
|
|
1238
|
+
export function parseScanResponse(text, expectedIds) {
|
|
1239
|
+
const expected = Array.isArray(expectedIds)
|
|
1240
|
+
? [...new Set(expectedIds
|
|
1241
|
+
.map(value => (typeof value === 'string' ? value.trim() : (typeof value === 'number' ? String(value) : '')))
|
|
1242
|
+
.filter(id => id !== ''))]
|
|
1243
|
+
: []
|
|
1244
|
+
const expectedSet = new Set(expected)
|
|
1245
|
+
const results = []
|
|
1246
|
+
const accepted = new Set()
|
|
1247
|
+
const items = extractAnalyses(text)
|
|
1248
|
+
|
|
1249
|
+
if (items !== null) {
|
|
1250
|
+
for (const item of items) {
|
|
1251
|
+
if (!isRecord(item)) continue
|
|
1252
|
+
const id = readEntryId(item)
|
|
1253
|
+
if (id === '' || !expectedSet.has(id) || accepted.has(id)) continue
|
|
1254
|
+
const title = readEntryText(item, TITLE_KEYS, TITLE_MAX_CHARS)
|
|
1255
|
+
const summary = readEntryText(item, SUMMARY_KEYS, SUMMARY_MAX_CHARS)
|
|
1256
|
+
if (title === '' || summary === '') continue
|
|
1257
|
+
accepted.add(id)
|
|
1258
|
+
results.push({
|
|
1259
|
+
id,
|
|
1260
|
+
category: normalizeCategoryId(readFieldValue(item, CATEGORY_KEYS)),
|
|
1261
|
+
title,
|
|
1262
|
+
summary,
|
|
1263
|
+
importance: normalizeImportance(readFieldValue(item, IMPORTANCE_KEYS)),
|
|
1264
|
+
importanceKind: normalizeImportanceKind(readFieldValue(item, IMPORTANCE_KIND_KEYS)),
|
|
1265
|
+
importanceReason: normalizeImportanceReason(readFieldValue(item, IMPORTANCE_REASON_KEYS)),
|
|
1266
|
+
})
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
return { results, invalid: expected.filter(id => !accepted.has(id)) }
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/* -------------------------------------------------------------------------- */
|
|
1274
|
+
/* 确定性兜底 */
|
|
1275
|
+
/* -------------------------------------------------------------------------- */
|
|
1276
|
+
|
|
1277
|
+
/**
|
|
1278
|
+
* 判断卡片是不是「工具类」(role=tool 或 kind 以 tool 开头)。
|
|
1279
|
+
* @param {{ kind: string, role: string }} card - 归一化后的卡片。
|
|
1280
|
+
* @returns {boolean} 判断结果。
|
|
1281
|
+
*/
|
|
1282
|
+
function isToolCard(card) {
|
|
1283
|
+
return card.role === 'tool' || (typeof card.kind === 'string' && card.kind.startsWith('tool'))
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
/**
|
|
1287
|
+
* 取文本里第一行有意义的内容(跳过空行、代码围栏、Markdown 装饰)。
|
|
1288
|
+
* @param {string} text - 文本。
|
|
1289
|
+
* @returns {string} 第一行有效内容(可能为空串)。
|
|
1290
|
+
*/
|
|
1291
|
+
function firstMeaningfulLine(text) {
|
|
1292
|
+
if (typeof text !== 'string' || text.trim() === '') return ''
|
|
1293
|
+
for (const rawLine of text.split(/\r?\n/u)) {
|
|
1294
|
+
let line = rawLine.trim()
|
|
1295
|
+
if (line === '') continue
|
|
1296
|
+
line = line.replace(/^`{3,}.*$/u, '').trim()
|
|
1297
|
+
if (line === '') continue
|
|
1298
|
+
line = line.replace(/^#{1,6}\s*/u, '')
|
|
1299
|
+
line = line.replace(/^[-*+>]\s+/u, '')
|
|
1300
|
+
line = line.replace(/^\d+[.)]\s+/u, '')
|
|
1301
|
+
line = line.replace(/[*_`~]+/gu, '')
|
|
1302
|
+
line = cleanInline(line)
|
|
1303
|
+
if (line !== '') return line
|
|
1304
|
+
}
|
|
1305
|
+
return ''
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
/**
|
|
1309
|
+
* 兜底分类:按工具 / 关键词 / role 的优先级给一个合理分类。
|
|
1310
|
+
* @param {{ kind: string, role: string, toolNames: string[] }} card - 归一化后的卡片。
|
|
1311
|
+
* @param {string} text - 预览文本(已去掉截断标记)。
|
|
1312
|
+
* @returns {string} 合法分类 id。
|
|
1313
|
+
*/
|
|
1314
|
+
function classifyFallback(card, text) {
|
|
1315
|
+
const probe = `${text} ${card.toolNames.join(' ')}`
|
|
1316
|
+
if (isToolCard(card)) return 'tooling'
|
|
1317
|
+
if (isPureConfirmationText(text)) return 'noise'
|
|
1318
|
+
if (ERROR_PATTERN.test(probe)) return 'error'
|
|
1319
|
+
if (VERIFY_PATTERN.test(probe)) return 'verify'
|
|
1320
|
+
if (CODE_PATTERN.test(probe)) return 'code'
|
|
1321
|
+
if (RESEARCH_PATTERN.test(probe)) return 'research'
|
|
1322
|
+
if (DECISION_PATTERN.test(probe)) return 'decision'
|
|
1323
|
+
if (card.kind === 'user' || card.role === 'user') return 'goal'
|
|
1324
|
+
if (card.kind === 'developer' || card.kind === 'system' || card.role === 'developer' || card.role === 'system') {
|
|
1325
|
+
return 'decision'
|
|
1326
|
+
}
|
|
1327
|
+
if (card.kind === 'context' || card.role === 'context') return 'research'
|
|
1328
|
+
if (card.toolNames.length > 0) return 'tooling'
|
|
1329
|
+
return 'other'
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/**
|
|
1333
|
+
* 兜底标题:优先用卡片自带 title,其次用第一行内容,再次用工具名/分类名。
|
|
1334
|
+
* @param {{ title: string, toolNames: string[] }} card - 归一化后的卡片。
|
|
1335
|
+
* @param {string} text - 预览文本。
|
|
1336
|
+
* @param {string} category - 兜底分类。
|
|
1337
|
+
* @returns {string} 非空标题(≤14 个字符)。
|
|
1338
|
+
*/
|
|
1339
|
+
function deriveFallbackTitle(card, text, category) {
|
|
1340
|
+
const existing = cleanInline(card.title)
|
|
1341
|
+
if (existing !== '') return truncateCodePoints(existing, TITLE_MAX_CHARS)
|
|
1342
|
+
const line = firstMeaningfulLine(text)
|
|
1343
|
+
if (line !== '') return truncateCodePoints(line, TITLE_MAX_CHARS)
|
|
1344
|
+
if (card.toolNames.length > 0) {
|
|
1345
|
+
const tools = truncateCodePoints(card.toolNames.slice(0, 2).join('/'), TITLE_MAX_CHARS)
|
|
1346
|
+
if (tools !== '') return tools
|
|
1347
|
+
}
|
|
1348
|
+
return truncateCodePoints(CATEGORY_LABEL_BY_ID.get(category) ?? '上下文卡片', TITLE_MAX_CHARS) || '上下文卡片'
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
/**
|
|
1352
|
+
* 兜底简介:分类引导语 + 第一行内容摘要,保证非空且不超过 48 个字符。
|
|
1353
|
+
* @param {{ toolNames: string[] }} card - 归一化后的卡片。
|
|
1354
|
+
* @param {string} text - 预览文本。
|
|
1355
|
+
* @param {string} category - 兜底分类。
|
|
1356
|
+
* @returns {string} 非空简介。
|
|
1357
|
+
*/
|
|
1358
|
+
function deriveFallbackSummary(card, text, category) {
|
|
1359
|
+
const lead = SUMMARY_LEAD_BY_CATEGORY[category] ?? SUMMARY_LEAD_BY_CATEGORY.other
|
|
1360
|
+
const excerpt = truncateCodePoints(firstMeaningfulLine(text), 40)
|
|
1361
|
+
let summary
|
|
1362
|
+
if (excerpt !== '') {
|
|
1363
|
+
summary = `${lead}:${excerpt}`
|
|
1364
|
+
} else if (card.toolNames.length > 0) {
|
|
1365
|
+
summary = `${lead}:${card.toolNames.slice(0, 2).join('/')}`
|
|
1366
|
+
} else {
|
|
1367
|
+
summary = lead
|
|
1368
|
+
}
|
|
1369
|
+
return truncateCodePoints(summary, SUMMARY_MAX_CHARS) || lead
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
/**
|
|
1373
|
+
* 兜底 importanceKind 启发式:给每张卡一个「为什么重要 / 为什么可以精简」的种类。
|
|
1374
|
+
*
|
|
1375
|
+
* 优先级从高到低:
|
|
1376
|
+
* 1. 规则提示 firstUserRequest(会话里最早的用户请求 = 项目整体指示)→ directive;
|
|
1377
|
+
* 2. 纯确认/寒暄(整段只有「好的 / 收到 / 谢谢」)→ noise;
|
|
1378
|
+
* 3. 小体量的系统提醒/时间戳(用户卡 / 含用户请求的卡豁免)→ noise;
|
|
1379
|
+
* 4. 关键语义:约束 → constraint;结构/架构 → architecture;决策/方案 → decision;
|
|
1380
|
+
* 交付/验收/结论 → deliverable;
|
|
1381
|
+
* 5. 用户整体指示关键词(需用户请求上下文,避免「运行项目代码」被误判);
|
|
1382
|
+
* 6. 用户请求/反馈 → feedback;
|
|
1383
|
+
* 7. 工具输出/读取结果 → tool;
|
|
1384
|
+
* 8. 其余 → process(分类兜底:goal→feedback、decision→decision、
|
|
1385
|
+
* tooling/research→tool、developer/system→constraint)。
|
|
1386
|
+
*
|
|
1387
|
+
* @param {{ kind: string, role: string, tokens: number | null, toolNames: string[], firstUserRequest: boolean, hasUserRequest: boolean }} card - 归一化卡片。
|
|
1388
|
+
* @param {string} text - 预览文本(已去掉截断标记)。
|
|
1389
|
+
* @param {string} category - 兜底分类。
|
|
1390
|
+
* @returns {string} 合法 importanceKind。
|
|
1391
|
+
*/
|
|
1392
|
+
function deriveFallbackImportanceKind(card, text, category) {
|
|
1393
|
+
const tokens = typeof card.tokens === 'number' && Number.isFinite(card.tokens) ? card.tokens : null
|
|
1394
|
+
const small = tokens !== null && tokens < 120
|
|
1395
|
+
const isUserCard = card.kind === 'user' || card.role === 'user'
|
|
1396
|
+
const hasUserRequest = card.hasUserRequest === true
|
|
1397
|
+
const firstUserRequest = card.firstUserRequest === true
|
|
1398
|
+
// v2 卡片是分组卡(kind=group / role=mixed),因此「用户需求」不能只看 kind=user。
|
|
1399
|
+
const userLike = isUserCard || hasUserRequest || card.kind === 'group' || card.role === 'mixed'
|
|
1400
|
+
const userIntent = text !== '' && USER_REQUEST_PATTERN.test(text)
|
|
1401
|
+
const pureNoise = isPureConfirmationText(text)
|
|
1402
|
+
const explicitNoise = text !== '' && NOISY_SIGNAL_PATTERN.test(text)
|
|
1403
|
+
|
|
1404
|
+
// 1) 规则最高优先级:会话里最早的用户请求 = 项目整体指示。
|
|
1405
|
+
if (firstUserRequest) return 'directive'
|
|
1406
|
+
|
|
1407
|
+
// 2) 纯确认/寒暄(不是真实用户请求)→ noise。
|
|
1408
|
+
if (pureNoise && !hasUserRequest) return 'noise'
|
|
1409
|
+
|
|
1410
|
+
// 3) 明确的系统提醒/时间戳(只在小体量时判噪音);用户卡片 / 请求语义优先。
|
|
1411
|
+
if (small && explicitNoise && !isUserCard && !hasUserRequest && !userIntent) return 'noise'
|
|
1412
|
+
|
|
1413
|
+
// 4) 关键语义:约束 / 结构 / 决策 / 交付。
|
|
1414
|
+
if (text !== '' && CONSTRAINT_KIND_PATTERN.test(text)) return 'constraint'
|
|
1415
|
+
if (text !== '' && ARCHITECTURE_KIND_PATTERN.test(text)) return 'architecture'
|
|
1416
|
+
if (text !== '' && DECISION_KIND_PATTERN.test(text)) return 'decision'
|
|
1417
|
+
if (text !== '' && DELIVERABLE_KIND_PATTERN.test(text)) return 'deliverable'
|
|
1418
|
+
|
|
1419
|
+
// 5) 用户整体指示(必须带用户请求上下文,避免把「运行项目代码」误判成 directive)。
|
|
1420
|
+
if ((hasUserRequest || isUserCard) && text !== '' && DIRECTIVE_KIND_PATTERN.test(text)) return 'directive'
|
|
1421
|
+
|
|
1422
|
+
// 6) 用户请求 / 反馈。
|
|
1423
|
+
if (userLike && userIntent) return 'feedback'
|
|
1424
|
+
if (isUserCard) return 'feedback'
|
|
1425
|
+
|
|
1426
|
+
// 7) 工具输出 / 读取结果 / 命令过程。
|
|
1427
|
+
if (isToolCard(card) || card.toolNames.length > 0 || (text !== '' && TOOL_KIND_PATTERN.test(text))) return 'tool'
|
|
1428
|
+
|
|
1429
|
+
// 8) 分类兜底(含用户请求的卡仍遵守「用户请求不得 noisy」总则)。
|
|
1430
|
+
if (category === 'noise' && !hasUserRequest) return 'noise'
|
|
1431
|
+
if (category === 'goal') return 'feedback'
|
|
1432
|
+
if (category === 'decision') return 'decision'
|
|
1433
|
+
if (category === 'tooling' || category === 'research') return 'tool'
|
|
1434
|
+
if (card.kind === 'developer' || card.kind === 'system' || card.role === 'developer' || card.role === 'system') {
|
|
1435
|
+
return 'constraint'
|
|
1436
|
+
}
|
|
1437
|
+
return 'process'
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
/**
|
|
1441
|
+
* 兜底 importance:与 importanceKind 保持一致性硬规则。
|
|
1442
|
+
* @param {string} kind - 已确定的重要性种类。
|
|
1443
|
+
* @param {{ hasUserRequest: boolean }} card - 归一化卡片。
|
|
1444
|
+
* @param {string} text - 预览文本。
|
|
1445
|
+
* @param {string} category - 兜底分类。
|
|
1446
|
+
* @returns {'important'|'keep'|'noisy'} 兜底 importance。
|
|
1447
|
+
*/
|
|
1448
|
+
function deriveFallbackImportance(kind, card, text, category) {
|
|
1449
|
+
if (IMPORTANT_KINDS.has(kind)) return 'important'
|
|
1450
|
+
if (kind === 'noise') return 'noisy'
|
|
1451
|
+
if (kind === 'process' || kind === 'tool') return 'keep'
|
|
1452
|
+
if (kind === 'feedback') {
|
|
1453
|
+
// 用户需求/反馈:含需求/约束/目标等关键词或分类为 goal 时判 important,其余 keep。
|
|
1454
|
+
const structural = text !== '' && IMPORTANT_HINT_PATTERN.test(text)
|
|
1455
|
+
return structural || category === 'goal' ? 'important' : 'keep'
|
|
1456
|
+
}
|
|
1457
|
+
return 'keep'
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
/**
|
|
1461
|
+
* 转义正则元字符(拼接动态正则时使用)。
|
|
1462
|
+
* @param {string} text - 原文。
|
|
1463
|
+
* @returns {string} 转义后文本。
|
|
1464
|
+
*/
|
|
1465
|
+
function escapeRegExp(text) {
|
|
1466
|
+
return String(text).replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')
|
|
1467
|
+
}
|
|
1468
|
+
|
|
1469
|
+
/**
|
|
1470
|
+
* 兜底 importanceReason:给一句 ≤24 字的中文理由,关键种类尽量带上原文摘要。
|
|
1471
|
+
* @param {string} kind - 重要性种类。
|
|
1472
|
+
* @param {string} text - 预览文本。
|
|
1473
|
+
* @returns {string} 非空短理由。
|
|
1474
|
+
*/
|
|
1475
|
+
function deriveFallbackImportanceReason(kind, text, title) {
|
|
1476
|
+
// 纯确认/寒暄:给出明确、可读的丢弃理由(不写通用「无用元信息」)。
|
|
1477
|
+
if (kind === 'noise' && isPureConfirmationText(text)) return '纯确认,可精简'
|
|
1478
|
+
const base = KIND_REASON[kind] ?? '上下文片段'
|
|
1479
|
+
if ((kind === 'constraint' || kind === 'architecture' || kind === 'decision' || kind === 'deliverable') && text !== '') {
|
|
1480
|
+
const prefix = base.split(/[\/或]/u)[0] || base
|
|
1481
|
+
// ① 原文里常自带「关键约束:历史不丢可恢复」这类短语:直接抽取标签后的内容,
|
|
1482
|
+
// 比取第一行摘要更精确(也避免「关键约束:用户要求……关键约束:……」)。
|
|
1483
|
+
try {
|
|
1484
|
+
const labelPattern = new RegExp(`${escapeRegExp(prefix)}[::]\\s*([^。;;,,]{2,40})`, 'u')
|
|
1485
|
+
const labeled = labelPattern.exec(text)
|
|
1486
|
+
if (labeled !== null && labeled[1] !== undefined) {
|
|
1487
|
+
const body = truncateCodePoints(cleanInline(labeled[1]), 12)
|
|
1488
|
+
if (body !== '') return truncateCodePoints(`${prefix}:${body}`, IMPORTANCE_REASON_MAX_CHARS) || base
|
|
1489
|
+
}
|
|
1490
|
+
} catch {
|
|
1491
|
+
/* 正则构造失败时退回普通摘要 */
|
|
1492
|
+
}
|
|
1493
|
+
// ② 没有显式标签:取第一行、剥掉开头同类标签后拼摘要。
|
|
1494
|
+
const line = firstMeaningfulLine(text)
|
|
1495
|
+
if (line !== '') {
|
|
1496
|
+
let body = line
|
|
1497
|
+
for (const label of [prefix, base]) {
|
|
1498
|
+
if (body.startsWith(label)) {
|
|
1499
|
+
body = body.slice(label.length).replace(/^[::,,。\s]+/u, '')
|
|
1500
|
+
break
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
body = truncateCodePoints(body, 12)
|
|
1504
|
+
if (body !== '') return truncateCodePoints(`${prefix}:${body}`, IMPORTANCE_REASON_MAX_CHARS) || base
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
// 兜底理由也必须具体:引用卡片标题,而不是「实现过程,可精简」这类通用文案。
|
|
1508
|
+
return buildSpecificReason(kind, title, base)
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
/**
|
|
1512
|
+
* 判断 importanceReason 是否是通用/模板化文案(没有引用任何任务或对象)。
|
|
1513
|
+
* @param {string} reason - 理由文本。
|
|
1514
|
+
* @returns {boolean} 是否通用/为空/过短。
|
|
1515
|
+
*/
|
|
1516
|
+
function isGenericReason(reason) {
|
|
1517
|
+
const text = normalizeImportanceReason(reason)
|
|
1518
|
+
if (text === '') return true
|
|
1519
|
+
if (GENERIC_REASONS.has(text)) return true
|
|
1520
|
+
return Array.from(text).length < 6
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
/**
|
|
1524
|
+
* 生成具体理由:`{种类前缀}:{title}`(按 code point 截断到 24 字)。
|
|
1525
|
+
* 标题为空时退回给定的兜底理由 / 种类默认理由。
|
|
1526
|
+
* @param {string} kind - 重要性种类。
|
|
1527
|
+
* @param {string} title - 卡片标题。
|
|
1528
|
+
* @param {string} [fallbackReason] - 兜底理由。
|
|
1529
|
+
* @returns {string} 非空的具体理由。
|
|
1530
|
+
*/
|
|
1531
|
+
function buildSpecificReason(kind, title, fallbackReason) {
|
|
1532
|
+
const prefix = REASON_PREFIX_BY_KIND[kind] ?? '上下文'
|
|
1533
|
+
const subject = truncateCodePoints(cleanInline(title), 16)
|
|
1534
|
+
if (subject !== '') return truncateCodePoints(`${prefix}:${subject}`, IMPORTANCE_REASON_MAX_CHARS) || prefix
|
|
1535
|
+
const fallback = truncateCodePoints(cleanInline(fallbackReason), IMPORTANCE_REASON_MAX_CHARS)
|
|
1536
|
+
if (fallback !== '') return fallback
|
|
1537
|
+
return truncateCodePoints(KIND_REASON[kind] ?? '上下文片段', IMPORTANCE_REASON_MAX_CHARS) || '上下文片段'
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
/**
|
|
1541
|
+
* v13 确定性后处理(解析后、写 entry 前):
|
|
1542
|
+
*
|
|
1543
|
+
* 1) 交付/验证结论强特征(全绿/验收/交付/已安装生效/测试通过/完成汇报/交付总结/
|
|
1544
|
+
* 验收报告/结论:)且 kind 是 process/tool → 提升为 deliverable/important,
|
|
1545
|
+
* reason 至少「交付结论:{title}」;
|
|
1546
|
+
* 2) 过程强特征(等待/调度/读取/修改/检索/探索…)且 kind=deliverable → 降回
|
|
1547
|
+
* process/keep,防止“过程卡被误升为交付结论”;
|
|
1548
|
+
* 3) 理由具体化:通用/模板化 reason(如「实现过程,可精简」)替换为
|
|
1549
|
+
* 「{种类前缀}:{title}」,满足 v4.1「必须引用任务/对象」的要求。
|
|
1550
|
+
*
|
|
1551
|
+
* 说明:先按 1) 提升、再按 2) 降级 —— 若一段文本同时命中交付与过程特征,最终
|
|
1552
|
+
* 以“过程”为准(任务书要求过程强特征不得被误升)。
|
|
1553
|
+
*
|
|
1554
|
+
* @param {{ category: string, title: string, summary: string, importance: string, importanceKind: string, importanceReason: string }} analysis - 已补齐的分析。
|
|
1555
|
+
* @returns {{ category: string, title: string, summary: string, importance: string, importanceKind: string, importanceReason: string }} 后处理后的分析。
|
|
1556
|
+
*/
|
|
1557
|
+
function postprocessDeliveryAnalysis(analysis) {
|
|
1558
|
+
const title = typeof analysis.title === 'string' ? analysis.title : ''
|
|
1559
|
+
const summary = typeof analysis.summary === 'string' ? analysis.summary : ''
|
|
1560
|
+
const text = `${title} ${summary}`
|
|
1561
|
+
const hasDeliverable = DELIVERABLE_STRONG_PATTERN.test(text)
|
|
1562
|
+
const hasProcess = PROCESS_STRONG_PATTERN.test(text)
|
|
1563
|
+
let importanceKind = normalizeImportanceKind(analysis.importanceKind) ?? 'process'
|
|
1564
|
+
let importance = normalizeImportance(analysis.importance)
|
|
1565
|
+
let importanceReason = normalizeImportanceReason(analysis.importanceReason)
|
|
1566
|
+
|
|
1567
|
+
// 1) 交付/验证结论文本:即使叙述像过程,也提升为 deliverable。
|
|
1568
|
+
if ((importanceKind === 'process' || importanceKind === 'tool') && hasDeliverable) {
|
|
1569
|
+
importanceKind = 'deliverable'
|
|
1570
|
+
importance = 'important'
|
|
1571
|
+
const subject = truncateCodePoints(cleanInline(title), 16)
|
|
1572
|
+
importanceReason = subject === '' ? '交付结论' : `交付结论:${subject}`
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
// 2) 防误升:kind 已是 deliverable,但 title/summary 明显是等待/调度/读取/修改/
|
|
1576
|
+
// 检索/探索过程 → 降回 process/keep。
|
|
1577
|
+
if (importanceKind === 'deliverable' && hasProcess) {
|
|
1578
|
+
importanceKind = 'process'
|
|
1579
|
+
importance = 'keep'
|
|
1580
|
+
importanceReason = buildSpecificReason('process', title, importanceReason)
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
// 3) 理由必须具体:通用模板/空理由 → 「{种类前缀}:{title}」。
|
|
1584
|
+
if (isGenericReason(importanceReason)) {
|
|
1585
|
+
importanceReason = buildSpecificReason(importanceKind, title, importanceReason)
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
return {
|
|
1589
|
+
category: analysis.category,
|
|
1590
|
+
title,
|
|
1591
|
+
summary,
|
|
1592
|
+
importance: reconcileImportance(importance, importanceKind),
|
|
1593
|
+
importanceKind,
|
|
1594
|
+
importanceReason: truncateCodePoints(importanceReason, IMPORTANCE_REASON_MAX_CHARS)
|
|
1595
|
+
|| buildSpecificReason(importanceKind, title, ''),
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
/**
|
|
1600
|
+
* 对「已归一化」的卡片生成确定性兜底分析(内部复用,避免重复归一化)。
|
|
1601
|
+
* @param {{ preview: string, title: string, kind: string, role: string, toolNames: string[], tokens: number | null, firstUserRequest: boolean, hasUserRequest: boolean }} card - 归一化卡片。
|
|
1602
|
+
* @returns {{ category: string, title: string, summary: string, importance: 'important'|'keep'|'noisy', importanceKind: string, importanceReason: string, source: 'fallback' }} 兜底结果。
|
|
1603
|
+
*/
|
|
1604
|
+
function analyzeFallback(card) {
|
|
1605
|
+
const text = cleanInline(typeof card.preview === 'string' ? card.preview.split(TRUNCATED_MARK)[0] : '')
|
|
1606
|
+
const category = classifyFallback(card, text)
|
|
1607
|
+
const importanceKind = deriveFallbackImportanceKind(card, text, category)
|
|
1608
|
+
const title = deriveFallbackTitle(card, text, category)
|
|
1609
|
+
// v13.3:fallback 也必须过与 AI 相同的交付/过程后处理。模型不可用(降级/超时/解析失败)
|
|
1610
|
+
// 时,「task-24 验证全绿报告」「v8 已安装生效」这类交付强特征同样要判
|
|
1611
|
+
// deliverable/important 并给出「交付结论:{title}」;等待/调度/读取/检索等过程卡则
|
|
1612
|
+
// 保持/降为 process,不得因“交付”字样误升。fallback 不进缓存,因此不影响 hash。
|
|
1613
|
+
const analysis = postprocessDeliveryAnalysis({
|
|
1614
|
+
category,
|
|
1615
|
+
title,
|
|
1616
|
+
summary: deriveFallbackSummary(card, text, category),
|
|
1617
|
+
importance: deriveFallbackImportance(importanceKind, card, text, category),
|
|
1618
|
+
importanceKind,
|
|
1619
|
+
importanceReason: deriveFallbackImportanceReason(importanceKind, text, title),
|
|
1620
|
+
})
|
|
1621
|
+
return { ...analysis, source: 'fallback' }
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
/**
|
|
1625
|
+
* 无 AI / AI 失败时的确定性兜底:只根据卡片自身的 kind / role / unitCount /
|
|
1626
|
+
* 工具名 / 标题 / 预览 / 规则提示生成合法的分类、非空标题、非空简介、importance、
|
|
1627
|
+
* importanceKind 与 importanceReason。同一张卡片每次调用结果完全一致。
|
|
1628
|
+
*
|
|
1629
|
+
* @param {unknown} card - 卡片对象(字段缺失可容忍)。
|
|
1630
|
+
* @returns {{ category: string, title: string, summary: string, importance: 'important'|'keep'|'noisy', importanceKind: string, importanceReason: string, source: 'fallback' }} 兜底结果。
|
|
1631
|
+
*/
|
|
1632
|
+
export function fallbackAnalysis(card) {
|
|
1633
|
+
return analyzeFallback(normalizeCardForScan(card))
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
/* -------------------------------------------------------------------------- */
|
|
1637
|
+
/* 模型流读取与取消 */
|
|
1638
|
+
/* -------------------------------------------------------------------------- */
|
|
1639
|
+
|
|
1640
|
+
/**
|
|
1641
|
+
* 构造取消错误:优先原样抛出 `signal.reason`(如果它像个错误对象),
|
|
1642
|
+
* 否则造一个 `name='AbortError'` 的 Error。
|
|
1643
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1644
|
+
* @returns {Error | DOMException} 可抛出的取消错误。
|
|
1645
|
+
*/
|
|
1646
|
+
function abortErrorFrom(signal) {
|
|
1647
|
+
let reason
|
|
1648
|
+
try {
|
|
1649
|
+
reason = signal !== null && signal !== undefined ? signal.reason : undefined
|
|
1650
|
+
} catch {
|
|
1651
|
+
reason = undefined
|
|
1652
|
+
}
|
|
1653
|
+
if (reason !== undefined && reason !== null
|
|
1654
|
+
&& (reason instanceof Error || (typeof reason === 'object' && typeof reason.name === 'string' && reason.name !== ''))) {
|
|
1655
|
+
return reason
|
|
1656
|
+
}
|
|
1657
|
+
const error = new Error(reason === undefined || reason === null ? '扫描已取消' : `扫描已取消:${String(reason)}`)
|
|
1658
|
+
error.name = 'AbortError'
|
|
1659
|
+
return error
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
/**
|
|
1663
|
+
* 信号已中止时立即抛出取消错误。
|
|
1664
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1665
|
+
*/
|
|
1666
|
+
function throwIfAborted(signal) {
|
|
1667
|
+
if (signal !== null && signal !== undefined && signal.aborted === true) throw abortErrorFrom(signal)
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
/**
|
|
1671
|
+
* 只接受「看起来像 AbortSignal」的对象(不可信入参的防御)。
|
|
1672
|
+
* @param {unknown} value - 候选值。
|
|
1673
|
+
* @returns {AbortSignal | null} 合法信号或 null。
|
|
1674
|
+
*/
|
|
1675
|
+
function normalizeAbortSignal(value) {
|
|
1676
|
+
if (value === undefined || value === null || typeof value !== 'object') return null
|
|
1677
|
+
try {
|
|
1678
|
+
if (typeof value.aborted !== 'boolean' || typeof value.addEventListener !== 'function') return null
|
|
1679
|
+
return value
|
|
1680
|
+
} catch {
|
|
1681
|
+
return null
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
/**
|
|
1686
|
+
* 让一个 promise 与 AbortSignal 赛跑:signal 一 abort 就立即 reject,不等底层
|
|
1687
|
+
* promise 自己反应过来。这样即使某个模型适配器不响应 signal,超时也能生效。
|
|
1688
|
+
* @template T
|
|
1689
|
+
* @param {Promise<T>} promise - 底层 promise。
|
|
1690
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1691
|
+
* @returns {Promise<T>} 与信号联动后的 promise。
|
|
1692
|
+
*/
|
|
1693
|
+
function raceWithSignal(promise, signal) {
|
|
1694
|
+
if (signal === undefined || signal === null || typeof signal.addEventListener !== 'function') return promise
|
|
1695
|
+
if (signal.aborted) return Promise.reject(abortErrorFrom(signal))
|
|
1696
|
+
return new Promise((resolve, reject) => {
|
|
1697
|
+
const cleanup = () => {
|
|
1698
|
+
try {
|
|
1699
|
+
signal.removeEventListener('abort', onAbort)
|
|
1700
|
+
} catch {
|
|
1701
|
+
/* 忽略:移除监听失败不影响结果 */
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
const onAbort = () => {
|
|
1705
|
+
cleanup()
|
|
1706
|
+
reject(abortErrorFrom(signal))
|
|
1707
|
+
}
|
|
1708
|
+
try {
|
|
1709
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
1710
|
+
} catch {
|
|
1711
|
+
resolve(promise)
|
|
1712
|
+
return
|
|
1713
|
+
}
|
|
1714
|
+
promise.then(
|
|
1715
|
+
value => {
|
|
1716
|
+
cleanup()
|
|
1717
|
+
resolve(value)
|
|
1718
|
+
},
|
|
1719
|
+
error => {
|
|
1720
|
+
cleanup()
|
|
1721
|
+
reject(error)
|
|
1722
|
+
},
|
|
1723
|
+
)
|
|
1724
|
+
})
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
/**
|
|
1728
|
+
* 读取异步迭代器的下一步,并与 signal 赛跑。
|
|
1729
|
+
* @param {AsyncIterator<unknown>} iterator - 异步迭代器。
|
|
1730
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1731
|
+
* @returns {Promise<IteratorResult<unknown>>} 迭代结果。
|
|
1732
|
+
*/
|
|
1733
|
+
function nextWithSignal(iterator, signal) {
|
|
1734
|
+
return raceWithSignal(Promise.resolve().then(() => iterator.next()), signal)
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
/**
|
|
1738
|
+
* 可被 signal 打断的 sleep(用于重试退避)。signal 一 abort 立即 reject 取消错误,
|
|
1739
|
+
* 不会让调用方白等完整个退避时长。
|
|
1740
|
+
* @param {number} ms - 等待毫秒数(<=0 直接返回)。
|
|
1741
|
+
* @param {AbortSignal | null} signal - 中止信号。
|
|
1742
|
+
* @returns {Promise<void>} 等待结束。
|
|
1743
|
+
*/
|
|
1744
|
+
function sleepWithSignal(ms, signal) {
|
|
1745
|
+
if (!(typeof ms === 'number' && Number.isFinite(ms) && ms > 0)) return Promise.resolve()
|
|
1746
|
+
return new Promise((resolve, reject) => {
|
|
1747
|
+
let timer
|
|
1748
|
+
const cleanup = () => {
|
|
1749
|
+
clearTimeout(timer)
|
|
1750
|
+
try {
|
|
1751
|
+
if (signal !== null && signal !== undefined && typeof signal.removeEventListener === 'function') {
|
|
1752
|
+
signal.removeEventListener('abort', onAbort)
|
|
1753
|
+
}
|
|
1754
|
+
} catch {
|
|
1755
|
+
/* 移除监听失败不影响结果 */
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
const onAbort = () => {
|
|
1759
|
+
cleanup()
|
|
1760
|
+
reject(abortErrorFrom(signal))
|
|
1761
|
+
}
|
|
1762
|
+
if (signal !== null && signal !== undefined && typeof signal.addEventListener === 'function') {
|
|
1763
|
+
if (signal.aborted) {
|
|
1764
|
+
reject(abortErrorFrom(signal))
|
|
1765
|
+
return
|
|
1766
|
+
}
|
|
1767
|
+
try {
|
|
1768
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
1769
|
+
} catch {
|
|
1770
|
+
/* 加不上监听就不管取消,退化为普通 sleep */
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
timer = setTimeout(() => {
|
|
1774
|
+
cleanup()
|
|
1775
|
+
resolve()
|
|
1776
|
+
}, ms)
|
|
1777
|
+
})
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
/**
|
|
1781
|
+
* finish reason 里的失败原因文本。
|
|
1782
|
+
* @param {unknown} failure - FinishReason.failure。
|
|
1783
|
+
* @returns {string} 可读原因。
|
|
1784
|
+
*/
|
|
1785
|
+
function failureText(failure) {
|
|
1786
|
+
if (typeof failure === 'string' && failure !== '') return failure
|
|
1787
|
+
if (isRecord(failure) && typeof failure.message === 'string' && failure.message !== '') return failure.message
|
|
1788
|
+
return '未知原因'
|
|
1789
|
+
}
|
|
1790
|
+
|
|
1791
|
+
/**
|
|
1792
|
+
* 把 finish reason 翻译成需要抛出的错误;'stop' / 'tool-calls' / 缺失都放行。
|
|
1793
|
+
* 缺失 finish 也放行(宽容处理不带 end 标记的简易适配器)。
|
|
1794
|
+
* @param {unknown} reason - finish reason。
|
|
1795
|
+
* @returns {Error | null} 失败错误或 null。
|
|
1796
|
+
*/
|
|
1797
|
+
function finishFailure(reason) {
|
|
1798
|
+
if (!isRecord(reason) || typeof reason.kind !== 'string') return null
|
|
1799
|
+
switch (reason.kind) {
|
|
1800
|
+
case 'error':
|
|
1801
|
+
return new Error(`模型返回错误:${failureText(reason.failure)}`)
|
|
1802
|
+
case 'aborted':
|
|
1803
|
+
return new Error(`模型调用被中止:${failureText(reason.failure)}`)
|
|
1804
|
+
case 'max-tokens':
|
|
1805
|
+
return new Error('模型输出触达 maxTokens 上限,结果被截断')
|
|
1806
|
+
default:
|
|
1807
|
+
return null
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
/**
|
|
1812
|
+
* 调用注入的 `llm.stream(options)` 并把流里的文本拼起来。
|
|
1813
|
+
*
|
|
1814
|
+
* options 严格按宿主契约构造(provider / model / messages / maxTokens /
|
|
1815
|
+
* temperature / signal),并兼容:
|
|
1816
|
+
* - `llm.stream` 同步抛错(转成 batch 失败);
|
|
1817
|
+
* - `llm.stream` 返回 Promise<AsyncIterable>;
|
|
1818
|
+
* - 只有 text-delta、没有 finish 的简易流;
|
|
1819
|
+
* - 只有 block-end、没有 text-delta 的流;
|
|
1820
|
+
* - signal 中止(立即 reject,不依赖适配器配合)。
|
|
1821
|
+
*
|
|
1822
|
+
* @param {{
|
|
1823
|
+
* streamFn: (options: object) => unknown,
|
|
1824
|
+
* target: { provider: string, model: string },
|
|
1825
|
+
* prompt: string,
|
|
1826
|
+
* maxTokens: number,
|
|
1827
|
+
* temperature: number,
|
|
1828
|
+
* signal: AbortSignal,
|
|
1829
|
+
* sessionId?: string,
|
|
1830
|
+
* }} options - 调用参数(sessionId 有值就透传进 GenerateOptions)。
|
|
1831
|
+
* @returns {Promise<string>} 模型输出的完整文本。
|
|
1832
|
+
*/
|
|
1833
|
+
async function collectModelText(options) {
|
|
1834
|
+
const generateOptions = {
|
|
1835
|
+
provider: options.target.provider,
|
|
1836
|
+
model: options.target.model,
|
|
1837
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: options.prompt }] }],
|
|
1838
|
+
maxTokens: options.maxTokens,
|
|
1839
|
+
temperature: options.temperature,
|
|
1840
|
+
signal: options.signal,
|
|
1841
|
+
}
|
|
1842
|
+
// 宿主用它把辅助调用归到同一 session(网关按 session 头路由/限流)。
|
|
1843
|
+
if (typeof options.sessionId === 'string' && options.sessionId !== '') {
|
|
1844
|
+
generateOptions.sessionId = options.sessionId
|
|
1845
|
+
}
|
|
1846
|
+
if (typeof options.reasoningEffort === 'string' && options.reasoningEffort !== '') {
|
|
1847
|
+
generateOptions.reasoningEffort = options.reasoningEffort
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
let stream
|
|
1851
|
+
try {
|
|
1852
|
+
stream = options.streamFn(generateOptions)
|
|
1853
|
+
} catch (error) {
|
|
1854
|
+
// 某些路由不支持显式 reasoningEffort(适配器会直接拒绝)。扫描只是分类,
|
|
1855
|
+
// 关不掉 reasoning 就退回“跟随路由默认”,不要因此让整批失败。
|
|
1856
|
+
const message = toErrorMessage(error)
|
|
1857
|
+
if (typeof generateOptions.reasoningEffort === 'string' && generateOptions.reasoningEffort !== ''
|
|
1858
|
+
&& /reasoning|effort/i.test(message)) {
|
|
1859
|
+
delete generateOptions.reasoningEffort
|
|
1860
|
+
try {
|
|
1861
|
+
stream = options.streamFn(generateOptions)
|
|
1862
|
+
} catch (retryError) {
|
|
1863
|
+
throw retryError instanceof Error ? retryError : new Error(toErrorMessage(retryError))
|
|
1864
|
+
}
|
|
1865
|
+
} else {
|
|
1866
|
+
throw error instanceof Error ? error : new Error(message)
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
|
|
1870
|
+
// 兼容返回 Promise<AsyncIterable> 的包装实现。
|
|
1871
|
+
if (stream !== null && typeof stream === 'object' && typeof stream.then === 'function'
|
|
1872
|
+
&& typeof stream[Symbol.asyncIterator] !== 'function') {
|
|
1873
|
+
stream = await raceWithSignal(stream, options.signal)
|
|
1874
|
+
}
|
|
1875
|
+
|
|
1876
|
+
const iterable = stream
|
|
1877
|
+
if (iterable === null || iterable === undefined
|
|
1878
|
+
|| (typeof iterable !== 'object' && typeof iterable !== 'function')
|
|
1879
|
+
|| typeof iterable[Symbol.asyncIterator] !== 'function') {
|
|
1880
|
+
throw new Error('模型调用接口没有返回可迭代的输出流')
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
const iterator = iterable[Symbol.asyncIterator]()
|
|
1884
|
+
const textParts = []
|
|
1885
|
+
const blockTextParts = []
|
|
1886
|
+
let finishReason = null
|
|
1887
|
+
let drained = false
|
|
1888
|
+
|
|
1889
|
+
try {
|
|
1890
|
+
while (true) {
|
|
1891
|
+
const step = await nextWithSignal(iterator, options.signal)
|
|
1892
|
+
if (!isRecord(step)) continue
|
|
1893
|
+
if (step.done === true) {
|
|
1894
|
+
drained = true
|
|
1895
|
+
break
|
|
1896
|
+
}
|
|
1897
|
+
const chunk = step.value
|
|
1898
|
+
if (!isRecord(chunk)) continue
|
|
1899
|
+
if (chunk.type === 'text-delta') {
|
|
1900
|
+
if (typeof chunk.text === 'string' && chunk.text !== '') textParts.push(chunk.text)
|
|
1901
|
+
continue
|
|
1902
|
+
}
|
|
1903
|
+
if (chunk.type === 'block-end') {
|
|
1904
|
+
const block = chunk.block
|
|
1905
|
+
if (isRecord(block) && block.type === 'text' && typeof block.text === 'string' && block.text !== '') {
|
|
1906
|
+
blockTextParts.push(block.text)
|
|
1907
|
+
}
|
|
1908
|
+
continue
|
|
1909
|
+
}
|
|
1910
|
+
if (chunk.type === 'finish') {
|
|
1911
|
+
// finish 是协议终止标记:记下原因后跳出,由 finally 主动关闭迭代器,
|
|
1912
|
+
// 让适配器有机会执行自己的清理逻辑(而不是把它挂起到 GC)。
|
|
1913
|
+
finishReason = isRecord(chunk.reason) ? chunk.reason : null
|
|
1914
|
+
break
|
|
1915
|
+
}
|
|
1916
|
+
// 其余 chunk(block-start / reasoning-delta / tool-call-delta / usage)与文本无关,忽略。
|
|
1917
|
+
}
|
|
1918
|
+
} finally {
|
|
1919
|
+
if (!drained) {
|
|
1920
|
+
// 被中止/抛错/提前看到 finish 时尽量关闭迭代器;不 await(某些实现可能永远不 resolve)。
|
|
1921
|
+
try {
|
|
1922
|
+
const returned = typeof iterator.return === 'function' ? iterator.return() : undefined
|
|
1923
|
+
if (returned !== null && returned !== undefined && typeof returned.then === 'function') {
|
|
1924
|
+
returned.then(() => undefined, () => undefined)
|
|
1925
|
+
}
|
|
1926
|
+
} catch {
|
|
1927
|
+
/* 关闭失败不影响结果 */
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
const failure = finishFailure(finishReason)
|
|
1933
|
+
if (failure !== null) throw failure
|
|
1934
|
+
const direct = textParts.join('')
|
|
1935
|
+
return direct.trim() === '' ? blockTextParts.join('') : direct
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
/* -------------------------------------------------------------------------- */
|
|
1939
|
+
/* 缓存 / 结果小工具 */
|
|
1940
|
+
/* -------------------------------------------------------------------------- */
|
|
1941
|
+
|
|
1942
|
+
/**
|
|
1943
|
+
* 从 cache 里读一条原始记录(普通对象或 Map 都支持;只读,不修改缓存)。
|
|
1944
|
+
* @param {unknown} cache - 缓存对象。
|
|
1945
|
+
* @param {string} id - 卡片 id。
|
|
1946
|
+
* @returns {Record<string, unknown> | null} 缓存条目或 null。
|
|
1947
|
+
*/
|
|
1948
|
+
function readCacheValue(cache, id) {
|
|
1949
|
+
try {
|
|
1950
|
+
if (cache instanceof Map) {
|
|
1951
|
+
const value = cache.get(id)
|
|
1952
|
+
return isRecord(value) ? value : null
|
|
1953
|
+
}
|
|
1954
|
+
if (!isRecord(cache)) return null
|
|
1955
|
+
if (!Object.prototype.hasOwnProperty.call(cache, id)) return null
|
|
1956
|
+
const value = cache[id]
|
|
1957
|
+
return isRecord(value) ? value : null
|
|
1958
|
+
} catch {
|
|
1959
|
+
return null
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
/**
|
|
1964
|
+
* 缓存命中判定:hash 必须完全相同,且已有可用的 title/summary(半坏条目重新分析)。
|
|
1965
|
+
* @param {unknown} cache - 缓存对象。
|
|
1966
|
+
* @param {string} id - 卡片 id。
|
|
1967
|
+
* @param {string} hash - 当前内容指纹。
|
|
1968
|
+
* @returns {Record<string, unknown> | null} 命中的缓存条目或 null。
|
|
1969
|
+
*/
|
|
1970
|
+
function findCachedEntry(cache, id, hash) {
|
|
1971
|
+
if (hash === '') return null
|
|
1972
|
+
const entry = readCacheValue(cache, id)
|
|
1973
|
+
if (entry === null) return null
|
|
1974
|
+
if (typeof entry.hash !== 'string' || entry.hash !== hash) return null
|
|
1975
|
+
if (typeof entry.title !== 'string' || cleanInline(entry.title) === '') return null
|
|
1976
|
+
if (typeof entry.summary !== 'string' || cleanInline(entry.summary) === '') return null
|
|
1977
|
+
return entry
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1980
|
+
/**
|
|
1981
|
+
* 复制一条缓存条目进本次结果(保持它原来的 at/model/source/importance/kind/reason,
|
|
1982
|
+
* 不重复花钱)。旧版缓存缺字段时按兜底规则补齐,保证宿主拿到的条目永远完整。
|
|
1983
|
+
* @param {Record<string, unknown>} entry - 缓存条目。
|
|
1984
|
+
* @param {string} hash - 当前内容指纹。
|
|
1985
|
+
* @param {string} fallbackModel - 缓存缺 model 时的当前模型名。
|
|
1986
|
+
* @returns {{ hash: string, category: string, title: string, summary: string, importance: 'important'|'keep'|'noisy', importanceKind: string, importanceReason: string, source: 'ai'|'fallback', at: number, model: string }}
|
|
1987
|
+
*/
|
|
1988
|
+
function copyCachedEntry(entry, hash, fallbackModel) {
|
|
1989
|
+
const source = entry.source === 'ai' ? 'ai' : 'fallback'
|
|
1990
|
+
const importance = normalizeImportance(entry.importance)
|
|
1991
|
+
const importanceKind = normalizeImportanceKind(entry.importanceKind) ?? inferImportanceKindFromImportance(importance)
|
|
1992
|
+
const importanceReason = normalizeImportanceReason(entry.importanceReason)
|
|
1993
|
+
|| buildSpecificReason(importanceKind, entry.title)
|
|
1994
|
+
return {
|
|
1995
|
+
hash,
|
|
1996
|
+
category: normalizeCategoryId(entry.category),
|
|
1997
|
+
title: entry.title,
|
|
1998
|
+
summary: entry.summary,
|
|
1999
|
+
importance: reconcileImportance(importance, importanceKind),
|
|
2000
|
+
importanceKind,
|
|
2001
|
+
importanceReason,
|
|
2002
|
+
source,
|
|
2003
|
+
at: Number.isFinite(entry.at) ? entry.at : Date.now(),
|
|
2004
|
+
model: typeof entry.model === 'string' && entry.model !== '' ? entry.model : fallbackModel,
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
/**
|
|
2009
|
+
* 构造一条写入结果集的条目(字段顺序即契约顺序)。
|
|
2010
|
+
*
|
|
2011
|
+
* 无论来源是 AI 还是 fallback,这里都统一执行一致性硬规则:kind 缺失/非法时按
|
|
2012
|
+
* importance 或兜底推断补齐;reason 缺失时按 kind 补默认短理由。
|
|
2013
|
+
*
|
|
2014
|
+
* @param {string} hash - 内容指纹。
|
|
2015
|
+
* @param {{ category: string, title: string, summary: string, importance?: string, importanceKind?: string | null, importanceReason?: string }} analysis - 分析结果。
|
|
2016
|
+
* @param {'ai' | 'fallback'} source - 结果来源。
|
|
2017
|
+
* @param {number} at - 时间戳。
|
|
2018
|
+
* @param {string} model - `${provider}/${model}`。
|
|
2019
|
+
* @returns {{ hash: string, category: string, title: string, summary: string, importance: 'important'|'keep'|'noisy', importanceKind: string, importanceReason: string, source: 'ai'|'fallback', at: number, model: string }}
|
|
2020
|
+
*/
|
|
2021
|
+
function buildAnalysisEntry(hash, analysis, source, at, model) {
|
|
2022
|
+
const importance = normalizeImportance(analysis.importance)
|
|
2023
|
+
const importanceKind = normalizeImportanceKind(analysis.importanceKind) ?? inferImportanceKindFromImportance(importance)
|
|
2024
|
+
const importanceReason = normalizeImportanceReason(analysis.importanceReason)
|
|
2025
|
+
|| buildSpecificReason(importanceKind, analysis.title)
|
|
2026
|
+
return {
|
|
2027
|
+
hash,
|
|
2028
|
+
category: analysis.category,
|
|
2029
|
+
title: analysis.title,
|
|
2030
|
+
summary: analysis.summary,
|
|
2031
|
+
importance: reconcileImportance(importance, importanceKind),
|
|
2032
|
+
importanceKind,
|
|
2033
|
+
importanceReason,
|
|
2034
|
+
source,
|
|
2035
|
+
at,
|
|
2036
|
+
model,
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
/** 是否有自有条目(避免误读原型链上的属性)。 */
|
|
2041
|
+
function hasEntry(entries, id) {
|
|
2042
|
+
return Object.prototype.hasOwnProperty.call(entries, id)
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
/**
|
|
2046
|
+
* 安全写结果集:卡片 id 理论上由宿主生成,但仍防御 `__proto__` 这类特殊键。
|
|
2047
|
+
* @param {Record<string, object>} entries - 结果集。
|
|
2048
|
+
* @param {string} id - 卡片 id。
|
|
2049
|
+
* @param {object} entry - 条目。
|
|
2050
|
+
*/
|
|
2051
|
+
function putEntry(entries, id, entry) {
|
|
2052
|
+
if (id === '__proto__' || id === 'constructor' || id === 'prototype') {
|
|
2053
|
+
Object.defineProperty(entries, id, { value: entry, enumerable: true, configurable: true, writable: true })
|
|
2054
|
+
return
|
|
2055
|
+
}
|
|
2056
|
+
entries[id] = entry
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
/**
|
|
2060
|
+
* 读取模型目标(provider/model 必须同时存在,否则视为没有可用模型)。
|
|
2061
|
+
* @param {unknown} model - 调用方传入的 { provider, model }。
|
|
2062
|
+
* @returns {{ provider: string, model: string, label: string } | null} 目标或 null。
|
|
2063
|
+
*/
|
|
2064
|
+
function resolveModelTarget(model) {
|
|
2065
|
+
const source = isRecord(model) ? model : {}
|
|
2066
|
+
const provider = typeof source.provider === 'string' ? source.provider.trim() : ''
|
|
2067
|
+
const name = typeof source.model === 'string' ? source.model.trim() : ''
|
|
2068
|
+
if (provider === '' || name === '') return null
|
|
2069
|
+
return { provider, model: name, label: `${provider}/${name}` }
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
/**
|
|
2073
|
+
* 从「看起来像 ctx.llm」的对象里取 stream 调用器(绑定 this)。
|
|
2074
|
+
* @param {unknown} llm - 调用方注入的 llm。
|
|
2075
|
+
* @returns {((options: object) => unknown) | null} stream 调用器或 null。
|
|
2076
|
+
*/
|
|
2077
|
+
function resolveStreamFn(llm) {
|
|
2078
|
+
try {
|
|
2079
|
+
if (!isRecord(llm) || typeof llm.stream !== 'function') return null
|
|
2080
|
+
return options => llm.stream(options)
|
|
2081
|
+
} catch {
|
|
2082
|
+
return null
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
/**
|
|
2087
|
+
* 预处理请求卡片:只保留带合法 id 的对象,按 id 去重(保持原顺序)。
|
|
2088
|
+
*
|
|
2089
|
+
* 这里刻意**不**按 maxCardsPerPass 截断:缓存命中不花钱、不占预算,应先让全部
|
|
2090
|
+
* 卡片命中缓存,再把「本次真正需要 AI 分析」的未命中卡片交给 buildScanBatches
|
|
2091
|
+
* 按 maxCardsPerPass 截断。否则超大会话里排在后面的卡片会永远被截掉、每次都
|
|
2092
|
+
* 轮不到分析;现在多扫几次就能渐进覆盖全部卡片。
|
|
2093
|
+
*
|
|
2094
|
+
* @param {unknown} cards - 原始卡片数组。
|
|
2095
|
+
* @returns {Array<{ id: string, raw: Record<string, unknown> }>} 待处理卡片。
|
|
2096
|
+
*/
|
|
2097
|
+
function prepareRequestedCards(cards) {
|
|
2098
|
+
if (!Array.isArray(cards)) return []
|
|
2099
|
+
const seen = new Set()
|
|
2100
|
+
const items = []
|
|
2101
|
+
for (const raw of cards) {
|
|
2102
|
+
if (!isRecord(raw)) continue
|
|
2103
|
+
let id = ''
|
|
2104
|
+
try {
|
|
2105
|
+
id = readCardId(raw)
|
|
2106
|
+
} catch {
|
|
2107
|
+
id = ''
|
|
2108
|
+
}
|
|
2109
|
+
if (id === '' || seen.has(id)) continue
|
|
2110
|
+
seen.add(id)
|
|
2111
|
+
items.push({ id, raw })
|
|
2112
|
+
}
|
|
2113
|
+
return items
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
/* -------------------------------------------------------------------------- */
|
|
2117
|
+
/* 主入口 */
|
|
2118
|
+
/* -------------------------------------------------------------------------- */
|
|
2119
|
+
|
|
2120
|
+
/**
|
|
2121
|
+
* 扫描主入口:只分析未命中缓存的卡片,分批调用注入的 `llm.stream`。
|
|
2122
|
+
*
|
|
2123
|
+
* v2 行为契约:
|
|
2124
|
+
* - 卡片是「按轮次的语义阶段分组卡」(kind=group / role=mixed,带 unitCount);
|
|
2125
|
+
* - 命中缓存(hash 相同)直接复制条目进 `entries`(含原 importance),不发请求;
|
|
2126
|
+
* - 其余卡片按 `batchSize` 分批,最多 `maxConcurrentBatches` 批并发;默认 1,
|
|
2127
|
+
* 因为同一 session 的网关通常只允许单并发流;
|
|
2128
|
+
* - 每批单独超时(AbortController + setTimeout,`config.timeoutMs`);
|
|
2129
|
+
* - 每批失败(模型 error/aborted finish、超时、解析完全失败、流抛错)按
|
|
2130
|
+
* `config.retries` 重试,退避 `retryDelayMs * 2^(attempt-1)`;调用方 abort
|
|
2131
|
+
* 不重试、整次扫描抛出;重试耗尽才整批 `fallbackAnalysis`,**不 reject**;
|
|
2132
|
+
* - `beforeBatch`(可选)在每次尝试(含重试)开始前 await 一次;它抛错表示
|
|
2133
|
+
* 「现在不该发请求」,整次扫描直接抛出该错误(不做 fallback)。宿主用它
|
|
2134
|
+
* 等待 agent 空闲,避免同一 session 的并发流撞上网关限制;
|
|
2135
|
+
* - AI 正常返回但个别 id 缺失/无效 → 那些卡片走 `fallbackAnalysis`;
|
|
2136
|
+
* - 每批完成后回调 `onProgress({ done, total })`,`total` = 需要请求的批数;
|
|
2137
|
+
* - 会抛出的只有两种情况:调用方 `signal` 被 abort(抛 AbortError 或
|
|
2138
|
+
* `signal.reason`),或 `beforeBatch` 抛错(原样抛出)。
|
|
2139
|
+
*
|
|
2140
|
+
* 预算语义:`maxCardsPerPass` 只限制「本次真正要发 AI 请求」的未命中卡片数,
|
|
2141
|
+
* 缓存命中不花钱、也不占预算。因此超大会话第一次扫描可能只分析前
|
|
2142
|
+
* `maxCardsPerPass` 张未命中卡片,后续扫描在前面的卡片命中缓存后继续往后覆盖,
|
|
2143
|
+
* 直到全部卡片都有分析结果(而不是永远截掉尾部)。
|
|
2144
|
+
*
|
|
2145
|
+
* `stats.requested` 是传入的有效卡片总数(去重后);由于上述预算限制,
|
|
2146
|
+
* 当未命中卡片超过 `maxCardsPerPass` 时 `fromCache + analyzed + failed`
|
|
2147
|
+
* 会小于 `requested`。
|
|
2148
|
+
*
|
|
2149
|
+
* @param {{
|
|
2150
|
+
* cards?: unknown,
|
|
2151
|
+
* cache?: unknown,
|
|
2152
|
+
* model?: unknown,
|
|
2153
|
+
* llm?: unknown,
|
|
2154
|
+
* config?: unknown,
|
|
2155
|
+
* sessionId?: string,
|
|
2156
|
+
* signal?: AbortSignal,
|
|
2157
|
+
* beforeBatch?: () => Promise<void>,
|
|
2158
|
+
* onProgress?: (progress: { done: number, total: number }) => void,
|
|
2159
|
+
* }} [options] - 扫描参数(全部可缺省,缺省时返回空结果而不是抛错)。
|
|
2160
|
+
* @returns {Promise<{
|
|
2161
|
+
* entries: Record<string, { hash: string, category: string, title: string, summary: string, importance: 'important'|'keep'|'noisy', importanceKind: string, importanceReason: string, source: 'ai'|'fallback', at: number, model: string }>,
|
|
2162
|
+
* stats: { requested: number, fromCache: number, analyzed: number, failed: number, batches: number, failedBatches: number },
|
|
2163
|
+
* lastError: { batch: number, message: string } | null,
|
|
2164
|
+
* }>} 扫描结果。
|
|
2165
|
+
* @throws {Error|DOMException} 调用方 signal 被 abort 时抛取消错误;beforeBatch 抛错时原样抛出。
|
|
2166
|
+
*/
|
|
2167
|
+
export async function scanCards(options = {}) {
|
|
2168
|
+
const params = isRecord(options) ? options : {}
|
|
2169
|
+
const config = resolveScanConfig(params.config)
|
|
2170
|
+
const callerSignal = normalizeAbortSignal(params.signal)
|
|
2171
|
+
const onProgress = typeof params.onProgress === 'function' ? params.onProgress : null
|
|
2172
|
+
const beforeBatch = typeof params.beforeBatch === 'function' ? params.beforeBatch : null
|
|
2173
|
+
const sessionId = typeof params.sessionId === 'string' ? params.sessionId : ''
|
|
2174
|
+
|
|
2175
|
+
/** @type {Record<string, object>} */
|
|
2176
|
+
const entries = {}
|
|
2177
|
+
const stats = {
|
|
2178
|
+
requested: 0,
|
|
2179
|
+
fromCache: 0,
|
|
2180
|
+
analyzed: 0,
|
|
2181
|
+
failed: 0,
|
|
2182
|
+
batches: 0,
|
|
2183
|
+
failedBatches: 0,
|
|
2184
|
+
}
|
|
2185
|
+
/** @type {{ batch: number, message: string } | null} */
|
|
2186
|
+
let lastError = null
|
|
2187
|
+
|
|
2188
|
+
/** 记录批次错误:并发下以「批次号更大的那个」为准,保证结果确定。 */
|
|
2189
|
+
const recordError = (batchNumber, message) => {
|
|
2190
|
+
if (lastError === null || batchNumber >= lastError.batch) {
|
|
2191
|
+
lastError = { batch: batchNumber, message: message === '' ? '分析失败' : message }
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
/**
|
|
2196
|
+
* 致命错误:`beforeBatch` 抛错代表「现在根本不该发请求」,按需求要中止整次扫描
|
|
2197
|
+
* 并原样抛出(不做 fallback)。这里同时中止其它在途批次,避免继续占用连接。
|
|
2198
|
+
* @type {Error | null}
|
|
2199
|
+
*/
|
|
2200
|
+
let fatalError = null
|
|
2201
|
+
/** 在途批次的 AbortController(致命错误时统一中止)。 */
|
|
2202
|
+
const activeControllers = new Set()
|
|
2203
|
+
/**
|
|
2204
|
+
* 标记致命错误并中止在途批次。
|
|
2205
|
+
* @param {unknown} error - 原始错误。
|
|
2206
|
+
* @returns {Error} 规范化后的致命错误。
|
|
2207
|
+
*/
|
|
2208
|
+
const raiseFatal = error => {
|
|
2209
|
+
const normalized = error instanceof Error ? error : new Error(toErrorMessage(error))
|
|
2210
|
+
if (fatalError === null) fatalError = normalized
|
|
2211
|
+
for (const controller of activeControllers) {
|
|
2212
|
+
try {
|
|
2213
|
+
controller.abort(fatalError)
|
|
2214
|
+
} catch {
|
|
2215
|
+
/* 已经中止过了 */
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
return fatalError
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2221
|
+
// 先收下全部有效卡片(缓存命中不占分析预算),maxCardsPerPass 只在分批时
|
|
2222
|
+
// 截断「需要真正发请求」的未命中卡片。
|
|
2223
|
+
const items = prepareRequestedCards(params.cards)
|
|
2224
|
+
stats.requested = items.length
|
|
2225
|
+
const target = resolveModelTarget(params.model)
|
|
2226
|
+
const targetLabel = target === null ? '' : target.label
|
|
2227
|
+
const streamFn = resolveStreamFn(params.llm)
|
|
2228
|
+
|
|
2229
|
+
/** 把 pending 卡片映射到原始对象(批里再按 id 找回 hash / 兜底素材)。 */
|
|
2230
|
+
const pendingById = new Map()
|
|
2231
|
+
for (const item of items) pendingById.set(item.id, item)
|
|
2232
|
+
|
|
2233
|
+
/**
|
|
2234
|
+
* 内容指纹表:一次扫描内每张卡片只算一次。
|
|
2235
|
+
*
|
|
2236
|
+
* 注意:AI 成功、AI 失败兜底、无模型兜底三条路径都必须拿到同一个 hash ——
|
|
2237
|
+
* 宿主用它判断「这张卡片的分析结果是否仍然新鲜」。缓存命中路径直接复用
|
|
2238
|
+
* 缓存里的 hash;其余路径统一走 hashOf()。
|
|
2239
|
+
*/
|
|
2240
|
+
const hashById = new Map()
|
|
2241
|
+
const hashOf = item => {
|
|
2242
|
+
const known = hashById.get(item.id)
|
|
2243
|
+
if (typeof known === 'string' && known !== '') return known
|
|
2244
|
+
let hash = ''
|
|
2245
|
+
try {
|
|
2246
|
+
hash = cardHash(item.raw)
|
|
2247
|
+
} catch {
|
|
2248
|
+
hash = ''
|
|
2249
|
+
}
|
|
2250
|
+
hashById.set(item.id, hash)
|
|
2251
|
+
return hash
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2254
|
+
/** 安全归一化(异常卡片退化成空卡片,仍不打断整批)。 */
|
|
2255
|
+
const normalizeSafely = raw => {
|
|
2256
|
+
try {
|
|
2257
|
+
return normalizeCardForScan(raw, config)
|
|
2258
|
+
} catch {
|
|
2259
|
+
return normalizeCardForScan({}, config)
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
2262
|
+
|
|
2263
|
+
/** 对一张归一化卡片写兜底条目(幂等:已有条目就跳过)。 */
|
|
2264
|
+
const applyFallback = (normalized, at) => {
|
|
2265
|
+
if (normalized === null || typeof normalized !== 'object' || normalized.id === '') return
|
|
2266
|
+
if (hasEntry(entries, normalized.id)) return
|
|
2267
|
+
const item = pendingById.get(normalized.id)
|
|
2268
|
+
if (item === undefined) return
|
|
2269
|
+
const analysis = analyzeFallback(normalized)
|
|
2270
|
+
putEntry(entries, normalized.id, buildAnalysisEntry(hashOf(item), analysis, 'fallback', at, targetLabel))
|
|
2271
|
+
stats.failed += 1
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
/** 对一张原始卡片写兜底条目。 */
|
|
2275
|
+
const applyFallbackForRaw = (raw, at) => applyFallback(normalizeSafely(raw), at)
|
|
2276
|
+
|
|
2277
|
+
/**
|
|
2278
|
+
* 把 AI 结果补齐成完整分析:kind 缺失/非法时用确定性兜底推断(绝不留给宿主 null),
|
|
2279
|
+
* reason 缺失时用「同 kind 的默认理由」或兜底推断出的具体理由补齐。
|
|
2280
|
+
* @param {Record<string, unknown>} raw - 原始卡片。
|
|
2281
|
+
* @param {{ category: string, title: string, summary: string, importance: string, importanceKind: string | null, importanceReason: string }} result - 解析出的 AI 结果。
|
|
2282
|
+
* @returns {{ category: string, title: string, summary: string, importance: string, importanceKind: string, importanceReason: string }} 完整分析。
|
|
2283
|
+
*/
|
|
2284
|
+
const completeAiAnalysis = (raw, result) => {
|
|
2285
|
+
const fallback = analyzeFallback(normalizeSafely(raw))
|
|
2286
|
+
const providedKind = normalizeImportanceKind(result.importanceKind)
|
|
2287
|
+
const importanceKind = providedKind
|
|
2288
|
+
?? inferImportanceKindForAi(normalizeImportance(result.importance), fallback.importanceKind)
|
|
2289
|
+
const providedReason = normalizeImportanceReason(result.importanceReason)
|
|
2290
|
+
// reason 必须与最终 kind 对齐:AI 没给 kind 且沿用 fallback 推断时用 fallback 的
|
|
2291
|
+
// 具体理由;否则用同 kind 的默认理由,避免 reason 与 kind 自相矛盾。
|
|
2292
|
+
const importanceReason = providedReason !== ''
|
|
2293
|
+
? providedReason
|
|
2294
|
+
: (providedKind === null && importanceKind === fallback.importanceKind
|
|
2295
|
+
? fallback.importanceReason
|
|
2296
|
+
: (KIND_REASON[importanceKind] ?? fallback.importanceReason))
|
|
2297
|
+
return {
|
|
2298
|
+
category: result.category,
|
|
2299
|
+
title: result.title,
|
|
2300
|
+
summary: result.summary,
|
|
2301
|
+
importance: reconcileImportance(result.importance, importanceKind),
|
|
2302
|
+
importanceKind,
|
|
2303
|
+
importanceReason,
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
try {
|
|
2308
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
2309
|
+
|
|
2310
|
+
// ── 1. 缓存命中:hash 相同直接复制,不发请求 ─────────────────────────────
|
|
2311
|
+
const pendingItems = []
|
|
2312
|
+
for (const item of items) {
|
|
2313
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
2314
|
+
const hash = hashOf(item)
|
|
2315
|
+
const cached = findCachedEntry(params.cache, item.id, hash)
|
|
2316
|
+
if (cached !== null) {
|
|
2317
|
+
putEntry(entries, item.id, copyCachedEntry(cached, hash, targetLabel))
|
|
2318
|
+
stats.fromCache += 1
|
|
2319
|
+
continue
|
|
2320
|
+
}
|
|
2321
|
+
pendingItems.push({ id: item.id, raw: item.raw })
|
|
2322
|
+
}
|
|
2323
|
+
|
|
2324
|
+
// ── 2. 分批 ────────────────────────────────────────────────────────────
|
|
2325
|
+
const batches = buildScanBatches(pendingItems.map(item => item.raw), config)
|
|
2326
|
+
stats.batches = batches.length
|
|
2327
|
+
if (batches.length === 0) return { entries, stats, lastError }
|
|
2328
|
+
|
|
2329
|
+
// 本次真正会进入批处理的未命中卡片。超过 maxCardsPerPass 的未命中卡片本次
|
|
2330
|
+
// 不处理(也不写 fallback),等下一次扫描前面的卡片命中缓存后继续覆盖。
|
|
2331
|
+
const processedPendingCount = batches.reduce((total, batch) => total + batch.length, 0)
|
|
2332
|
+
const plannedItems = pendingItems.slice(0, processedPendingCount)
|
|
2333
|
+
|
|
2334
|
+
const total = batches.length
|
|
2335
|
+
let done = 0
|
|
2336
|
+
const reportProgress = () => {
|
|
2337
|
+
done += 1
|
|
2338
|
+
if (onProgress === null) return
|
|
2339
|
+
try {
|
|
2340
|
+
onProgress({ done, total })
|
|
2341
|
+
} catch {
|
|
2342
|
+
/* 进度回调抛错不能影响扫描本身 */
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
// ── 3. 没有可用模型/调用接口:全部确定性兜底,不抛错 ────────────────────
|
|
2347
|
+
if (target === null || streamFn === null) {
|
|
2348
|
+
const message = target === null ? '没有可用的分析模型(缺少 provider/model)' : '模型调用接口不可用(缺少 llm.stream)'
|
|
2349
|
+
for (let index = 0; index < batches.length; index += 1) {
|
|
2350
|
+
const at = Date.now()
|
|
2351
|
+
for (const raw of batches[index]) applyFallbackForRaw(raw, at)
|
|
2352
|
+
stats.failedBatches += 1
|
|
2353
|
+
reportProgress()
|
|
2354
|
+
}
|
|
2355
|
+
recordError(1, message)
|
|
2356
|
+
return { entries, stats, lastError }
|
|
2357
|
+
}
|
|
2358
|
+
|
|
2359
|
+
// ── 4. 执行单批:独立超时 + 重试 + 独立失败兜底 ─────────────────────────
|
|
2360
|
+
/**
|
|
2361
|
+
* 分析一批卡片:每次尝试独立超时;失败按 config.retries 重试(指数退避),
|
|
2362
|
+
* 重试耗尽才整批兜底。除调用方 abort / beforeBatch 抛错外不向外抛错。
|
|
2363
|
+
* @param {unknown[]} batchRaws - 本批原始卡片。
|
|
2364
|
+
* @param {number} batchNumber - 批次号(1 开始,用于 lastError)。
|
|
2365
|
+
*/
|
|
2366
|
+
const runBatch = async (batchRaws, batchNumber) => {
|
|
2367
|
+
throwIfAborted(callerSignal)
|
|
2368
|
+
if (fatalError !== null) throw fatalError
|
|
2369
|
+
const totalAttempts = config.retries + 1
|
|
2370
|
+
|
|
2371
|
+
for (let attempt = 1; attempt <= totalAttempts; attempt += 1) {
|
|
2372
|
+
throwIfAborted(callerSignal)
|
|
2373
|
+
if (fatalError !== null) throw fatalError
|
|
2374
|
+
|
|
2375
|
+
// 每次尝试(含重试)开始前都先 await 一次宿主钩子:同 session 的网关
|
|
2376
|
+
// 通常只允许单并发流,宿主用它等 agent 空闲再发请求。
|
|
2377
|
+
// 钩子抛错 → 整次扫描抛出该错误(这是「不该发请求」,不是单批失败)。
|
|
2378
|
+
if (beforeBatch !== null) {
|
|
2379
|
+
try {
|
|
2380
|
+
await beforeBatch()
|
|
2381
|
+
} catch (error) {
|
|
2382
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
2383
|
+
throw raiseFatal(error)
|
|
2384
|
+
}
|
|
2385
|
+
throwIfAborted(callerSignal)
|
|
2386
|
+
if (fatalError !== null) throw fatalError
|
|
2387
|
+
}
|
|
2388
|
+
|
|
2389
|
+
const controller = new AbortController()
|
|
2390
|
+
activeControllers.add(controller)
|
|
2391
|
+
let timedOut = false
|
|
2392
|
+
const handleCallerAbort = () => {
|
|
2393
|
+
try {
|
|
2394
|
+
controller.abort(callerSignal === null ? undefined : callerSignal.reason)
|
|
2395
|
+
} catch {
|
|
2396
|
+
try {
|
|
2397
|
+
controller.abort()
|
|
2398
|
+
} catch {
|
|
2399
|
+
/* 已经中止过了 */
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
}
|
|
2403
|
+
if (callerSignal !== null) callerSignal.addEventListener('abort', handleCallerAbort, { once: true })
|
|
2404
|
+
const timer = setTimeout(() => {
|
|
2405
|
+
timedOut = true
|
|
2406
|
+
const error = new Error(`分析请求超时(超过 ${config.timeoutMs}ms)`)
|
|
2407
|
+
error.name = 'TimeoutError'
|
|
2408
|
+
try {
|
|
2409
|
+
controller.abort(error)
|
|
2410
|
+
} catch {
|
|
2411
|
+
/* 已经中止过了 */
|
|
2412
|
+
}
|
|
2413
|
+
}, config.timeoutMs)
|
|
2414
|
+
|
|
2415
|
+
try {
|
|
2416
|
+
const normalizedBatch = batchRaws.map(normalizeSafely)
|
|
2417
|
+
const expectedIds = normalizedBatch.map(card => card.id).filter(id => id !== '')
|
|
2418
|
+
const prompt = buildScanPrompt(batchRaws, config)
|
|
2419
|
+
const text = await collectModelText({
|
|
2420
|
+
streamFn,
|
|
2421
|
+
target,
|
|
2422
|
+
prompt,
|
|
2423
|
+
maxTokens: config.maxTokens,
|
|
2424
|
+
temperature: config.temperature,
|
|
2425
|
+
reasoningEffort: config.reasoningEffort,
|
|
2426
|
+
signal: controller.signal,
|
|
2427
|
+
sessionId,
|
|
2428
|
+
})
|
|
2429
|
+
if (fatalError !== null) throw fatalError
|
|
2430
|
+
const parsed = parseScanResponse(text, expectedIds)
|
|
2431
|
+
if (parsed.results.length === 0) throw new Error('模型输出中没有任何可用的卡片分析结果')
|
|
2432
|
+
|
|
2433
|
+
const at = Date.now()
|
|
2434
|
+
for (const result of parsed.results) {
|
|
2435
|
+
const item = pendingById.get(result.id)
|
|
2436
|
+
if (item === undefined || hasEntry(entries, result.id)) continue
|
|
2437
|
+
// v13 确定性后处理:交付/验证结论识别 + 理由具体化(解析后、写 entry 前)。
|
|
2438
|
+
const analysis = postprocessDeliveryAnalysis(completeAiAnalysis(item.raw, result))
|
|
2439
|
+
putEntry(entries, result.id, buildAnalysisEntry(hashOf(item), analysis, 'ai', at, targetLabel))
|
|
2440
|
+
stats.analyzed += 1
|
|
2441
|
+
}
|
|
2442
|
+
// AI 正常返回但个别 id 缺失/无效:这些卡片确定性兜底(不算整批失败)。
|
|
2443
|
+
for (const id of parsed.invalid) {
|
|
2444
|
+
const item = pendingById.get(id)
|
|
2445
|
+
if (item === undefined || hasEntry(entries, id)) continue
|
|
2446
|
+
applyFallback(normalizeSafely(item.raw), at)
|
|
2447
|
+
}
|
|
2448
|
+
reportProgress()
|
|
2449
|
+
return
|
|
2450
|
+
} catch (error) {
|
|
2451
|
+
// 调用方主动取消:整次扫描抛出,让上层区分「取消」与「失败」;不重试。
|
|
2452
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
2453
|
+
// 其它批次触发的致命错误(beforeBatch 抛错):同样中止,不做兜底。
|
|
2454
|
+
if (fatalError !== null) throw fatalError
|
|
2455
|
+
const failureMessage = timedOut ? `分析请求超时(超过 ${config.timeoutMs}ms)` : toErrorMessage(error)
|
|
2456
|
+
if (attempt < totalAttempts) {
|
|
2457
|
+
// 指数退避:retryDelayMs * 2^(attempt-1);abort 会立刻打断等待。
|
|
2458
|
+
await sleepWithSignal(config.retryDelayMs * 2 ** (attempt - 1), callerSignal)
|
|
2459
|
+
throwIfAborted(callerSignal)
|
|
2460
|
+
continue
|
|
2461
|
+
}
|
|
2462
|
+
// 重试耗尽:整批兜底,不 reject。
|
|
2463
|
+
const at = Date.now()
|
|
2464
|
+
for (const raw of batchRaws) applyFallbackForRaw(raw, at)
|
|
2465
|
+
stats.failedBatches += 1
|
|
2466
|
+
recordError(
|
|
2467
|
+
batchNumber,
|
|
2468
|
+
config.retries > 0 ? `${failureMessage}(已尝试 ${attempt} 次仍失败)` : failureMessage,
|
|
2469
|
+
)
|
|
2470
|
+
reportProgress()
|
|
2471
|
+
return
|
|
2472
|
+
} finally {
|
|
2473
|
+
clearTimeout(timer)
|
|
2474
|
+
activeControllers.delete(controller)
|
|
2475
|
+
if (callerSignal !== null) {
|
|
2476
|
+
try {
|
|
2477
|
+
callerSignal.removeEventListener('abort', handleCallerAbort)
|
|
2478
|
+
} catch {
|
|
2479
|
+
/* 忽略 */
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
}
|
|
2485
|
+
|
|
2486
|
+
// ── 5. 并发调度:最多 maxConcurrentBatches 个 worker 抄同一份批次队列 ────
|
|
2487
|
+
let cursor = 0
|
|
2488
|
+
const worker = async () => {
|
|
2489
|
+
while (true) {
|
|
2490
|
+
if (fatalError !== null) throw fatalError
|
|
2491
|
+
throwIfAborted(callerSignal)
|
|
2492
|
+
const index = cursor
|
|
2493
|
+
cursor += 1
|
|
2494
|
+
if (index >= total) return
|
|
2495
|
+
await runBatch(batches[index], index + 1)
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
const workerCount = Math.max(1, Math.min(config.maxConcurrentBatches, total))
|
|
2499
|
+
const workers = []
|
|
2500
|
+
for (let index = 0; index < workerCount; index += 1) workers.push(worker())
|
|
2501
|
+
const settled = await Promise.allSettled(workers)
|
|
2502
|
+
|
|
2503
|
+
// beforeBatch 抛错 = 致命错误:整次扫描抛出(不做 fallback)。
|
|
2504
|
+
if (fatalError !== null) throw fatalError
|
|
2505
|
+
|
|
2506
|
+
// worker 理论上只会因「调用方 abort / 致命错误」reject;其余情况这里再兜一层。
|
|
2507
|
+
const rejected = settled.find(result => result.status === 'rejected')
|
|
2508
|
+
if (rejected !== undefined) {
|
|
2509
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
2510
|
+
recordError(stats.batches, toErrorMessage(rejected.reason))
|
|
2511
|
+
}
|
|
2512
|
+
throwIfAborted(callerSignal)
|
|
2513
|
+
|
|
2514
|
+
// 兜底:本次计划处理的卡片若因意外没有写入结果,都补一份确定性分析
|
|
2515
|
+
//(正常情况下为空操作;被 maxCardsPerPass 有意跳过的卡片不在此列)。
|
|
2516
|
+
const at = Date.now()
|
|
2517
|
+
for (const item of plannedItems) {
|
|
2518
|
+
if (hasEntry(entries, item.id)) continue
|
|
2519
|
+
applyFallback(normalizeSafely(item.raw), at)
|
|
2520
|
+
}
|
|
2521
|
+
return { entries, stats, lastError }
|
|
2522
|
+
} catch (error) {
|
|
2523
|
+
// 调用方取消:按契约抛出(AbortError 或 signal.reason)。
|
|
2524
|
+
if (callerSignal !== null && callerSignal.aborted) throw abortErrorFrom(callerSignal)
|
|
2525
|
+
// beforeBatch 抛错:按契约抛出该错误(不做 fallback)。
|
|
2526
|
+
if (fatalError !== null) throw fatalError
|
|
2527
|
+
// 最后兜底:其它意外异常不能让整次扫描 reject。
|
|
2528
|
+
const message = toErrorMessage(error)
|
|
2529
|
+
if (lastError === null) lastError = { batch: Math.min(1, stats.batches), message }
|
|
2530
|
+
const at = Date.now()
|
|
2531
|
+
for (const item of items) {
|
|
2532
|
+
if (hasEntry(entries, item.id)) continue
|
|
2533
|
+
applyFallback(normalizeSafely(item.raw), at)
|
|
2534
|
+
}
|
|
2535
|
+
return { entries, stats, lastError }
|
|
2536
|
+
}
|
|
2537
|
+
}
|