dsh-cot-anchor 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,70 +1,39 @@
1
1
  # dsh-cot-anchor
2
2
 
3
- DeepSeek Harness(DSH)插件:治一类特定的模型毛病——**思考着思考,但没在推进**。表现为反复重新推导已经得出的结论、把工具调用写成纯文本、原地重复同一段话、输出无意义的递增数字流。
3
+ 做这个插件的起因很直接:想弄清楚人不介入代码细节时,模型靠什么机制约束自己的思考,以及怎么验收它确实做对了。它盯生成途中那些「看着在忙、其实没往前走」的信号——原地重复、伪工具调用、无意义的数字流、过长的思维链,命中就切断当前生成、让回合从断点接着跑。判据全部落在本地能机械计算的字符串信号上,不额外调模型;判定阈值和误拦截是我反复调的部分,早期词典太宽会误截断正常思考,后来靠收紧词典、滑窗长度和匹配次数缓解。成本在一个约 924 万 token 的真实长会话上复算过,口径和复算方法都写在文档里;代码借助 AI 协作完成,装机实测由我逐版做。
4
4
 
5
- 插件做两件事:
5
+ DeepSeek Harness(DSH)插件,治的是一类特定的模型毛病:思考着思考,但没在推进。表现为反复重新推导已经得出的结论、把工具调用写成纯文本、原地重复同一段话、输出无意义的递增数字流。
6
6
 
7
- 1. **结论回流**:每次工具结果返回后,从最新思考中摘出已成立的结论(最多 3 条、每条 ≤ 220 字)插回上下文,下一步起手就能看到,不必重推一遍。**装上默认生效。**
8
- 2. **生成中途打断(软切)**:生成过程中每 32 个字符检查一次,发现打转 / 原地重复 / 伪工具调用 / 数字流就立即切断本次请求,把已生成部分作为正常消息落盘、排好结论锚点,让回合从断点续跑——不会因为一次误判丢掉整轮工作。
7
+ 它做的事是在生成途中盯着这些信号:每生成一小段就按本地规则检查一次,命中就切断这一次生成,把已经写出来的部分作为正常消息落盘,让回合从断点续跑,不会因为一次误判丢掉整轮工作。判定不调用模型,也不改写会话里已有的内容。外部插件也可以向它请求软切,过长的思维链同样能触发。
9
8
 
10
9
  它不解决一切长任务问题,只解决「单流内思考链极度冗余、结论反复重新发现」。跨步骤的折返跑(同一结论在十几步里重推)不在能力范围内,那是姊妹插件 [dsh-step-governor](https://github.com/JiewiW/dsh-step-governor) 的职责。
11
10
 
12
11
  ## 快速开始
13
12
 
14
13
  ```sh
15
- dsh plugin --profile <你的profile> add github:JiewiW/dsh-cot-anchor#v0.3.0
14
+ dsh plugin --profile <你的profile> add github:JiewiW/dsh-cot-anchor#v0.4.2
16
15
  ```
17
16
 
18
- 重启实例后设置页出现「COT 锚点」标签即生效。结论注入无需任何配置;软切需要内核支持(见[兼容性](#兼容性与软切内核))。
19
-
20
- ## 工作方式
21
-
22
- ```
23
- 模型思考 → 工具执行 → [插件] 摘出已成立的结论插回上下文 → 下一步思考
24
- ↑
25
- 只在工具边界注入
26
- ```
27
-
28
- 注入消息以 `user` 角色追加在工具结果之后、下一次请求之前,尾部追加写入会话日志,不改写已有内容,因此不会打穿前缀缓存。
17
+ 重启实例后设置页出现「COT 锚点」标签即生效。软切需要内核支持,见[兼容性](#兼容性)。
29
18
 
30
19
  ## 成本
31
20
 
32
- | 场景 | 额外成本 |
33
- | --- | --- |
34
- | 默认(结论注入开启,其余关闭) | 每个工具结果后一条短消息,上界 660 字符(3 条 × 220 字);无额外模型调用 |
35
- | 命令执行纪律提醒 | 每轮一次、随运行时上下文快照("Current runtime context…")注入,位于记忆规则之后;单条全文固定约 380 token(字符估算),作为稳定前缀段参与上下文,不再随工具调用堆叠 |
36
- | 开启 LLM 提炼结论(默认关) | 每个助手回合**多一次**小模型调用 |
37
- | 开启打转 / 重复等判定 | 纯本地字符串计算,零 token 成本;可能增加少量回合数 |
38
- | 开启 CoT 静默采集 | 每个助手回合留一条本地样本;默认关闭 |
39
-
40
- 注入消息会随之后续请求的上下文一同发送,因此持续占用少量上下文窗口。按中英混排估算,660 字符约合 200–500 token 量级——相对于一次工具往返的上下文可以忽略,但它在**每一步**都会累积。注入以尾部追加方式写入会话日志,不改写已有内容,因此不会打穿前缀缓存:除新追加的一块外,此前内容始终是稳定前缀。新追加块在其首次出现的那次请求上按未命中计费一次,此后转为缓存命中——这一点与文本是否固定无关。推理锚点每次不同,其排列顺序仅为内容组织上的一致性,不影响缓存行为(自 411cb74/v0.2.2 起命令执行纪律已改走运行时上下文快照的固定段,不再参与本次工具注入)。
21
+ 判定本身是本地字符串计算,不额外调模型。少数需要写回上下文的消息采用尾部追加,不改写已有内容,因此不会打穿前缀缓存。
41
22
 
42
- 在一个约 924 万 token 的真实长会话上实测:插件注入总量约占全会话 0.23%(每个注入块只在首现那一次请求按未命中计费,此后转为缓存命中)。具体分项口径见下文「实测成本占比」。
23
+ 早期版本在一轮约 924 万 token 的真实长会话上复算过注入占比,那是旧机制下的历史数据;字符换算 token 用的是启发式估算,不是 tokenizer 实测。口径、修正与限定见 [docs/cot-anchor-prefix-cache-claim-correction.md](docs/cot-anchor-prefix-cache-claim-correction.md) 与 [RELEASE-NOTES.md](RELEASE-NOTES.md),不代表当前版本的开销。
43
24
 
44
- ## 能力边界(请先读)
25
+ ## 能力边界
45
26
 
46
- - 两类机制都是**单步边界内**的:软切只看当前一次生成流,进入下一步计数归零。治得了单流内退化,治不了跨步骤折返跑。
27
+ - 软切只看当前一次生成流,进入下一步计数归零。治得了单流内退化,治不了跨步骤折返跑。
47
28
  - 软切不减少回合步数。长任务账单的大头是「步数 × 每步膨胀的上下文重读」,步数治理请用 step-governor。
48
- - 模型可能**知道自己在空转却停不下来**——实测出现过思考中自述「I'm burning turns, let me stop」之后继续生成下一条探索路线。注入的前提是模型会读且照做,自知不构成刹车。
49
- - 软切每回合按判定类别分桶计预算 **6/20/3**(启发式判定 6 次、字节级确证重复 20 次、伪工具调用 3 次),总闸 **29**(6+20+3)。打满后启发式判定升级为终止本回合,高置信重复仍照常拦截;预算事件(`agent/soft-cut-suppressed` / `phase.abortTurn`)在会话日志可观测。这些常量由内核定义、不由插件持有。
50
-
51
- > 以下统计数据自 **v0.2.1 之前的机制**采集:当时命令执行纪律是随每次工具执行后剥出的独立 `user` 消息(`source.summary = cot-anchor: exec-discipline`)与推理锚点同车注入。**自 v0.2.1 起(并入 411cb74 迁移后)**,纪律不再随工具注入,而是注册为运行时上下文快照的一个固定段(每轮出现一次、位于记忆规则之后、用户唠叨之前),不再按工具条数线性堆叠;下述注入量只是旧机制的上限参照。
29
+ - 模型可能知道自己在空转却停不下来——实测出现过思考中自述「I'm burning turns, let me stop」之后继续生成下一条探索路线。软切的前提是能机械识别出打转,自知不构成刹车。
30
+ - 每回合的软切次数有内核侧预算上限,打满后启发式判定不再触发,高置信的重复仍照常拦截,避免误判把一次正常生成反复掐断。预算事件在会话日志里可观测。
52
31
 
53
- 在一个 95 次助手请求、累计约 924 万 token 的真实长会话上按消息级口径统计(字符→token 为启发式估算,非 tokenizer 实测;任何人可在自己的 DSH 会话日志上按同口径复算:逐条统计 `user/message` 中 `source.summary` 为 `cot-anchor: exec-discipline`(固定纪律)与其他 `cot-anchor:*`(动态锚点)的文本,并对照各次助手请求 `usage` 的 `inputTokens` / `cacheReadTokens`):
32
+ ## 兼容性
54
33
 
55
- > 结论:插件带来的新增输入在全会话 token 总量的 0.3% 以内。每个注入块在首现时按未命中计费一次,此后随上下文增长参与后续每一次请求。纪律块体积约占注入量五分之四,但"文本固定"不带来额外缓存收益——该占比只反映体积,不反映命中。(该占比为 v0.2.1 之前旧机制的历史数据;新版纪律块已移入运行时上下文快照固定段,不再按工具条数累计。)
34
+ 0.1.5-rc.3 起内核移除了软切所需的 `agent/soft-cut` 钩子,这一能力会静默失效;插件在启动日志和设置页顶部明确提示当前内核是否支持,以设置页显示为准,不要凭开关是开的就认为在生效。
56
35
 
57
- ## 兼容性与软切内核
58
-
59
- | 能力 | 支持的 DSH 版本 |
60
- | --- | --- |
61
- | --- | --- |
62
- | 结论注入、设置页 | 0.1.5 起全部版本 |
63
- | 生成中途打断(软切) | 仅 0.1.5-rc.1 / rc.2 开箱可用 |
64
-
65
- 0.1.5-rc.3 起内核移除了软切所需的 `agent/soft-cut` 钩子,该能力会静默失效;插件在启动日志和设置页顶部明确提示当前内核是否支持——**以设置页显示为准**,不要凭开关是开的就认为在生效。
66
-
67
- 新版内核可用随包工具把软切机构移植回去(带版本与哈希自检,幂等、可回滚,不符自动还原):
36
+ 新版内核可以用随包工具把软切机构移植回去,带版本与哈希自检,幂等、可回滚,不符自动还原:
68
37
 
69
38
  ```sh
70
39
  node node_modules/dsh-cot-anchor/tools/apply-softcut-port.mjs --check # 查看状态
@@ -75,64 +44,14 @@ node node_modules/dsh-cot-anchor/tools/apply-softcut-port.mjs # 应用
75
44
 
76
45
  ## 设置
77
46
 
78
- 设置页「COT 锚点」共 61 项、分组展示,多数场景用默认值即可。下面只列常用项与容易误判的项;其余阈值在设置页内均有内联说明。
79
-
80
- ### 总开关
81
-
82
- | 键 | 默认 | 说明 |
83
- | --- | --- | --- |
84
- | `enableToolInject` | 开 | 工具结果后注入结论锚点,本插件的主要价值,建议保持开启 |
85
- | `enableSoftCut` | 开 | 允许生成中途打断;内核不支持时自动无效 |
86
- | `enableExecDisciplineBlock` | 开 | 随锚点同车注入命令执行纪律提醒;与锚点注入共用去重节奏,关闭后锚点注入行为不变 |
87
-
88
- ### 五项软切判定
47
+ 设置页「COT 锚点」按用途分组,常调的是几项软切判定的开关和阈值:伪工具调用、原地重复、反复重新分析、转折句、数字流,以及各自的匹配次数与滑窗长度。每项在页面里有内联说明,键名、默认值和分组以设置页与源码为准。
89
48
 
90
- 全部关闭时插件只做结论注入。
91
-
92
- | 键 | 识别什么 | 注意 |
93
- | --- | --- | --- |
94
- | `enablePseudoTool` | 把工具调用写成普通文本(如 `<seed:tool_call>...`) | 只能识别已知文本形态 |
95
- | `enableRepeat` | 逐字节相同的内容反复吐出 | 换措辞的重复抓不到 |
96
- | `enableChurn` | 措辞不同但反复「重新分析」 | 启发式判定,遇到未闭合代码块自动让路 |
97
- | `enableTransition` | 「接下来我要……」类转折句 | **最容易误判**:正常分阶段思考也有转折句;若频繁在正常思考中切断,先关它(v0.3.0 起已要求转折词后跟随执行动词、并剥离已注入锚点后再判定,误判面已显著收窄) |
98
- | `enableNumberRunaway` | 无意义递增数字流 | 要求数字流足够长(≥ 500 字符跨度等阈值) |
99
-
100
- 打断太频繁时:先关 `enableTransition`,其次调高判定阈值(`churnMinHits` 默认 18 等)。
101
-
102
- 自 v0.2.4 起,转折句判定自带「结论-转折间距」守卫(`softCutGapThreshold`,默认 80):当尾部扫描窗口内最后一个结论开启词(如「所以」)与最后一个转折宣告(如「接下来」)间距超过阈值时,判定为「子阶段小结论 + 后续分析 + 转折宣告」而非阶段边界,拒绝软切——避免「所以 X 是根因」这类中途小结论与后续转折词各自命中检测器、把一次正常分析拦腰切断。
103
-
104
- 自 v0.3.0 起,转折句判定叠加三层加固(详见[发行说明](RELEASE-NOTES.md)):① 已注入锚点按会话去重,同内容不再重复注入,命中时记录去重事件而非切断;② 「结论-转折间距」守卫在结论开启词缺失时由放行改为拒绝(fail-closed);③ 切句与转折识别改为引号感知——报告正文中引用的推理原文、正则文本不再被切成以「所以/现在」开头的伪句;同时转折宣告词后必须跟随执行动词(「现在写报告」命中、「Now I have the full chain.」这类状态陈述不命中),已注入锚点文本也先剥离再参与判定,阻断「锚点自我触发」的自反馈环。
105
-
106
- ### 锚点内容
107
-
108
- | 键 | 默认 | 说明 |
109
- | --- | --- | --- |
110
- | `minReasoningChars` | 250 | 思考短于此长度不提取结论 |
111
- | `maxPoints` | 3 | 最多保留几条结论 |
112
- | `maxPointChars` | 220 | 单条结论字数上限 |
113
-
114
- 结论由规则从思考文本中摘句得到,不理解句子的语义角色,因此入池前会剔除两类无命题内容:纯话语标记句(剥掉 Actually / wait / Hmm / 其实 / 等等 等标记后实词不足 6 字符,如「Actually, wait.」「其实,等等。」)与路线意图宣告句(「the decisive route: ask the user…」)。标记词**领起但带事实命题**的句子(「Wait, the kernel never marks in verbose mode.」)照常保留。
115
-
116
- 注意:Wait / Actually / Hmm 等转折词在推理链中承担结构控制作用,插件**不从模型输出里删除它们**,只阻止它们被当成结论回灌。
117
-
118
- ### LLM 提炼与 CoT 采集(默认全关)
119
-
120
- - `enableLlmRefine`:用一次小模型调用把整段思考压成摘要式结论,通常比规则摘句更准;provider/model 留空则跟随当前会话。
121
- - `enableHarvest` / `enableAutoAnalyze` / `enableLearnedPatterns`:静默采集思考样本、自动归纳检测器看不见的打转形态、把学习成果用于判定。开启会在本地留存思考文本,启用前请自行评估隐私;学习模式默认有 20 轮影子期(`learnedShadowRounds`)防止一次误学永久改变判定。
49
+ 打断太频繁时,先关转折句判定,其次调高重复判定的阈值。
122
50
 
123
51
  ## 隐私
124
52
 
125
- - 结论注入与全部软切判定都在本地完成,不向任何外部服务发送数据。
126
- - LLM 提炼开启时,思考文本会发给你指定的 provider(留空则跟随当前会话)。
127
- - CoT 采集开启时,思考文本与工具轨迹只留存本地。
128
-
129
- ## 常见问题
130
-
131
- **设置页显示「当前内核没有掐断能力」**
132
- 内核不提供软切钩子,结论注入不受影响。需要软切可停留在 0.1.5-rc.1/rc.2,或按上文移植。
133
-
134
- **模型好像没收到提醒**
135
- 确认 `enableToolInject` 已开、且思考长度超过 `minReasoningChars`——思考过短本来就不提取。
53
+ - 软切与相关判定都在本地完成,不向外部服务发送数据。
54
+ - 开启 CoT 采集或自动归纳后,思考文本会留在本地;自动归纳还会把样本发给你指定的 provider(留空则跟随当前会话),启用前请自行评估隐私。
136
55
 
137
56
  ## 开发
138
57
 
package/lib/index.js CHANGED
@@ -29,6 +29,7 @@ import { createRequire } from "node:module";
29
29
  import { homedir } from "node:os";
30
30
  import { join } from "node:path";
31
31
  import { BlockAssembler, createUserMessage } from "@deepseek-ai/dsh-llm";
32
+ import { trace, setTraceConfig } from "./trace-runtime.js";
32
33
 
33
34
  const name = "dsh-cot-anchor";
34
35
 
@@ -623,6 +624,21 @@ const EVENT_INVALID_ARGS_DEDUP_SKIPPED = "cot-anchor/invalid-args-dedup-skipped"
623
624
  const EVENT_INVALID_ARGS_RECOVERED = "cot-anchor/invalid-args-recovered";
624
625
  const EVENT_ANCHOR_INJECTION_SUPPRESSED = "cot-anchor/anchor-injection-suppressed";
625
626
 
627
+ /** TRC-R5/R10:既有 ctx.emit 事件与 trace/* 类别的映射;未列出的事件走 invocation 兜底。 */
628
+ const TRACE_EVENT_CATEGORY = Object.freeze({
629
+ [EVENT_SOFTCUT_TAKEN]: "decision",
630
+ [EVENT_SOFTCUT_INBOX_RESUMED]: "action",
631
+ [EVENT_ANCHOR_INJECTED]: "action",
632
+ [EVENT_ANCHOR_DEDUP_SKIPPED]: "action",
633
+ [EVENT_ANCHOR_INJECTION_SUPPRESSED]: "action",
634
+ [EVENT_INVALID_ARGS_DEDUP_SKIPPED]: "action",
635
+ [EVENT_INVALID_ARGS_RECOVERED]: "action",
636
+ [EVENT_REFLOW_MISJUDGED]: "outcome",
637
+ [EVENT_LENGTH_CONSERVATION_FAILED]: "outcome",
638
+ [EVENT_STRUCTURE_UNBALANCED]: "outcome",
639
+ [EVENT_POINT_TRUNCATED]: "scan"
640
+ });
641
+
626
642
  /** Monotonic evidence sequence for event payloads(D4 工程要求:事件必带 evidenceSeq). */
627
643
  let evidenceSeqCounter = 0;
628
644
  function nextEvidenceSeq() {
@@ -655,6 +671,42 @@ function evidenceBase(sessionId, turn, step) {
655
671
  * @param {object} payload - already carries the evidence header.
656
672
  */
657
673
  function emitCotAnchorEvent(ctx, eventName, payload) {
674
+ const p = payload && typeof payload === "object" ? payload : {};
675
+ // TRC-R9/R10:只补 ctx.emit 而不 append,会话落盘文件里搜不到 "type":"trace/decision"。
676
+ try {
677
+ const known = Object.prototype.hasOwnProperty.call(TRACE_EVENT_CATEGORY, eventName);
678
+ const category = known ? TRACE_EVENT_CATEGORY[eventName] : "invocation";
679
+ const matched = eventName === EVENT_SOFTCUT_TAKEN || p.matched === true;
680
+ const base = {
681
+ sessionId: p.sessionId ?? null,
682
+ turn: p.turn,
683
+ step: p.step,
684
+ rule: `cot-anchor/${eventName}`,
685
+ matched,
686
+ values: {
687
+ cutClass: p.cutClass ?? null,
688
+ detector: p.detector ?? null,
689
+ detectorValues: p.detectorValues ?? null,
690
+ evidenceSeq: p.evidenceSeq ?? null,
691
+ occurrence: p.occurrence ?? null
692
+ },
693
+ thresholds: p.thresholds ?? {},
694
+ inputHash: p.inputHash ?? null,
695
+ comparedIds: Array.isArray(p.comparedIds) ? p.comparedIds : [],
696
+ reason: p.reason ?? (matched ? "hit" : "below-threshold"),
697
+ evidenceSeq: p.evidenceSeq ?? null,
698
+ seqNamespace: "counter",
699
+ unclassified: !known
700
+ };
701
+ trace.emit(category, base);
702
+ if (eventName === EVENT_SOFTCUT_TAKEN) {
703
+ // 一次真实软切 = 拦截动作 + 验收器结论,二者与 decision 共享同一复合键。
704
+ trace.emit("action", { ...base, rule: `${base.rule}/action`, reason: "cut" });
705
+ trace.emit("outcome", { ...base, rule: `${base.rule}/outcome`, reason: "soft-cut-taken" });
706
+ }
707
+ } catch (error) {
708
+ console.warn(`[cot-anchor] trace 落盘失败 ${eventName}:${error?.message ?? error}`);
709
+ }
658
710
  if (!ctx || typeof ctx.emit !== "function") return;
659
711
  try {
660
712
  ctx.emit(eventName, payload);
@@ -2432,22 +2484,95 @@ function renderActionChurnAnchor(churn) {
2432
2484
  }
2433
2485
 
2434
2486
  /**
2435
- * Over-long CoT soft-cut anchor. Triggered purely on text length — this is a
2436
- * "gentle nudge" detector, not an anomaly detector like churn/repeat. The
2437
- * wording tells the model to settle conclusions into notes or tool calls
2438
- * instead of continuing to think. Unlike other anchors, this one does not
2439
- * extract or echo prior reasoning — it is a fresh reminder.
2440
- * @param {number} currentChars - the actual length that fired the cut.
2441
- * @param {number} threshold - the threshold that was exceeded.
2487
+ * Over-long CoT soft-cut anchor. Triggered purely on text length — a
2488
+ * "last-resort" reminder, not an anomaly detector like churn/repeat.
2489
+ * 2026-11-05: wording hardened from a gentle nudge into an explicit
2490
+ * two-way-only instruction, with per-turn escalation appended on repeats.
2491
+ */
2492
+ /**
2493
+ * 渲染 over-long-cot 提醒锚点。
2494
+ * @param {number} reasoningChars - 计数口径内字符数(纯思考或 merged 全长估算)
2495
+ * @param {number} threshold - 阈值(设置值原样)
2496
+ * @param {boolean} hasStreams - 是否用内核分离计数
2497
+ * @param {number} occurrence - 本 turn 内第几次因过长被切(从 1 开始)
2442
2498
  * @returns {string}
2443
2499
  */
2444
- function renderOverLongCoTAnchor(currentChars, threshold) {
2445
- return [
2446
- `COT anchor — CoT 过长提醒:本轮已累计约 ${currentChars} 字(阈值 ${threshold}),思考阶段已显著偏长。`,
2447
- "如有阶段性结论,应该落实为笔记或工具执行,避免过度思考。",
2448
- "停止继续展开新的分析分支,直接输出你已确定的结论,或执行下一步工具调用。",
2449
- `(CoT length reminder: ~${currentChars} chars emitted this turn, threshold ${threshold}. Settle conclusions into notes or tool execution instead of overthinking.)`
2450
- ].join("\n");
2500
+ function renderOverLongCoTAnchor(reasoningChars, threshold, hasStreams, occurrence = 1) {
2501
+ const scope = hasStreams
2502
+ ? `本次思考已达约 ${reasoningChars} 字(阈值 ${threshold})`
2503
+ : `本次输出已达约 ${reasoningChars} 字(阈值 ${threshold},含回答文本,思考部分估算)`;
2504
+ const lines = [
2505
+ `COT anchor — 停止生成思考内容:${scope},已判定为过度思考。`,
2506
+ "从这一刻起,不要再写任何分析、排查、计划、复述,也不要写「我应该立即行动」「接下来我会…」这类表态——表态不等于执行。",
2507
+ "下一条消息只能是以下两种之一(二选一):① 一次真实工具调用(选当前最可执行的一步,先做再判断);② 直接给用户的最终答案(写出已确认结论,未确认项列为待办)。",
2508
+ "信息不足时选①中最小的可验证动作;不得以「再查一下 / 再确认一下」为理由继续输出文字。",
2509
+ "(Stop generating reasoning now. Your next message MUST be either one real tool call, or the final answer to the user. No analysis, no plans, no restating, no \"I should act now\" declarations. If information is insufficient, make the smallest verifiable tool call instead of writing more text.)"
2510
+ ];
2511
+ return lines.join("\n") + renderOverLongEscalation(occurrence);
2512
+ }
2513
+
2514
+ /**
2515
+ * 第 2 次及以后追加的升级指令。逐次加码,避免连续多次注入逐字相同的提醒
2516
+ * 被模型当成环境噪声或思考开场模板;不声称插件能强制中止(内核才持有剪刀)。
2517
+ * @param {number} occurrence - 本 turn 内第几次命中(>=1)
2518
+ * @returns {string} 第 1 次返回空串
2519
+ */
2520
+ function renderOverLongEscalation(occurrence) {
2521
+ if (occurrence < 2) return "";
2522
+ const lines = ["",
2523
+ `本 turn 第 ${occurrence} 次因 CoT 过长被切断。上一次提醒之后你没有执行工具调用、也没有给出结论,而是继续分析——这正是再次被切断的原因。`];
2524
+ if (occurrence >= 3) {
2525
+ lines.push(`重复提醒已达 ${occurrence} 次:把上面的「二选一」当作硬约束。不要再写任何新的分析段落或行动计划,现在直接调用工具或输出最终答案。`);
2526
+ }
2527
+ if (occurrence >= 5) {
2528
+ lines.push("内核的启发式打断预算(与其他检测器共享)可能已接近上限,后续不一定再有提醒;这一次必须收尾。");
2529
+ }
2530
+ return lines.join("\n");
2531
+ }
2532
+
2533
+ /** over-long-cot 每 turn 命中计数。与 churn 计数隔离,避免不同检测器互相污染。 */
2534
+ const overLongCountBySession = new Map();
2535
+ /** LRU 上限,与 churnCountBySession 同值。 */
2536
+ const OVER_LONG_COUNT_MAP_LIMIT = 32;
2537
+
2538
+ function evictOverLongCountOldest() {
2539
+ if (overLongCountBySession.size <= OVER_LONG_COUNT_MAP_LIMIT) return;
2540
+ const oldestKey = overLongCountBySession.keys().next().value;
2541
+ if (oldestKey !== undefined) overLongCountBySession.delete(oldestKey);
2542
+ }
2543
+
2544
+ /**
2545
+ * 递增并回传 occurrence;turn 大于上次记录时就地归零(同 turn 结算消息不误归零)。
2546
+ * 计数的是插件返回的 cut 决策,与内核是否采纳无关。
2547
+ */
2548
+ function recordOverLongCut(sessionId, turn) {
2549
+ let state = overLongCountBySession.get(sessionId);
2550
+ if (!state) {
2551
+ state = { lastTurn: 0, count: 0 };
2552
+ overLongCountBySession.set(sessionId, state);
2553
+ evictOverLongCountOldest();
2554
+ }
2555
+ if (Number.isFinite(turn) && turn > state.lastTurn) {
2556
+ state.lastTurn = turn;
2557
+ state.count = 0;
2558
+ }
2559
+ state.count += 1;
2560
+ return state.count;
2561
+ }
2562
+
2563
+ /** session/event 观察者的 turn 边界回调,与 resetChurnCountOnTurnBoundary 并列。 */
2564
+ function resetOverLongCountOnTurnBoundary(sessionId, turn) {
2565
+ if (!Number.isFinite(turn)) return;
2566
+ const state = overLongCountBySession.get(sessionId);
2567
+ if (!state) {
2568
+ overLongCountBySession.set(sessionId, { lastTurn: turn, count: 0 });
2569
+ evictOverLongCountOldest();
2570
+ return;
2571
+ }
2572
+ if (turn > state.lastTurn) {
2573
+ state.lastTurn = turn;
2574
+ state.count = 0;
2575
+ }
2451
2576
  }
2452
2577
 
2453
2578
  /**
@@ -3352,8 +3477,9 @@ const DEFAULT_SETTINGS = { // Master switches
3352
3477
  softCutTransitionWindow: 48,
3353
3478
  softCutMinFollowChars: 6,
3354
3479
  softCutGapThreshold: 80,
3355
- // Over-long CoT soft-cut: total visible text exceeds this threshold triggers a reminder.
3356
- // 0 = disabled. Default 8000 chars (~4000 Chinese chars of thinking).
3480
+ // Over-long CoT soft-cut: the length that triggers a reminder cut.
3481
+ // 0 = disabled. Default 8000 chars. This is the FINAL threshold in both
3482
+ // kernel counting modes — no implicit multiplier is applied at the hook site.
3357
3483
  overLongCoTThreshold: 8000,
3358
3484
  // Repetition detector
3359
3485
  repeatProbeChars: 128,
@@ -3464,7 +3590,7 @@ const SETTINGS_SCHEMA = [
3464
3590
  { key: "enableNumberRunaway", label: "识别数字递增流退化", type: "boolean", group: "打断判定",
3465
3591
  hint: "长段递增数字流(如 639.640) 640.641)…)连续多字且无实质内容时打断。启发式判定,仅在数字流足够长时触发。" },
3466
3592
  { key: "enableOverLongCoT", label: "过长 CoT 软切", type: "boolean", group: "打断判定",
3467
- hint: "当本轮 CoT(思考+正文)总字数超过下方阈值时软切并提醒模型「落实阶段性结论、避免过度思考」。属兜底提醒,独立于其他启发式检测。默认关闭。" },
3593
+ hint: "当本轮 CoT 累计字符数达到下方阈值时软切并提醒模型「落实阶段性结论、避免过度思考」。属兜底提醒,独立于其他启发式检测。默认关闭。" },
3468
3594
 
3469
3595
  { key: "minReasoningChars", label: "最少思考字数", type: "number", min: 50, max: 5000, group: "锚点内容",
3470
3596
  hint: "思考短于此长度时不提取结论、不注入。" },
@@ -3482,7 +3608,7 @@ const SETTINGS_SCHEMA = [
3482
3608
  hint: "默认开启。开启时会把「执行命令要守规矩」这段提醒和结论摘要一起插回上下文;关闭就完全不插这段提醒,结论摘要和其他识别、去重功能都不受影响。" },
3483
3609
 
3484
3610
  { key: "overLongCoTThreshold", advanced: true, label: "CoT 长度阈值(字符)", type: "number", min: 0, max: 100000, group: "过长 CoT 参数",
3485
- hint: "本轮 CoT(思考+正文)累计字符数超过此值时触发软切提醒。默认 8000;设为 0 即关闭(同关闭上方开关效果一致)。" },
3611
+ hint: "本轮 CoT 累计字符数达到此值即触发软切提醒,设置值直接生效、不会被放大。默认 8000;设为 0 即关闭(同关闭上方开关效果一致)。内核未分流 text/reasoning 时按整段输出长度估算(含回答文本);只想统计纯思考字数,请把内核切到 separateThreshold 模式。" },
3486
3612
 
3487
3613
  { key: "numberRunMinTextChars", advanced: true, label: "数字流启用最小文本长度", type: "number", min: 100, max: 50000, group: "数字流参数" },
3488
3614
  { key: "numberRunMinChars", advanced: true, label: "数字流最短跨度", type: "number", min: 50, max: 20000, group: "数字流参数" },
@@ -4252,6 +4378,7 @@ function apply(ctx, config) {
4252
4378
  try {
4253
4379
  mkdirSync(settingsDir, { recursive: true });
4254
4380
  writeFileSync(settingsPath, JSON.stringify(value, null, 2), "utf8");
4381
+ setTraceConfig({ ...value });
4255
4382
  return true;
4256
4383
  } catch (error) {
4257
4384
  console.warn(`[cot-anchor] 设置写入失败:${error?.message ?? error}`);
@@ -4261,6 +4388,7 @@ function apply(ctx, config) {
4261
4388
 
4262
4389
  const persisted = loadPersistedSettings();
4263
4390
  if (persisted) applyRuntimeSettings({ ...declarative, ...persisted });
4391
+ setTraceConfig({ ...settings });
4264
4392
 
4265
4393
  // --- COT harvest: storage, observer, routes ------------------------------
4266
4394
  // Everything below is inert until `enableHarvest` is turned on: the observer
@@ -4917,18 +5045,37 @@ function apply(ctx, config) {
4917
5045
  // failure is contained by the host, so it can never break the append it is
4918
5046
  // watching. With the switch off this is the whole cost — one property read.
4919
5047
  ctx.on("session/event", (session, event) => {
4920
- // churn 计数的 turn 边界(唯一可用边界,插件无 turn 生命周期事件):
4921
- // assistant/message 携带 data.turn,大于该 session 上次记录值即视为进入
4922
- // 新 turn,把 churn 计数归零。置于 harvest 开关之前——计数归零与采集
4923
- // 开关无关。软切结算消息同带本 turn 号,但因 churn 决策时已就地推进
4924
- // lastTurn(recordChurnCut),结算号不大于 lastTurn,不会误归零。
5048
+ // TRC-R7/R25:订阅回调首参 session、次参 event.seq;trace/* 自产事件由 bind 内部忽略。
5049
+ try { trace.bind(session, event); } catch { /* 绑定失败不阻断观察 */ }
5050
+ // TRC-R6:观察本身即一次「检查了但未命中」的 scan;放行与验收结论同链留痕。
5051
+ if (event?.type === "assistant/message" || event?.type === "user/message") {
5052
+ const pos = {
5053
+ sessionId: session?.id ?? null,
5054
+ turn: event?.data?.turn,
5055
+ step: event?.data?.step,
5056
+ sourceEventSeq: event?.seq,
5057
+ inputHash: trace.hashInput(JSON.stringify(event?.data?.message ?? "")),
5058
+ evidenceSeq: evidenceSeqCounter,
5059
+ seqNamespace: "counter"
5060
+ };
5061
+ trace.emit("scan", { ...pos, rule: "cot-anchor/observation", matched: false,
5062
+ values: { eventType: event?.type }, thresholds: {}, reason: "below-threshold" });
5063
+ trace.emit("action", { ...pos, rule: "cot-anchor/observation", matched: false,
5064
+ values: { eventType: event?.type }, thresholds: {}, reason: "allow" });
5065
+ trace.emit("outcome", { ...pos, rule: "cot-anchor/observation", matched: false,
5066
+ values: { eventType: event?.type }, thresholds: {}, reason: "no-intervention" });
5067
+ }
5068
+ // churn / over-long 计数的 turn 边界(唯一可用边界,插件无 turn 生命周期
5069
+ // 事件):assistant/message 携带 data.turn,大于该 session 上次记录值即
5070
+ // 视为进入新 turn,两个计数各自归零。置于 harvest 开关之前——计数归零与
5071
+ // 采集开关无关。软切结算消息同带本 turn 号,但决策时已就地推进
5072
+ // lastTurn,结算号不大于 lastTurn,不会误归零。
4925
5073
  if (event?.type === "assistant/message") {
4926
5074
  const boundaryTurn = event?.data?.turn;
4927
5075
  if (Number.isFinite(boundaryTurn)) {
4928
- resetChurnCountOnTurnBoundary(
4929
- typeof session?.id === "string" ? session.id : "",
4930
- boundaryTurn
4931
- );
5076
+ const boundaryKey = typeof session?.id === "string" ? session.id : "";
5077
+ resetChurnCountOnTurnBoundary(boundaryKey, boundaryTurn);
5078
+ resetOverLongCountOnTurnBoundary(boundaryKey, boundaryTurn);
4932
5079
  }
4933
5080
  }
4934
5081
  if (!settings.enableHarvest) return;
@@ -4994,6 +5141,26 @@ function apply(ctx, config) {
4994
5141
  // 宁可留下回调也不要误伤旧内核上的截停能力。
4995
5142
  if (softCutProbe !== CAPABILITY_ABSENT) {
4996
5143
  ctx.on("agent/soft-cut", async (payload, next) => {
5144
+ // TRC-R10/R19:只写输入摘要,inputRef 恒 null;阈值为本次实际生效值。
5145
+ const softCutInputHash = trace.hashInput(String(payload?.fullVisibleText ?? ""));
5146
+ const softCutThresholds = {
5147
+ churnMinHits: CHURN_MIN_HITS, churnWindowChars: CHURN_WINDOW_CHARS,
5148
+ churnMinTextChars: CHURN_MIN_TEXT_CHARS, overLongCoTThreshold: OVER_LONG_COT_THRESHOLD,
5149
+ minReasoningChars: MIN_REASONING_CHARS, maxPoints: MAX_POINTS, maxPointChars: MAX_POINT_CHARS
5150
+ };
5151
+ const scanDetector = (detector, matched, values, reason = null) => trace.emit("scan", {
5152
+ sessionId: payload?.sessionId ?? null,
5153
+ turn: payload?.turn,
5154
+ step: payload?.step,
5155
+ rule: `cot-anchor/${detector}`,
5156
+ matched: matched === true,
5157
+ values,
5158
+ thresholds: softCutThresholds,
5159
+ inputHash: softCutInputHash,
5160
+ reason: reason ?? (matched ? "hit" : "below-threshold"),
5161
+ evidenceSeq: evidenceSeqCounter,
5162
+ seqNamespace: "counter"
5163
+ });
4997
5164
  // budgetClass 兼容契约:每个 cut 决策都带 budgetClass,供内核移植段
4998
5165
  // decideSoftCut 分类裁决(confirmed-repeat=20 / heuristic=6 /
4999
5166
  // confirmed-pseudo=3 三类独立有界预算;confirmed-pseudo 耗尽时内核
@@ -5011,7 +5178,11 @@ function apply(ctx, config) {
5011
5178
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5012
5179
  cutClass: "external",
5013
5180
  reason: external.reason ?? null,
5014
- evidenceSeq: external.evidenceSeq ?? null
5181
+ evidenceSeq: external.evidenceSeq ?? null,
5182
+ detector: "external-request",
5183
+ detectorValues: { reason: external.reason ?? null, evidenceSeq: external.evidenceSeq ?? null },
5184
+ thresholds: softCutThresholds,
5185
+ inputHash: softCutInputHash
5015
5186
  });
5016
5187
  return {
5017
5188
  kind: "cut",
@@ -5042,11 +5213,18 @@ function apply(ctx, config) {
5042
5213
  // the same attempt is also repeating, the loop's `trimTo` is reused
5043
5214
  // so the runaway copies never reach the session.
5044
5215
  const looping = settings.enableRepeat ? findRepeatingTail(fullText) : null;
5045
- if (settings.enablePseudoTool && hasPseudoToolCall(fullText)) {
5216
+ scanDetector("byte-repeat", !!looping, { hasLoop: !!looping, count: looping?.count ?? 0 });
5217
+ const pseudoTool = settings.enablePseudoTool && hasPseudoToolCall(fullText);
5218
+ scanDetector("pseudo-tool-call", pseudoTool, { hasPseudoToolCall: pseudoTool, hasLoop: !!looping });
5219
+ if (pseudoTool) {
5046
5220
  noteSoftCutFired();
5047
5221
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5048
5222
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5049
- cutClass: "pseudoTool"
5223
+ cutClass: "pseudoTool",
5224
+ detector: "pseudo-tool-call",
5225
+ detectorValues: { hasPseudoToolCall: true, hasLoop: !!looping },
5226
+ thresholds: softCutThresholds,
5227
+ inputHash: softCutInputHash
5050
5228
  });
5051
5229
  return {
5052
5230
  kind: "cut",
@@ -5068,7 +5246,11 @@ function apply(ctx, config) {
5068
5246
  noteSoftCutFired();
5069
5247
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5070
5248
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5071
- cutClass: "confirmed-repeat"
5249
+ cutClass: "confirmed-repeat",
5250
+ detector: "byte-repeat",
5251
+ detectorValues: { count: looping.count },
5252
+ thresholds: softCutThresholds,
5253
+ inputHash: softCutInputHash
5072
5254
  });
5073
5255
  return {
5074
5256
  kind: "cut",
@@ -5083,12 +5265,17 @@ function apply(ctx, config) {
5083
5265
  // 循环(每句数字变、动词结构不变)字节级抓不到,但数字归一 + n-gram 频率
5084
5266
  // 能稳定定位。运行时零 LLM:哈希分窗 + HashMap 计数。
5085
5267
  const ngramLoop = settings.enableRepeat ? detectNGramLoop(fullText) : null;
5268
+ scanDetector("ngram-loop", !!ngramLoop, { count: ngramLoop?.count ?? 0, maxGram: ngramLoop?.maxGram ?? null });
5086
5269
  if (ngramLoop) {
5087
5270
  noteSoftCutFired();
5088
5271
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5089
5272
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5090
5273
  cutClass: "heuristic",
5091
- detector: "ngram-loop"
5274
+ detector: "ngram-loop",
5275
+ detector: "ngram-loop",
5276
+ detectorValues: { count: ngramLoop.count, maxGram: ngramLoop.maxGram },
5277
+ thresholds: softCutThresholds,
5278
+ inputHash: softCutInputHash
5092
5279
  });
5093
5280
  return {
5094
5281
  kind: "cut",
@@ -5104,11 +5291,16 @@ function apply(ctx, config) {
5104
5291
  // cut to the run start so the runaway copies never reach the session.
5105
5292
  const numberRunaway = settings.enableNumberRunaway
5106
5293
  ? detectNumberRunaway(fullText) : null;
5294
+ scanDetector("number-runaway", !!numberRunaway, { chars: numberRunaway?.chars ?? 0 });
5107
5295
  if (numberRunaway) {
5108
5296
  noteSoftCutFired();
5109
5297
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5110
5298
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5111
- cutClass: "confirmed-repeat"
5299
+ cutClass: "confirmed-repeat",
5300
+ detector: "number-runaway",
5301
+ detectorValues: { chars: numberRunaway.chars },
5302
+ thresholds: softCutThresholds,
5303
+ inputHash: softCutInputHash
5112
5304
  });
5113
5305
  return {
5114
5306
  kind: "cut",
@@ -5124,6 +5316,7 @@ function apply(ctx, config) {
5124
5316
  // runaway that the period detector structurally cannot see. Being a
5125
5317
  // heuristic, it backs off inside an unclosed code fence.
5126
5318
  const churn = !settings.enableChurn || insideUnclosedCodeFence(fullText) ? null : detectChurn(fullText);
5319
+ scanDetector("churn", !!churn, { hits: churn?.hits ?? 0 }, churn ? null : "detector-disabled-or-in-code-fence");
5127
5320
  if (churn) {
5128
5321
  // Shadow period: a cut produced ONLY by learned additions is counted
5129
5322
  // but not taken, so a fresh pattern cannot sever real work before the
@@ -5133,6 +5326,15 @@ function apply(ctx, config) {
5133
5326
  return null;
5134
5327
  }
5135
5328
  noteSoftCutFired();
5329
+ // TRC-R10:churn 命中分支此前不发事件,补发并带完整判定依据。
5330
+ emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5331
+ ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5332
+ cutClass: "heuristic",
5333
+ detector: "churn",
5334
+ detectorValues: { hits: churn.hits, windowChars: CHURN_WINDOW_CHARS },
5335
+ thresholds: softCutThresholds,
5336
+ inputHash: softCutInputHash
5337
+ });
5136
5338
  // 缺陷 3:按 session+turn 计数(recordChurnCut,含就地归零与 LRU 界),
5137
5339
  // 第 2 次起在锚点追加升级指令。计数的是 handler 返回 cut 决策的次数
5138
5340
  // (与内核是否采纳无关)。
@@ -5155,6 +5357,7 @@ function apply(ctx, config) {
5155
5357
  // 独立于 enableChurn,默认与 enableChurn 同开关语义——通过 enableChurn 统一门禁,
5156
5358
  // 无需新增 settings key;如需独立控制可后续扩展 enableActionChurn。
5157
5359
  const actionChurn = !settings.enableChurn || insideUnclosedCodeFence(fullText) ? null : detectActionChurn(fullText);
5360
+ scanDetector("action-churn", !!actionChurn, { hits: actionChurn?.hits ?? 0 });
5158
5361
  if (actionChurn) {
5159
5362
  noteSoftCutFired();
5160
5363
  const churnKey = typeof payload?.sessionId === "string" ? payload.sessionId : "";
@@ -5164,7 +5367,11 @@ function apply(ctx, config) {
5164
5367
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5165
5368
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5166
5369
  cutClass: "heuristic",
5167
- detector: "action-churn"
5370
+ detector: "action-churn",
5371
+ detector: "action-churn",
5372
+ detectorValues: { hits: actionChurn.hits, occurrence: churnOccurrence },
5373
+ thresholds: softCutThresholds,
5374
+ inputHash: softCutInputHash
5168
5375
  });
5169
5376
  return {
5170
5377
  kind: "cut",
@@ -5174,30 +5381,49 @@ function apply(ctx, config) {
5174
5381
  };
5175
5382
  }
5176
5383
 
5177
- // (3b) Over-long CoT reminder: pure length-based nudge. This is a
5178
- // "last-resort" detector — it fires only when nothing above caught
5179
- // a concrete anomaly but the thinking has grown too long. Unlike
5180
- // the anomaly detectors above, there is NO per-turn gate: every
5181
- // soft-cut poll that finds us past the threshold can fire, so the
5182
- // reminder keeps pressing until the model actually steps back.
5183
- // Inside unclosed code fences we skip (same guard as churn): the
5184
- // model is writing code, not overthinking.
5384
+ // (3b) Over-long CoT reminder: pure length-based, last-resort detector.
5385
+ // No "cut once per turn" gate — but each fire now appends a
5386
+ // per-turn escalation so repeated reminders are not byte-identical
5387
+ // text the model can echo as an "I should act now" opener.
5388
+ // Inside unclosed code fences we skip (same guard as churn).
5389
+ //
5390
+ // 计数口径:优先用内核传入的 streams.reasoningLength(纯思考字符数),
5391
+ // 老内核未传时降级为 fullText.length 估算,锚点文案标注 merged estimate。
5392
+ // overLongCoTThreshold 就是唯一生效阈值,两种口径下都不放大。需要只按
5393
+ // 纯思考字数计时,把内核切到 separateThreshold
5394
+ // (DSH_TRANSITION_TEXT_MODE=separateThreshold,重跑移植脚本并重启)。
5395
+ const streams = payload?.streams;
5396
+ const hasReasoningCount = streams && typeof streams.reasoningLength === "number";
5397
+ const reasoningChars = hasReasoningCount ? streams.reasoningLength : fullText.length;
5398
+ scanDetector("over-long-cot", settings.enableOverLongCoT && OVER_LONG_COT_THRESHOLD > 0
5399
+ && reasoningChars >= OVER_LONG_COT_THRESHOLD,
5400
+ { reasoningChars, threshold: OVER_LONG_COT_THRESHOLD, hasStreams: !!hasReasoningCount });
5185
5401
  if (settings.enableOverLongCoT && OVER_LONG_COT_THRESHOLD > 0
5186
- && fullText.length >= OVER_LONG_COT_THRESHOLD
5402
+ && reasoningChars >= OVER_LONG_COT_THRESHOLD
5187
5403
  && !insideUnclosedCodeFence(fullText)) {
5188
5404
  noteSoftCutFired();
5405
+ const overLongKey = typeof payload?.sessionId === "string" ? payload.sessionId : "";
5406
+ const occurrence = recordOverLongCut(overLongKey, payload?.turn);
5189
5407
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5190
5408
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5191
5409
  cutClass: "heuristic",
5192
- detector: "over-long-cot"
5410
+ detector: "over-long-cot",
5411
+ reasoningChars,
5412
+ hasStreams: !!hasReasoningCount,
5413
+ occurrence,
5414
+ detector: "over-long-cot",
5415
+ detectorValues: { reasoningChars, threshold: OVER_LONG_COT_THRESHOLD, occurrence },
5416
+ thresholds: softCutThresholds,
5417
+ inputHash: softCutInputHash
5193
5418
  });
5194
- const anchorText = renderOverLongCoTAnchor(fullText.length, OVER_LONG_COT_THRESHOLD);
5419
+ const anchorText = renderOverLongCoTAnchor(
5420
+ reasoningChars, OVER_LONG_COT_THRESHOLD, !!hasReasoningCount, occurrence);
5195
5421
  return {
5196
5422
  kind: "cut",
5197
5423
  budgetClass: "heuristic",
5198
5424
  cutClass: "heuristic",
5199
5425
  contexts: [buildAnchorContext(anchorText,
5200
- `cot-anchor: over-long-cot ${fullText.length}/${OVER_LONG_COT_THRESHOLD}`)]
5426
+ `cot-anchor: over-long-cot ${reasoningChars}/${OVER_LONG_COT_THRESHOLD} x${occurrence}${hasReasoningCount ? "" : " [merged estimate]"}`)]
5201
5427
  };
5202
5428
  }
5203
5429
 
@@ -5206,6 +5432,8 @@ function apply(ctx, config) {
5206
5432
  // ("所以/因此/综上/therefore …") already present — a density-only
5207
5433
  // Tier-2 sentence (a file name / number in prose) is not "phase A
5208
5434
  // settled" and must never trigger a mid-stream cut.
5435
+ scanDetector("transition", false, { enabled: settings.enableTransition },
5436
+ settings.enableTransition ? "below-threshold" : "detector-disabled");
5209
5437
  if (!settings.enableTransition) return null;
5210
5438
  // P1-5 (2026-10-22): strip previously-injected anchor point texts from a
5211
5439
  // DETECTION COPY before the transition chain reads it. Models echo a
@@ -5278,7 +5506,11 @@ function apply(ctx, config) {
5278
5506
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5279
5507
  ...evidence,
5280
5508
  cutClass: "heuristic",
5281
- detector: "transition"
5509
+ detector: "transition",
5510
+ detector: "transition",
5511
+ detectorValues: { points: points.length },
5512
+ thresholds: softCutThresholds,
5513
+ inputHash: softCutInputHash
5282
5514
  });
5283
5515
  return {
5284
5516
  kind: "cut",
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 单插件 trace 运行时胶水(四包同源;与 lib/trace.js 同为内联,不跨包 import)。
3
+ *
4
+ * configHash 取「实际生效配置」:由各插件在 settings 合并完成后调用
5
+ * setTraceConfig(...) 注入(优先级 env > 持久化 settings.json > 默认值),
6
+ * 每次注入即 append 一条配置变更史(TRC-R8)。
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+ import { createTraceSink } from "./trace.js";
10
+
11
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
12
+ let liveConfig = Object.freeze({ plugin: pkg.name, version: pkg.version, defaultsApplied: true });
13
+
14
+ /** 本插件唯一的 trace 出口;订阅回调与判定发射点共用同一实例。 */
15
+ export const trace = createTraceSink({
16
+ plugin: pkg.name,
17
+ pluginVersion: pkg.version,
18
+ effectiveConfig: () => liveConfig
19
+ });
20
+
21
+ /** 注入生效配置并重算 configHash(写一条变更史,确定性去重)。 */
22
+ export function setTraceConfig(effectiveConfig) {
23
+ liveConfig = Object.freeze({ ...(effectiveConfig ?? {}) });
24
+ trace.recordConfigChange();
25
+ return trace.configHash;
26
+ }
package/lib/trace.js ADDED
@@ -0,0 +1,292 @@
1
+ /**
2
+ * DSH trace 契约底座 —— 四包内联同源副本(TRC-R4/R5/R6/R7/R8/R9/R19/R25)。
3
+ *
4
+ * 为什么内联:四包 package.json 的 exports 是封闭白名单,跨包 import
5
+ * `dsh-derive-watcher/lib/trace.js` 必抛 ERR_PACKAGE_PATH_NOT_EXPORTED。
6
+ * 本文件由 D:/dsh/_b1scratch/trace-build/trace.js 复制到四包 lib/ 下,
7
+ * 四份必须 sha256 一致;不得改成共享包。
8
+ *
9
+ * 写入路径:session.append("trace/<category>", data, { ignorable: true })。
10
+ * 顶层只允许内核补的 ignorable / seq / time,所有业务字段进 data。
11
+ * 三处内核补丁 marker 是未知 trace/* 能被写入/读出的唯一依据。
12
+ */
13
+ import { createHash } from "node:crypto";
14
+ import { appendFileSync, mkdirSync } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { join } from "node:path";
17
+
18
+ /** 改字段模板、脱敏边界或指标口径时递增(TRC-R25)。 */
19
+ export const TRACE_VERSION = 1;
20
+
21
+ /** data 固定 12 键;payload 固定 8 键,unclassified 是唯一允许的第 9 键。 */
22
+ export const DATA_KEYS = Object.freeze([
23
+ "traceVersion", "plugin", "pluginVersion", "runId", "groupId", "sessionId",
24
+ "turn", "step", "sourceEventSeq", "ts", "configHash", "payload"
25
+ ]);
26
+ export const PAYLOAD_KEYS = Object.freeze([
27
+ "rule", "matched", "values", "thresholds", "inputHash", "inputRef",
28
+ "comparedIds", "reason"
29
+ ]);
30
+ export const CATEGORIES = Object.freeze([
31
+ "scan", "decision", "action", "outcome", "invocation"
32
+ ]);
33
+
34
+ /** evidenceSeq 四类语义 + 保留原有 step 命名,共 5 个枚举值(TRC-R7)。 */
35
+ export const SEQ_NAMESPACES = Object.freeze([
36
+ "counter", "step", "session", "stall", "external"
37
+ ]);
38
+
39
+ /** 宿主未提供 turn/step 时的显式哨兵:必填键不得为 null,也不伪造真实步序。 */
40
+ export const UNKNOWN_POSITION = -1;
41
+
42
+ const DEFAULT_CONFIG_ROOT = join(homedir(), ".dsh", "trace");
43
+ const SHA256_PREFIX = "sha256:";
44
+
45
+ /** 按键名排序(递归)序列化,展开默认值后的生效配置才参与 hash。 */
46
+ function sortedClone(value) {
47
+ if (Array.isArray(value)) return value.map(sortedClone);
48
+ if (value !== null && typeof value === "object") {
49
+ const out = {};
50
+ for (const key of Object.keys(value).sort()) out[key] = sortedClone(value[key]);
51
+ return out;
52
+ }
53
+ return value === undefined ? null : value;
54
+ }
55
+
56
+ /** 脱敏:只写摘要,inputRef 恒为 null(TRC-R19 冻结)。 */
57
+ export function hashInput(text) {
58
+ return SHA256_PREFIX + createHash("sha256").update(String(text ?? "")).digest("hex");
59
+ }
60
+
61
+ /** @returns {"sha256:<hex>"} 生效配置的确定性 hash(TRC-R8)。 */
62
+ export function computeConfigHash(effectiveConfig) {
63
+ const canonical = JSON.stringify(sortedClone(effectiveConfig ?? {}));
64
+ return SHA256_PREFIX + createHash("sha256").update(canonical).digest("hex");
65
+ }
66
+
67
+ function dayStamp(now = new Date()) {
68
+ return now.getFullYear() + "-" + String(now.getMonth() + 1).padStart(2, "0")
69
+ + "-" + String(now.getDate()).padStart(2, "0");
70
+ }
71
+
72
+ /** 按日分片 append-only JSONL(骨架复用 auto-memory/evidence-store.js)。 */
73
+ function appendJsonl(root, fileName, record) {
74
+ try {
75
+ mkdirSync(root, { recursive: true });
76
+ appendFileSync(join(root, fileName), JSON.stringify(record) + "\n", "utf8");
77
+ return true;
78
+ } catch (error) {
79
+ try { console.warn(`[trace] append-jsonl-failed ${fileName}: ${error?.message ?? error}`); } catch { /* ignore */ }
80
+ return false;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * 创建单插件的 trace 出口。
86
+ * @param {object} options
87
+ * @param {string} options.plugin 插件 id
88
+ * @param {string} options.pluginVersion 插件版本
89
+ * @param {object|Function} [options.effectiveConfig] 生效配置(env > settings.json > defaults 合并结果)
90
+ * @param {string} [options.configRoot] 变更史 / 降级 sidecar 落盘根
91
+ * @param {Function} [options.log] 结构化日志行输出
92
+ */
93
+ export function createTraceSink(options = {}) {
94
+ const {
95
+ plugin,
96
+ pluginVersion,
97
+ effectiveConfig = {},
98
+ configRoot = process.env.DSH_TRACE_CONFIG_ROOT || DEFAULT_CONFIG_ROOT,
99
+ log = (line) => console.warn(line)
100
+ } = options;
101
+ const resolveConfig = typeof effectiveConfig === "function"
102
+ ? effectiveConfig
103
+ : () => effectiveConfig;
104
+
105
+ const runId = process.env.DSH_TRACE_RUN_ID ?? null;
106
+ const groupId = process.env.DSH_TRACE_GROUP_ID ?? null;
107
+ /** sessionId -> { session, lastSeq, lastTurn, lastStep };只记录非 trace/* 的上游事件。 */
108
+ const bindings = new Map();
109
+ /** 最近一次 bind 的 sessionId:判定点未显式带 sessionId 时的唯一回退(多会话下仍以显式值为准)。 */
110
+ let lastBoundSessionId = null;
111
+ const recordedConfigKeys = new Set();
112
+ let configHash = computeConfigHash(resolveConfig());
113
+ let missingWarned = false;
114
+
115
+ function warnMissing(detail) {
116
+ if (missingWarned) return;
117
+ missingWarned = true;
118
+ try { log(`TRACE_CONFIG_MISSING ${detail}`); } catch { /* ignore */ }
119
+ }
120
+ if (runId === null || groupId === null) {
121
+ warnMissing(`plugin=${plugin} runId=${runId} groupId=${groupId}`);
122
+ }
123
+
124
+ /** 变更史:启动时写一条,保证每条 decision 的 hash 可回溯(TRC-R8)。 */
125
+ function recordConfigChange() {
126
+ const current = computeConfigHash(resolveConfig());
127
+ configHash = current;
128
+ const key = `${dayStamp()}:${plugin}:${current}`;
129
+ if (recordedConfigKeys.has(key)) return current;
130
+ const ok = appendJsonl(configRoot, `config-history-${dayStamp()}.jsonl`, {
131
+ ts: new Date().toISOString(), plugin, configHash: current, config: sortedClone(resolveConfig())
132
+ });
133
+ if (ok) recordedConfigKeys.add(key);
134
+ return current;
135
+ }
136
+ recordConfigChange();
137
+
138
+ /**
139
+ * session/event 订阅回调里调用:登记会话句柄与上游事件 seq。
140
+ * trace/* 自产事件不覆盖 lastSeq,否则 sourceEventSeq 会指向上一条 trace(自引用,join 失效)。
141
+ */
142
+ function bind(session, event) {
143
+ if (typeof event?.type === "string" && event.type.startsWith("trace/")) return null;
144
+ const sid = session?.id ?? event?.data?.sessionId ?? null;
145
+ if (!sid) { warnMissing(`plugin=${plugin} session-id-unavailable`); return null; }
146
+ const prev = bindings.get(sid) ?? { session: null, lastSeq: null, lastTurn: null, lastStep: null };
147
+ if (session && typeof session.append === "function") prev.session = session;
148
+ if (Number.isInteger(event?.seq)) prev.lastSeq = event.seq;
149
+ const data = event?.data ?? {};
150
+ if (Number.isFinite(data.turn)) prev.lastTurn = data.turn;
151
+ if (Number.isFinite(data.step)) prev.lastStep = data.step;
152
+ bindings.set(sid, prev);
153
+ lastBoundSessionId = sid;
154
+ return prev;
155
+ }
156
+
157
+ /** 缺失降级:完整落到 sidecar,不得只 try/catch 吞掉(TRC-R25)。 */
158
+ function degrade(data, reason) {
159
+ appendJsonl(configRoot, `trace-degraded-${dayStamp()}.jsonl`, {
160
+ type: "trace/invocation",
161
+ ts: new Date().toISOString(),
162
+ reason,
163
+ data: { ...data, payload: { ...data.payload, reason } }
164
+ });
165
+ warnMissing(`plugin=${plugin} ${reason}`);
166
+ }
167
+
168
+ /**
169
+ * dsh-session.append 用 snapshotJsonValue 做无损 JSON 校验:undefined / NaN /
170
+ * -0 / BigInt / 函数 / 异类对象一律整条拒收。判定逻辑已经跑完,values 与
171
+ * thresholds 只是观测快照,这里统一走一次 JSON 往返把不可序列化值洗掉,
172
+ * 保证事件能落盘;顶层 12 键与 payload 8 键由 emit 显式构造,不受影响。
173
+ */
174
+ function jsonSafe(value) {
175
+ try {
176
+ const text = JSON.stringify(value);
177
+ return text === undefined ? null : JSON.parse(text);
178
+ } catch { return null; }
179
+ }
180
+
181
+ function appendTrace(session, type, data) {
182
+ const safeData = jsonSafe(data);
183
+ if (safeData === null) {
184
+ degrade(data, "append-failed: data-not-json-safe");
185
+ return false;
186
+ }
187
+ try {
188
+ session.append(type, safeData, { ignorable: true });
189
+ return true;
190
+ } catch (error) {
191
+ const message = String(error?.message ?? error);
192
+ if (message.includes("cannot reenter")) {
193
+ // dsh-session 的 publish 期间禁止再 append;延迟到 publish 结束后重发(TRC-R9)。
194
+ queueMicrotask(() => {
195
+ try { session.append(type, safeData, { ignorable: true }); }
196
+ catch (retryError) { degrade(data, `append-retry-failed: ${String(retryError?.message ?? retryError)}`); }
197
+ });
198
+ return true;
199
+ }
200
+ degrade(data, `append-failed: ${message}`);
201
+ return false;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * 发一条 trace 事件。类别非法时按 TRC-R5 兜底成 invocation + unclassified。
207
+ * @param {string} category scan|decision|action|outcome|invocation
208
+ * @param {object} spec 判定上下文
209
+ */
210
+ function emit(category, spec = {}) {
211
+ const known = CATEGORIES.includes(category);
212
+ const resolved = known ? category : "invocation";
213
+ const unclassified = !known || spec.unclassified === true;
214
+ const sid = spec.sessionId ?? lastBoundSessionId ?? null;
215
+ const binding = sid !== null ? bindings.get(sid) : null;
216
+ const session = binding?.session ?? null;
217
+
218
+ const values = { ...(spec.values ?? {}) };
219
+ if (spec.evidenceSeq !== undefined && spec.evidenceSeq !== null) values.evidenceSeq = spec.evidenceSeq;
220
+ if (spec.seqNamespace !== undefined && spec.seqNamespace !== null) {
221
+ if (SEQ_NAMESPACES.includes(spec.seqNamespace)) values.seqNamespace = spec.seqNamespace;
222
+ else {
223
+ values.seqNamespace = null;
224
+ try { log(`[trace] unknown seqNamespace ${spec.seqNamespace}`); } catch { /* ignore */ }
225
+ }
226
+ }
227
+
228
+ const payload = {
229
+ rule: spec.rule ?? null,
230
+ matched: spec.matched === true,
231
+ values,
232
+ thresholds: spec.thresholds ?? {},
233
+ inputHash: spec.inputHash ?? null,
234
+ inputRef: null,
235
+ comparedIds: Array.isArray(spec.comparedIds) ? spec.comparedIds : [],
236
+ reason: unclassified ? "unclassified" : (spec.reason ?? null)
237
+ };
238
+ if (unclassified) payload.unclassified = true;
239
+
240
+ const turn = Number.isFinite(spec.turn) ? spec.turn
241
+ : (Number.isFinite(binding?.lastTurn) ? binding.lastTurn : UNKNOWN_POSITION);
242
+ const step = Number.isFinite(spec.step) ? spec.step
243
+ : (Number.isFinite(binding?.lastStep) ? binding.lastStep : UNKNOWN_POSITION);
244
+ const sourceEventSeq = Number.isInteger(spec.sourceEventSeq)
245
+ ? spec.sourceEventSeq
246
+ : (Number.isInteger(binding?.lastSeq) ? binding.lastSeq : null);
247
+
248
+ const data = {
249
+ traceVersion: TRACE_VERSION,
250
+ plugin,
251
+ pluginVersion,
252
+ runId,
253
+ groupId,
254
+ sessionId: sid,
255
+ turn,
256
+ step,
257
+ sourceEventSeq,
258
+ ts: new Date().toISOString(),
259
+ configHash,
260
+ payload
261
+ };
262
+
263
+ const type = `trace/${resolved}`;
264
+ if (!session || typeof session.append !== "function") {
265
+ // session 不可用:无法 append 时写 sidecar 并显式告警,绝不静默丢弃。
266
+ degrade(data, "session-unavailable");
267
+ return data;
268
+ }
269
+ if (sourceEventSeq === null) {
270
+ // 上游 seq 缺失:仍要发 invocation 留痕,不得只 try/catch 吞掉。
271
+ appendTrace(session, "trace/invocation", {
272
+ ...data,
273
+ payload: { ...payload, reason: "session-unavailable" }
274
+ });
275
+ }
276
+ appendTrace(session, type, data);
277
+ return data;
278
+ }
279
+
280
+ return {
281
+ plugin,
282
+ pluginVersion,
283
+ runId,
284
+ groupId,
285
+ get configHash() { return configHash; },
286
+ bind,
287
+ emit,
288
+ recordConfigChange,
289
+ hashInput,
290
+ getBinding: (sid) => bindings.get(sid) ?? null
291
+ };
292
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cot-anchor",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
4
4
  "description": "思考锚点:从模型上一段思考中提取已确立结论,在工具结果后注入,减少重复推导;并可识别打转与伪工具调用",
5
5
  "keywords": [
6
6
  "dsh",
@@ -250,7 +250,21 @@ if (mode === "check") {
250
250
 
251
251
  // ---- apply ----------------------------------------------------------------
252
252
  if (applied) {
253
- log("✓ 目标内核已处于移植状态,不重复补丁(幂等)。");
253
+ // TRC-R14:已移植 ≠ 字段已就位。旧模板缺 detector/阈值时增量注入,不重复移植。
254
+ const OLD_TAKEN = `\t\t\t\t\t\t\tbudgetState: { ...budgetState }\n\t\t\t\t\t\t}, { ignorable: true });`;
255
+ const NEW_TAKEN = `\t\t\t\t\t\t\tbudgetState: { ...budgetState },\n\t\t\t\t\t\t\tdetector: cutDecision.detector ?? cutDecision.cutClass ?? "heuristic",\n\t\t\t\t\t\t\tthresholds: { budgetKey, budgetTotal: budgetState.total }\n\t\t\t\t\t\t}, { ignorable: true });`;
256
+ if (source.includes(OLD_TAKEN)) {
257
+ writeFileSync(TARGET, source.split(OLD_TAKEN).join(NEW_TAKEN), "utf8");
258
+ const upgradeSyntaxError = syntaxCheck(TARGET);
259
+ if (upgradeSyntaxError !== null) {
260
+ writeFileSync(TARGET, source, "utf8");
261
+ log(`✗ 增量注入语法校验失败,已回滚:${upgradeSyntaxError}`);
262
+ process.exit(1);
263
+ }
264
+ log("✓ 已移植:增量补 detector/阈值(不重复移植)");
265
+ process.exit(0);
266
+ }
267
+ log("✓ 目标内核已处于移植状态且字段已就位(幂等)。");
254
268
  log(" 内核升级或需要重跑本脚本前,必须先执行:node apply-softcut-port.mjs --revert");
255
269
  log(" 若内核已被包管理器整体覆盖(无移植标记),直接重新 apply 即可,但需通过下方版本/哈希自检。");
256
270
  process.exit(0);
@@ -971,6 +985,9 @@ const AGENT_LOOP_BLOCKS = [
971
985
  },
972
986
  {
973
987
  name: 'p5-soft-cut-taken',
988
+ // TRC-R14:已打旧模板的内核走 PRESENT_MARKER 分支,用 upgrade pair 补字段而非跳过。
989
+ oldClose: `\t\t\t\t\t\t\tbudgetState: { ...budgetState }\n\t\t\t\t\t\t}, { ignorable: true });`,
990
+ newClose: `\t\t\t\t\t\t\tbudgetState: { ...budgetState },\n\t\t\t\t\t\t\tdetector: cutDecision.detector ?? cutDecision.cutClass ?? "heuristic",\n\t\t\t\t\t\t\tthresholds: { budgetKey, budgetTotal: budgetState.total }\n\t\t\t\t\t\t}, { ignorable: true });`,
974
991
  find: L(
975
992
  '\t\t\t\t\tsoftCutDecision = cutDecision;',
976
993
  '\t\t\t\t\tbudgetState[budgetKey] += 1;',
@@ -990,7 +1007,9 @@ const AGENT_LOOP_BLOCKS = [
990
1007
  '\t\t\t\t\t\t\tstep,',
991
1008
  '\t\t\t\t\t\t\tcutClass: cutDecision.cutClass ?? "heuristic",',
992
1009
  '\t\t\t\t\t\t\tbudgetKey,',
993
- '\t\t\t\t\t\t\tbudgetState: { ...budgetState }',
1010
+ '\t\t\t\t\t\t\tbudgetState: { ...budgetState },',
1011
+ '\t\t\t\t\t\t\tdetector: cutDecision.detector ?? cutDecision.cutClass ?? "heuristic",',
1012
+ '\t\t\t\t\t\t\tthresholds: { budgetKey, budgetTotal: budgetState.total }',
994
1013
  '\t\t\t\t\t\t}, { ignorable: true });',
995
1014
  '\t\t\t\t\t\tthis.dispatch.emit("agent/soft-cut-taken", {',
996
1015
  '\t\t\t\t\t\t\tturn,',
@@ -998,6 +1017,8 @@ const AGENT_LOOP_BLOCKS = [
998
1017
  '\t\t\t\t\t\t\tcutClass: cutDecision.cutClass ?? "heuristic",',
999
1018
  '\t\t\t\t\t\t\tbudgetKey,',
1000
1019
  '\t\t\t\t\t\t\tbudgetState: { ...budgetState },',
1020
+ '\t\t\t\t\t\t\tdetector: cutDecision.detector ?? cutDecision.cutClass ?? "heuristic",',
1021
+ '\t\t\t\t\t\t\tthresholds: { budgetKey, budgetTotal: budgetState.total },',
1001
1022
  '\t\t\t\t\t\t\tevidenceSeq: takenEvent.seq',
1002
1023
  '\t\t\t\t\t\t});',
1003
1024
  '\t\t\t\t\t} catch {',