dsh-cot-anchor 0.4.1 → 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/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);
@@ -1063,6 +1115,10 @@ let SOFT_CUT_TRANSITION_WINDOW = 48;
1063
1115
  */
1064
1116
  let SOFT_CUT_GAP_THRESHOLD = 80;
1065
1117
 
1118
+ /** Over-long CoT soft-cut threshold: fullVisibleText length beyond which a
1119
+ * reminder cut fires. 0 means effectively disabled (checked at the hook site). */
1120
+ let OVER_LONG_COT_THRESHOLD = 8000;
1121
+
1066
1122
  /**
1067
1123
  * Finds the LAST Tier-1 conclusion opener inside the tail scan window and
1068
1124
  * returns its index relative to the tail start, or null if none matches.
@@ -1546,7 +1602,57 @@ let NGram_PHRASE_MIN = 5;
1546
1602
  let NGram_MIN_COUNT = 5;
1547
1603
  /** 修复②:最高频短语覆盖尾窗的占比下限(默认 0.05;运行时可经 ngramCoverageRatio 覆盖)。 */
1548
1604
  let NGram_COVERAGE_RATIO = 0.05;
1549
- /** 修复②:停用词集合,过滤普通高频词以防误报。 */
1605
+ /**
1606
+ * 修复③(误软切回归):英文词轨的 token 与短语形态守卫。
1607
+ * 事故样本(cot-anchor 误软切样例 1/2/3)里最高频 gram 分别是 "s l"(公式
1608
+ * S·l 的单字母变量)与 "t t"(补丁脚本的 «T» 制表符占位符)——它们都不是
1609
+ * 英文单词,只是结构字符;词轨把它们当词后,2-gram 在千字级尾窗里随便就
1610
+ * 凑够 5 次、5% 覆盖率,于是每次写公式/写补丁都会被误切。
1611
+ * 因此词轨改为:token 至少 2 个字母(单字母变量/占位符永不入表);gram 取
1612
+ * 相邻 4 词(2~3 词搭配在技术文本/表格列骨架里天然高频,4 词才构成"句子
1613
+ * 骨架"重复);再叠加最短字母数守卫,滤掉 "cn cl n l" 这类公式变量组合。
1614
+ */
1615
+ const NGram_WORD_TOKEN_MIN_CHARS = 2;
1616
+ const NGram_WORD_GRAM_SIZE = 4;
1617
+ /** 词轨 gram 的最少字母总数(不含空格):4 个两字母词的 8 字母组合属公式变量,不是短语。 */
1618
+ const NGram_WORD_MIN_LETTERS = 10;
1619
+ /** 字符轨 gram 至少包含的 CJK 字数:纯符号/版本号/DIGIT 组合("«t»«t"、"vDIGI")不是语义短语。 */
1620
+ const NGram_CJK_MIN_CHARS = 2;
1621
+ /**
1622
+ * 修复③(第二轮):上下文稳定性下限(词轨/字符轨共用)。
1623
+ * 真正的语义循环是把同一句骨架反复吐出来,命中短语的左右邻居高度一致;
1624
+ * 而"标识符/术语复用"(样例 3 的 "dsh patch chat" 7 次)左邻分别来自
1625
+ * patchmarker / window / says / oldpatchmarker / marker / string / contains,
1626
+ * 每次上下文都不同。要求最高频左右邻组合占命中次数的 ≥65%,把后者挡掉。
1627
+ * 阈值从 50% 提到 65%(第六轮真实轨迹复盘):UI 错误文案 "failed to load
1628
+ * plugins" 在调试文本里出现 8 次、最高频上下文恰好占 50%,是标签复用不是循环;
1629
+ * 而真正重复整句骨架的样本里该比例通常接近 100%,65% 留有充分余量。
1630
+ */
1631
+ const NGram_CONTEXT_MIN_RATIO = 0.65;
1632
+ /** 修复③(第三轮):词轨逐个候选校验的上限,避免尾窗内几千个 gram 全做上下文扫描。 */
1633
+ const NGram_WORD_CANDIDATE_LIMIT = 12;
1634
+ /**
1635
+ * 修复③(第七轮,长上下文稀释):覆盖率的分母改用「命中区间」而不是整个尾窗。
1636
+ *
1637
+ * 尾窗固定 16000 字符,但一个 turn 的 `reasoning+text` 可能长达十几万字符。
1638
+ * 只要 turn 够长,即使模型在末尾真的把同一句重复 30 次,也凑不够 5%——真实
1639
+ * 会话回放实测:240k 字符的 turn 末尾追加 30 次中文整句(60 次短语命中),
1640
+ * count=60、coverage 仅 1.9%,完全不触发;英文侧稍好(5.8%)但同样被摊薄。
1641
+ *
1642
+ * 语义上要判的是「重复有多密集」,而不是「重复占全文多大比例」:把分母换成
1643
+ * 首次命中到末次命中的跨度(即重复集中在多长的区间里)。跨度天然 ≥ 命中总
1644
+ * 长度(count × gramSize,overlap 除外),所以覆盖率不会因此虚高到 1 以上。
1645
+ *
1646
+ * 但不能只用密度口径:短 turn(2~5k 字符)里一个术语出现 5~7 次、每次都挨得
1647
+ * 很近时,跨度分母会把占比抬到 5% 以上(真实轨迹回放:`远程不存在` 7 次、
1648
+ * 计划书术语 `blocked followup user turn` 5 次、状态字段骨架 7 次全部误判)。
1649
+ * 因此保留旧口径(分母 = 整个尾窗)与新口径取**最大值**,并给密度分母设下限,
1650
+ * 让"短文本里少量集中出现"仍按旧比例判定,"超长 turn 末尾成段打转"才被密度
1651
+ * 口径救回(实测 240k 字符 turn 内重复 30 次可命中,旧口径只有 1.9%)。
1652
+ */
1653
+ const NGram_DENSITY_MIN_CHARS = 800;
1654
+ const NGram_DENSITY_MIN_TOKENS = 600;
1655
+
1550
1656
  const NGram_STOPWORDS = new Set([
1551
1657
  "的", "了", "是", "我", "你", "他", "她", "它", "们", "这", "那", "就", "也", "都",
1552
1658
  "要", "会", "能", "可以", "让", "把", "给", "对", "从", "用", "到", "在", "和", "与",
@@ -1583,9 +1689,15 @@ function normalizeForNGram(text) {
1583
1689
  return text
1584
1690
  .toLowerCase()
1585
1691
  .replace(/\d+/g, "DIGIT")
1586
- // 下划线 `_` 与标点同样替换为空格:避免 web_fetch / settings_mutate 切出
1587
- // "web_f"/"web fe" 之类伪子串虚高(下划线在字符类里按字面量处理)
1588
- .replace(/[,,。.!!??;;::""''()()【】\[\]<>《》—–\-_]/g, " ")
1692
+ // 修复③(第五轮):连字符/下划线/路径分隔符做「粘合」而不是切分——
1693
+ // 标识符必须保持原子 token。否则 no-blind-wait-polling、
1694
+ // D:\dsh\dsh-cot-anchor\lib\index.js 会被拆成 4 个以上普通词,
1695
+ // 在长会话里按短语重复计数(真实轨迹实测:技能名 x6、文件路径 x7)。
1696
+ // 粘合后它们变成单个长 token,无法组成 4 词 gram;正常带连字符的英文
1697
+ // (re-analyze)成为单 token,不影响真循环检测。
1698
+ .replace(/[-_\/\\]/g, "")
1699
+ // 其余标点仍替换为空格(下划线等已在上一行粘合,不在此字符类中)
1700
+ .replace(/[,,。.!!??;;::""''()()【】\[\]<>《》—–]/g, " ")
1589
1701
  .replace(/\s+/g, " ")
1590
1702
  .trim();
1591
1703
  }
@@ -1606,44 +1718,143 @@ function pickMaxFromCountMap(gramCount, totalGrams) {
1606
1718
  }
1607
1719
 
1608
1720
  /**
1609
- * 修复②:英文词级 2-gram 频率统计。相邻两个英文词([a-z]+ 抽取)为一个 gram,
1610
- * 如 "settings path"。英文单词是原子 token:单词内部子串("setti"/"etting")
1611
- * 永远不会成为 gram。词级 gram 允许含空格——两词之间的空白正是短语边界。
1612
- * @param {string[]} words 英文词序列
1721
+ * 修复③(第三轮):英文词级 n-gram 频率统计。相邻 N 个英文词为一个 gram
1722
+ * (默认 4 词),如 "verify checksum before releasing"。英文单词是原子 token:
1723
+ * 单词内部子串("setti"/"etting")永远不会成为 gram;单字母结构字符(S·l 的
1724
+ * "s"/"l"、«T» 的 "t")在 token 抽取阶段就被长度守卫挡掉。
1725
+ * 修复③(第四轮):只在**同一句/同一子句**内组 gram。中文句子间隔不让英文词
1726
+ * 假装相邻——否则中文主体里零散的 settings/session/anchor/tool 会被拼成
1727
+ * "settings tool session anchor" 这类跨句假短语(F 用例 30.8% 覆盖率误报)。
1728
+ * @param {string[][]} segments 按句/子句切分后的英文词序列
1729
+ * @param {number} gramSize 词数(相邻 N 词)
1613
1730
  * @returns {{maxCount:number, maxGram:string, totalGrams:number, gramCount:Map<string, number>}|null}
1614
1731
  */
1615
- function computeWordBigramFingerprint(words) {
1732
+ function computeWordGramFingerprint(segments, gramSize) {
1616
1733
  const gramCount = new Map();
1617
1734
  let totalGrams = 0;
1618
- for (let i = 0; i < words.length - 1; i++) {
1619
- const gram = words[i] + " " + words[i + 1];
1620
- let v = gramCount.get(gram) ?? 0;
1621
- gramCount.set(gram, ++v);
1622
- totalGrams++;
1735
+ for (const words of segments) {
1736
+ for (let i = 0; i <= words.length - gramSize; i++) {
1737
+ const gram = words.slice(i, i + gramSize).join(" ");
1738
+ let v = gramCount.get(gram) ?? 0;
1739
+ gramCount.set(gram, ++v);
1740
+ totalGrams++;
1741
+ }
1623
1742
  }
1624
1743
  if (totalGrams === 0) return null;
1625
1744
  return pickMaxFromCountMap(gramCount, totalGrams);
1626
1745
  }
1627
1746
 
1747
+ /**
1748
+ * 修复③(第四轮):按句/子句切分尾窗原文,再逐段抽取英文词。
1749
+ * 切分符覆盖中英文句读与换行;数字/下划线等仍由 normalizeForNGram 处理。
1750
+ * 目的:词级 gram 只在同一句/子句内形成,中文间隔不再让英文术语"假装相邻"。
1751
+ * @param {string} rawText
1752
+ * @returns {string[][]} 每段的英文词序列(长度 ≥1)
1753
+ */
1754
+ function extractEnglishWordSegments(rawText) {
1755
+ const segments = [];
1756
+ const wordRe = new RegExp(`[a-z]{${NGram_WORD_TOKEN_MIN_CHARS},}`, "g");
1757
+ for (const part of rawText.split(/[。!?!?;;::,,、.\n\r]+/)) {
1758
+ if (part.trim().length === 0) continue;
1759
+ const words = normalizeForNGram(part).match(wordRe);
1760
+ if (words && words.length > 0) segments.push(words);
1761
+ }
1762
+ return segments;
1763
+ }
1764
+
1765
+ /**
1766
+ * 修复③(第六轮):剔除引号/反引号包裹的片段。
1767
+ * 真实轨迹实测:模型在正文里 5 次引用会话开头的 "Let me understand the task"
1768
+ * 做起点核对,被词轨当成循环。引号内的内容是**被引用对象**(标识符/旧文本),
1769
+ * 不是模型自己在重复的骨架;统计前先剔除,避免引用型误切。
1770
+ * 只处理成对的双引号、中文引号、单引号(‘’)与反引号;
1771
+ * ASCII 单引号与英文缩写撇号冲突,不处理。
1772
+ * @param {string} text
1773
+ * @returns {string}
1774
+ */
1775
+ function stripQuotedSegments(text) {
1776
+ if (typeof text !== "string") return "";
1777
+ return text
1778
+ .replace(/"[^"\n]{0,500}"/g, " ")
1779
+ .replace(/“[^”\n]{0,500}”/g, " ")
1780
+ .replace(/‘[^’\n]{0,500}’/g, " ")
1781
+ .replace(/`[^`\n]{0,500}`/g, " ");
1782
+ }
1783
+
1784
+ /**
1785
+ * 修复③(第八轮):剔除三引号代码块(```…```,可跨行)。
1786
+ * 模型把日志、命令输出、表格、补丁粘进正文时,里面天然有大量重复行;
1787
+ * 这些是**引用数据**,不是模型自己在重复的推理骨架。单引号剔除
1788
+ * (stripQuotedSegments)只覆盖行内的 `…`,跨行块会漏过去——真实轨迹里
1789
+ * 粘贴失败日志后按短语高频误判,即属此类。
1790
+ * 不设长度上限:非贪婪匹配天然在下一个 ``` 处收尾,而输入的尾窗本身只有
1791
+ * 16000 字符;设上限反而会把超过上限的长堆栈块漏在正文里(真实轨迹实测:
1792
+ * 一段 6000+ 字符的 Unity 异步堆栈被漏掉,"end of stack trace" 命中 6 次)。
1793
+ * @param {string} text
1794
+ * @returns {string}
1795
+ */
1796
+ function stripFencedBlocks(text) {
1797
+ if (typeof text !== "string") return "";
1798
+ return text.replace(/```[\s\S]*?```/g, " ");
1799
+ }
1800
+
1801
+ /**
1802
+ * 修复③(第八轮):剔除 markdown 表格行。
1803
+ * 表格行(含 ≥2 个竖线)是结构化数据,同一列标签在每行重复出现是表格的
1804
+ * 正常形态,不是推理骨架在打转。真实轨迹实测:清单表格里"增补 P1-x"这类
1805
+ * 单元格被数字归一后互相等价,字符轨命中 11 次("增补pDI",稳定性 1.00)。
1806
+ * @param {string} text
1807
+ * @returns {string}
1808
+ */
1809
+ function stripTableRows(text) {
1810
+ if (typeof text !== "string") return "";
1811
+ return text.replace(/^[^\n]*\|[^\n]*\|[^\n]*$/gm, " ");
1812
+ }
1813
+
1814
+ /**
1815
+ * 修复③(第八轮):剔除堆栈帧/分隔线这类"数据行"。
1816
+ * 尾窗可能从一段超长代码块的中间开始(块的开 ``` 在前一屏之外),此时
1817
+ * stripFencedBlocks 找不到配对的起始标记,块内文字会残留在正文里。真实轨迹
1818
+ * 实测:Unity 异步堆栈里 `--- End of stack trace … ---` 重复 6 次、上下文
1819
+ * 完全一致,被词轨判成循环。堆栈帧与分隔线是工具输出,不是推理骨架,直接剔除。
1820
+ * @param {string} text
1821
+ * @returns {string}
1822
+ */
1823
+ function stripTraceLines(text) {
1824
+ if (typeof text !== "string") return "";
1825
+ return text
1826
+ .replace(/^\s*at [^\n]*$/gm, " ")
1827
+ .replace(/^\s*---[^\n]*---\s*$/gm, " ")
1828
+ .replace(/^\s*File "[^"]*", line \d+[^\n]*$/gm, " ");
1829
+ }
1830
+
1628
1831
  /**
1629
1832
  * 修复②:尾窗 n-gram 频率统计(双轨)。
1630
- * 输入 normText(已过 normalizeForNGram),同时产出两套指纹:
1833
+ * 输入尾窗原文,内部先归一化再切分,同时产出两套指纹:
1631
1834
  * - charFp:字符级 n-gram(原实现,保留中文/混合文本检测能力),gram 为无空白字符窗;
1632
- * - wordFp:英文词级 2-gram(相邻两个英文词为一个 gram);
1633
- * 以及英文主导判定(英文 token 数 / 全部 token 数 > 0.5),供 detectNGramLoop
1634
- * 分支互斥选用。判定逻辑不在本函数内做——detectNGramLoop 是唯一决策入口。
1635
- * @param {string} normText 已过 normalizeForNGram
1835
+ * gram 必须含 ≥NGram_CJK_MIN_CHARS 个 CJK 字——纯符号/版本号/DIGIT 组合不是语义短语;
1836
+ * - wordFp:英文词级 4-gram(同一句/子句内相邻四个英文词为一个 gram,单字母 token 不参与);
1837
+ * 以及英文 token 数(供覆盖率分母使用)。
1838
+ * 判定逻辑不在本函数内做——detectNGramLoop 是唯一决策入口。
1839
+ * @param {string} rawText 尾窗原文(未归一化)
1636
1840
  * @param {number} nGramSize 字符级短语粒度
1637
- * @returns {{charFp:object|null, wordFp:object|null, englishTokenCount:number, totalTokenCount:number, englishDominant:boolean}|null}
1841
+ * @returns {{charFp:object|null, wordFp:object|null, wordSegments:string[][], englishTokenCount:number, totalTokenCount:number, hasEnglishWords:boolean}|null}
1638
1842
  */
1639
- function computeNGramFingerprint(normText, nGramSize) {
1640
- if (typeof normText !== "string" || normText.length < nGramSize * 4) return null;
1843
+ function computeNGramFingerprint(rawText, nGramSize) {
1844
+ if (typeof rawText !== "string" || rawText.length < nGramSize * 4) return null;
1845
+ // 修复③(第六轮):统计前剔除引号内被引用文本(见 stripQuotedSegments)。
1846
+ // 修复③(第八轮):依次剔除三引号代码块、表格行、堆栈帧、行内引号段。
1847
+ const scanText = stripQuotedSegments(stripTraceLines(stripTableRows(stripFencedBlocks(rawText))));
1848
+ const normText = normalizeForNGram(scanText);
1641
1849
 
1642
1850
  // 轨 1:字符级 n-gram(原逻辑不变 + 英文词内部子串隔离)。
1643
1851
  // 隔离规则:gram 完全由英文字母组成时跳过(normalize 已小写化,/^[a-z]+$/ 即纯英文)。
1644
1852
  // 纯英文 gram 一定是某个英文词的内部子串或跨词片段,英文语义统一交给词轨判定;
1645
1853
  // 字符轨只保留含 CJK/数字/符号的 gram,避免中英混合文本里 "sessi"/"ancho" 这类
1646
1854
  // 英文词子串被独立计数而误报(本会话实测复现:count 16、coverage 8.8% 触发 cut)。
1855
+ // 修复③:再要求 gram 含 ≥2 个 CJK 字。事故样本里字符轨最高频是 "«t»«t"(制表符
1856
+ // 占位符)与 "vDIGI"(版本号归一后的片段),它们不含 CJK、纯属结构重复;
1857
+ // 不设此守卫时,词轨修好后字符轨仍可能接棒误切。
1647
1858
  const charGramCount = new Map();
1648
1859
  let charTotalGrams = 0;
1649
1860
  for (let i = 0; i <= normText.length - nGramSize; i++) {
@@ -1652,23 +1863,32 @@ function computeNGramFingerprint(normText, nGramSize) {
1652
1863
  if (gram.includes(" ") || gram.includes("\n") || gram.includes("\t")) continue;
1653
1864
  // 跳过纯英文 gram:英文词内部子串隔离(方案 1)
1654
1865
  if (/^[a-z]+$/.test(gram)) continue;
1866
+ // 修复③:CJK 字数守卫(见上)
1867
+ const cjkCount = [...gram].filter((ch) => /[\u4e00-\u9fff]/.test(ch)).length;
1868
+ if (cjkCount < NGram_CJK_MIN_CHARS) continue;
1655
1869
  let v = charGramCount.get(gram) ?? 0;
1656
1870
  charGramCount.set(gram, ++v);
1657
1871
  charTotalGrams++;
1658
1872
  }
1659
1873
  const charFp = charTotalGrams === 0 ? null : pickMaxFromCountMap(charGramCount, charTotalGrams);
1660
1874
 
1661
- // 轨 2:英文词级 2-gram——[a-z]+ 抽取英文词序列,相邻两词为一个 gram。
1662
- const words = normText.match(/[a-z]+/g) || [];
1663
- const wordFp = words.length >= 2 ? computeWordBigramFingerprint(words) : null;
1664
-
1665
- // 英文 token 占比统计(供 detectNGramLoop 词轨覆盖率分母用)。
1666
- const englishTokenCount = words.length;
1875
+ // 轨 2:英文词级 4-gram——按句/子句切分后,在各段内抽 [a-z]{2,} 英文词
1876
+ // (单字母变量/占位符不入表),相邻 NGram_WORD_GRAM_SIZE 个词为一个 gram。
1877
+ // 跨句不组 gram,避免中文主体把零散英文术语拼成假短语。
1878
+ const wordSegments = extractEnglishWordSegments(scanText);
1879
+ const allWords = wordSegments.flat();
1880
+ const wordFp = allWords.length >= NGram_WORD_GRAM_SIZE
1881
+ ? computeWordGramFingerprint(wordSegments, NGram_WORD_GRAM_SIZE)
1882
+ : null;
1883
+
1884
+ // 英文 token 占比统计(供 detectNGramLoop 词轨覆盖率分母 / 上下文守卫用)。
1885
+ const englishTokenCount = allWords.length;
1667
1886
  const cjkCount = (normText.match(/[\u4e00-\u9fff]/g) || []).length;
1668
1887
  const totalTokenCount = englishTokenCount + cjkCount;
1669
1888
  return {
1670
1889
  charFp,
1671
1890
  wordFp,
1891
+ wordSegments,
1672
1892
  englishTokenCount,
1673
1893
  totalTokenCount,
1674
1894
  // 方案 1:英文词轨并行——只要有英文词就具备走词轨的条件,不再要求英文主导。
@@ -1696,33 +1916,153 @@ function pickHighestNonStopwordGram(gramCount) {
1696
1916
  }
1697
1917
 
1698
1918
  /**
1699
- * 修复②:按频次降序取第一个非停用词 gram(英文词级 2-gram 专用)。
1700
- * 词级 gram 形如 "settings path",停用过滤按「词」检查:两个英文词中任一个命中
1701
- * 英文停用词表即跳过——"the settings" / "web fetch" 这类虚词+技术词/工具名搭配
1702
- * 是英文技术文本的高频噪声,不是循环证据(stopCharRatio 按字符比对对英文整词
1703
- * 无效,故词轨不能复用字符轨的守卫)。
1919
+ * 修复③:按频次降序列出全部合格词级 gram(英文 4-gram 专用)。
1920
+ * 词级 gram 形如 "verify checksum before releasing"。修复③(第三轮)不再
1921
+ * "含任一停用词即丢弃"——"please verify the checksum" 这类带冠词的正常短语
1922
+ * 会因此整条消失(P 用例漏检)。改为要求 **至少 2 个实词**(不在停用词表):
1923
+ * 纯虚词组合("the settings path from")与公式变量组合(4 个两字母词)被滤掉,
1924
+ * 含冠词但骨架完整的短语保留。返回全部候选而非只取第一名:最高频的可能是
1925
+ * 上下文噪声,真正循环骨架会排在后面,由 detectNGramLoop 逐个校验稳定性。
1704
1926
  * @param {Map<string, number>} gramCount
1705
- * @returns {{gram:string, count:number}|null}
1927
+ * @param {number} gramSize 词数
1928
+ * @returns {{gram:string, count:number}[]}
1706
1929
  */
1707
- function pickHighestNonStopwordBigram(gramCount) {
1930
+ function listEligibleWordGrams(gramCount, gramSize) {
1708
1931
  const sorted = [...gramCount.entries()].sort((a, b) => b[1] - a[1]);
1932
+ const out = [];
1709
1933
  for (const [gram, count] of sorted) {
1710
1934
  const words = gram.split(" ");
1711
- if (words.length !== 2) continue;
1712
- if (words.some((w) => NGram_STOPWORDS.has(w))) continue;
1713
- return { gram, count };
1935
+ if (words.length !== gramSize) continue;
1936
+ const contentWords = words.filter((w) => !NGram_STOPWORDS.has(w)).length;
1937
+ if (contentWords < 2) continue;
1938
+ const letters = words.reduce((sum, w) => sum + w.length, 0);
1939
+ if (letters < NGram_WORD_MIN_LETTERS) continue;
1940
+ out.push({ gram, count });
1714
1941
  }
1715
- return null;
1942
+ return out;
1943
+ }
1944
+
1945
+ /**
1946
+ * 修复③(第二轮):词轨命中短语的上下文稳定性。
1947
+ * 统计该 gram 每次出现时「前一个词 | 后一个词」的分布,返回最高频组合占比。
1948
+ * 真循环重复整句骨架 → 邻居一致 → 占比接近 1;术语/标识符复用 → 占比很低。
1949
+ * 修复③(第四轮):按句段统计,段首/段尾以 ^/$ 记上下文,不跨句拼接。
1950
+ * @param {string[][]} segments 按句/子句切分后的英文词序列
1951
+ * @param {string} gram 已命中的词级 gram
1952
+ * @param {number} gramSize 词数
1953
+ * @returns {number} 最高频上下文占比(0~1)
1954
+ */
1955
+ function wordGramContextStability(segments, gram, gramSize) {
1956
+ const parts = gram.split(" ");
1957
+ const ctx = new Map();
1958
+ let total = 0;
1959
+ for (const words of segments) {
1960
+ for (let i = 0; i + gramSize <= words.length; i++) {
1961
+ let same = true;
1962
+ for (let k = 0; k < gramSize; k++) {
1963
+ if (words[i + k] !== parts[k]) { same = false; break; }
1964
+ }
1965
+ if (!same) continue;
1966
+ const key = `${words[i - 1] ?? "^"}|${words[i + gramSize] ?? "$"}`;
1967
+ ctx.set(key, (ctx.get(key) ?? 0) + 1);
1968
+ total++;
1969
+ }
1970
+ }
1971
+ if (total === 0) return 0;
1972
+ return Math.max(...ctx.values()) / total;
1973
+ }
1974
+
1975
+ /**
1976
+ * 修复③(第三轮):字符轨命中短语的上下文稳定性。
1977
+ * 与词轨同一思路,邻居换成「前一个字符 | 后一个字符」。中文术语复用
1978
+ * ("配置项说明" 出现在不同句子里,前后字各不相同)占比很低;
1979
+ * 中文真循环重复整句 → 前后字一致 → 占比接近 1。
1980
+ * 修复③(第八轮):右侧改为取 3 个字符。表格行 `| 配置项说明:超时时间 |` 里
1981
+ * gram 两侧紧贴空格/竖线,只取 1 个字符时邻居恒定(对抗用例:15 行同标签表格
1982
+ * 稳定性 1.00,误判为循环);取 3 个字符后,标点之后的单元格正文进入上下文,
1983
+ * 行与行之间不再"稳定"。
1984
+ * 左侧仍只取 1 个字符:中文真循环常以变化的连接词开头(首先/其次/然后…),
1985
+ * 左扩 3 会把连接词差异算进上下文而漏检(对抗用例 P4 复现)。左侧紧邻的
1986
+ * 单字符足以区分"句首变化"与"整句重复"。
1987
+ * @param {string} text 已归一化的尾窗文本
1988
+ * @param {string} gram 已命中的字符 gram
1989
+ * @returns {number} 最高频上下文占比(0~1)
1990
+ */
1991
+ function charGramContextStability(text, gram) {
1992
+ const LEFT = 1;
1993
+ const RIGHT = 3;
1994
+ const ctx = new Map();
1995
+ let total = 0;
1996
+ let i = text.indexOf(gram);
1997
+ while (i >= 0) {
1998
+ const before = i > 0 ? text.slice(Math.max(0, i - LEFT), i) : "^";
1999
+ const after = i + gram.length < text.length ? text.slice(i + gram.length, i + gram.length + RIGHT) : "$";
2000
+ const key = `${before}|${after}`;
2001
+ ctx.set(key, (ctx.get(key) ?? 0) + 1);
2002
+ total++;
2003
+ i = text.indexOf(gram, i + 1);
2004
+ }
2005
+ if (total === 0) return 0;
2006
+ return Math.max(...ctx.values()) / total;
1716
2007
  }
1717
2008
 
1718
2009
  /**
1719
- * 修复②:判定是否为"语义漂移型循环"——跳过停用词 gram 后取最高频非停用 gram,
1720
- * 其出现次数 ≥ NGram_MIN_COUNT 且覆盖占尾窗比例 ≥ NGram_COVERAGE_RATIO。
2010
+ * 修复③(第七轮):字符轨命中区间长度——首次命中起点到末次命中终点。
2011
+ * 用于覆盖率分母(把"重复有多密集"而不是"占全文多大比例"作为判据)。
2012
+ * 只有一次命中时区间即 gram 长度。
2013
+ * @param {string} text 已归一化的尾窗文本
2014
+ * @param {string} gram 已命中的字符 gram
2015
+ * @returns {number}
2016
+ */
2017
+ function charGramSpanLength(text, gram) {
2018
+ const first = text.indexOf(gram);
2019
+ if (first < 0) return 0;
2020
+ const last = text.lastIndexOf(gram);
2021
+ return last + gram.length - first;
2022
+ }
2023
+
2024
+ /**
2025
+ * 修复③(第七轮):词轨命中区间长度(以 token 计)——首次命中起点到末次命中共多少个
2026
+ * 英文 token。相邻句子之间不组 gram,但游标照常累计,区间因此可能跨越句子间隔。
2027
+ * @param {string[][]} segments 按句/子句切分后的英文词序列
2028
+ * @param {string} gram 已命中的词级 gram
2029
+ * @param {number} gramSize 词数
2030
+ * @returns {number}
2031
+ */
2032
+ function wordGramSpanTokens(segments, gram, gramSize) {
2033
+ const parts = gram.split(" ");
2034
+ let cursor = 0;
2035
+ let firstStart = -1;
2036
+ let lastEnd = -1;
2037
+ for (const words of segments) {
2038
+ for (let i = 0; i + gramSize <= words.length; i++) {
2039
+ let same = true;
2040
+ for (let k = 0; k < gramSize; k++) {
2041
+ if (words[i + k] !== parts[k]) { same = false; break; }
2042
+ }
2043
+ if (!same) continue;
2044
+ if (firstStart < 0) firstStart = cursor + i;
2045
+ lastEnd = cursor + i + gramSize;
2046
+ }
2047
+ cursor += words.length;
2048
+ }
2049
+ if (firstStart < 0) return 0;
2050
+ return lastEnd - firstStart;
2051
+ }
2052
+
2053
+ /**
2054
+ * 修复②:判定是否为"语义漂移型循环"——按频次逐个取合格 gram 候选,要求
2055
+ * 出现次数 ≥ NGram_MIN_COUNT、覆盖尾窗比例 ≥ NGram_COVERAGE_RATIO,且
2056
+ * 命中短语的上下文稳定(同一句骨架反复出现,而非术语/标识符在不同句里复用)。
1721
2057
  * 双轨分支(互斥,不许混合):
1722
- * - 英文主导(英文 token 数 > 全部 token 数的一半):只走英文词级 2-gram 路径,
1723
- * 绝不回退字符 5-gram——否则 "settings" 的任意 5 字符子串("setti" 等)会被
1724
- * 独立计数而误报。词级覆盖率 = count × 2 / 英文 token 总数。
1725
- * - 非英文主导(中文/混合):保持原字符 n-gram 路径,覆盖率 = count × n / 尾窗字符数。
2058
+ * - 英文词轨(含英文词即可):只走英文词级 4-gram 路径,绝不回退字符
2059
+ * 5-gram——否则 "settings" 的任意 5 字符子串("setti" 等)会被独立计数而误报。
2060
+ * 词级覆盖率 = count × 4 / min(英文 token 总数, 命中区间 token 数)——两种口径
2061
+ * 取最大值(见 NGram_DENSITY_MIN_TOKENS);token 只计 ≥2 字母的词,
2062
+ * 单字母变量/占位符("s"/"l"/"t")既不进 gram 也不撑大分母。
2063
+ * - 字符轨(中文/混合):字符 n-gram 路径,覆盖率 = count × n / min(尾窗字符数,
2064
+ * 命中区间字符数),同样两种口径取最大值;gram 必须含 ≥2 个 CJK 字,
2065
+ * 纯符号/版本号重复不参与。
1726
2066
  * 与 findRepeatingTail 并行,不破坏原逻辑。
1727
2067
  * @param {string} fullVisibleText
1728
2068
  * @returns {{maxGram:string,count:number,coverage:number}|null}
@@ -1731,29 +2071,51 @@ function detectNGramLoop(fullVisibleText) {
1731
2071
  if (typeof fullVisibleText !== "string" || fullVisibleText.length < REPEAT_MIN_TEXT_CHARS) return null;
1732
2072
  const tail = fullVisibleText.slice(-REPEAT_WINDOW_CHARS);
1733
2073
  const norm = normalizeForNGram(tail);
1734
- const fp = computeNGramFingerprint(norm, NGram_PHRASE_MIN);
2074
+ const fp = computeNGramFingerprint(tail, NGram_PHRASE_MIN);
1735
2075
  if (!fp) return null;
1736
2076
 
1737
- // 轨 A(方案 1 并行):英文词级 2-gram——只要文本含英文词就跑词轨。
2077
+ // 轨 A(方案 1 并行):英文词级 4-gram——只要文本含英文词就跑词轨。
1738
2078
  // 英文单词是原子 token,词轨本身不会产生 "sessi"/"ancho" 这类词内子串误报;
1739
2079
  // 覆盖率分母用英文 token 总数,避免中文主体把分母撑大掩盖英文真循环。
1740
2080
  if (fp.hasEnglishWords && fp.wordFp) {
1741
- const chosen = pickHighestNonStopwordBigram(fp.wordFp.gramCount);
1742
- if (chosen && chosen.count >= NGram_MIN_COUNT) {
1743
- const coverage = chosen.count * 2 / fp.englishTokenCount;
1744
- if (coverage >= NGram_COVERAGE_RATIO) {
2081
+ // 修复③(第三轮):逐个候选校验,最多看前 NGram_WORD_CANDIDATE_LIMIT 个。
2082
+ // 最高频的候选可能恰是上下文噪声("now/then/next" 开头的连接词 4-gram),
2083
+ // 真正循环的骨架排在后面;但同一表格单元格骨架也可能排在后面,故仍用
2084
+ // 上下文稳定性把关,稳定命中才返回。
2085
+ const candidates = listEligibleWordGrams(fp.wordFp.gramCount, NGram_WORD_GRAM_SIZE);
2086
+ for (const chosen of candidates.slice(0, NGram_WORD_CANDIDATE_LIMIT)) {
2087
+ if (chosen.count < NGram_MIN_COUNT) break;
2088
+ // 修复③(第七轮):覆盖率同时按旧口径(整个尾窗)与密度口径(命中区间)
2089
+ // 计算并取最大值;密度分母带下限,避免短文本里集中出现的术语被抬过阈值。
2090
+ // 覆盖率不足只跳过该候选、不 break——候选按频次降序,区间更紧凑的
2091
+ // 候选可能排在后面(覆盖率和频次不同序)。
2092
+ const spanTokens = wordGramSpanTokens(fp.wordSegments, chosen.gram, NGram_WORD_GRAM_SIZE);
2093
+ const fullCoverage = chosen.count * NGram_WORD_GRAM_SIZE / fp.englishTokenCount;
2094
+ const densityCoverage = chosen.count * NGram_WORD_GRAM_SIZE / Math.max(spanTokens, NGram_DENSITY_MIN_TOKENS);
2095
+ const coverage = Math.max(fullCoverage, densityCoverage);
2096
+ if (coverage < NGram_COVERAGE_RATIO) continue;
2097
+ // 修复③(第二轮):上下文稳定性守卫——命中短语必须在相近句骨架里反复出现,
2098
+ // 而不是作为术语/标识符在不同句子里被复用(样例 3:7 次命中全部左邻不同)。
2099
+ if (wordGramContextStability(fp.wordSegments, chosen.gram, NGram_WORD_GRAM_SIZE) >= NGram_CONTEXT_MIN_RATIO) {
1745
2100
  return { maxGram: chosen.gram, count: chosen.count, coverage };
1746
2101
  }
1747
2102
  }
1748
2103
  }
1749
2104
 
1750
2105
  // 轨 B(方案 1 并行):字符级 n-gram——纯英文 gram 已在 computeNGramFingerprint
1751
- // 中被隔离(英文词内部子串不再计入),字符轨只承担含 CJK/数字/符号的文本。
2106
+ // 中被隔离(英文词内部子串不再计入),字符轨只承担含 CJK 的文本。
1752
2107
  if (!fp.charFp) return null;
1753
2108
  const chosen = pickHighestNonStopwordGram(fp.charFp.gramCount);
1754
2109
  if (!chosen || chosen.count < NGram_MIN_COUNT) return null;
1755
- const coverage = chosen.count * NGram_PHRASE_MIN / tail.length;
2110
+ // 修复③(第七轮):同样两种口径取最大值,密度分母带下限(见上方常量注释)。
2111
+ const spanChars = charGramSpanLength(norm, chosen.gram);
2112
+ const fullCoverage = chosen.count * NGram_PHRASE_MIN / tail.length;
2113
+ const densityCoverage = chosen.count * NGram_PHRASE_MIN / Math.max(spanChars, NGram_DENSITY_MIN_CHARS);
2114
+ const coverage = Math.max(fullCoverage, densityCoverage);
1756
2115
  if (coverage < NGram_COVERAGE_RATIO) return null;
2116
+ // 修复③(第三轮):字符轨同样要求上下文稳定——"配置项说明"这类术语在 12 个
2117
+ // 不同句子里复用(每次前后字都不同)不是循环;重复整句的中文真循环前后字一致。
2118
+ if (charGramContextStability(norm, chosen.gram) < NGram_CONTEXT_MIN_RATIO) return null;
1757
2119
  return { maxGram: chosen.gram, count: chosen.count, coverage };
1758
2120
  }
1759
2121
 
@@ -2121,6 +2483,98 @@ function renderActionChurnAnchor(churn) {
2121
2483
  ].join("\n");
2122
2484
  }
2123
2485
 
2486
+ /**
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 开始)
2498
+ * @returns {string}
2499
+ */
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
+ }
2576
+ }
2577
+
2124
2578
  /**
2125
2579
  * 缺陷 3 修复(2026-10-07 升级版):churn 每 turn 命中计数。键 = sessionId,值为
2126
2580
  * { lastTurn, count }:count 是本 turn handler 返回 churn cut 决策的次数。计数口径
@@ -3004,6 +3458,7 @@ const DEFAULT_SETTINGS = { // Master switches
3004
3458
  enableChurn: true,
3005
3459
  enableTransition: true,
3006
3460
  enableNumberRunaway: true,
3461
+ enableOverLongCoT: false,
3007
3462
  // Notice/anchor shaping
3008
3463
  minReasoningChars: 250,
3009
3464
  maxPoints: 3,
@@ -3022,6 +3477,10 @@ const DEFAULT_SETTINGS = { // Master switches
3022
3477
  softCutTransitionWindow: 48,
3023
3478
  softCutMinFollowChars: 6,
3024
3479
  softCutGapThreshold: 80,
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.
3483
+ overLongCoTThreshold: 8000,
3025
3484
  // Repetition detector
3026
3485
  repeatProbeChars: 128,
3027
3486
  repeatWindowChars: 16000,
@@ -3130,6 +3589,8 @@ const SETTINGS_SCHEMA = [
3130
3589
  hint: "\"接下来我要……\"这类转折句出现时打断,先注入结论锚点。" },
3131
3590
  { key: "enableNumberRunaway", label: "识别数字递增流退化", type: "boolean", group: "打断判定",
3132
3591
  hint: "长段递增数字流(如 639.640) 640.641)…)连续多字且无实质内容时打断。启发式判定,仅在数字流足够长时触发。" },
3592
+ { key: "enableOverLongCoT", label: "过长 CoT 软切", type: "boolean", group: "打断判定",
3593
+ hint: "当本轮 CoT 累计字符数达到下方阈值时软切并提醒模型「落实阶段性结论、避免过度思考」。属兜底提醒,独立于其他启发式检测。默认关闭。" },
3133
3594
 
3134
3595
  { key: "minReasoningChars", label: "最少思考字数", type: "number", min: 50, max: 5000, group: "锚点内容",
3135
3596
  hint: "思考短于此长度时不提取结论、不注入。" },
@@ -3145,6 +3606,10 @@ const SETTINGS_SCHEMA = [
3145
3606
  hint: "决定怎么把模型的「思考」和「正文」区分开来。内核还没支持这一项,选什么都不会改变行为,先按默认放着即可。" },
3146
3607
  { key: "enableExecDisciplineBlock", label: "随锚点注入命令执行纪律块", type: "boolean", group: "锚点内容",
3147
3608
  hint: "默认开启。开启时会把「执行命令要守规矩」这段提醒和结论摘要一起插回上下文;关闭就完全不插这段提醒,结论摘要和其他识别、去重功能都不受影响。" },
3609
+
3610
+ { key: "overLongCoTThreshold", advanced: true, label: "CoT 长度阈值(字符)", type: "number", min: 0, max: 100000, group: "过长 CoT 参数",
3611
+ hint: "本轮 CoT 累计字符数达到此值即触发软切提醒,设置值直接生效、不会被放大。默认 8000;设为 0 即关闭(同关闭上方开关效果一致)。内核未分流 text/reasoning 时按整段输出长度估算(含回答文本);只想统计纯思考字数,请把内核切到 separateThreshold 模式。" },
3612
+
3148
3613
  { key: "numberRunMinTextChars", advanced: true, label: "数字流启用最小文本长度", type: "number", min: 100, max: 50000, group: "数字流参数" },
3149
3614
  { key: "numberRunMinChars", advanced: true, label: "数字流最短跨度", type: "number", min: 50, max: 20000, group: "数字流参数" },
3150
3615
  { key: "numberRunMaxGap", advanced: true, label: "数字流最大间隙", type: "number", min: 1, max: 200, group: "数字流参数",
@@ -3166,7 +3631,7 @@ const SETTINGS_SCHEMA = [
3166
3631
  { key: "repeatProbeChars", advanced: true, label: "周期探针长度", type: "number", min: 16, max: 2000, group: "重复循环参数" },
3167
3632
  { key: "repeatMinTextChars", advanced: true, label: "启用最小文本长度", type: "number", min: 500, max: 50000, group: "重复循环参数" },
3168
3633
  { key: "ngramPhraseMin", advanced: true, label: "n-gram 短语最小长度(字符)", type: "number", min: 3, max: 20, group: "重复循环参数",
3169
- hint: "字符级 n-gram 的滑窗粒度(中文路径)。默认 5;调高要求更长的短语才计数(更保守)。英文路径固定按相邻 2 词,不受此项影响。" },
3634
+ hint: "字符级 n-gram 的滑窗粒度(中文路径)。默认 5;调高要求更长的短语才计数(更保守)。英文路径固定按相邻 4 个词(每词 ≥2 字母),不受此项影响。" },
3170
3635
  { key: "ngramMinCount", advanced: true, label: "n-gram 最高频短语最小出现次数", type: "number", min: 2, max: 50, group: "重复循环参数",
3171
3636
  hint: "最高频短语至少出现这么多次才判定循环;调低更激进、调高更保守。" },
3172
3637
  { key: "ngramCoverageRatio", advanced: true, label: "n-gram 短语覆盖占比下限", type: "number", min: 0.01, max: 0.5, group: "重复循环参数",
@@ -3297,6 +3762,7 @@ function applyRuntimeSettings(raw) {
3297
3762
  SOFT_CUT_TRANSITION_WINDOW = merged.softCutTransitionWindow;
3298
3763
  SOFT_CUT_MIN_FOLLOW_CHARS = merged.softCutMinFollowChars;
3299
3764
  SOFT_CUT_GAP_THRESHOLD = merged.softCutGapThreshold;
3765
+ OVER_LONG_COT_THRESHOLD = merged.overLongCoTThreshold;
3300
3766
  REPEAT_PROBE_CHARS = merged.repeatProbeChars;
3301
3767
  REPEAT_WINDOW_CHARS = merged.repeatWindowChars;
3302
3768
  REPEAT_MIN_PERIOD = merged.repeatMinPeriod;
@@ -3912,6 +4378,7 @@ function apply(ctx, config) {
3912
4378
  try {
3913
4379
  mkdirSync(settingsDir, { recursive: true });
3914
4380
  writeFileSync(settingsPath, JSON.stringify(value, null, 2), "utf8");
4381
+ setTraceConfig({ ...value });
3915
4382
  return true;
3916
4383
  } catch (error) {
3917
4384
  console.warn(`[cot-anchor] 设置写入失败:${error?.message ?? error}`);
@@ -3921,6 +4388,7 @@ function apply(ctx, config) {
3921
4388
 
3922
4389
  const persisted = loadPersistedSettings();
3923
4390
  if (persisted) applyRuntimeSettings({ ...declarative, ...persisted });
4391
+ setTraceConfig({ ...settings });
3924
4392
 
3925
4393
  // --- COT harvest: storage, observer, routes ------------------------------
3926
4394
  // Everything below is inert until `enableHarvest` is turned on: the observer
@@ -4577,18 +5045,37 @@ function apply(ctx, config) {
4577
5045
  // failure is contained by the host, so it can never break the append it is
4578
5046
  // watching. With the switch off this is the whole cost — one property read.
4579
5047
  ctx.on("session/event", (session, event) => {
4580
- // churn 计数的 turn 边界(唯一可用边界,插件无 turn 生命周期事件):
4581
- // assistant/message 携带 data.turn,大于该 session 上次记录值即视为进入
4582
- // 新 turn,把 churn 计数归零。置于 harvest 开关之前——计数归零与采集
4583
- // 开关无关。软切结算消息同带本 turn 号,但因 churn 决策时已就地推进
4584
- // 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,不会误归零。
4585
5073
  if (event?.type === "assistant/message") {
4586
5074
  const boundaryTurn = event?.data?.turn;
4587
5075
  if (Number.isFinite(boundaryTurn)) {
4588
- resetChurnCountOnTurnBoundary(
4589
- typeof session?.id === "string" ? session.id : "",
4590
- boundaryTurn
4591
- );
5076
+ const boundaryKey = typeof session?.id === "string" ? session.id : "";
5077
+ resetChurnCountOnTurnBoundary(boundaryKey, boundaryTurn);
5078
+ resetOverLongCountOnTurnBoundary(boundaryKey, boundaryTurn);
4592
5079
  }
4593
5080
  }
4594
5081
  if (!settings.enableHarvest) return;
@@ -4654,6 +5141,26 @@ function apply(ctx, config) {
4654
5141
  // 宁可留下回调也不要误伤旧内核上的截停能力。
4655
5142
  if (softCutProbe !== CAPABILITY_ABSENT) {
4656
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
+ });
4657
5164
  // budgetClass 兼容契约:每个 cut 决策都带 budgetClass,供内核移植段
4658
5165
  // decideSoftCut 分类裁决(confirmed-repeat=20 / heuristic=6 /
4659
5166
  // confirmed-pseudo=3 三类独立有界预算;confirmed-pseudo 耗尽时内核
@@ -4671,7 +5178,11 @@ function apply(ctx, config) {
4671
5178
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
4672
5179
  cutClass: "external",
4673
5180
  reason: external.reason ?? null,
4674
- 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
4675
5186
  });
4676
5187
  return {
4677
5188
  kind: "cut",
@@ -4702,11 +5213,18 @@ function apply(ctx, config) {
4702
5213
  // the same attempt is also repeating, the loop's `trimTo` is reused
4703
5214
  // so the runaway copies never reach the session.
4704
5215
  const looping = settings.enableRepeat ? findRepeatingTail(fullText) : null;
4705
- 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) {
4706
5220
  noteSoftCutFired();
4707
5221
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
4708
5222
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
4709
- cutClass: "pseudoTool"
5223
+ cutClass: "pseudoTool",
5224
+ detector: "pseudo-tool-call",
5225
+ detectorValues: { hasPseudoToolCall: true, hasLoop: !!looping },
5226
+ thresholds: softCutThresholds,
5227
+ inputHash: softCutInputHash
4710
5228
  });
4711
5229
  return {
4712
5230
  kind: "cut",
@@ -4728,7 +5246,11 @@ function apply(ctx, config) {
4728
5246
  noteSoftCutFired();
4729
5247
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
4730
5248
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
4731
- cutClass: "confirmed-repeat"
5249
+ cutClass: "confirmed-repeat",
5250
+ detector: "byte-repeat",
5251
+ detectorValues: { count: looping.count },
5252
+ thresholds: softCutThresholds,
5253
+ inputHash: softCutInputHash
4732
5254
  });
4733
5255
  return {
4734
5256
  kind: "cut",
@@ -4743,12 +5265,17 @@ function apply(ctx, config) {
4743
5265
  // 循环(每句数字变、动词结构不变)字节级抓不到,但数字归一 + n-gram 频率
4744
5266
  // 能稳定定位。运行时零 LLM:哈希分窗 + HashMap 计数。
4745
5267
  const ngramLoop = settings.enableRepeat ? detectNGramLoop(fullText) : null;
5268
+ scanDetector("ngram-loop", !!ngramLoop, { count: ngramLoop?.count ?? 0, maxGram: ngramLoop?.maxGram ?? null });
4746
5269
  if (ngramLoop) {
4747
5270
  noteSoftCutFired();
4748
5271
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
4749
5272
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
4750
5273
  cutClass: "heuristic",
4751
- 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
4752
5279
  });
4753
5280
  return {
4754
5281
  kind: "cut",
@@ -4764,11 +5291,16 @@ function apply(ctx, config) {
4764
5291
  // cut to the run start so the runaway copies never reach the session.
4765
5292
  const numberRunaway = settings.enableNumberRunaway
4766
5293
  ? detectNumberRunaway(fullText) : null;
5294
+ scanDetector("number-runaway", !!numberRunaway, { chars: numberRunaway?.chars ?? 0 });
4767
5295
  if (numberRunaway) {
4768
5296
  noteSoftCutFired();
4769
5297
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
4770
5298
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
4771
- cutClass: "confirmed-repeat"
5299
+ cutClass: "confirmed-repeat",
5300
+ detector: "number-runaway",
5301
+ detectorValues: { chars: numberRunaway.chars },
5302
+ thresholds: softCutThresholds,
5303
+ inputHash: softCutInputHash
4772
5304
  });
4773
5305
  return {
4774
5306
  kind: "cut",
@@ -4784,6 +5316,7 @@ function apply(ctx, config) {
4784
5316
  // runaway that the period detector structurally cannot see. Being a
4785
5317
  // heuristic, it backs off inside an unclosed code fence.
4786
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");
4787
5320
  if (churn) {
4788
5321
  // Shadow period: a cut produced ONLY by learned additions is counted
4789
5322
  // but not taken, so a fresh pattern cannot sever real work before the
@@ -4793,6 +5326,15 @@ function apply(ctx, config) {
4793
5326
  return null;
4794
5327
  }
4795
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
+ });
4796
5338
  // 缺陷 3:按 session+turn 计数(recordChurnCut,含就地归零与 LRU 界),
4797
5339
  // 第 2 次起在锚点追加升级指令。计数的是 handler 返回 cut 决策的次数
4798
5340
  // (与内核是否采纳无关)。
@@ -4815,6 +5357,7 @@ function apply(ctx, config) {
4815
5357
  // 独立于 enableChurn,默认与 enableChurn 同开关语义——通过 enableChurn 统一门禁,
4816
5358
  // 无需新增 settings key;如需独立控制可后续扩展 enableActionChurn。
4817
5359
  const actionChurn = !settings.enableChurn || insideUnclosedCodeFence(fullText) ? null : detectActionChurn(fullText);
5360
+ scanDetector("action-churn", !!actionChurn, { hits: actionChurn?.hits ?? 0 });
4818
5361
  if (actionChurn) {
4819
5362
  noteSoftCutFired();
4820
5363
  const churnKey = typeof payload?.sessionId === "string" ? payload.sessionId : "";
@@ -4824,7 +5367,11 @@ function apply(ctx, config) {
4824
5367
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
4825
5368
  ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
4826
5369
  cutClass: "heuristic",
4827
- detector: "action-churn"
5370
+ detector: "action-churn",
5371
+ detector: "action-churn",
5372
+ detectorValues: { hits: actionChurn.hits, occurrence: churnOccurrence },
5373
+ thresholds: softCutThresholds,
5374
+ inputHash: softCutInputHash
4828
5375
  });
4829
5376
  return {
4830
5377
  kind: "cut",
@@ -4834,11 +5381,59 @@ function apply(ctx, config) {
4834
5381
  };
4835
5382
  }
4836
5383
 
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 });
5401
+ if (settings.enableOverLongCoT && OVER_LONG_COT_THRESHOLD > 0
5402
+ && reasoningChars >= OVER_LONG_COT_THRESHOLD
5403
+ && !insideUnclosedCodeFence(fullText)) {
5404
+ noteSoftCutFired();
5405
+ const overLongKey = typeof payload?.sessionId === "string" ? payload.sessionId : "";
5406
+ const occurrence = recordOverLongCut(overLongKey, payload?.turn);
5407
+ emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5408
+ ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5409
+ cutClass: "heuristic",
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
5418
+ });
5419
+ const anchorText = renderOverLongCoTAnchor(
5420
+ reasoningChars, OVER_LONG_COT_THRESHOLD, !!hasReasoningCount, occurrence);
5421
+ return {
5422
+ kind: "cut",
5423
+ budgetClass: "heuristic",
5424
+ cutClass: "heuristic",
5425
+ contexts: [buildAnchorContext(anchorText,
5426
+ `cot-anchor: over-long-cot ${reasoningChars}/${OVER_LONG_COT_THRESHOLD} x${occurrence}${hasReasoningCount ? "" : " [merged estimate]"}`)]
5427
+ };
5428
+ }
5429
+
4837
5430
  // (4) A→"接下来我要…"→B transition inside one generation.
4838
5431
  // The cut is destructive, so it requires an EXPLICIT conclusion
4839
5432
  // ("所以/因此/综上/therefore …") already present — a density-only
4840
5433
  // Tier-2 sentence (a file name / number in prose) is not "phase A
4841
5434
  // settled" and must never trigger a mid-stream cut.
5435
+ scanDetector("transition", false, { enabled: settings.enableTransition },
5436
+ settings.enableTransition ? "below-threshold" : "detector-disabled");
4842
5437
  if (!settings.enableTransition) return null;
4843
5438
  // P1-5 (2026-10-22): strip previously-injected anchor point texts from a
4844
5439
  // DETECTION COPY before the transition chain reads it. Models echo a
@@ -4911,7 +5506,11 @@ function apply(ctx, config) {
4911
5506
  emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
4912
5507
  ...evidence,
4913
5508
  cutClass: "heuristic",
4914
- detector: "transition"
5509
+ detector: "transition",
5510
+ detector: "transition",
5511
+ detectorValues: { points: points.length },
5512
+ thresholds: softCutThresholds,
5513
+ inputHash: softCutInputHash
4915
5514
  });
4916
5515
  return {
4917
5516
  kind: "cut",