carlos-flow 2.12.0 → 2.12.6
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/AGENTS.md +5 -0
- package/CHANGELOG.md +660 -631
- package/README.md +34 -527
- package/README.zh.md +34 -527
- package/TRIGGER_GUIDE.md +2 -2
- package/bridge/mcp-bridge.js +203 -203
- package/check-all.sh +0 -0
- package/ghost.json +32 -1
- package/package.json +114 -113
- package/plugins/carlos-flow-trigger.js +215 -215
- package/scripts/check-artifacts.mjs +7 -0
- package/scripts/check-no-dead-handler.mjs +87 -87
- package/scripts/check-refs.mjs +10 -0
- package/scripts/check-stubs.mjs +90 -0
- package/scripts/check-templates.mjs +126 -126
- package/scripts/clean-readme-noise.mjs +53 -53
- package/scripts/install-hooks.mjs +166 -166
- package/scripts/lang-audit.mjs +172 -172
- package/scripts/mutation-check.mjs +483 -483
- package/scripts/release.mjs +6 -1
- package/scripts/sync-readme.mjs +102 -102
- package/scripts/verify-activation-e2e.sh +55 -55
- package/smoke-test.js +142 -142
- package/src/card.js +296 -288
- package/src/commander.js +10 -0
- package/src/dispatch.js +557 -548
- package/src/index.js +1713 -1686
- package/src/profiles.js +17 -0
- package/src/protocol.js +95 -85
- package/src/state.js +930 -898
- package/src/trigger.js +909 -909
package/src/trigger.js
CHANGED
|
@@ -1,909 +1,909 @@
|
|
|
1
|
-
// Carlos 工作流智能触发引擎
|
|
2
|
-
// 三层智能触发系统:动态上限、评分系统、决策引擎
|
|
3
|
-
|
|
4
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
|
|
5
|
-
import { join, dirname, resolve } from 'node:path';
|
|
6
|
-
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import os from 'node:os';
|
|
8
|
-
|
|
9
|
-
// 触发器状态/配置目录:与 state.js 的 FLOW_HOME 保持同一约定,避免污染仓库目录
|
|
10
|
-
const TRIGGER_HOME = (() => {
|
|
11
|
-
// 与 state.js 同一套 `~` 展开:否则 CARLOS_FLOW_HOME=~/.carlos-flow 不会被展开,
|
|
12
|
-
// 触发器状态/配置会写到「当前目录下的一个名叫 ~ 的目录」里。
|
|
13
|
-
const raw = process.env.CARLOS_FLOW_HOME || process.env.CARLOS_FLOW_ROOT || join(os.homedir(), '.carlos-flow');
|
|
14
|
-
if (typeof raw !== 'string' || raw === '') return join(os.homedir(), '.carlos-flow');
|
|
15
|
-
if (raw === '~') return os.homedir();
|
|
16
|
-
if (raw.startsWith('~/') || raw.startsWith('~\\')) return join(os.homedir(), raw.slice(2));
|
|
17
|
-
return raw;
|
|
18
|
-
})();
|
|
19
|
-
const CONFIG_PATH = join(TRIGGER_HOME, 'trigger-config.json');
|
|
20
|
-
const STATE_DIR = join(TRIGGER_HOME, 'trigger-state');
|
|
21
|
-
const DEFAULT_STATE_PATH = join(TRIGGER_HOME, 'trigger-state.json');
|
|
22
|
-
|
|
23
|
-
// 按会话隔离状态文件:不同会话的触发历史 / 限流状态互不影响。
|
|
24
|
-
// sessionId 会被清洗成安全的文件名,避免路径穿越。
|
|
25
|
-
// Windows 保留设备名(CON / PRN / AUX / NUL / COM1-9 / LPT1-9 …)
|
|
26
|
-
// 即便带扩展名(CON.json)在 NTFS 上也无法创建,必须避开。
|
|
27
|
-
const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
|
|
28
|
-
|
|
29
|
-
function sanitizeSessionId(sessionId) {
|
|
30
|
-
const raw = String(sessionId || 'default');
|
|
31
|
-
// 1) 清洗路径分隔符与非法字符(斜杠、背杠、冒号等)
|
|
32
|
-
let safe = raw.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 48);
|
|
33
|
-
// 2) 不允许以点开头(避免 "." / ".." 语义)
|
|
34
|
-
safe = safe.replace(/^\.+/, '_');
|
|
35
|
-
if (!safe) safe = 'default';
|
|
36
|
-
// 3) 避开 Windows 保留设备名
|
|
37
|
-
if (WINDOWS_RESERVED.test(safe)) safe = '_' + safe;
|
|
38
|
-
// 3) 追加原始 id 的短哈希:清洗后可能撞名("a/b" 与 "a_b" 都会变成 "a_b"),
|
|
39
|
-
// 用哈希保证不同 session 不会共用同一份状态文件
|
|
40
|
-
let h = 0;
|
|
41
|
-
for (let i = 0; i < raw.length; i++) {
|
|
42
|
-
h = (h * 31 + raw.charCodeAt(i)) >>> 0;
|
|
43
|
-
}
|
|
44
|
-
const suffix = h.toString(16).padStart(8, '0').slice(0, 8);
|
|
45
|
-
return safe + '-' + suffix;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function statePathFor(sessionId) {
|
|
49
|
-
if (!sessionId || sessionId === 'default') return DEFAULT_STATE_PATH;
|
|
50
|
-
return join(STATE_DIR, sanitizeSessionId(sessionId) + '.json');
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// 确保目录存在(FLOW_HOME 可能尚未创建)
|
|
54
|
-
function ensureHome() {
|
|
55
|
-
try { mkdirSync(TRIGGER_HOME, { recursive: true }); } catch { /* 目录已存在或不可写 */ }
|
|
56
|
-
}
|
|
57
|
-
const DEFAULT_CONFIG = {
|
|
58
|
-
// 动态上限参数
|
|
59
|
-
baseTriggerLimit: 5, // 基础触发上限
|
|
60
|
-
maxTriggerLimit: 15, // 最大触发上限
|
|
61
|
-
sessionLengthCoeff: 0.5, // 会话时长系数(每小时增加 0.5 个)
|
|
62
|
-
complexityCoeff: 2, // 任务复杂度系数
|
|
63
|
-
historyCoeff: 0.3, // 历史触发频率系数(惩罚项)
|
|
64
|
-
|
|
65
|
-
// 评分参数
|
|
66
|
-
// 关键词表:只收**流程性**词汇(表示“要走门禁/工作流”),不收普通开发动词
|
|
67
|
-
// (如「实现」「新增」「接口」)—— 否则每条普通需求都会命中,触发器就退化成噪声。
|
|
68
|
-
// 中文词与英文词同权重:用户用中文提需求时,触发行为与英文一致。
|
|
69
|
-
keywordWeights: {
|
|
70
|
-
'work': 3, 'flow': 3, 'carlos': 4, 'dispatch': 3,
|
|
71
|
-
'trigger': 2, 'start': 1, 'run': 1, 'execute': 2,
|
|
72
|
-
// 中文流程词
|
|
73
|
-
'工作流': 3, '门禁': 4, '任务卡': 3, '派发': 3, '子代理': 3,
|
|
74
|
-
'流程': 2, '触发': 2, '执行': 2, '调度': 2,
|
|
75
|
-
'审计': 2, '复核': 2, '留痕': 2, '裁定': 2,
|
|
76
|
-
},
|
|
77
|
-
contextRelevanceWeight: 0.3,
|
|
78
|
-
userIntentWeight: 0.2,
|
|
79
|
-
|
|
80
|
-
// 决策阈值
|
|
81
|
-
triggerThreshold: 15, // 触发阈值(0-100)
|
|
82
|
-
autoTriggerThreshold: 25, // 自动触发阈值(高中意图时)
|
|
83
|
-
lowConfidenceThreshold: 10, // 低置信度阈值
|
|
84
|
-
|
|
85
|
-
// 只读意图识别:命中只读词且**不含**改动动词 → 不进入工作流门禁。
|
|
86
|
-
// 原因:占位卡恒为 read_only 档(scope=[]),若一个只需要只读调研的任务
|
|
87
|
-
// 被激活,它的待补项(scope/acceptance/verify.cmd)永远无法被满足 ——
|
|
88
|
-
// 因为只读任务本来就不需要改文件 —— 该会话会被永久锁死。
|
|
89
|
-
readOnlyIntentWords: [
|
|
90
|
-
'explain', 'describe', 'analyse', 'analyze', 'summarize', 'summarise',
|
|
91
|
-
'what', 'why', 'how', 'understand', 'overview', 'compare', 'inspect',
|
|
92
|
-
'read', '查找', '解释', '分析', '总结', '为什么', '是什么', '调研', '对比', '了解', '查看', '读一下', '看看',
|
|
93
|
-
],
|
|
94
|
-
mutatingActionWords: [
|
|
95
|
-
'fix', 'refactor', 'change', 'update', 'implement', 'add', 'remove',
|
|
96
|
-
'modify', 'rewrite', 'migrate', 'patch', 'upgrade', 'rename',
|
|
97
|
-
'修复', '重构', '修改', '更新', '实现', '新增', '删除', '重写', '迁移', '改造', '写一个', '写个',
|
|
98
|
-
],
|
|
99
|
-
|
|
100
|
-
// 用户反馈学习
|
|
101
|
-
feedbackLearningRate: 0.1,
|
|
102
|
-
feedbackLearningCycle: 10, // 每累积多少条反馈重新学习一次
|
|
103
|
-
feedbackThresholdOffset: 0, // 学习结果:负反馈多 → 抬高触发阈值
|
|
104
|
-
positiveFeedbackWeight: 1.5,
|
|
105
|
-
negativeFeedbackWeight: 0.7,
|
|
106
|
-
|
|
107
|
-
// 触发窗口
|
|
108
|
-
triggerWindowMinutes: 60, // 触发窗口期(分钟)——需 ≥ 最长间隔×窗口倍数,
|
|
109
|
-
// 否则「窗口内次数达上限」分支永远不可达
|
|
110
|
-
minTriggerIntervalSeconds: 300 // 最少触发间隔(秒)
|
|
111
|
-
};
|
|
112
|
-
|
|
113
|
-
// 加载配置文件
|
|
114
|
-
//
|
|
115
|
-
// 词表类字段必须做**合并**而不是整体替换。
|
|
116
|
-
// 原实现 `config = { ...DEFAULT_CONFIG, ...loaded }` 是浅合并 —— 用户一旦写了
|
|
117
|
-
// `keywordWeights`,就会把默认词表(含内置的中文流程词)**整个丢掉**,
|
|
118
|
-
// 于是「我只是加一个自定义词」反而让所有默认词失效,中文场景重新变回 0 分。
|
|
119
|
-
// 语义修正:
|
|
120
|
-
// · keywordWeights:对象 → 合并(用户词覆盖同名默认词,其余默认词保留)
|
|
121
|
-
// · readOnlyIntentWords / mutatingActionWords:数组 → 追加去重(“扩展”而非“替换”)
|
|
122
|
-
// · 其余标量字段:覆盖(阈值、权重等本来就是单值)
|
|
123
|
-
let config = DEFAULT_CONFIG;
|
|
124
|
-
if (existsSync(CONFIG_PATH)) {
|
|
125
|
-
try {
|
|
126
|
-
const loaded = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
|
|
127
|
-
config = { ...DEFAULT_CONFIG, ...loaded };
|
|
128
|
-
// keywordWeights 必须是**对象**才能合并。
|
|
129
|
-
// 浅合并会把 null / 数组 / 数字一并带进 config.keywordWeights,
|
|
130
|
-
// 而下面的 if 因假值跳过深合并 → config.keywordWeights 保持非法值 →
|
|
131
|
-
// buildKeywordIndex() 的 Object.entries(null) 抛 TypeError →
|
|
132
|
-
// 触发引擎在该进程内**每次调用都失败**(客户端 catch 掉 → 静默失去自动触发)。
|
|
133
|
-
// 所以:类型不对就丢弃用户值、回退默认表,并在合并后再兜一次底。
|
|
134
|
-
if (loaded.keywordWeights !== undefined) {
|
|
135
|
-
if (loaded.keywordWeights && typeof loaded.keywordWeights === 'object' && !Array.isArray(loaded.keywordWeights)) {
|
|
136
|
-
config.keywordWeights = { ...DEFAULT_CONFIG.keywordWeights, ...loaded.keywordWeights };
|
|
137
|
-
} else {
|
|
138
|
-
console.warn('[Carlos Trigger] keywordWeights 必须是对象,已忽略该配置项(使用默认词表)');
|
|
139
|
-
config.keywordWeights = { ...DEFAULT_CONFIG.keywordWeights };
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
for (const key of ['readOnlyIntentWords', 'mutatingActionWords']) {
|
|
143
|
-
if (Array.isArray(loaded[key]) && Array.isArray(DEFAULT_CONFIG[key])) {
|
|
144
|
-
config[key] = [...new Set([...DEFAULT_CONFIG[key], ...loaded[key]])];
|
|
145
|
-
} else if (loaded[key] !== undefined) {
|
|
146
|
-
console.warn(`[Carlos Trigger] ${key} 必须是数组,已忽略该配置项(使用默认词表)`);
|
|
147
|
-
config[key] = [...DEFAULT_CONFIG[key]];
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
} catch (e) {
|
|
151
|
-
console.warn('[Carlos Trigger] 配置加载失败:', e.message);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// ============ 激活动作辅助 ============
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* 只读意图识别。
|
|
159
|
-
*
|
|
160
|
-
* 命中只读词(explain/analyze/调研/看看…)且**不含**改动动词
|
|
161
|
-
* (fix/refactor/修改/修复…)→ 判定为只读调研。
|
|
162
|
-
*
|
|
163
|
-
* 为什么要单独识别:智能触发引擎开的占位卡恒为 read_only 档(scope=[]),
|
|
164
|
-
* 其待补项是 scope/acceptance/verify.cmd。如果一个**只需要只读调研**的任务
|
|
165
|
-
* 被激活,这三项永远无法被满足(只读任务本来就不改文件)——
|
|
166
|
-
* 该会话会被永久锁死,且没有任何合法路径解闸。
|
|
167
|
-
*/
|
|
168
|
-
function isReadOnlyIntent(message) {
|
|
169
|
-
const s = String(message || '').toLowerCase();
|
|
170
|
-
if (!s) return false;
|
|
171
|
-
const ro = config.readOnlyIntentWords || [];
|
|
172
|
-
const mut = config.mutatingActionWords || [];
|
|
173
|
-
const hasReadOnly = ro.some((w) => s.includes(String(w).toLowerCase()));
|
|
174
|
-
if (!hasReadOnly) return false;
|
|
175
|
-
// 同时含改动动词 → 以改动为准(避免 "analyze and refactor" 被误判为只读)
|
|
176
|
-
const hasMutating = mut.some((w) => s.includes(String(w).toLowerCase()));
|
|
177
|
-
return !hasMutating;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* 从用户原话与命中关键词推导一个粗粒度目标。
|
|
182
|
-
* 引擎无法知道真实目标,因此这只是**占位推断**,必须由 Agent 确认或改写。
|
|
183
|
-
*/
|
|
184
|
-
function deriveGoal(message, matchedKeywords = []) {
|
|
185
|
-
const text = String(message || '').trim();
|
|
186
|
-
const head = text.split(/[\n\r。.;;!?!?]/)[0].trim();
|
|
187
|
-
const kw = matchedKeywords.length ? `(命中:${matchedKeywords.join(', ')})` : '';
|
|
188
|
-
const base = head ? head.slice(0, 60) : '待补充目标';
|
|
189
|
-
return `执行 Carlos 工作流任务:${base}${kw}`;
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/**
|
|
193
|
-
* 生成给 Agent 的补全指令(激活后的第一件事)。
|
|
194
|
-
*/
|
|
195
|
-
function buildActivationPrompt(result, goal, matchedKeywords, mode = 'auto') {
|
|
196
|
-
const isAuto = mode === 'auto';
|
|
197
|
-
return [
|
|
198
|
-
isAuto ? '【Carlos 触发引擎已激活工作流】' : '【Carlos 触发引擎建议手动启动门禁】',
|
|
199
|
-
'',
|
|
200
|
-
`判定:${result.decision}(评分 ${result.score} / 置信度 ${result.confidence})`,
|
|
201
|
-
`命中关键词:${matchedKeywords.length ? matchedKeywords.join(', ') : '(无直接关键词命中)'}`,
|
|
202
|
-
`推断目标(占位,需确认或改写):${goal}`,
|
|
203
|
-
'',
|
|
204
|
-
isAuto
|
|
205
|
-
? '已完成:用户原话已留痕,占位任务卡已提交,会话已进入门禁状态。'
|
|
206
|
-
: '尚未执行任何动作(未留痕、未开卡)—— 本次评分未达自动激活条件,请自行决定是否启动门禁。',
|
|
207
|
-
'',
|
|
208
|
-
'接下来请:',
|
|
209
|
-
'1. 与用户确认上面的目标描述是否准确;',
|
|
210
|
-
isAuto
|
|
211
|
-
? '2. 补齐 scope(只准改动的文件)、acceptance(可判定的验收标准)、verify.cmd(验证命令);'
|
|
212
|
-
: '2. 若决定启动门禁:先 flow_add_user_msg 留痕,再 flow_submit_requirement 提交任务卡(需含 scope / acceptance / verify.cmd);',
|
|
213
|
-
isAuto
|
|
214
|
-
? '3. 重新调用 flow_submit_requirement 提交完整任务卡(会替换占位卡);'
|
|
215
|
-
: '3. 再调用 flow_claim / flow_dispatch 派发。',
|
|
216
|
-
isAuto
|
|
217
|
-
? '4. 再调用 flow_claim / flow_dispatch 派发。'
|
|
218
|
-
: '',
|
|
219
|
-
'',
|
|
220
|
-
isAuto
|
|
221
|
-
? '注意:在 scope / acceptance / verify.cmd 补齐之前,flow_claim 与 flow_dispatch 会拒绝派发。'
|
|
222
|
-
: '注意:本次建议不会自动提交任何卡片。',
|
|
223
|
-
].join('\n');
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// ============ 状态管理 ============
|
|
227
|
-
class TriggerState {
|
|
228
|
-
constructor(sessionId = 'default') {
|
|
229
|
-
this.sessionId = sessionId;
|
|
230
|
-
this.triggerHistory = [];
|
|
231
|
-
this.sessionStartTime = Date.now();
|
|
232
|
-
this.lastTriggerTime = 0;
|
|
233
|
-
this.impressionCount = 0; // 关联 impressionId
|
|
234
|
-
this.feedback = { positive: 0, negative: 0 }; // 用户反馈(持久化)
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
getSessionAgeHours() {
|
|
238
|
-
return (Date.now() - this.sessionStartTime) / (1000 * 60 * 60);
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
save() {
|
|
242
|
-
ensureHome();
|
|
243
|
-
const target = statePathFor(this.sessionId);
|
|
244
|
-
try {
|
|
245
|
-
mkdirSync(dirname(target), { recursive: true });
|
|
246
|
-
} catch { /* 目录已存在或不可写 */ }
|
|
247
|
-
try {
|
|
248
|
-
writeFileSync(target, JSON.stringify(this, null, 2));
|
|
249
|
-
} catch (e) {
|
|
250
|
-
// 状态落盘失败(如保留设备名、权限不足、磁盘满)不能让引擎整体崩掉:
|
|
251
|
-
// 降级为「本次不持久化」,主流程继续。
|
|
252
|
-
try {
|
|
253
|
-
process.stderr.write(`[carlos-trigger] 状态保存失败(${this.sessionId}):${e && e.message ? e.message : e}
|
|
254
|
-
`);
|
|
255
|
-
} catch { /* stderr 不可写 */ }
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
static load(sessionId = 'default') {
|
|
260
|
-
const target = statePathFor(sessionId);
|
|
261
|
-
if (existsSync(target)) {
|
|
262
|
-
try {
|
|
263
|
-
const loaded = JSON.parse(readFileSync(target, 'utf8'));
|
|
264
|
-
const state = new TriggerState(sessionId);
|
|
265
|
-
Object.assign(state, loaded);
|
|
266
|
-
// sessionId 由调用方决定,不允许被持久化文件覆盖
|
|
267
|
-
state.sessionId = sessionId;
|
|
268
|
-
return state;
|
|
269
|
-
} catch (e) {
|
|
270
|
-
// 状态文件损坏时降级为新状态,不阻断主流程
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
return new TriggerState(sessionId);
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// ============ L1: DynamicTriggerManager ============
|
|
278
|
-
class DynamicTriggerManager {
|
|
279
|
-
constructor(state = null) {
|
|
280
|
-
this.state = state || TriggerState.load();
|
|
281
|
-
this.triggerCache = new Map();
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/**
|
|
285
|
-
* 计算当前动态触发上限
|
|
286
|
-
* 基于会话时长、任务复杂度和历史触发频率
|
|
287
|
-
*
|
|
288
|
-
* 设计要点:
|
|
289
|
-
* - 会话越长、任务越复杂 → 上限越高(允许更多触发)
|
|
290
|
-
* - 近期触发越频繁 → 上限越低(收敛打扰),否则上限会被历史反向抬高而永不生效
|
|
291
|
-
*/
|
|
292
|
-
calculateDynamicLimit(sessionComplexity = 1.0) {
|
|
293
|
-
const sessionAge = this.state.getSessionAgeHours();
|
|
294
|
-
const recentCount = this.countTriggersInWindow();
|
|
295
|
-
|
|
296
|
-
// 上限 = 基础 + 会话时长增益 + 复杂度增益 - 近期频繁触发惩罚
|
|
297
|
-
const rawLimit =
|
|
298
|
-
config.baseTriggerLimit +
|
|
299
|
-
(sessionAge * config.sessionLengthCoeff) +
|
|
300
|
-
(sessionComplexity * config.complexityCoeff) -
|
|
301
|
-
(recentCount * config.historyCoeff);
|
|
302
|
-
|
|
303
|
-
const dynamicLimit = Math.max(1, Math.min(rawLimit, config.maxTriggerLimit));
|
|
304
|
-
|
|
305
|
-
return Math.floor(dynamicLimit);
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
/**
|
|
309
|
-
* 统计触发窗口内的实际触发次数(原始计数,用于上限判定)
|
|
310
|
-
*/
|
|
311
|
-
countTriggersInWindow() {
|
|
312
|
-
const windowStart = Date.now() - (config.triggerWindowMinutes * 60 * 1000);
|
|
313
|
-
return this.state.triggerHistory.filter(t => t.timestamp > windowStart).length;
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
/**
|
|
317
|
-
* 记录触发事件
|
|
318
|
-
*/
|
|
319
|
-
recordTrigger(triggerData = {}) {
|
|
320
|
-
this.state.triggerHistory.push({
|
|
321
|
-
timestamp: Date.now(),
|
|
322
|
-
impulseScore: triggerData.impulseScore || 0,
|
|
323
|
-
context: triggerData.context || 'unknown',
|
|
324
|
-
userResponse: triggerData.userResponse || 'pending'
|
|
325
|
-
});
|
|
326
|
-
|
|
327
|
-
this.state.lastTriggerTime = Date.now();
|
|
328
|
-
this.state.impressionCount++;
|
|
329
|
-
this.state.save();
|
|
330
|
-
|
|
331
|
-
// 清理过期记录
|
|
332
|
-
this.cleanupHistory();
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
/**
|
|
336
|
-
* 清理过期历史数据
|
|
337
|
-
*/
|
|
338
|
-
cleanupHistory() {
|
|
339
|
-
const cutoff = Date.now() - (24 * 60 * 60 * 1000); // 24小时
|
|
340
|
-
this.state.triggerHistory = this.state.triggerHistory.filter(
|
|
341
|
-
t => t.timestamp > cutoff
|
|
342
|
-
);
|
|
343
|
-
this.state.save();
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
/**
|
|
347
|
-
* 检查是否可以触发
|
|
348
|
-
*/
|
|
349
|
-
canTrigger(sessionComplexity = 1.0) {
|
|
350
|
-
// 检查最小时间间隔
|
|
351
|
-
const timeSinceLastTrigger = Date.now() - this.state.lastTriggerTime;
|
|
352
|
-
if (timeSinceLastTrigger < config.minTriggerIntervalSeconds * 1000) {
|
|
353
|
-
return { can: false, reason: '时间间隔不足' };
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
// 检查动态上限:用窗口内的实际触发次数与上限比较
|
|
357
|
-
const currentLimit = this.calculateDynamicLimit(sessionComplexity);
|
|
358
|
-
const triggerCountInWindow = this.countTriggersInWindow();
|
|
359
|
-
|
|
360
|
-
if (triggerCountInWindow >= currentLimit) {
|
|
361
|
-
return { can: false, reason: `触发次数已达上限 (${triggerCountInWindow}/${currentLimit})` };
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
return { can: true, limit: currentLimit, count: triggerCountInWindow };
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
reset() {
|
|
368
|
-
this.state.triggerHistory = [];
|
|
369
|
-
this.state.lastTriggerTime = 0;
|
|
370
|
-
this.state.save();
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
// ============ L2: TriggerScorer ============
|
|
375
|
-
class TriggerScorer {
|
|
376
|
-
constructor() {
|
|
377
|
-
this.keywordIndex = new Map();
|
|
378
|
-
this.buildKeywordIndex();
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
/**
|
|
382
|
-
* 构建关键词索引
|
|
383
|
-
*/
|
|
384
|
-
buildKeywordIndex() {
|
|
385
|
-
Object.entries(config.keywordWeights).forEach(([keyword, weight]) => {
|
|
386
|
-
this.keywordIndex.set(keyword.toLowerCase(), weight);
|
|
387
|
-
});
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
/**
|
|
391
|
-
* 计算关键词匹配分数
|
|
392
|
-
*/
|
|
393
|
-
calculateKeywordScore(message) {
|
|
394
|
-
const lowerMsg = message.toLowerCase();
|
|
395
|
-
let score = 0;
|
|
396
|
-
let matchedKeywords = [];
|
|
397
|
-
|
|
398
|
-
this.keywordIndex.forEach((weight, keyword) => {
|
|
399
|
-
if (lowerMsg.includes(keyword)) {
|
|
400
|
-
score += weight;
|
|
401
|
-
matchedKeywords.push(keyword);
|
|
402
|
-
}
|
|
403
|
-
});
|
|
404
|
-
|
|
405
|
-
// 标准化到 0-50 范围
|
|
406
|
-
const normalizedScore = Math.min(score * 5, 50);
|
|
407
|
-
|
|
408
|
-
return {
|
|
409
|
-
score: normalizedScore,
|
|
410
|
-
matchedKeywords,
|
|
411
|
-
maxKeywordScore: 50
|
|
412
|
-
};
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
* 计算上下文相关性分数
|
|
417
|
-
*/
|
|
418
|
-
calculateContextRelevance(message, context = {}) {
|
|
419
|
-
// 简单实现:基于工作流相关关键词
|
|
420
|
-
const workFlowKeywords = ['work', 'flow', 'dispatch', 'executor', 'auditor',
|
|
421
|
-
'工作流', '门禁', '派发', '审计', '复核', '任务卡'];
|
|
422
|
-
const lowerMsg = message.toLowerCase();
|
|
423
|
-
|
|
424
|
-
let contextScore = 0;
|
|
425
|
-
let matchedContext = [];
|
|
426
|
-
|
|
427
|
-
workFlowKeywords.forEach(keyword => {
|
|
428
|
-
if (lowerMsg.includes(keyword)) {
|
|
429
|
-
contextScore += 3;
|
|
430
|
-
matchedContext.push(keyword);
|
|
431
|
-
}
|
|
432
|
-
});
|
|
433
|
-
|
|
434
|
-
// 基于上下文复杂度调整
|
|
435
|
-
if (context.complexity) {
|
|
436
|
-
contextScore *= context.complexity;
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
// 标准化到 0-30 范围
|
|
440
|
-
const normalizedScore = Math.min(contextScore * 3, 30);
|
|
441
|
-
|
|
442
|
-
return {
|
|
443
|
-
score: normalizedScore,
|
|
444
|
-
matchedContext,
|
|
445
|
-
maxContextScore: 30
|
|
446
|
-
};
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
/**
|
|
450
|
-
* 计算用户意图分数
|
|
451
|
-
*
|
|
452
|
-
* @param {string} message 用户输入
|
|
453
|
-
* @param {number} historyCount 当前会话的触发历史条数(由 L3 传入)
|
|
454
|
-
* —— 评分层不再自己去磁盘读状态,避免与 L1 读到不同会话
|
|
455
|
-
*/
|
|
456
|
-
calculateUserIntent(message, historyCount = 0) {
|
|
457
|
-
// 简单实现:基于用户行为模式
|
|
458
|
-
const userIntentCandidates = {
|
|
459
|
-
'workflow': ['dispatch', 'run', 'execute', 'trigger', 'start', '执行', '派发', '触发', '工作流', '门禁'],
|
|
460
|
-
'automation': ['auto', 'automate', 'workflow', 'process', '自动', '流程', '调度'],
|
|
461
|
-
'management': ['manage', 'control', 'monitor', 'track', '管理', '监控']
|
|
462
|
-
};
|
|
463
|
-
|
|
464
|
-
const lowerMsg = message.toLowerCase();
|
|
465
|
-
let intentScore = 0;
|
|
466
|
-
let intentType = 'generic';
|
|
467
|
-
|
|
468
|
-
Object.entries(userIntentCandidates).forEach(([type, keywords]) => {
|
|
469
|
-
const hasKeyword = keywords.some(k => lowerMsg.includes(k));
|
|
470
|
-
if (hasKeyword) {
|
|
471
|
-
intentScore += 20;
|
|
472
|
-
intentType = type;
|
|
473
|
-
}
|
|
474
|
-
});
|
|
475
|
-
|
|
476
|
-
// 基于会话历史调整(活跃用户意图分上浮)
|
|
477
|
-
if (historyCount > 10) {
|
|
478
|
-
intentScore *= 1.2; // 活跃用户
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
// 标准化到 0-20 范围
|
|
482
|
-
const normalizedScore = Math.min(intentScore, 20);
|
|
483
|
-
|
|
484
|
-
return {
|
|
485
|
-
score: normalizedScore,
|
|
486
|
-
intentType,
|
|
487
|
-
maxIntentScore: 20
|
|
488
|
-
};
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
/**
|
|
492
|
-
* 综合评分
|
|
493
|
-
*
|
|
494
|
-
* @param {string} message 用户输入
|
|
495
|
-
* @param {object} context 上下文(complexity 等)
|
|
496
|
-
* @param {number} historyCount 当前会话触发历史条数(由 L3 传入,保证与 L1 同会话)
|
|
497
|
-
*/
|
|
498
|
-
calculateImpulseScore(message, context = {}, historyCount = 0) {
|
|
499
|
-
const keywordResult = this.calculateKeywordScore(message);
|
|
500
|
-
const contextResult = this.calculateContextRelevance(message, context);
|
|
501
|
-
const intentResult = this.calculateUserIntent(message, historyCount);
|
|
502
|
-
|
|
503
|
-
const totalScore =
|
|
504
|
-
keywordResult.score * (1 - config.contextRelevanceWeight - config.userIntentWeight) +
|
|
505
|
-
contextResult.score * config.contextRelevanceWeight +
|
|
506
|
-
intentResult.score * config.userIntentWeight;
|
|
507
|
-
|
|
508
|
-
return {
|
|
509
|
-
score: Math.round(totalScore),
|
|
510
|
-
breakdown: {
|
|
511
|
-
keyword: keywordResult,
|
|
512
|
-
context: contextResult,
|
|
513
|
-
intent: intentResult
|
|
514
|
-
},
|
|
515
|
-
confidence: this.calculateConfidence(keywordResult, contextResult, intentResult)
|
|
516
|
-
};
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
/**
|
|
520
|
-
* 计算置信度
|
|
521
|
-
*/
|
|
522
|
-
calculateConfidence(keyword, context, intent) {
|
|
523
|
-
const allMatched = keyword.matchedKeywords.length +
|
|
524
|
-
context.matchedContext.length +
|
|
525
|
-
(intent.intentType !== 'generic' ? 1 : 0);
|
|
526
|
-
|
|
527
|
-
if (allMatched === 0) return 0.3; // 低置信度
|
|
528
|
-
if (allMatched <= 2) return 0.6; // 中等置信度
|
|
529
|
-
return 0.9; // 高置信度
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
// ============ L3: TriggerDecisionEngine ============
|
|
534
|
-
class TriggerDecisionEngine {
|
|
535
|
-
constructor(triggerManager = null, scorer = null, sessionId = null) {
|
|
536
|
-
this.triggerManager = triggerManager || new DynamicTriggerManager();
|
|
537
|
-
this.scorer = scorer || new TriggerScorer();
|
|
538
|
-
// 会话维度:L1(上限/历史)与 L2(评分)必须读同一个会话,
|
|
539
|
-
// 否则会出现「上限算的是 A 会话、历史算的是 B 会话」的串扰。
|
|
540
|
-
this.sessionId = sessionId || (this.triggerManager && this.triggerManager.state && this.triggerManager.state.sessionId) || 'default';
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
/**
|
|
544
|
-
* 主触发决策
|
|
545
|
-
* 基于评分和动态上限决定是否触发
|
|
546
|
-
*
|
|
547
|
-
* @param {string} message 用户输入
|
|
548
|
-
* @param {object} context 上下文
|
|
549
|
-
* @param {string} [sessionId] 会话 ID;省略时使用引擎实例自己的会话
|
|
550
|
-
*/
|
|
551
|
-
shouldTrigger(message, context = {}, sessionId = null) {
|
|
552
|
-
// 会话统一到一处:显式传入 > 引擎实例会话 > default
|
|
553
|
-
const sid = sessionId || this.sessionId;
|
|
554
|
-
// 1. 先计算触发评分(即使被限流,评分与置信度也要如实返回,不能丢成 0/undefined)
|
|
555
|
-
const historyCount = Array.isArray(this.triggerManager.state.triggerHistory)
|
|
556
|
-
? this.triggerManager.state.triggerHistory.length
|
|
557
|
-
: 0;
|
|
558
|
-
const impulseResult = this.scorer.calculateImpulseScore(message, context, historyCount);
|
|
559
|
-
const score = impulseResult.score;
|
|
560
|
-
|
|
561
|
-
// 2. 检查是否可以触发(上限和时间间隔)
|
|
562
|
-
const complexity = Number(context.complexity) || 1.0;
|
|
563
|
-
const canTrigger = this.triggerManager.canTrigger(complexity);
|
|
564
|
-
if (!canTrigger.can) {
|
|
565
|
-
const throttled = {
|
|
566
|
-
shouldTrigger: false,
|
|
567
|
-
reason: canTrigger.reason,
|
|
568
|
-
score,
|
|
569
|
-
confidence: impulseResult.confidence,
|
|
570
|
-
breakdown: impulseResult.breakdown,
|
|
571
|
-
decision: 'throttled',
|
|
572
|
-
action: null,
|
|
573
|
-
};
|
|
574
|
-
// 被限流时不激活(决策不是 trigger)
|
|
575
|
-
throttled.activationPlan = this.buildActivationPlan(throttled, message, sid);
|
|
576
|
-
return throttled;
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
// 3. 决策逻辑
|
|
580
|
-
const threshold = score >= config.autoTriggerThreshold && impulseResult.confidence >= 0.8
|
|
581
|
-
? config.autoTriggerThreshold
|
|
582
|
-
: config.triggerThreshold;
|
|
583
|
-
|
|
584
|
-
// 反馈学习:负反馈多 → 抬高触发阈值(更保守);正反馈多 → 降低阈值(更灵敏)
|
|
585
|
-
// 两个来源:当前会话的即时反馈 + 持久化的历史学习结果
|
|
586
|
-
const feedbackAdj = this.getFeedbackThresholdAdjustment() + (Number(config.feedbackThresholdOffset) || 0);
|
|
587
|
-
const effectiveThreshold = Math.max(1, threshold + feedbackAdj);
|
|
588
|
-
|
|
589
|
-
let decision;
|
|
590
|
-
let action = null;
|
|
591
|
-
|
|
592
|
-
if (score >= effectiveThreshold) {
|
|
593
|
-
decision = 'trigger';
|
|
594
|
-
action = this.buildTriggerAction(impulseResult);
|
|
595
|
-
} else if (score < config.lowConfidenceThreshold) {
|
|
596
|
-
decision = 'ignore';
|
|
597
|
-
} else {
|
|
598
|
-
decision = 'review';
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
// 4. 记录触发历史
|
|
602
|
-
if (decision === 'trigger') {
|
|
603
|
-
this.triggerManager.recordTrigger({
|
|
604
|
-
impulseScore: score,
|
|
605
|
-
context,
|
|
606
|
-
userResponse: 'pending'
|
|
607
|
-
});
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
const outcome = {
|
|
611
|
-
shouldTrigger: decision === 'trigger',
|
|
612
|
-
decision,
|
|
613
|
-
score,
|
|
614
|
-
confidence: impulseResult.confidence,
|
|
615
|
-
action,
|
|
616
|
-
breakdown: impulseResult.breakdown,
|
|
617
|
-
reason: decision === 'trigger' ? '触发评分达标' : `评分${score}低于阈值${threshold}`
|
|
618
|
-
};
|
|
619
|
-
// 决策 → 激活:把判定翻译成可执行的 MCP 动作序列
|
|
620
|
-
outcome.activationPlan = this.buildActivationPlan(outcome, message, sid);
|
|
621
|
-
return outcome;
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
/**
|
|
625
|
-
* 构建触发动作
|
|
626
|
-
*/
|
|
627
|
-
buildTriggerAction(impulseResult) {
|
|
628
|
-
const { score, breakdown } = impulseResult;
|
|
629
|
-
|
|
630
|
-
return {
|
|
631
|
-
type: 'workflow_trigger',
|
|
632
|
-
score,
|
|
633
|
-
triggeredBy: breakdown.keyword.matchedKeywords.join(', '),
|
|
634
|
-
confidence: impulseResult.confidence,
|
|
635
|
-
// 自动档需要「分数达标」且「置信度足够」两道条件
|
|
636
|
-
recommendedAction: (score >= config.autoTriggerThreshold && impulseResult.confidence >= 0.8) ? 'auto' : 'manual'
|
|
637
|
-
};
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
/**
|
|
641
|
-
* 构建激活计划(动态决策 → 判断 → 激活 的最后一跳)
|
|
642
|
-
*
|
|
643
|
-
* 判断层已经决定了「要不要触发」,这一层把决定翻译成**可执行的 MCP 动作序列**:
|
|
644
|
-
* - 自动步骤(auto: true):参数完整,可直接执行
|
|
645
|
-
* - 引导步骤(auto: false):需要 Agent 补齐字段后再执行
|
|
646
|
-
*
|
|
647
|
-
* 激活后不会直接放开派发:占位卡会被标记 activation_pending,
|
|
648
|
-
* 在 scope / acceptance / verify.cmd 补齐之前,flow_claim / flow_dispatch 一律拒绝。
|
|
649
|
-
*/
|
|
650
|
-
buildActivationPlan(result, message, sessionId = 'default') {
|
|
651
|
-
if (!result || result.decision !== 'trigger') {
|
|
652
|
-
return { activated: false, reason: '决策不是 trigger,不激活' };
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
// 只读调研不进入工作流门禁(否则该会话永远无法解闸,见 isReadOnlyIntent 注释)
|
|
656
|
-
if (isReadOnlyIntent(message)) {
|
|
657
|
-
return {
|
|
658
|
-
activated: false,
|
|
659
|
-
reason: '只读调研意图,不进入工作流门禁(占位卡的待补项对只读任务永远无法满足)',
|
|
660
|
-
decision: result.decision,
|
|
661
|
-
score: result.score,
|
|
662
|
-
confidence: result.confidence,
|
|
663
|
-
steps: [],
|
|
664
|
-
pendingFields: [],
|
|
665
|
-
};
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
const matched = (result.breakdown && result.breakdown.keyword &&
|
|
669
|
-
result.breakdown.keyword.matchedKeywords) || [];
|
|
670
|
-
const goal = deriveGoal(message, matched);
|
|
671
|
-
|
|
672
|
-
// 自动步骤 1:写入用户原话(quote 锚点的唯一数据源,必须先于开卡)
|
|
673
|
-
const steps = [
|
|
674
|
-
{
|
|
675
|
-
tool: 'flow_add_user_msg',
|
|
676
|
-
auto: true,
|
|
677
|
-
reason: '写入用户原话,作为任务卡 quote 锚点校验的数据源',
|
|
678
|
-
args: { sessionId, text: String(message || '') },
|
|
679
|
-
},
|
|
680
|
-
// 自动步骤 2:提交 read_only 占位卡 —— 会话进入「已留痕」门禁态
|
|
681
|
-
{
|
|
682
|
-
tool: 'flow_submit_requirement',
|
|
683
|
-
auto: true,
|
|
684
|
-
reason: '开卡:将会话置为已留痕状态,审计链记录 activation 事件',
|
|
685
|
-
args: {
|
|
686
|
-
sessionId,
|
|
687
|
-
goal,
|
|
688
|
-
quote: String(message || ''),
|
|
689
|
-
scope: [],
|
|
690
|
-
acceptance: [],
|
|
691
|
-
confirmed: false,
|
|
692
|
-
activation: true,
|
|
693
|
-
},
|
|
694
|
-
},
|
|
695
|
-
// 引导步骤:Agent 补齐后重新提交完整卡
|
|
696
|
-
{
|
|
697
|
-
tool: 'flow_submit_requirement',
|
|
698
|
-
auto: false,
|
|
699
|
-
reason: '补齐字段后重新提交完整任务卡,替换占位卡',
|
|
700
|
-
needsFill: ['scope', 'acceptance', 'verify.cmd'],
|
|
701
|
-
args: {
|
|
702
|
-
sessionId,
|
|
703
|
-
goal,
|
|
704
|
-
quote: String(message || ''),
|
|
705
|
-
scope: ['<只准改动的文件>'],
|
|
706
|
-
acceptance: ['<可判定的验收标准>'],
|
|
707
|
-
verify: { cmd: '<验证命令>' },
|
|
708
|
-
confirmed: false,
|
|
709
|
-
},
|
|
710
|
-
},
|
|
711
|
-
];
|
|
712
|
-
|
|
713
|
-
return {
|
|
714
|
-
activated: true,
|
|
715
|
-
decision: result.decision,
|
|
716
|
-
score: result.score,
|
|
717
|
-
confidence: result.confidence,
|
|
718
|
-
matchedKeywords: matched,
|
|
719
|
-
goal,
|
|
720
|
-
steps,
|
|
721
|
-
pendingFields: ['scope', 'acceptance', 'verify.cmd'],
|
|
722
|
-
prompt: buildActivationPrompt(
|
|
723
|
-
result, goal, matched,
|
|
724
|
-
(result.action && result.action.recommendedAction) === 'auto' ? 'auto' : 'manual'
|
|
725
|
-
),
|
|
726
|
-
};
|
|
727
|
-
}
|
|
728
|
-
|
|
729
|
-
/**
|
|
730
|
-
* 记录用户反馈(持久化到会话状态,进程退出也不丢)
|
|
731
|
-
*
|
|
732
|
-
* feedbackType: 'positive'(用户接受了这次触发)/ 'negative'(拒绝了)
|
|
733
|
-
*/
|
|
734
|
-
recordFeedback(feedbackType) {
|
|
735
|
-
const type = feedbackType === 'positive' ? 'positive' : 'negative';
|
|
736
|
-
const state = this.triggerManager.state;
|
|
737
|
-
if (!state.feedback) state.feedback = { positive: 0, negative: 0 };
|
|
738
|
-
state.feedback[type] = (Number(state.feedback[type]) || 0) + 1;
|
|
739
|
-
state.save();
|
|
740
|
-
|
|
741
|
-
// 达到一个学习周期就自动更新阈值(之前是无调用点的死代码)
|
|
742
|
-
const total = state.feedback.positive + state.feedback.negative;
|
|
743
|
-
if (total >= config.feedbackLearningCycle) {
|
|
744
|
-
this.updateFeedbackWeights();
|
|
745
|
-
}
|
|
746
|
-
return { ok: true, feedback: { ...state.feedback }, thresholdAdjustment: this.getFeedbackThresholdAdjustment() };
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
/**
|
|
750
|
-
* 根据正/负反馈计算触发阈值的调整量
|
|
751
|
-
* 负反馈多 → 抬高阈值(更保守);正反馈多 → 降低阈值(更灵敏)
|
|
752
|
-
*/
|
|
753
|
-
getFeedbackThresholdAdjustment() {
|
|
754
|
-
const fb = this.triggerManager.state.feedback || { positive: 0, negative: 0 };
|
|
755
|
-
const positive = Number(fb.positive) || 0;
|
|
756
|
-
const negative = Number(fb.negative) || 0;
|
|
757
|
-
const total = positive + negative;
|
|
758
|
-
if (total === 0) return 0;
|
|
759
|
-
// 净负反馈比例 → 调整量(范围约 [-learningRate*10, +learningRate*10])
|
|
760
|
-
const negativeRatio = negative / total;
|
|
761
|
-
const adj = Math.round((negativeRatio - 0.5) * 2 * config.feedbackLearningRate * 10);
|
|
762
|
-
return adj;
|
|
763
|
-
}
|
|
764
|
-
|
|
765
|
-
/**
|
|
766
|
-
* 更新反馈学习结果:把正/负反馈比写回配置里的阈值偏移
|
|
767
|
-
*/
|
|
768
|
-
updateFeedbackWeights() {
|
|
769
|
-
const fb = this.triggerManager.state.feedback || { positive: 0, negative: 0 };
|
|
770
|
-
const total = (Number(fb.positive) || 0) + (Number(fb.negative) || 0);
|
|
771
|
-
if (total === 0) return { ok: false, reason: '尚无反馈记录' };
|
|
772
|
-
|
|
773
|
-
const negativeRatio = (Number(fb.negative) || 0) / total;
|
|
774
|
-
// 持久化的学习结果:负反馈占多数 → 提高触发阈值
|
|
775
|
-
const learned = Math.max(0, Math.round((negativeRatio - 0.5) * 2 * config.feedbackLearningRate * 10));
|
|
776
|
-
config.feedbackThresholdOffset = learned;
|
|
777
|
-
config.positiveFeedbackWeight = Number((1 + (1 - negativeRatio)).toFixed(3));
|
|
778
|
-
config.negativeFeedbackWeight = Number((1 + negativeRatio).toFixed(3));
|
|
779
|
-
|
|
780
|
-
this.saveConfig();
|
|
781
|
-
return { ok: true, thresholdOffset: learned, positive: fb.positive, negative: fb.negative };
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
saveConfig() {
|
|
785
|
-
ensureHome();
|
|
786
|
-
writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
/**
|
|
790
|
-
* 获取触发统计
|
|
791
|
-
*/
|
|
792
|
-
getStats() {
|
|
793
|
-
return {
|
|
794
|
-
totalTriggers: this.triggerManager.state.triggerHistory.length,
|
|
795
|
-
currentLimit: this.triggerManager.calculateDynamicLimit(),
|
|
796
|
-
recentActivity: this.triggerManager.state.triggerHistory.slice(-10)
|
|
797
|
-
};
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
|
|
801
|
-
// ============ 导出接口 ============
|
|
802
|
-
export const TriggerEngine = {
|
|
803
|
-
/**
|
|
804
|
-
* 创建触发引擎实例
|
|
805
|
-
*/
|
|
806
|
-
create(sessionId = 'default') {
|
|
807
|
-
const state = TriggerState.load(sessionId);
|
|
808
|
-
return new TriggerDecisionEngine(
|
|
809
|
-
new DynamicTriggerManager(state),
|
|
810
|
-
new TriggerScorer(),
|
|
811
|
-
sessionId
|
|
812
|
-
);
|
|
813
|
-
},
|
|
814
|
-
|
|
815
|
-
/**
|
|
816
|
-
* 用户消息处理(单例模式)
|
|
817
|
-
* sessionId 优先取 context.sessionId,默认 'default'
|
|
818
|
-
*/
|
|
819
|
-
processUserMessage(message, context = {}) {
|
|
820
|
-
const sessionId = context.sessionId || 'default';
|
|
821
|
-
const engine = this.create(sessionId);
|
|
822
|
-
return engine.shouldTrigger(message, context, sessionId);
|
|
823
|
-
},
|
|
824
|
-
|
|
825
|
-
/**
|
|
826
|
-
* 获取当前配置
|
|
827
|
-
*/
|
|
828
|
-
getConfig() {
|
|
829
|
-
return { ...config };
|
|
830
|
-
},
|
|
831
|
-
|
|
832
|
-
/**
|
|
833
|
-
* 只读意图判定(供测试与外部查询)
|
|
834
|
-
*/
|
|
835
|
-
isReadOnlyIntent(message) {
|
|
836
|
-
return isReadOnlyIntent(message);
|
|
837
|
-
},
|
|
838
|
-
|
|
839
|
-
/**
|
|
840
|
-
* 重置引擎状态
|
|
841
|
-
* 默认只重置 'default' 会话;传 sessionId 可重置指定会话;
|
|
842
|
-
* 传 '*' 重置全部会话(包含 trigger-state/ 目录下的所有会话文件)。
|
|
843
|
-
*/
|
|
844
|
-
reset(sessionId = 'default') {
|
|
845
|
-
if (sessionId === '*') {
|
|
846
|
-
// 清空所有会话文件(默认会话 + trigger-state/ 目录)
|
|
847
|
-
try { rmSync(DEFAULT_STATE_PATH, { force: true }); } catch { /* 不存在 */ }
|
|
848
|
-
try {
|
|
849
|
-
if (existsSync(STATE_DIR)) {
|
|
850
|
-
for (const f of readdirSync(STATE_DIR)) {
|
|
851
|
-
if (f.endsWith('.json')) {
|
|
852
|
-
try { rmSync(join(STATE_DIR, f), { force: true }); } catch { /* 忽略 */ }
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
} catch { /* 目录不存在 */ }
|
|
857
|
-
return { ok: true, scope: 'all' };
|
|
858
|
-
}
|
|
859
|
-
TriggerState.load(sessionId).reset();
|
|
860
|
-
return { ok: true, scope: sessionId };
|
|
861
|
-
},
|
|
862
|
-
|
|
863
|
-
/**
|
|
864
|
-
* 获取统计信息
|
|
865
|
-
*/
|
|
866
|
-
getStats() {
|
|
867
|
-
const engine = this.create();
|
|
868
|
-
return engine.getStats();
|
|
869
|
-
}
|
|
870
|
-
};
|
|
871
|
-
|
|
872
|
-
// ============ 命令行接口 ============
|
|
873
|
-
// import.meta.url 是 file:// URL,process.argv[1] 是本地路径,不能直接 endsWith 比较
|
|
874
|
-
const isCliEntry = (() => {
|
|
875
|
-
try {
|
|
876
|
-
const selfPath = fileURLToPath(import.meta.url);
|
|
877
|
-
const entry = process.argv[1];
|
|
878
|
-
return !!entry && resolve(selfPath) === resolve(entry);
|
|
879
|
-
} catch {
|
|
880
|
-
return false;
|
|
881
|
-
}
|
|
882
|
-
})();
|
|
883
|
-
|
|
884
|
-
if (isCliEntry) {
|
|
885
|
-
// 测试模式
|
|
886
|
-
const testMessage = process.argv[2] || '运行 carlos 工作流';
|
|
887
|
-
const context = { complexity: 1.2 };
|
|
888
|
-
|
|
889
|
-
console.log('[Carlos Trigger] 测试模式');
|
|
890
|
-
console.log('输入:', testMessage);
|
|
891
|
-
|
|
892
|
-
const engine = TriggerEngine.create();
|
|
893
|
-
const result = engine.shouldTrigger(testMessage, context);
|
|
894
|
-
|
|
895
|
-
console.log('\n决策结果:');
|
|
896
|
-
console.log('- 是否触发:', result.shouldTrigger ? '是' : '否');
|
|
897
|
-
console.log('- 决策:', result.decision);
|
|
898
|
-
console.log('- 评分:', result.score);
|
|
899
|
-
console.log('- 置信度:', result.confidence);
|
|
900
|
-
console.log('- 理由:', result.reason);
|
|
901
|
-
|
|
902
|
-
if (result.action) {
|
|
903
|
-
console.log('\n触发动作:');
|
|
904
|
-
console.log('- 类型:', result.action.type);
|
|
905
|
-
console.log('- 推荐操作:', result.action.recommendedAction);
|
|
906
|
-
}
|
|
907
|
-
}
|
|
908
|
-
|
|
909
|
-
export default TriggerEngine;
|
|
1
|
+
// Carlos 工作流智能触发引擎
|
|
2
|
+
// 三层智能触发系统:动态上限、评分系统、决策引擎
|
|
3
|
+
|
|
4
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
|
|
5
|
+
import { join, dirname, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
|
|
9
|
+
// 触发器状态/配置目录:与 state.js 的 FLOW_HOME 保持同一约定,避免污染仓库目录
|
|
10
|
+
const TRIGGER_HOME = (() => {
|
|
11
|
+
// 与 state.js 同一套 `~` 展开:否则 CARLOS_FLOW_HOME=~/.carlos-flow 不会被展开,
|
|
12
|
+
// 触发器状态/配置会写到「当前目录下的一个名叫 ~ 的目录」里。
|
|
13
|
+
const raw = process.env.CARLOS_FLOW_HOME || process.env.CARLOS_FLOW_ROOT || join(os.homedir(), '.carlos-flow');
|
|
14
|
+
if (typeof raw !== 'string' || raw === '') return join(os.homedir(), '.carlos-flow');
|
|
15
|
+
if (raw === '~') return os.homedir();
|
|
16
|
+
if (raw.startsWith('~/') || raw.startsWith('~\\')) return join(os.homedir(), raw.slice(2));
|
|
17
|
+
return raw;
|
|
18
|
+
})();
|
|
19
|
+
const CONFIG_PATH = join(TRIGGER_HOME, 'trigger-config.json');
|
|
20
|
+
const STATE_DIR = join(TRIGGER_HOME, 'trigger-state');
|
|
21
|
+
const DEFAULT_STATE_PATH = join(TRIGGER_HOME, 'trigger-state.json');
|
|
22
|
+
|
|
23
|
+
// 按会话隔离状态文件:不同会话的触发历史 / 限流状态互不影响。
|
|
24
|
+
// sessionId 会被清洗成安全的文件名,避免路径穿越。
|
|
25
|
+
// Windows 保留设备名(CON / PRN / AUX / NUL / COM1-9 / LPT1-9 …)
|
|
26
|
+
// 即便带扩展名(CON.json)在 NTFS 上也无法创建,必须避开。
|
|
27
|
+
const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
|
|
28
|
+
|
|
29
|
+
function sanitizeSessionId(sessionId) {
|
|
30
|
+
const raw = String(sessionId || 'default');
|
|
31
|
+
// 1) 清洗路径分隔符与非法字符(斜杠、背杠、冒号等)
|
|
32
|
+
let safe = raw.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 48);
|
|
33
|
+
// 2) 不允许以点开头(避免 "." / ".." 语义)
|
|
34
|
+
safe = safe.replace(/^\.+/, '_');
|
|
35
|
+
if (!safe) safe = 'default';
|
|
36
|
+
// 3) 避开 Windows 保留设备名
|
|
37
|
+
if (WINDOWS_RESERVED.test(safe)) safe = '_' + safe;
|
|
38
|
+
// 3) 追加原始 id 的短哈希:清洗后可能撞名("a/b" 与 "a_b" 都会变成 "a_b"),
|
|
39
|
+
// 用哈希保证不同 session 不会共用同一份状态文件
|
|
40
|
+
let h = 0;
|
|
41
|
+
for (let i = 0; i < raw.length; i++) {
|
|
42
|
+
h = (h * 31 + raw.charCodeAt(i)) >>> 0;
|
|
43
|
+
}
|
|
44
|
+
const suffix = h.toString(16).padStart(8, '0').slice(0, 8);
|
|
45
|
+
return safe + '-' + suffix;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function statePathFor(sessionId) {
|
|
49
|
+
if (!sessionId || sessionId === 'default') return DEFAULT_STATE_PATH;
|
|
50
|
+
return join(STATE_DIR, sanitizeSessionId(sessionId) + '.json');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// 确保目录存在(FLOW_HOME 可能尚未创建)
|
|
54
|
+
function ensureHome() {
|
|
55
|
+
try { mkdirSync(TRIGGER_HOME, { recursive: true }); } catch { /* 目录已存在或不可写 */ }
|
|
56
|
+
}
|
|
57
|
+
const DEFAULT_CONFIG = {
|
|
58
|
+
// 动态上限参数
|
|
59
|
+
baseTriggerLimit: 5, // 基础触发上限
|
|
60
|
+
maxTriggerLimit: 15, // 最大触发上限
|
|
61
|
+
sessionLengthCoeff: 0.5, // 会话时长系数(每小时增加 0.5 个)
|
|
62
|
+
complexityCoeff: 2, // 任务复杂度系数
|
|
63
|
+
historyCoeff: 0.3, // 历史触发频率系数(惩罚项)
|
|
64
|
+
|
|
65
|
+
// 评分参数
|
|
66
|
+
// 关键词表:只收**流程性**词汇(表示“要走门禁/工作流”),不收普通开发动词
|
|
67
|
+
// (如「实现」「新增」「接口」)—— 否则每条普通需求都会命中,触发器就退化成噪声。
|
|
68
|
+
// 中文词与英文词同权重:用户用中文提需求时,触发行为与英文一致。
|
|
69
|
+
keywordWeights: {
|
|
70
|
+
'work': 3, 'flow': 3, 'carlos': 4, 'dispatch': 3,
|
|
71
|
+
'trigger': 2, 'start': 1, 'run': 1, 'execute': 2,
|
|
72
|
+
// 中文流程词
|
|
73
|
+
'工作流': 3, '门禁': 4, '任务卡': 3, '派发': 3, '子代理': 3,
|
|
74
|
+
'流程': 2, '触发': 2, '执行': 2, '调度': 2,
|
|
75
|
+
'审计': 2, '复核': 2, '留痕': 2, '裁定': 2,
|
|
76
|
+
},
|
|
77
|
+
contextRelevanceWeight: 0.3,
|
|
78
|
+
userIntentWeight: 0.2,
|
|
79
|
+
|
|
80
|
+
// 决策阈值
|
|
81
|
+
triggerThreshold: 15, // 触发阈值(0-100)
|
|
82
|
+
autoTriggerThreshold: 25, // 自动触发阈值(高中意图时)
|
|
83
|
+
lowConfidenceThreshold: 10, // 低置信度阈值
|
|
84
|
+
|
|
85
|
+
// 只读意图识别:命中只读词且**不含**改动动词 → 不进入工作流门禁。
|
|
86
|
+
// 原因:占位卡恒为 read_only 档(scope=[]),若一个只需要只读调研的任务
|
|
87
|
+
// 被激活,它的待补项(scope/acceptance/verify.cmd)永远无法被满足 ——
|
|
88
|
+
// 因为只读任务本来就不需要改文件 —— 该会话会被永久锁死。
|
|
89
|
+
readOnlyIntentWords: [
|
|
90
|
+
'explain', 'describe', 'analyse', 'analyze', 'summarize', 'summarise',
|
|
91
|
+
'what', 'why', 'how', 'understand', 'overview', 'compare', 'inspect',
|
|
92
|
+
'read', '查找', '解释', '分析', '总结', '为什么', '是什么', '调研', '对比', '了解', '查看', '读一下', '看看',
|
|
93
|
+
],
|
|
94
|
+
mutatingActionWords: [
|
|
95
|
+
'fix', 'refactor', 'change', 'update', 'implement', 'add', 'remove',
|
|
96
|
+
'modify', 'rewrite', 'migrate', 'patch', 'upgrade', 'rename',
|
|
97
|
+
'修复', '重构', '修改', '更新', '实现', '新增', '删除', '重写', '迁移', '改造', '写一个', '写个',
|
|
98
|
+
],
|
|
99
|
+
|
|
100
|
+
// 用户反馈学习
|
|
101
|
+
feedbackLearningRate: 0.1,
|
|
102
|
+
feedbackLearningCycle: 10, // 每累积多少条反馈重新学习一次
|
|
103
|
+
feedbackThresholdOffset: 0, // 学习结果:负反馈多 → 抬高触发阈值
|
|
104
|
+
positiveFeedbackWeight: 1.5,
|
|
105
|
+
negativeFeedbackWeight: 0.7,
|
|
106
|
+
|
|
107
|
+
// 触发窗口
|
|
108
|
+
triggerWindowMinutes: 60, // 触发窗口期(分钟)——需 ≥ 最长间隔×窗口倍数,
|
|
109
|
+
// 否则「窗口内次数达上限」分支永远不可达
|
|
110
|
+
minTriggerIntervalSeconds: 300 // 最少触发间隔(秒)
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// 加载配置文件
|
|
114
|
+
//
|
|
115
|
+
// 词表类字段必须做**合并**而不是整体替换。
|
|
116
|
+
// 原实现 `config = { ...DEFAULT_CONFIG, ...loaded }` 是浅合并 —— 用户一旦写了
|
|
117
|
+
// `keywordWeights`,就会把默认词表(含内置的中文流程词)**整个丢掉**,
|
|
118
|
+
// 于是「我只是加一个自定义词」反而让所有默认词失效,中文场景重新变回 0 分。
|
|
119
|
+
// 语义修正:
|
|
120
|
+
// · keywordWeights:对象 → 合并(用户词覆盖同名默认词,其余默认词保留)
|
|
121
|
+
// · readOnlyIntentWords / mutatingActionWords:数组 → 追加去重(“扩展”而非“替换”)
|
|
122
|
+
// · 其余标量字段:覆盖(阈值、权重等本来就是单值)
|
|
123
|
+
let config = DEFAULT_CONFIG;
|
|
124
|
+
if (existsSync(CONFIG_PATH)) {
|
|
125
|
+
try {
|
|
126
|
+
const loaded = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
|
|
127
|
+
config = { ...DEFAULT_CONFIG, ...loaded };
|
|
128
|
+
// keywordWeights 必须是**对象**才能合并。
|
|
129
|
+
// 浅合并会把 null / 数组 / 数字一并带进 config.keywordWeights,
|
|
130
|
+
// 而下面的 if 因假值跳过深合并 → config.keywordWeights 保持非法值 →
|
|
131
|
+
// buildKeywordIndex() 的 Object.entries(null) 抛 TypeError →
|
|
132
|
+
// 触发引擎在该进程内**每次调用都失败**(客户端 catch 掉 → 静默失去自动触发)。
|
|
133
|
+
// 所以:类型不对就丢弃用户值、回退默认表,并在合并后再兜一次底。
|
|
134
|
+
if (loaded.keywordWeights !== undefined) {
|
|
135
|
+
if (loaded.keywordWeights && typeof loaded.keywordWeights === 'object' && !Array.isArray(loaded.keywordWeights)) {
|
|
136
|
+
config.keywordWeights = { ...DEFAULT_CONFIG.keywordWeights, ...loaded.keywordWeights };
|
|
137
|
+
} else {
|
|
138
|
+
console.warn('[Carlos Trigger] keywordWeights 必须是对象,已忽略该配置项(使用默认词表)');
|
|
139
|
+
config.keywordWeights = { ...DEFAULT_CONFIG.keywordWeights };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
for (const key of ['readOnlyIntentWords', 'mutatingActionWords']) {
|
|
143
|
+
if (Array.isArray(loaded[key]) && Array.isArray(DEFAULT_CONFIG[key])) {
|
|
144
|
+
config[key] = [...new Set([...DEFAULT_CONFIG[key], ...loaded[key]])];
|
|
145
|
+
} else if (loaded[key] !== undefined) {
|
|
146
|
+
console.warn(`[Carlos Trigger] ${key} 必须是数组,已忽略该配置项(使用默认词表)`);
|
|
147
|
+
config[key] = [...DEFAULT_CONFIG[key]];
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
} catch (e) {
|
|
151
|
+
console.warn('[Carlos Trigger] 配置加载失败:', e.message);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ============ 激活动作辅助 ============
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* 只读意图识别。
|
|
159
|
+
*
|
|
160
|
+
* 命中只读词(explain/analyze/调研/看看…)且**不含**改动动词
|
|
161
|
+
* (fix/refactor/修改/修复…)→ 判定为只读调研。
|
|
162
|
+
*
|
|
163
|
+
* 为什么要单独识别:智能触发引擎开的占位卡恒为 read_only 档(scope=[]),
|
|
164
|
+
* 其待补项是 scope/acceptance/verify.cmd。如果一个**只需要只读调研**的任务
|
|
165
|
+
* 被激活,这三项永远无法被满足(只读任务本来就不改文件)——
|
|
166
|
+
* 该会话会被永久锁死,且没有任何合法路径解闸。
|
|
167
|
+
*/
|
|
168
|
+
function isReadOnlyIntent(message) {
|
|
169
|
+
const s = String(message || '').toLowerCase();
|
|
170
|
+
if (!s) return false;
|
|
171
|
+
const ro = config.readOnlyIntentWords || [];
|
|
172
|
+
const mut = config.mutatingActionWords || [];
|
|
173
|
+
const hasReadOnly = ro.some((w) => s.includes(String(w).toLowerCase()));
|
|
174
|
+
if (!hasReadOnly) return false;
|
|
175
|
+
// 同时含改动动词 → 以改动为准(避免 "analyze and refactor" 被误判为只读)
|
|
176
|
+
const hasMutating = mut.some((w) => s.includes(String(w).toLowerCase()));
|
|
177
|
+
return !hasMutating;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 从用户原话与命中关键词推导一个粗粒度目标。
|
|
182
|
+
* 引擎无法知道真实目标,因此这只是**占位推断**,必须由 Agent 确认或改写。
|
|
183
|
+
*/
|
|
184
|
+
function deriveGoal(message, matchedKeywords = []) {
|
|
185
|
+
const text = String(message || '').trim();
|
|
186
|
+
const head = text.split(/[\n\r。.;;!?!?]/)[0].trim();
|
|
187
|
+
const kw = matchedKeywords.length ? `(命中:${matchedKeywords.join(', ')})` : '';
|
|
188
|
+
const base = head ? head.slice(0, 60) : '待补充目标';
|
|
189
|
+
return `执行 Carlos 工作流任务:${base}${kw}`;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* 生成给 Agent 的补全指令(激活后的第一件事)。
|
|
194
|
+
*/
|
|
195
|
+
function buildActivationPrompt(result, goal, matchedKeywords, mode = 'auto') {
|
|
196
|
+
const isAuto = mode === 'auto';
|
|
197
|
+
return [
|
|
198
|
+
isAuto ? '【Carlos 触发引擎已激活工作流】' : '【Carlos 触发引擎建议手动启动门禁】',
|
|
199
|
+
'',
|
|
200
|
+
`判定:${result.decision}(评分 ${result.score} / 置信度 ${result.confidence})`,
|
|
201
|
+
`命中关键词:${matchedKeywords.length ? matchedKeywords.join(', ') : '(无直接关键词命中)'}`,
|
|
202
|
+
`推断目标(占位,需确认或改写):${goal}`,
|
|
203
|
+
'',
|
|
204
|
+
isAuto
|
|
205
|
+
? '已完成:用户原话已留痕,占位任务卡已提交,会话已进入门禁状态。'
|
|
206
|
+
: '尚未执行任何动作(未留痕、未开卡)—— 本次评分未达自动激活条件,请自行决定是否启动门禁。',
|
|
207
|
+
'',
|
|
208
|
+
'接下来请:',
|
|
209
|
+
'1. 与用户确认上面的目标描述是否准确;',
|
|
210
|
+
isAuto
|
|
211
|
+
? '2. 补齐 scope(只准改动的文件)、acceptance(可判定的验收标准)、verify.cmd(验证命令);'
|
|
212
|
+
: '2. 若决定启动门禁:先 flow_add_user_msg 留痕,再 flow_submit_requirement 提交任务卡(需含 scope / acceptance / verify.cmd);',
|
|
213
|
+
isAuto
|
|
214
|
+
? '3. 重新调用 flow_submit_requirement 提交完整任务卡(会替换占位卡);'
|
|
215
|
+
: '3. 再调用 flow_claim / flow_dispatch 派发。',
|
|
216
|
+
isAuto
|
|
217
|
+
? '4. 再调用 flow_claim / flow_dispatch 派发。'
|
|
218
|
+
: '',
|
|
219
|
+
'',
|
|
220
|
+
isAuto
|
|
221
|
+
? '注意:在 scope / acceptance / verify.cmd 补齐之前,flow_claim 与 flow_dispatch 会拒绝派发。'
|
|
222
|
+
: '注意:本次建议不会自动提交任何卡片。',
|
|
223
|
+
].join('\n');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// ============ 状态管理 ============
|
|
227
|
+
class TriggerState {
|
|
228
|
+
constructor(sessionId = 'default') {
|
|
229
|
+
this.sessionId = sessionId;
|
|
230
|
+
this.triggerHistory = [];
|
|
231
|
+
this.sessionStartTime = Date.now();
|
|
232
|
+
this.lastTriggerTime = 0;
|
|
233
|
+
this.impressionCount = 0; // 关联 impressionId
|
|
234
|
+
this.feedback = { positive: 0, negative: 0 }; // 用户反馈(持久化)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
getSessionAgeHours() {
|
|
238
|
+
return (Date.now() - this.sessionStartTime) / (1000 * 60 * 60);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
save() {
|
|
242
|
+
ensureHome();
|
|
243
|
+
const target = statePathFor(this.sessionId);
|
|
244
|
+
try {
|
|
245
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
246
|
+
} catch { /* 目录已存在或不可写 */ }
|
|
247
|
+
try {
|
|
248
|
+
writeFileSync(target, JSON.stringify(this, null, 2));
|
|
249
|
+
} catch (e) {
|
|
250
|
+
// 状态落盘失败(如保留设备名、权限不足、磁盘满)不能让引擎整体崩掉:
|
|
251
|
+
// 降级为「本次不持久化」,主流程继续。
|
|
252
|
+
try {
|
|
253
|
+
process.stderr.write(`[carlos-trigger] 状态保存失败(${this.sessionId}):${e && e.message ? e.message : e}
|
|
254
|
+
`);
|
|
255
|
+
} catch { /* stderr 不可写 */ }
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
static load(sessionId = 'default') {
|
|
260
|
+
const target = statePathFor(sessionId);
|
|
261
|
+
if (existsSync(target)) {
|
|
262
|
+
try {
|
|
263
|
+
const loaded = JSON.parse(readFileSync(target, 'utf8'));
|
|
264
|
+
const state = new TriggerState(sessionId);
|
|
265
|
+
Object.assign(state, loaded);
|
|
266
|
+
// sessionId 由调用方决定,不允许被持久化文件覆盖
|
|
267
|
+
state.sessionId = sessionId;
|
|
268
|
+
return state;
|
|
269
|
+
} catch (e) {
|
|
270
|
+
// 状态文件损坏时降级为新状态,不阻断主流程
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return new TriggerState(sessionId);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// ============ L1: DynamicTriggerManager ============
|
|
278
|
+
class DynamicTriggerManager {
|
|
279
|
+
constructor(state = null) {
|
|
280
|
+
this.state = state || TriggerState.load();
|
|
281
|
+
this.triggerCache = new Map();
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* 计算当前动态触发上限
|
|
286
|
+
* 基于会话时长、任务复杂度和历史触发频率
|
|
287
|
+
*
|
|
288
|
+
* 设计要点:
|
|
289
|
+
* - 会话越长、任务越复杂 → 上限越高(允许更多触发)
|
|
290
|
+
* - 近期触发越频繁 → 上限越低(收敛打扰),否则上限会被历史反向抬高而永不生效
|
|
291
|
+
*/
|
|
292
|
+
calculateDynamicLimit(sessionComplexity = 1.0) {
|
|
293
|
+
const sessionAge = this.state.getSessionAgeHours();
|
|
294
|
+
const recentCount = this.countTriggersInWindow();
|
|
295
|
+
|
|
296
|
+
// 上限 = 基础 + 会话时长增益 + 复杂度增益 - 近期频繁触发惩罚
|
|
297
|
+
const rawLimit =
|
|
298
|
+
config.baseTriggerLimit +
|
|
299
|
+
(sessionAge * config.sessionLengthCoeff) +
|
|
300
|
+
(sessionComplexity * config.complexityCoeff) -
|
|
301
|
+
(recentCount * config.historyCoeff);
|
|
302
|
+
|
|
303
|
+
const dynamicLimit = Math.max(1, Math.min(rawLimit, config.maxTriggerLimit));
|
|
304
|
+
|
|
305
|
+
return Math.floor(dynamicLimit);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* 统计触发窗口内的实际触发次数(原始计数,用于上限判定)
|
|
310
|
+
*/
|
|
311
|
+
countTriggersInWindow() {
|
|
312
|
+
const windowStart = Date.now() - (config.triggerWindowMinutes * 60 * 1000);
|
|
313
|
+
return this.state.triggerHistory.filter(t => t.timestamp > windowStart).length;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* 记录触发事件
|
|
318
|
+
*/
|
|
319
|
+
recordTrigger(triggerData = {}) {
|
|
320
|
+
this.state.triggerHistory.push({
|
|
321
|
+
timestamp: Date.now(),
|
|
322
|
+
impulseScore: triggerData.impulseScore || 0,
|
|
323
|
+
context: triggerData.context || 'unknown',
|
|
324
|
+
userResponse: triggerData.userResponse || 'pending'
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
this.state.lastTriggerTime = Date.now();
|
|
328
|
+
this.state.impressionCount++;
|
|
329
|
+
this.state.save();
|
|
330
|
+
|
|
331
|
+
// 清理过期记录
|
|
332
|
+
this.cleanupHistory();
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* 清理过期历史数据
|
|
337
|
+
*/
|
|
338
|
+
cleanupHistory() {
|
|
339
|
+
const cutoff = Date.now() - (24 * 60 * 60 * 1000); // 24小时
|
|
340
|
+
this.state.triggerHistory = this.state.triggerHistory.filter(
|
|
341
|
+
t => t.timestamp > cutoff
|
|
342
|
+
);
|
|
343
|
+
this.state.save();
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* 检查是否可以触发
|
|
348
|
+
*/
|
|
349
|
+
canTrigger(sessionComplexity = 1.0) {
|
|
350
|
+
// 检查最小时间间隔
|
|
351
|
+
const timeSinceLastTrigger = Date.now() - this.state.lastTriggerTime;
|
|
352
|
+
if (timeSinceLastTrigger < config.minTriggerIntervalSeconds * 1000) {
|
|
353
|
+
return { can: false, reason: '时间间隔不足' };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// 检查动态上限:用窗口内的实际触发次数与上限比较
|
|
357
|
+
const currentLimit = this.calculateDynamicLimit(sessionComplexity);
|
|
358
|
+
const triggerCountInWindow = this.countTriggersInWindow();
|
|
359
|
+
|
|
360
|
+
if (triggerCountInWindow >= currentLimit) {
|
|
361
|
+
return { can: false, reason: `触发次数已达上限 (${triggerCountInWindow}/${currentLimit})` };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return { can: true, limit: currentLimit, count: triggerCountInWindow };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
reset() {
|
|
368
|
+
this.state.triggerHistory = [];
|
|
369
|
+
this.state.lastTriggerTime = 0;
|
|
370
|
+
this.state.save();
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// ============ L2: TriggerScorer ============
|
|
375
|
+
class TriggerScorer {
|
|
376
|
+
constructor() {
|
|
377
|
+
this.keywordIndex = new Map();
|
|
378
|
+
this.buildKeywordIndex();
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* 构建关键词索引
|
|
383
|
+
*/
|
|
384
|
+
buildKeywordIndex() {
|
|
385
|
+
Object.entries(config.keywordWeights).forEach(([keyword, weight]) => {
|
|
386
|
+
this.keywordIndex.set(keyword.toLowerCase(), weight);
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* 计算关键词匹配分数
|
|
392
|
+
*/
|
|
393
|
+
calculateKeywordScore(message) {
|
|
394
|
+
const lowerMsg = message.toLowerCase();
|
|
395
|
+
let score = 0;
|
|
396
|
+
let matchedKeywords = [];
|
|
397
|
+
|
|
398
|
+
this.keywordIndex.forEach((weight, keyword) => {
|
|
399
|
+
if (lowerMsg.includes(keyword)) {
|
|
400
|
+
score += weight;
|
|
401
|
+
matchedKeywords.push(keyword);
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
// 标准化到 0-50 范围
|
|
406
|
+
const normalizedScore = Math.min(score * 5, 50);
|
|
407
|
+
|
|
408
|
+
return {
|
|
409
|
+
score: normalizedScore,
|
|
410
|
+
matchedKeywords,
|
|
411
|
+
maxKeywordScore: 50
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* 计算上下文相关性分数
|
|
417
|
+
*/
|
|
418
|
+
calculateContextRelevance(message, context = {}) {
|
|
419
|
+
// 简单实现:基于工作流相关关键词
|
|
420
|
+
const workFlowKeywords = ['work', 'flow', 'dispatch', 'executor', 'auditor',
|
|
421
|
+
'工作流', '门禁', '派发', '审计', '复核', '任务卡'];
|
|
422
|
+
const lowerMsg = message.toLowerCase();
|
|
423
|
+
|
|
424
|
+
let contextScore = 0;
|
|
425
|
+
let matchedContext = [];
|
|
426
|
+
|
|
427
|
+
workFlowKeywords.forEach(keyword => {
|
|
428
|
+
if (lowerMsg.includes(keyword)) {
|
|
429
|
+
contextScore += 3;
|
|
430
|
+
matchedContext.push(keyword);
|
|
431
|
+
}
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
// 基于上下文复杂度调整
|
|
435
|
+
if (context.complexity) {
|
|
436
|
+
contextScore *= context.complexity;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// 标准化到 0-30 范围
|
|
440
|
+
const normalizedScore = Math.min(contextScore * 3, 30);
|
|
441
|
+
|
|
442
|
+
return {
|
|
443
|
+
score: normalizedScore,
|
|
444
|
+
matchedContext,
|
|
445
|
+
maxContextScore: 30
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* 计算用户意图分数
|
|
451
|
+
*
|
|
452
|
+
* @param {string} message 用户输入
|
|
453
|
+
* @param {number} historyCount 当前会话的触发历史条数(由 L3 传入)
|
|
454
|
+
* —— 评分层不再自己去磁盘读状态,避免与 L1 读到不同会话
|
|
455
|
+
*/
|
|
456
|
+
calculateUserIntent(message, historyCount = 0) {
|
|
457
|
+
// 简单实现:基于用户行为模式
|
|
458
|
+
const userIntentCandidates = {
|
|
459
|
+
'workflow': ['dispatch', 'run', 'execute', 'trigger', 'start', '执行', '派发', '触发', '工作流', '门禁'],
|
|
460
|
+
'automation': ['auto', 'automate', 'workflow', 'process', '自动', '流程', '调度'],
|
|
461
|
+
'management': ['manage', 'control', 'monitor', 'track', '管理', '监控']
|
|
462
|
+
};
|
|
463
|
+
|
|
464
|
+
const lowerMsg = message.toLowerCase();
|
|
465
|
+
let intentScore = 0;
|
|
466
|
+
let intentType = 'generic';
|
|
467
|
+
|
|
468
|
+
Object.entries(userIntentCandidates).forEach(([type, keywords]) => {
|
|
469
|
+
const hasKeyword = keywords.some(k => lowerMsg.includes(k));
|
|
470
|
+
if (hasKeyword) {
|
|
471
|
+
intentScore += 20;
|
|
472
|
+
intentType = type;
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
// 基于会话历史调整(活跃用户意图分上浮)
|
|
477
|
+
if (historyCount > 10) {
|
|
478
|
+
intentScore *= 1.2; // 活跃用户
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// 标准化到 0-20 范围
|
|
482
|
+
const normalizedScore = Math.min(intentScore, 20);
|
|
483
|
+
|
|
484
|
+
return {
|
|
485
|
+
score: normalizedScore,
|
|
486
|
+
intentType,
|
|
487
|
+
maxIntentScore: 20
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* 综合评分
|
|
493
|
+
*
|
|
494
|
+
* @param {string} message 用户输入
|
|
495
|
+
* @param {object} context 上下文(complexity 等)
|
|
496
|
+
* @param {number} historyCount 当前会话触发历史条数(由 L3 传入,保证与 L1 同会话)
|
|
497
|
+
*/
|
|
498
|
+
calculateImpulseScore(message, context = {}, historyCount = 0) {
|
|
499
|
+
const keywordResult = this.calculateKeywordScore(message);
|
|
500
|
+
const contextResult = this.calculateContextRelevance(message, context);
|
|
501
|
+
const intentResult = this.calculateUserIntent(message, historyCount);
|
|
502
|
+
|
|
503
|
+
const totalScore =
|
|
504
|
+
keywordResult.score * (1 - config.contextRelevanceWeight - config.userIntentWeight) +
|
|
505
|
+
contextResult.score * config.contextRelevanceWeight +
|
|
506
|
+
intentResult.score * config.userIntentWeight;
|
|
507
|
+
|
|
508
|
+
return {
|
|
509
|
+
score: Math.round(totalScore),
|
|
510
|
+
breakdown: {
|
|
511
|
+
keyword: keywordResult,
|
|
512
|
+
context: contextResult,
|
|
513
|
+
intent: intentResult
|
|
514
|
+
},
|
|
515
|
+
confidence: this.calculateConfidence(keywordResult, contextResult, intentResult)
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* 计算置信度
|
|
521
|
+
*/
|
|
522
|
+
calculateConfidence(keyword, context, intent) {
|
|
523
|
+
const allMatched = keyword.matchedKeywords.length +
|
|
524
|
+
context.matchedContext.length +
|
|
525
|
+
(intent.intentType !== 'generic' ? 1 : 0);
|
|
526
|
+
|
|
527
|
+
if (allMatched === 0) return 0.3; // 低置信度
|
|
528
|
+
if (allMatched <= 2) return 0.6; // 中等置信度
|
|
529
|
+
return 0.9; // 高置信度
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// ============ L3: TriggerDecisionEngine ============
|
|
534
|
+
class TriggerDecisionEngine {
|
|
535
|
+
constructor(triggerManager = null, scorer = null, sessionId = null) {
|
|
536
|
+
this.triggerManager = triggerManager || new DynamicTriggerManager();
|
|
537
|
+
this.scorer = scorer || new TriggerScorer();
|
|
538
|
+
// 会话维度:L1(上限/历史)与 L2(评分)必须读同一个会话,
|
|
539
|
+
// 否则会出现「上限算的是 A 会话、历史算的是 B 会话」的串扰。
|
|
540
|
+
this.sessionId = sessionId || (this.triggerManager && this.triggerManager.state && this.triggerManager.state.sessionId) || 'default';
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* 主触发决策
|
|
545
|
+
* 基于评分和动态上限决定是否触发
|
|
546
|
+
*
|
|
547
|
+
* @param {string} message 用户输入
|
|
548
|
+
* @param {object} context 上下文
|
|
549
|
+
* @param {string} [sessionId] 会话 ID;省略时使用引擎实例自己的会话
|
|
550
|
+
*/
|
|
551
|
+
shouldTrigger(message, context = {}, sessionId = null) {
|
|
552
|
+
// 会话统一到一处:显式传入 > 引擎实例会话 > default
|
|
553
|
+
const sid = sessionId || this.sessionId;
|
|
554
|
+
// 1. 先计算触发评分(即使被限流,评分与置信度也要如实返回,不能丢成 0/undefined)
|
|
555
|
+
const historyCount = Array.isArray(this.triggerManager.state.triggerHistory)
|
|
556
|
+
? this.triggerManager.state.triggerHistory.length
|
|
557
|
+
: 0;
|
|
558
|
+
const impulseResult = this.scorer.calculateImpulseScore(message, context, historyCount);
|
|
559
|
+
const score = impulseResult.score;
|
|
560
|
+
|
|
561
|
+
// 2. 检查是否可以触发(上限和时间间隔)
|
|
562
|
+
const complexity = Number(context.complexity) || 1.0;
|
|
563
|
+
const canTrigger = this.triggerManager.canTrigger(complexity);
|
|
564
|
+
if (!canTrigger.can) {
|
|
565
|
+
const throttled = {
|
|
566
|
+
shouldTrigger: false,
|
|
567
|
+
reason: canTrigger.reason,
|
|
568
|
+
score,
|
|
569
|
+
confidence: impulseResult.confidence,
|
|
570
|
+
breakdown: impulseResult.breakdown,
|
|
571
|
+
decision: 'throttled',
|
|
572
|
+
action: null,
|
|
573
|
+
};
|
|
574
|
+
// 被限流时不激活(决策不是 trigger)
|
|
575
|
+
throttled.activationPlan = this.buildActivationPlan(throttled, message, sid);
|
|
576
|
+
return throttled;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// 3. 决策逻辑
|
|
580
|
+
const threshold = score >= config.autoTriggerThreshold && impulseResult.confidence >= 0.8
|
|
581
|
+
? config.autoTriggerThreshold
|
|
582
|
+
: config.triggerThreshold;
|
|
583
|
+
|
|
584
|
+
// 反馈学习:负反馈多 → 抬高触发阈值(更保守);正反馈多 → 降低阈值(更灵敏)
|
|
585
|
+
// 两个来源:当前会话的即时反馈 + 持久化的历史学习结果
|
|
586
|
+
const feedbackAdj = this.getFeedbackThresholdAdjustment() + (Number(config.feedbackThresholdOffset) || 0);
|
|
587
|
+
const effectiveThreshold = Math.max(1, threshold + feedbackAdj);
|
|
588
|
+
|
|
589
|
+
let decision;
|
|
590
|
+
let action = null;
|
|
591
|
+
|
|
592
|
+
if (score >= effectiveThreshold) {
|
|
593
|
+
decision = 'trigger';
|
|
594
|
+
action = this.buildTriggerAction(impulseResult);
|
|
595
|
+
} else if (score < config.lowConfidenceThreshold) {
|
|
596
|
+
decision = 'ignore';
|
|
597
|
+
} else {
|
|
598
|
+
decision = 'review';
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// 4. 记录触发历史
|
|
602
|
+
if (decision === 'trigger') {
|
|
603
|
+
this.triggerManager.recordTrigger({
|
|
604
|
+
impulseScore: score,
|
|
605
|
+
context,
|
|
606
|
+
userResponse: 'pending'
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const outcome = {
|
|
611
|
+
shouldTrigger: decision === 'trigger',
|
|
612
|
+
decision,
|
|
613
|
+
score,
|
|
614
|
+
confidence: impulseResult.confidence,
|
|
615
|
+
action,
|
|
616
|
+
breakdown: impulseResult.breakdown,
|
|
617
|
+
reason: decision === 'trigger' ? '触发评分达标' : `评分${score}低于阈值${threshold}`
|
|
618
|
+
};
|
|
619
|
+
// 决策 → 激活:把判定翻译成可执行的 MCP 动作序列
|
|
620
|
+
outcome.activationPlan = this.buildActivationPlan(outcome, message, sid);
|
|
621
|
+
return outcome;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* 构建触发动作
|
|
626
|
+
*/
|
|
627
|
+
buildTriggerAction(impulseResult) {
|
|
628
|
+
const { score, breakdown } = impulseResult;
|
|
629
|
+
|
|
630
|
+
return {
|
|
631
|
+
type: 'workflow_trigger',
|
|
632
|
+
score,
|
|
633
|
+
triggeredBy: breakdown.keyword.matchedKeywords.join(', '),
|
|
634
|
+
confidence: impulseResult.confidence,
|
|
635
|
+
// 自动档需要「分数达标」且「置信度足够」两道条件
|
|
636
|
+
recommendedAction: (score >= config.autoTriggerThreshold && impulseResult.confidence >= 0.8) ? 'auto' : 'manual'
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* 构建激活计划(动态决策 → 判断 → 激活 的最后一跳)
|
|
642
|
+
*
|
|
643
|
+
* 判断层已经决定了「要不要触发」,这一层把决定翻译成**可执行的 MCP 动作序列**:
|
|
644
|
+
* - 自动步骤(auto: true):参数完整,可直接执行
|
|
645
|
+
* - 引导步骤(auto: false):需要 Agent 补齐字段后再执行
|
|
646
|
+
*
|
|
647
|
+
* 激活后不会直接放开派发:占位卡会被标记 activation_pending,
|
|
648
|
+
* 在 scope / acceptance / verify.cmd 补齐之前,flow_claim / flow_dispatch 一律拒绝。
|
|
649
|
+
*/
|
|
650
|
+
buildActivationPlan(result, message, sessionId = 'default') {
|
|
651
|
+
if (!result || result.decision !== 'trigger') {
|
|
652
|
+
return { activated: false, reason: '决策不是 trigger,不激活' };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// 只读调研不进入工作流门禁(否则该会话永远无法解闸,见 isReadOnlyIntent 注释)
|
|
656
|
+
if (isReadOnlyIntent(message)) {
|
|
657
|
+
return {
|
|
658
|
+
activated: false,
|
|
659
|
+
reason: '只读调研意图,不进入工作流门禁(占位卡的待补项对只读任务永远无法满足)',
|
|
660
|
+
decision: result.decision,
|
|
661
|
+
score: result.score,
|
|
662
|
+
confidence: result.confidence,
|
|
663
|
+
steps: [],
|
|
664
|
+
pendingFields: [],
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const matched = (result.breakdown && result.breakdown.keyword &&
|
|
669
|
+
result.breakdown.keyword.matchedKeywords) || [];
|
|
670
|
+
const goal = deriveGoal(message, matched);
|
|
671
|
+
|
|
672
|
+
// 自动步骤 1:写入用户原话(quote 锚点的唯一数据源,必须先于开卡)
|
|
673
|
+
const steps = [
|
|
674
|
+
{
|
|
675
|
+
tool: 'flow_add_user_msg',
|
|
676
|
+
auto: true,
|
|
677
|
+
reason: '写入用户原话,作为任务卡 quote 锚点校验的数据源',
|
|
678
|
+
args: { sessionId, text: String(message || '') },
|
|
679
|
+
},
|
|
680
|
+
// 自动步骤 2:提交 read_only 占位卡 —— 会话进入「已留痕」门禁态
|
|
681
|
+
{
|
|
682
|
+
tool: 'flow_submit_requirement',
|
|
683
|
+
auto: true,
|
|
684
|
+
reason: '开卡:将会话置为已留痕状态,审计链记录 activation 事件',
|
|
685
|
+
args: {
|
|
686
|
+
sessionId,
|
|
687
|
+
goal,
|
|
688
|
+
quote: String(message || ''),
|
|
689
|
+
scope: [],
|
|
690
|
+
acceptance: [],
|
|
691
|
+
confirmed: false,
|
|
692
|
+
activation: true,
|
|
693
|
+
},
|
|
694
|
+
},
|
|
695
|
+
// 引导步骤:Agent 补齐后重新提交完整卡
|
|
696
|
+
{
|
|
697
|
+
tool: 'flow_submit_requirement',
|
|
698
|
+
auto: false,
|
|
699
|
+
reason: '补齐字段后重新提交完整任务卡,替换占位卡',
|
|
700
|
+
needsFill: ['scope', 'acceptance', 'verify.cmd'],
|
|
701
|
+
args: {
|
|
702
|
+
sessionId,
|
|
703
|
+
goal,
|
|
704
|
+
quote: String(message || ''),
|
|
705
|
+
scope: ['<只准改动的文件>'],
|
|
706
|
+
acceptance: ['<可判定的验收标准>'],
|
|
707
|
+
verify: { cmd: '<验证命令>' },
|
|
708
|
+
confirmed: false,
|
|
709
|
+
},
|
|
710
|
+
},
|
|
711
|
+
];
|
|
712
|
+
|
|
713
|
+
return {
|
|
714
|
+
activated: true,
|
|
715
|
+
decision: result.decision,
|
|
716
|
+
score: result.score,
|
|
717
|
+
confidence: result.confidence,
|
|
718
|
+
matchedKeywords: matched,
|
|
719
|
+
goal,
|
|
720
|
+
steps,
|
|
721
|
+
pendingFields: ['scope', 'acceptance', 'verify.cmd'],
|
|
722
|
+
prompt: buildActivationPrompt(
|
|
723
|
+
result, goal, matched,
|
|
724
|
+
(result.action && result.action.recommendedAction) === 'auto' ? 'auto' : 'manual'
|
|
725
|
+
),
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* 记录用户反馈(持久化到会话状态,进程退出也不丢)
|
|
731
|
+
*
|
|
732
|
+
* feedbackType: 'positive'(用户接受了这次触发)/ 'negative'(拒绝了)
|
|
733
|
+
*/
|
|
734
|
+
recordFeedback(feedbackType) {
|
|
735
|
+
const type = feedbackType === 'positive' ? 'positive' : 'negative';
|
|
736
|
+
const state = this.triggerManager.state;
|
|
737
|
+
if (!state.feedback) state.feedback = { positive: 0, negative: 0 };
|
|
738
|
+
state.feedback[type] = (Number(state.feedback[type]) || 0) + 1;
|
|
739
|
+
state.save();
|
|
740
|
+
|
|
741
|
+
// 达到一个学习周期就自动更新阈值(之前是无调用点的死代码)
|
|
742
|
+
const total = state.feedback.positive + state.feedback.negative;
|
|
743
|
+
if (total >= config.feedbackLearningCycle) {
|
|
744
|
+
this.updateFeedbackWeights();
|
|
745
|
+
}
|
|
746
|
+
return { ok: true, feedback: { ...state.feedback }, thresholdAdjustment: this.getFeedbackThresholdAdjustment() };
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* 根据正/负反馈计算触发阈值的调整量
|
|
751
|
+
* 负反馈多 → 抬高阈值(更保守);正反馈多 → 降低阈值(更灵敏)
|
|
752
|
+
*/
|
|
753
|
+
getFeedbackThresholdAdjustment() {
|
|
754
|
+
const fb = this.triggerManager.state.feedback || { positive: 0, negative: 0 };
|
|
755
|
+
const positive = Number(fb.positive) || 0;
|
|
756
|
+
const negative = Number(fb.negative) || 0;
|
|
757
|
+
const total = positive + negative;
|
|
758
|
+
if (total === 0) return 0;
|
|
759
|
+
// 净负反馈比例 → 调整量(范围约 [-learningRate*10, +learningRate*10])
|
|
760
|
+
const negativeRatio = negative / total;
|
|
761
|
+
const adj = Math.round((negativeRatio - 0.5) * 2 * config.feedbackLearningRate * 10);
|
|
762
|
+
return adj;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* 更新反馈学习结果:把正/负反馈比写回配置里的阈值偏移
|
|
767
|
+
*/
|
|
768
|
+
updateFeedbackWeights() {
|
|
769
|
+
const fb = this.triggerManager.state.feedback || { positive: 0, negative: 0 };
|
|
770
|
+
const total = (Number(fb.positive) || 0) + (Number(fb.negative) || 0);
|
|
771
|
+
if (total === 0) return { ok: false, reason: '尚无反馈记录' };
|
|
772
|
+
|
|
773
|
+
const negativeRatio = (Number(fb.negative) || 0) / total;
|
|
774
|
+
// 持久化的学习结果:负反馈占多数 → 提高触发阈值
|
|
775
|
+
const learned = Math.max(0, Math.round((negativeRatio - 0.5) * 2 * config.feedbackLearningRate * 10));
|
|
776
|
+
config.feedbackThresholdOffset = learned;
|
|
777
|
+
config.positiveFeedbackWeight = Number((1 + (1 - negativeRatio)).toFixed(3));
|
|
778
|
+
config.negativeFeedbackWeight = Number((1 + negativeRatio).toFixed(3));
|
|
779
|
+
|
|
780
|
+
this.saveConfig();
|
|
781
|
+
return { ok: true, thresholdOffset: learned, positive: fb.positive, negative: fb.negative };
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
saveConfig() {
|
|
785
|
+
ensureHome();
|
|
786
|
+
writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* 获取触发统计
|
|
791
|
+
*/
|
|
792
|
+
getStats() {
|
|
793
|
+
return {
|
|
794
|
+
totalTriggers: this.triggerManager.state.triggerHistory.length,
|
|
795
|
+
currentLimit: this.triggerManager.calculateDynamicLimit(),
|
|
796
|
+
recentActivity: this.triggerManager.state.triggerHistory.slice(-10)
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// ============ 导出接口 ============
|
|
802
|
+
export const TriggerEngine = {
|
|
803
|
+
/**
|
|
804
|
+
* 创建触发引擎实例
|
|
805
|
+
*/
|
|
806
|
+
create(sessionId = 'default') {
|
|
807
|
+
const state = TriggerState.load(sessionId);
|
|
808
|
+
return new TriggerDecisionEngine(
|
|
809
|
+
new DynamicTriggerManager(state),
|
|
810
|
+
new TriggerScorer(),
|
|
811
|
+
sessionId
|
|
812
|
+
);
|
|
813
|
+
},
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* 用户消息处理(单例模式)
|
|
817
|
+
* sessionId 优先取 context.sessionId,默认 'default'
|
|
818
|
+
*/
|
|
819
|
+
processUserMessage(message, context = {}) {
|
|
820
|
+
const sessionId = context.sessionId || 'default';
|
|
821
|
+
const engine = this.create(sessionId);
|
|
822
|
+
return engine.shouldTrigger(message, context, sessionId);
|
|
823
|
+
},
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* 获取当前配置
|
|
827
|
+
*/
|
|
828
|
+
getConfig() {
|
|
829
|
+
return { ...config };
|
|
830
|
+
},
|
|
831
|
+
|
|
832
|
+
/**
|
|
833
|
+
* 只读意图判定(供测试与外部查询)
|
|
834
|
+
*/
|
|
835
|
+
isReadOnlyIntent(message) {
|
|
836
|
+
return isReadOnlyIntent(message);
|
|
837
|
+
},
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* 重置引擎状态
|
|
841
|
+
* 默认只重置 'default' 会话;传 sessionId 可重置指定会话;
|
|
842
|
+
* 传 '*' 重置全部会话(包含 trigger-state/ 目录下的所有会话文件)。
|
|
843
|
+
*/
|
|
844
|
+
reset(sessionId = 'default') {
|
|
845
|
+
if (sessionId === '*') {
|
|
846
|
+
// 清空所有会话文件(默认会话 + trigger-state/ 目录)
|
|
847
|
+
try { rmSync(DEFAULT_STATE_PATH, { force: true }); } catch { /* 不存在 */ }
|
|
848
|
+
try {
|
|
849
|
+
if (existsSync(STATE_DIR)) {
|
|
850
|
+
for (const f of readdirSync(STATE_DIR)) {
|
|
851
|
+
if (f.endsWith('.json')) {
|
|
852
|
+
try { rmSync(join(STATE_DIR, f), { force: true }); } catch { /* 忽略 */ }
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
} catch { /* 目录不存在 */ }
|
|
857
|
+
return { ok: true, scope: 'all' };
|
|
858
|
+
}
|
|
859
|
+
TriggerState.load(sessionId).reset();
|
|
860
|
+
return { ok: true, scope: sessionId };
|
|
861
|
+
},
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* 获取统计信息
|
|
865
|
+
*/
|
|
866
|
+
getStats() {
|
|
867
|
+
const engine = this.create();
|
|
868
|
+
return engine.getStats();
|
|
869
|
+
}
|
|
870
|
+
};
|
|
871
|
+
|
|
872
|
+
// ============ 命令行接口 ============
|
|
873
|
+
// import.meta.url 是 file:// URL,process.argv[1] 是本地路径,不能直接 endsWith 比较
|
|
874
|
+
const isCliEntry = (() => {
|
|
875
|
+
try {
|
|
876
|
+
const selfPath = fileURLToPath(import.meta.url);
|
|
877
|
+
const entry = process.argv[1];
|
|
878
|
+
return !!entry && resolve(selfPath) === resolve(entry);
|
|
879
|
+
} catch {
|
|
880
|
+
return false;
|
|
881
|
+
}
|
|
882
|
+
})();
|
|
883
|
+
|
|
884
|
+
if (isCliEntry) {
|
|
885
|
+
// 测试模式
|
|
886
|
+
const testMessage = process.argv[2] || '运行 carlos 工作流';
|
|
887
|
+
const context = { complexity: 1.2 };
|
|
888
|
+
|
|
889
|
+
console.log('[Carlos Trigger] 测试模式');
|
|
890
|
+
console.log('输入:', testMessage);
|
|
891
|
+
|
|
892
|
+
const engine = TriggerEngine.create();
|
|
893
|
+
const result = engine.shouldTrigger(testMessage, context);
|
|
894
|
+
|
|
895
|
+
console.log('\n决策结果:');
|
|
896
|
+
console.log('- 是否触发:', result.shouldTrigger ? '是' : '否');
|
|
897
|
+
console.log('- 决策:', result.decision);
|
|
898
|
+
console.log('- 评分:', result.score);
|
|
899
|
+
console.log('- 置信度:', result.confidence);
|
|
900
|
+
console.log('- 理由:', result.reason);
|
|
901
|
+
|
|
902
|
+
if (result.action) {
|
|
903
|
+
console.log('\n触发动作:');
|
|
904
|
+
console.log('- 类型:', result.action.type);
|
|
905
|
+
console.log('- 推荐操作:', result.action.recommendedAction);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
export default TriggerEngine;
|