dsh-cot-anchor 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/lib/index.js +421 -54
  2. package/package.json +1 -1
package/lib/index.js CHANGED
@@ -1063,6 +1063,10 @@ let SOFT_CUT_TRANSITION_WINDOW = 48;
1063
1063
  */
1064
1064
  let SOFT_CUT_GAP_THRESHOLD = 80;
1065
1065
 
1066
+ /** Over-long CoT soft-cut threshold: fullVisibleText length beyond which a
1067
+ * reminder cut fires. 0 means effectively disabled (checked at the hook site). */
1068
+ let OVER_LONG_COT_THRESHOLD = 8000;
1069
+
1066
1070
  /**
1067
1071
  * Finds the LAST Tier-1 conclusion opener inside the tail scan window and
1068
1072
  * returns its index relative to the tail start, or null if none matches.
@@ -1546,7 +1550,57 @@ let NGram_PHRASE_MIN = 5;
1546
1550
  let NGram_MIN_COUNT = 5;
1547
1551
  /** 修复②:最高频短语覆盖尾窗的占比下限(默认 0.05;运行时可经 ngramCoverageRatio 覆盖)。 */
1548
1552
  let NGram_COVERAGE_RATIO = 0.05;
1549
- /** 修复②:停用词集合,过滤普通高频词以防误报。 */
1553
+ /**
1554
+ * 修复③(误软切回归):英文词轨的 token 与短语形态守卫。
1555
+ * 事故样本(cot-anchor 误软切样例 1/2/3)里最高频 gram 分别是 "s l"(公式
1556
+ * S·l 的单字母变量)与 "t t"(补丁脚本的 «T» 制表符占位符)——它们都不是
1557
+ * 英文单词,只是结构字符;词轨把它们当词后,2-gram 在千字级尾窗里随便就
1558
+ * 凑够 5 次、5% 覆盖率,于是每次写公式/写补丁都会被误切。
1559
+ * 因此词轨改为:token 至少 2 个字母(单字母变量/占位符永不入表);gram 取
1560
+ * 相邻 4 词(2~3 词搭配在技术文本/表格列骨架里天然高频,4 词才构成"句子
1561
+ * 骨架"重复);再叠加最短字母数守卫,滤掉 "cn cl n l" 这类公式变量组合。
1562
+ */
1563
+ const NGram_WORD_TOKEN_MIN_CHARS = 2;
1564
+ const NGram_WORD_GRAM_SIZE = 4;
1565
+ /** 词轨 gram 的最少字母总数(不含空格):4 个两字母词的 8 字母组合属公式变量,不是短语。 */
1566
+ const NGram_WORD_MIN_LETTERS = 10;
1567
+ /** 字符轨 gram 至少包含的 CJK 字数:纯符号/版本号/DIGIT 组合("«t»«t"、"vDIGI")不是语义短语。 */
1568
+ const NGram_CJK_MIN_CHARS = 2;
1569
+ /**
1570
+ * 修复③(第二轮):上下文稳定性下限(词轨/字符轨共用)。
1571
+ * 真正的语义循环是把同一句骨架反复吐出来,命中短语的左右邻居高度一致;
1572
+ * 而"标识符/术语复用"(样例 3 的 "dsh patch chat" 7 次)左邻分别来自
1573
+ * patchmarker / window / says / oldpatchmarker / marker / string / contains,
1574
+ * 每次上下文都不同。要求最高频左右邻组合占命中次数的 ≥65%,把后者挡掉。
1575
+ * 阈值从 50% 提到 65%(第六轮真实轨迹复盘):UI 错误文案 "failed to load
1576
+ * plugins" 在调试文本里出现 8 次、最高频上下文恰好占 50%,是标签复用不是循环;
1577
+ * 而真正重复整句骨架的样本里该比例通常接近 100%,65% 留有充分余量。
1578
+ */
1579
+ const NGram_CONTEXT_MIN_RATIO = 0.65;
1580
+ /** 修复③(第三轮):词轨逐个候选校验的上限,避免尾窗内几千个 gram 全做上下文扫描。 */
1581
+ const NGram_WORD_CANDIDATE_LIMIT = 12;
1582
+ /**
1583
+ * 修复③(第七轮,长上下文稀释):覆盖率的分母改用「命中区间」而不是整个尾窗。
1584
+ *
1585
+ * 尾窗固定 16000 字符,但一个 turn 的 `reasoning+text` 可能长达十几万字符。
1586
+ * 只要 turn 够长,即使模型在末尾真的把同一句重复 30 次,也凑不够 5%——真实
1587
+ * 会话回放实测:240k 字符的 turn 末尾追加 30 次中文整句(60 次短语命中),
1588
+ * count=60、coverage 仅 1.9%,完全不触发;英文侧稍好(5.8%)但同样被摊薄。
1589
+ *
1590
+ * 语义上要判的是「重复有多密集」,而不是「重复占全文多大比例」:把分母换成
1591
+ * 首次命中到末次命中的跨度(即重复集中在多长的区间里)。跨度天然 ≥ 命中总
1592
+ * 长度(count × gramSize,overlap 除外),所以覆盖率不会因此虚高到 1 以上。
1593
+ *
1594
+ * 但不能只用密度口径:短 turn(2~5k 字符)里一个术语出现 5~7 次、每次都挨得
1595
+ * 很近时,跨度分母会把占比抬到 5% 以上(真实轨迹回放:`远程不存在` 7 次、
1596
+ * 计划书术语 `blocked followup user turn` 5 次、状态字段骨架 7 次全部误判)。
1597
+ * 因此保留旧口径(分母 = 整个尾窗)与新口径取**最大值**,并给密度分母设下限,
1598
+ * 让"短文本里少量集中出现"仍按旧比例判定,"超长 turn 末尾成段打转"才被密度
1599
+ * 口径救回(实测 240k 字符 turn 内重复 30 次可命中,旧口径只有 1.9%)。
1600
+ */
1601
+ const NGram_DENSITY_MIN_CHARS = 800;
1602
+ const NGram_DENSITY_MIN_TOKENS = 600;
1603
+
1550
1604
  const NGram_STOPWORDS = new Set([
1551
1605
  "的", "了", "是", "我", "你", "他", "她", "它", "们", "这", "那", "就", "也", "都",
1552
1606
  "要", "会", "能", "可以", "让", "把", "给", "对", "从", "用", "到", "在", "和", "与",
@@ -1583,9 +1637,15 @@ function normalizeForNGram(text) {
1583
1637
  return text
1584
1638
  .toLowerCase()
1585
1639
  .replace(/\d+/g, "DIGIT")
1586
- // 下划线 `_` 与标点同样替换为空格:避免 web_fetch / settings_mutate 切出
1587
- // "web_f"/"web fe" 之类伪子串虚高(下划线在字符类里按字面量处理)
1588
- .replace(/[,,。.!!??;;::""''()()【】\[\]<>《》—–\-_]/g, " ")
1640
+ // 修复③(第五轮):连字符/下划线/路径分隔符做「粘合」而不是切分——
1641
+ // 标识符必须保持原子 token。否则 no-blind-wait-polling、
1642
+ // D:\dsh\dsh-cot-anchor\lib\index.js 会被拆成 4 个以上普通词,
1643
+ // 在长会话里按短语重复计数(真实轨迹实测:技能名 x6、文件路径 x7)。
1644
+ // 粘合后它们变成单个长 token,无法组成 4 词 gram;正常带连字符的英文
1645
+ // (re-analyze)成为单 token,不影响真循环检测。
1646
+ .replace(/[-_\/\\]/g, "")
1647
+ // 其余标点仍替换为空格(下划线等已在上一行粘合,不在此字符类中)
1648
+ .replace(/[,,。.!!??;;::""''()()【】\[\]<>《》—–]/g, " ")
1589
1649
  .replace(/\s+/g, " ")
1590
1650
  .trim();
1591
1651
  }
@@ -1606,44 +1666,143 @@ function pickMaxFromCountMap(gramCount, totalGrams) {
1606
1666
  }
1607
1667
 
1608
1668
  /**
1609
- * 修复②:英文词级 2-gram 频率统计。相邻两个英文词([a-z]+ 抽取)为一个 gram,
1610
- * 如 "settings path"。英文单词是原子 token:单词内部子串("setti"/"etting")
1611
- * 永远不会成为 gram。词级 gram 允许含空格——两词之间的空白正是短语边界。
1612
- * @param {string[]} words 英文词序列
1669
+ * 修复③(第三轮):英文词级 n-gram 频率统计。相邻 N 个英文词为一个 gram
1670
+ * (默认 4 词),如 "verify checksum before releasing"。英文单词是原子 token:
1671
+ * 单词内部子串("setti"/"etting")永远不会成为 gram;单字母结构字符(S·l 的
1672
+ * "s"/"l"、«T» 的 "t")在 token 抽取阶段就被长度守卫挡掉。
1673
+ * 修复③(第四轮):只在**同一句/同一子句**内组 gram。中文句子间隔不让英文词
1674
+ * 假装相邻——否则中文主体里零散的 settings/session/anchor/tool 会被拼成
1675
+ * "settings tool session anchor" 这类跨句假短语(F 用例 30.8% 覆盖率误报)。
1676
+ * @param {string[][]} segments 按句/子句切分后的英文词序列
1677
+ * @param {number} gramSize 词数(相邻 N 词)
1613
1678
  * @returns {{maxCount:number, maxGram:string, totalGrams:number, gramCount:Map<string, number>}|null}
1614
1679
  */
1615
- function computeWordBigramFingerprint(words) {
1680
+ function computeWordGramFingerprint(segments, gramSize) {
1616
1681
  const gramCount = new Map();
1617
1682
  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++;
1683
+ for (const words of segments) {
1684
+ for (let i = 0; i <= words.length - gramSize; i++) {
1685
+ const gram = words.slice(i, i + gramSize).join(" ");
1686
+ let v = gramCount.get(gram) ?? 0;
1687
+ gramCount.set(gram, ++v);
1688
+ totalGrams++;
1689
+ }
1623
1690
  }
1624
1691
  if (totalGrams === 0) return null;
1625
1692
  return pickMaxFromCountMap(gramCount, totalGrams);
1626
1693
  }
1627
1694
 
1695
+ /**
1696
+ * 修复③(第四轮):按句/子句切分尾窗原文,再逐段抽取英文词。
1697
+ * 切分符覆盖中英文句读与换行;数字/下划线等仍由 normalizeForNGram 处理。
1698
+ * 目的:词级 gram 只在同一句/子句内形成,中文间隔不再让英文术语"假装相邻"。
1699
+ * @param {string} rawText
1700
+ * @returns {string[][]} 每段的英文词序列(长度 ≥1)
1701
+ */
1702
+ function extractEnglishWordSegments(rawText) {
1703
+ const segments = [];
1704
+ const wordRe = new RegExp(`[a-z]{${NGram_WORD_TOKEN_MIN_CHARS},}`, "g");
1705
+ for (const part of rawText.split(/[。!?!?;;::,,、.\n\r]+/)) {
1706
+ if (part.trim().length === 0) continue;
1707
+ const words = normalizeForNGram(part).match(wordRe);
1708
+ if (words && words.length > 0) segments.push(words);
1709
+ }
1710
+ return segments;
1711
+ }
1712
+
1713
+ /**
1714
+ * 修复③(第六轮):剔除引号/反引号包裹的片段。
1715
+ * 真实轨迹实测:模型在正文里 5 次引用会话开头的 "Let me understand the task"
1716
+ * 做起点核对,被词轨当成循环。引号内的内容是**被引用对象**(标识符/旧文本),
1717
+ * 不是模型自己在重复的骨架;统计前先剔除,避免引用型误切。
1718
+ * 只处理成对的双引号、中文引号、单引号(‘’)与反引号;
1719
+ * ASCII 单引号与英文缩写撇号冲突,不处理。
1720
+ * @param {string} text
1721
+ * @returns {string}
1722
+ */
1723
+ function stripQuotedSegments(text) {
1724
+ if (typeof text !== "string") return "";
1725
+ return text
1726
+ .replace(/"[^"\n]{0,500}"/g, " ")
1727
+ .replace(/“[^”\n]{0,500}”/g, " ")
1728
+ .replace(/‘[^’\n]{0,500}’/g, " ")
1729
+ .replace(/`[^`\n]{0,500}`/g, " ");
1730
+ }
1731
+
1732
+ /**
1733
+ * 修复③(第八轮):剔除三引号代码块(```…```,可跨行)。
1734
+ * 模型把日志、命令输出、表格、补丁粘进正文时,里面天然有大量重复行;
1735
+ * 这些是**引用数据**,不是模型自己在重复的推理骨架。单引号剔除
1736
+ * (stripQuotedSegments)只覆盖行内的 `…`,跨行块会漏过去——真实轨迹里
1737
+ * 粘贴失败日志后按短语高频误判,即属此类。
1738
+ * 不设长度上限:非贪婪匹配天然在下一个 ``` 处收尾,而输入的尾窗本身只有
1739
+ * 16000 字符;设上限反而会把超过上限的长堆栈块漏在正文里(真实轨迹实测:
1740
+ * 一段 6000+ 字符的 Unity 异步堆栈被漏掉,"end of stack trace" 命中 6 次)。
1741
+ * @param {string} text
1742
+ * @returns {string}
1743
+ */
1744
+ function stripFencedBlocks(text) {
1745
+ if (typeof text !== "string") return "";
1746
+ return text.replace(/```[\s\S]*?```/g, " ");
1747
+ }
1748
+
1749
+ /**
1750
+ * 修复③(第八轮):剔除 markdown 表格行。
1751
+ * 表格行(含 ≥2 个竖线)是结构化数据,同一列标签在每行重复出现是表格的
1752
+ * 正常形态,不是推理骨架在打转。真实轨迹实测:清单表格里"增补 P1-x"这类
1753
+ * 单元格被数字归一后互相等价,字符轨命中 11 次("增补pDI",稳定性 1.00)。
1754
+ * @param {string} text
1755
+ * @returns {string}
1756
+ */
1757
+ function stripTableRows(text) {
1758
+ if (typeof text !== "string") return "";
1759
+ return text.replace(/^[^\n]*\|[^\n]*\|[^\n]*$/gm, " ");
1760
+ }
1761
+
1762
+ /**
1763
+ * 修复③(第八轮):剔除堆栈帧/分隔线这类"数据行"。
1764
+ * 尾窗可能从一段超长代码块的中间开始(块的开 ``` 在前一屏之外),此时
1765
+ * stripFencedBlocks 找不到配对的起始标记,块内文字会残留在正文里。真实轨迹
1766
+ * 实测:Unity 异步堆栈里 `--- End of stack trace … ---` 重复 6 次、上下文
1767
+ * 完全一致,被词轨判成循环。堆栈帧与分隔线是工具输出,不是推理骨架,直接剔除。
1768
+ * @param {string} text
1769
+ * @returns {string}
1770
+ */
1771
+ function stripTraceLines(text) {
1772
+ if (typeof text !== "string") return "";
1773
+ return text
1774
+ .replace(/^\s*at [^\n]*$/gm, " ")
1775
+ .replace(/^\s*---[^\n]*---\s*$/gm, " ")
1776
+ .replace(/^\s*File "[^"]*", line \d+[^\n]*$/gm, " ");
1777
+ }
1778
+
1628
1779
  /**
1629
1780
  * 修复②:尾窗 n-gram 频率统计(双轨)。
1630
- * 输入 normText(已过 normalizeForNGram),同时产出两套指纹:
1781
+ * 输入尾窗原文,内部先归一化再切分,同时产出两套指纹:
1631
1782
  * - charFp:字符级 n-gram(原实现,保留中文/混合文本检测能力),gram 为无空白字符窗;
1632
- * - wordFp:英文词级 2-gram(相邻两个英文词为一个 gram);
1633
- * 以及英文主导判定(英文 token 数 / 全部 token 数 > 0.5),供 detectNGramLoop
1634
- * 分支互斥选用。判定逻辑不在本函数内做——detectNGramLoop 是唯一决策入口。
1635
- * @param {string} normText 已过 normalizeForNGram
1783
+ * gram 必须含 ≥NGram_CJK_MIN_CHARS 个 CJK 字——纯符号/版本号/DIGIT 组合不是语义短语;
1784
+ * - wordFp:英文词级 4-gram(同一句/子句内相邻四个英文词为一个 gram,单字母 token 不参与);
1785
+ * 以及英文 token 数(供覆盖率分母使用)。
1786
+ * 判定逻辑不在本函数内做——detectNGramLoop 是唯一决策入口。
1787
+ * @param {string} rawText 尾窗原文(未归一化)
1636
1788
  * @param {number} nGramSize 字符级短语粒度
1637
- * @returns {{charFp:object|null, wordFp:object|null, englishTokenCount:number, totalTokenCount:number, englishDominant:boolean}|null}
1789
+ * @returns {{charFp:object|null, wordFp:object|null, wordSegments:string[][], englishTokenCount:number, totalTokenCount:number, hasEnglishWords:boolean}|null}
1638
1790
  */
1639
- function computeNGramFingerprint(normText, nGramSize) {
1640
- if (typeof normText !== "string" || normText.length < nGramSize * 4) return null;
1791
+ function computeNGramFingerprint(rawText, nGramSize) {
1792
+ if (typeof rawText !== "string" || rawText.length < nGramSize * 4) return null;
1793
+ // 修复③(第六轮):统计前剔除引号内被引用文本(见 stripQuotedSegments)。
1794
+ // 修复③(第八轮):依次剔除三引号代码块、表格行、堆栈帧、行内引号段。
1795
+ const scanText = stripQuotedSegments(stripTraceLines(stripTableRows(stripFencedBlocks(rawText))));
1796
+ const normText = normalizeForNGram(scanText);
1641
1797
 
1642
1798
  // 轨 1:字符级 n-gram(原逻辑不变 + 英文词内部子串隔离)。
1643
1799
  // 隔离规则:gram 完全由英文字母组成时跳过(normalize 已小写化,/^[a-z]+$/ 即纯英文)。
1644
1800
  // 纯英文 gram 一定是某个英文词的内部子串或跨词片段,英文语义统一交给词轨判定;
1645
1801
  // 字符轨只保留含 CJK/数字/符号的 gram,避免中英混合文本里 "sessi"/"ancho" 这类
1646
1802
  // 英文词子串被独立计数而误报(本会话实测复现:count 16、coverage 8.8% 触发 cut)。
1803
+ // 修复③:再要求 gram 含 ≥2 个 CJK 字。事故样本里字符轨最高频是 "«t»«t"(制表符
1804
+ // 占位符)与 "vDIGI"(版本号归一后的片段),它们不含 CJK、纯属结构重复;
1805
+ // 不设此守卫时,词轨修好后字符轨仍可能接棒误切。
1647
1806
  const charGramCount = new Map();
1648
1807
  let charTotalGrams = 0;
1649
1808
  for (let i = 0; i <= normText.length - nGramSize; i++) {
@@ -1652,23 +1811,32 @@ function computeNGramFingerprint(normText, nGramSize) {
1652
1811
  if (gram.includes(" ") || gram.includes("\n") || gram.includes("\t")) continue;
1653
1812
  // 跳过纯英文 gram:英文词内部子串隔离(方案 1)
1654
1813
  if (/^[a-z]+$/.test(gram)) continue;
1814
+ // 修复③:CJK 字数守卫(见上)
1815
+ const cjkCount = [...gram].filter((ch) => /[\u4e00-\u9fff]/.test(ch)).length;
1816
+ if (cjkCount < NGram_CJK_MIN_CHARS) continue;
1655
1817
  let v = charGramCount.get(gram) ?? 0;
1656
1818
  charGramCount.set(gram, ++v);
1657
1819
  charTotalGrams++;
1658
1820
  }
1659
1821
  const charFp = charTotalGrams === 0 ? null : pickMaxFromCountMap(charGramCount, charTotalGrams);
1660
1822
 
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;
1823
+ // 轨 2:英文词级 4-gram——按句/子句切分后,在各段内抽 [a-z]{2,} 英文词
1824
+ // (单字母变量/占位符不入表),相邻 NGram_WORD_GRAM_SIZE 个词为一个 gram。
1825
+ // 跨句不组 gram,避免中文主体把零散英文术语拼成假短语。
1826
+ const wordSegments = extractEnglishWordSegments(scanText);
1827
+ const allWords = wordSegments.flat();
1828
+ const wordFp = allWords.length >= NGram_WORD_GRAM_SIZE
1829
+ ? computeWordGramFingerprint(wordSegments, NGram_WORD_GRAM_SIZE)
1830
+ : null;
1831
+
1832
+ // 英文 token 占比统计(供 detectNGramLoop 词轨覆盖率分母 / 上下文守卫用)。
1833
+ const englishTokenCount = allWords.length;
1667
1834
  const cjkCount = (normText.match(/[\u4e00-\u9fff]/g) || []).length;
1668
1835
  const totalTokenCount = englishTokenCount + cjkCount;
1669
1836
  return {
1670
1837
  charFp,
1671
1838
  wordFp,
1839
+ wordSegments,
1672
1840
  englishTokenCount,
1673
1841
  totalTokenCount,
1674
1842
  // 方案 1:英文词轨并行——只要有英文词就具备走词轨的条件,不再要求英文主导。
@@ -1696,33 +1864,153 @@ function pickHighestNonStopwordGram(gramCount) {
1696
1864
  }
1697
1865
 
1698
1866
  /**
1699
- * 修复②:按频次降序取第一个非停用词 gram(英文词级 2-gram 专用)。
1700
- * 词级 gram 形如 "settings path",停用过滤按「词」检查:两个英文词中任一个命中
1701
- * 英文停用词表即跳过——"the settings" / "web fetch" 这类虚词+技术词/工具名搭配
1702
- * 是英文技术文本的高频噪声,不是循环证据(stopCharRatio 按字符比对对英文整词
1703
- * 无效,故词轨不能复用字符轨的守卫)。
1867
+ * 修复③:按频次降序列出全部合格词级 gram(英文 4-gram 专用)。
1868
+ * 词级 gram 形如 "verify checksum before releasing"。修复③(第三轮)不再
1869
+ * "含任一停用词即丢弃"——"please verify the checksum" 这类带冠词的正常短语
1870
+ * 会因此整条消失(P 用例漏检)。改为要求 **至少 2 个实词**(不在停用词表):
1871
+ * 纯虚词组合("the settings path from")与公式变量组合(4 个两字母词)被滤掉,
1872
+ * 含冠词但骨架完整的短语保留。返回全部候选而非只取第一名:最高频的可能是
1873
+ * 上下文噪声,真正循环骨架会排在后面,由 detectNGramLoop 逐个校验稳定性。
1704
1874
  * @param {Map<string, number>} gramCount
1705
- * @returns {{gram:string, count:number}|null}
1875
+ * @param {number} gramSize 词数
1876
+ * @returns {{gram:string, count:number}[]}
1706
1877
  */
1707
- function pickHighestNonStopwordBigram(gramCount) {
1878
+ function listEligibleWordGrams(gramCount, gramSize) {
1708
1879
  const sorted = [...gramCount.entries()].sort((a, b) => b[1] - a[1]);
1880
+ const out = [];
1709
1881
  for (const [gram, count] of sorted) {
1710
1882
  const words = gram.split(" ");
1711
- if (words.length !== 2) continue;
1712
- if (words.some((w) => NGram_STOPWORDS.has(w))) continue;
1713
- return { gram, count };
1883
+ if (words.length !== gramSize) continue;
1884
+ const contentWords = words.filter((w) => !NGram_STOPWORDS.has(w)).length;
1885
+ if (contentWords < 2) continue;
1886
+ const letters = words.reduce((sum, w) => sum + w.length, 0);
1887
+ if (letters < NGram_WORD_MIN_LETTERS) continue;
1888
+ out.push({ gram, count });
1714
1889
  }
1715
- return null;
1890
+ return out;
1891
+ }
1892
+
1893
+ /**
1894
+ * 修复③(第二轮):词轨命中短语的上下文稳定性。
1895
+ * 统计该 gram 每次出现时「前一个词 | 后一个词」的分布,返回最高频组合占比。
1896
+ * 真循环重复整句骨架 → 邻居一致 → 占比接近 1;术语/标识符复用 → 占比很低。
1897
+ * 修复③(第四轮):按句段统计,段首/段尾以 ^/$ 记上下文,不跨句拼接。
1898
+ * @param {string[][]} segments 按句/子句切分后的英文词序列
1899
+ * @param {string} gram 已命中的词级 gram
1900
+ * @param {number} gramSize 词数
1901
+ * @returns {number} 最高频上下文占比(0~1)
1902
+ */
1903
+ function wordGramContextStability(segments, gram, gramSize) {
1904
+ const parts = gram.split(" ");
1905
+ const ctx = new Map();
1906
+ let total = 0;
1907
+ for (const words of segments) {
1908
+ for (let i = 0; i + gramSize <= words.length; i++) {
1909
+ let same = true;
1910
+ for (let k = 0; k < gramSize; k++) {
1911
+ if (words[i + k] !== parts[k]) { same = false; break; }
1912
+ }
1913
+ if (!same) continue;
1914
+ const key = `${words[i - 1] ?? "^"}|${words[i + gramSize] ?? "$"}`;
1915
+ ctx.set(key, (ctx.get(key) ?? 0) + 1);
1916
+ total++;
1917
+ }
1918
+ }
1919
+ if (total === 0) return 0;
1920
+ return Math.max(...ctx.values()) / total;
1921
+ }
1922
+
1923
+ /**
1924
+ * 修复③(第三轮):字符轨命中短语的上下文稳定性。
1925
+ * 与词轨同一思路,邻居换成「前一个字符 | 后一个字符」。中文术语复用
1926
+ * ("配置项说明" 出现在不同句子里,前后字各不相同)占比很低;
1927
+ * 中文真循环重复整句 → 前后字一致 → 占比接近 1。
1928
+ * 修复③(第八轮):右侧改为取 3 个字符。表格行 `| 配置项说明:超时时间 |` 里
1929
+ * gram 两侧紧贴空格/竖线,只取 1 个字符时邻居恒定(对抗用例:15 行同标签表格
1930
+ * 稳定性 1.00,误判为循环);取 3 个字符后,标点之后的单元格正文进入上下文,
1931
+ * 行与行之间不再"稳定"。
1932
+ * 左侧仍只取 1 个字符:中文真循环常以变化的连接词开头(首先/其次/然后…),
1933
+ * 左扩 3 会把连接词差异算进上下文而漏检(对抗用例 P4 复现)。左侧紧邻的
1934
+ * 单字符足以区分"句首变化"与"整句重复"。
1935
+ * @param {string} text 已归一化的尾窗文本
1936
+ * @param {string} gram 已命中的字符 gram
1937
+ * @returns {number} 最高频上下文占比(0~1)
1938
+ */
1939
+ function charGramContextStability(text, gram) {
1940
+ const LEFT = 1;
1941
+ const RIGHT = 3;
1942
+ const ctx = new Map();
1943
+ let total = 0;
1944
+ let i = text.indexOf(gram);
1945
+ while (i >= 0) {
1946
+ const before = i > 0 ? text.slice(Math.max(0, i - LEFT), i) : "^";
1947
+ const after = i + gram.length < text.length ? text.slice(i + gram.length, i + gram.length + RIGHT) : "$";
1948
+ const key = `${before}|${after}`;
1949
+ ctx.set(key, (ctx.get(key) ?? 0) + 1);
1950
+ total++;
1951
+ i = text.indexOf(gram, i + 1);
1952
+ }
1953
+ if (total === 0) return 0;
1954
+ return Math.max(...ctx.values()) / total;
1716
1955
  }
1717
1956
 
1718
1957
  /**
1719
- * 修复②:判定是否为"语义漂移型循环"——跳过停用词 gram 后取最高频非停用 gram,
1720
- * 其出现次数 ≥ NGram_MIN_COUNT 且覆盖占尾窗比例 ≥ NGram_COVERAGE_RATIO。
1958
+ * 修复③(第七轮):字符轨命中区间长度——首次命中起点到末次命中终点。
1959
+ * 用于覆盖率分母(把"重复有多密集"而不是"占全文多大比例"作为判据)。
1960
+ * 只有一次命中时区间即 gram 长度。
1961
+ * @param {string} text 已归一化的尾窗文本
1962
+ * @param {string} gram 已命中的字符 gram
1963
+ * @returns {number}
1964
+ */
1965
+ function charGramSpanLength(text, gram) {
1966
+ const first = text.indexOf(gram);
1967
+ if (first < 0) return 0;
1968
+ const last = text.lastIndexOf(gram);
1969
+ return last + gram.length - first;
1970
+ }
1971
+
1972
+ /**
1973
+ * 修复③(第七轮):词轨命中区间长度(以 token 计)——首次命中起点到末次命中共多少个
1974
+ * 英文 token。相邻句子之间不组 gram,但游标照常累计,区间因此可能跨越句子间隔。
1975
+ * @param {string[][]} segments 按句/子句切分后的英文词序列
1976
+ * @param {string} gram 已命中的词级 gram
1977
+ * @param {number} gramSize 词数
1978
+ * @returns {number}
1979
+ */
1980
+ function wordGramSpanTokens(segments, gram, gramSize) {
1981
+ const parts = gram.split(" ");
1982
+ let cursor = 0;
1983
+ let firstStart = -1;
1984
+ let lastEnd = -1;
1985
+ for (const words of segments) {
1986
+ for (let i = 0; i + gramSize <= words.length; i++) {
1987
+ let same = true;
1988
+ for (let k = 0; k < gramSize; k++) {
1989
+ if (words[i + k] !== parts[k]) { same = false; break; }
1990
+ }
1991
+ if (!same) continue;
1992
+ if (firstStart < 0) firstStart = cursor + i;
1993
+ lastEnd = cursor + i + gramSize;
1994
+ }
1995
+ cursor += words.length;
1996
+ }
1997
+ if (firstStart < 0) return 0;
1998
+ return lastEnd - firstStart;
1999
+ }
2000
+
2001
+ /**
2002
+ * 修复②:判定是否为"语义漂移型循环"——按频次逐个取合格 gram 候选,要求
2003
+ * 出现次数 ≥ NGram_MIN_COUNT、覆盖尾窗比例 ≥ NGram_COVERAGE_RATIO,且
2004
+ * 命中短语的上下文稳定(同一句骨架反复出现,而非术语/标识符在不同句里复用)。
1721
2005
  * 双轨分支(互斥,不许混合):
1722
- * - 英文主导(英文 token 数 > 全部 token 数的一半):只走英文词级 2-gram 路径,
1723
- * 绝不回退字符 5-gram——否则 "settings" 的任意 5 字符子串("setti" 等)会被
1724
- * 独立计数而误报。词级覆盖率 = count × 2 / 英文 token 总数。
1725
- * - 非英文主导(中文/混合):保持原字符 n-gram 路径,覆盖率 = count × n / 尾窗字符数。
2006
+ * - 英文词轨(含英文词即可):只走英文词级 4-gram 路径,绝不回退字符
2007
+ * 5-gram——否则 "settings" 的任意 5 字符子串("setti" 等)会被独立计数而误报。
2008
+ * 词级覆盖率 = count × 4 / min(英文 token 总数, 命中区间 token 数)——两种口径
2009
+ * 取最大值(见 NGram_DENSITY_MIN_TOKENS);token 只计 ≥2 字母的词,
2010
+ * 单字母变量/占位符("s"/"l"/"t")既不进 gram 也不撑大分母。
2011
+ * - 字符轨(中文/混合):字符 n-gram 路径,覆盖率 = count × n / min(尾窗字符数,
2012
+ * 命中区间字符数),同样两种口径取最大值;gram 必须含 ≥2 个 CJK 字,
2013
+ * 纯符号/版本号重复不参与。
1726
2014
  * 与 findRepeatingTail 并行,不破坏原逻辑。
1727
2015
  * @param {string} fullVisibleText
1728
2016
  * @returns {{maxGram:string,count:number,coverage:number}|null}
@@ -1731,29 +2019,51 @@ function detectNGramLoop(fullVisibleText) {
1731
2019
  if (typeof fullVisibleText !== "string" || fullVisibleText.length < REPEAT_MIN_TEXT_CHARS) return null;
1732
2020
  const tail = fullVisibleText.slice(-REPEAT_WINDOW_CHARS);
1733
2021
  const norm = normalizeForNGram(tail);
1734
- const fp = computeNGramFingerprint(norm, NGram_PHRASE_MIN);
2022
+ const fp = computeNGramFingerprint(tail, NGram_PHRASE_MIN);
1735
2023
  if (!fp) return null;
1736
2024
 
1737
- // 轨 A(方案 1 并行):英文词级 2-gram——只要文本含英文词就跑词轨。
2025
+ // 轨 A(方案 1 并行):英文词级 4-gram——只要文本含英文词就跑词轨。
1738
2026
  // 英文单词是原子 token,词轨本身不会产生 "sessi"/"ancho" 这类词内子串误报;
1739
2027
  // 覆盖率分母用英文 token 总数,避免中文主体把分母撑大掩盖英文真循环。
1740
2028
  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) {
2029
+ // 修复③(第三轮):逐个候选校验,最多看前 NGram_WORD_CANDIDATE_LIMIT 个。
2030
+ // 最高频的候选可能恰是上下文噪声("now/then/next" 开头的连接词 4-gram),
2031
+ // 真正循环的骨架排在后面;但同一表格单元格骨架也可能排在后面,故仍用
2032
+ // 上下文稳定性把关,稳定命中才返回。
2033
+ const candidates = listEligibleWordGrams(fp.wordFp.gramCount, NGram_WORD_GRAM_SIZE);
2034
+ for (const chosen of candidates.slice(0, NGram_WORD_CANDIDATE_LIMIT)) {
2035
+ if (chosen.count < NGram_MIN_COUNT) break;
2036
+ // 修复③(第七轮):覆盖率同时按旧口径(整个尾窗)与密度口径(命中区间)
2037
+ // 计算并取最大值;密度分母带下限,避免短文本里集中出现的术语被抬过阈值。
2038
+ // 覆盖率不足只跳过该候选、不 break——候选按频次降序,区间更紧凑的
2039
+ // 候选可能排在后面(覆盖率和频次不同序)。
2040
+ const spanTokens = wordGramSpanTokens(fp.wordSegments, chosen.gram, NGram_WORD_GRAM_SIZE);
2041
+ const fullCoverage = chosen.count * NGram_WORD_GRAM_SIZE / fp.englishTokenCount;
2042
+ const densityCoverage = chosen.count * NGram_WORD_GRAM_SIZE / Math.max(spanTokens, NGram_DENSITY_MIN_TOKENS);
2043
+ const coverage = Math.max(fullCoverage, densityCoverage);
2044
+ if (coverage < NGram_COVERAGE_RATIO) continue;
2045
+ // 修复③(第二轮):上下文稳定性守卫——命中短语必须在相近句骨架里反复出现,
2046
+ // 而不是作为术语/标识符在不同句子里被复用(样例 3:7 次命中全部左邻不同)。
2047
+ if (wordGramContextStability(fp.wordSegments, chosen.gram, NGram_WORD_GRAM_SIZE) >= NGram_CONTEXT_MIN_RATIO) {
1745
2048
  return { maxGram: chosen.gram, count: chosen.count, coverage };
1746
2049
  }
1747
2050
  }
1748
2051
  }
1749
2052
 
1750
2053
  // 轨 B(方案 1 并行):字符级 n-gram——纯英文 gram 已在 computeNGramFingerprint
1751
- // 中被隔离(英文词内部子串不再计入),字符轨只承担含 CJK/数字/符号的文本。
2054
+ // 中被隔离(英文词内部子串不再计入),字符轨只承担含 CJK 的文本。
1752
2055
  if (!fp.charFp) return null;
1753
2056
  const chosen = pickHighestNonStopwordGram(fp.charFp.gramCount);
1754
2057
  if (!chosen || chosen.count < NGram_MIN_COUNT) return null;
1755
- const coverage = chosen.count * NGram_PHRASE_MIN / tail.length;
2058
+ // 修复③(第七轮):同样两种口径取最大值,密度分母带下限(见上方常量注释)。
2059
+ const spanChars = charGramSpanLength(norm, chosen.gram);
2060
+ const fullCoverage = chosen.count * NGram_PHRASE_MIN / tail.length;
2061
+ const densityCoverage = chosen.count * NGram_PHRASE_MIN / Math.max(spanChars, NGram_DENSITY_MIN_CHARS);
2062
+ const coverage = Math.max(fullCoverage, densityCoverage);
1756
2063
  if (coverage < NGram_COVERAGE_RATIO) return null;
2064
+ // 修复③(第三轮):字符轨同样要求上下文稳定——"配置项说明"这类术语在 12 个
2065
+ // 不同句子里复用(每次前后字都不同)不是循环;重复整句的中文真循环前后字一致。
2066
+ if (charGramContextStability(norm, chosen.gram) < NGram_CONTEXT_MIN_RATIO) return null;
1757
2067
  return { maxGram: chosen.gram, count: chosen.count, coverage };
1758
2068
  }
1759
2069
 
@@ -2121,6 +2431,25 @@ function renderActionChurnAnchor(churn) {
2121
2431
  ].join("\n");
2122
2432
  }
2123
2433
 
2434
+ /**
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.
2442
+ * @returns {string}
2443
+ */
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");
2451
+ }
2452
+
2124
2453
  /**
2125
2454
  * 缺陷 3 修复(2026-10-07 升级版):churn 每 turn 命中计数。键 = sessionId,值为
2126
2455
  * { lastTurn, count }:count 是本 turn handler 返回 churn cut 决策的次数。计数口径
@@ -3004,6 +3333,7 @@ const DEFAULT_SETTINGS = { // Master switches
3004
3333
  enableChurn: true,
3005
3334
  enableTransition: true,
3006
3335
  enableNumberRunaway: true,
3336
+ enableOverLongCoT: false,
3007
3337
  // Notice/anchor shaping
3008
3338
  minReasoningChars: 250,
3009
3339
  maxPoints: 3,
@@ -3022,6 +3352,9 @@ const DEFAULT_SETTINGS = { // Master switches
3022
3352
  softCutTransitionWindow: 48,
3023
3353
  softCutMinFollowChars: 6,
3024
3354
  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).
3357
+ overLongCoTThreshold: 8000,
3025
3358
  // Repetition detector
3026
3359
  repeatProbeChars: 128,
3027
3360
  repeatWindowChars: 16000,
@@ -3130,6 +3463,8 @@ const SETTINGS_SCHEMA = [
3130
3463
  hint: "\"接下来我要……\"这类转折句出现时打断,先注入结论锚点。" },
3131
3464
  { key: "enableNumberRunaway", label: "识别数字递增流退化", type: "boolean", group: "打断判定",
3132
3465
  hint: "长段递增数字流(如 639.640) 640.641)…)连续多字且无实质内容时打断。启发式判定,仅在数字流足够长时触发。" },
3466
+ { key: "enableOverLongCoT", label: "过长 CoT 软切", type: "boolean", group: "打断判定",
3467
+ hint: "当本轮 CoT(思考+正文)总字数超过下方阈值时软切并提醒模型「落实阶段性结论、避免过度思考」。属兜底提醒,独立于其他启发式检测。默认关闭。" },
3133
3468
 
3134
3469
  { key: "minReasoningChars", label: "最少思考字数", type: "number", min: 50, max: 5000, group: "锚点内容",
3135
3470
  hint: "思考短于此长度时不提取结论、不注入。" },
@@ -3145,6 +3480,10 @@ const SETTINGS_SCHEMA = [
3145
3480
  hint: "决定怎么把模型的「思考」和「正文」区分开来。内核还没支持这一项,选什么都不会改变行为,先按默认放着即可。" },
3146
3481
  { key: "enableExecDisciplineBlock", label: "随锚点注入命令执行纪律块", type: "boolean", group: "锚点内容",
3147
3482
  hint: "默认开启。开启时会把「执行命令要守规矩」这段提醒和结论摘要一起插回上下文;关闭就完全不插这段提醒,结论摘要和其他识别、去重功能都不受影响。" },
3483
+
3484
+ { key: "overLongCoTThreshold", advanced: true, label: "CoT 长度阈值(字符)", type: "number", min: 0, max: 100000, group: "过长 CoT 参数",
3485
+ hint: "本轮 CoT(思考+正文)累计字符数超过此值时触发软切提醒。默认 8000;设为 0 即关闭(同关闭上方开关效果一致)。" },
3486
+
3148
3487
  { key: "numberRunMinTextChars", advanced: true, label: "数字流启用最小文本长度", type: "number", min: 100, max: 50000, group: "数字流参数" },
3149
3488
  { key: "numberRunMinChars", advanced: true, label: "数字流最短跨度", type: "number", min: 50, max: 20000, group: "数字流参数" },
3150
3489
  { key: "numberRunMaxGap", advanced: true, label: "数字流最大间隙", type: "number", min: 1, max: 200, group: "数字流参数",
@@ -3166,7 +3505,7 @@ const SETTINGS_SCHEMA = [
3166
3505
  { key: "repeatProbeChars", advanced: true, label: "周期探针长度", type: "number", min: 16, max: 2000, group: "重复循环参数" },
3167
3506
  { key: "repeatMinTextChars", advanced: true, label: "启用最小文本长度", type: "number", min: 500, max: 50000, group: "重复循环参数" },
3168
3507
  { key: "ngramPhraseMin", advanced: true, label: "n-gram 短语最小长度(字符)", type: "number", min: 3, max: 20, group: "重复循环参数",
3169
- hint: "字符级 n-gram 的滑窗粒度(中文路径)。默认 5;调高要求更长的短语才计数(更保守)。英文路径固定按相邻 2 词,不受此项影响。" },
3508
+ hint: "字符级 n-gram 的滑窗粒度(中文路径)。默认 5;调高要求更长的短语才计数(更保守)。英文路径固定按相邻 4 个词(每词 ≥2 字母),不受此项影响。" },
3170
3509
  { key: "ngramMinCount", advanced: true, label: "n-gram 最高频短语最小出现次数", type: "number", min: 2, max: 50, group: "重复循环参数",
3171
3510
  hint: "最高频短语至少出现这么多次才判定循环;调低更激进、调高更保守。" },
3172
3511
  { key: "ngramCoverageRatio", advanced: true, label: "n-gram 短语覆盖占比下限", type: "number", min: 0.01, max: 0.5, group: "重复循环参数",
@@ -3297,6 +3636,7 @@ function applyRuntimeSettings(raw) {
3297
3636
  SOFT_CUT_TRANSITION_WINDOW = merged.softCutTransitionWindow;
3298
3637
  SOFT_CUT_MIN_FOLLOW_CHARS = merged.softCutMinFollowChars;
3299
3638
  SOFT_CUT_GAP_THRESHOLD = merged.softCutGapThreshold;
3639
+ OVER_LONG_COT_THRESHOLD = merged.overLongCoTThreshold;
3300
3640
  REPEAT_PROBE_CHARS = merged.repeatProbeChars;
3301
3641
  REPEAT_WINDOW_CHARS = merged.repeatWindowChars;
3302
3642
  REPEAT_MIN_PERIOD = merged.repeatMinPeriod;
@@ -4834,6 +5174,33 @@ function apply(ctx, config) {
4834
5174
  };
4835
5175
  }
4836
5176
 
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.
5185
+ if (settings.enableOverLongCoT && OVER_LONG_COT_THRESHOLD > 0
5186
+ && fullText.length >= OVER_LONG_COT_THRESHOLD
5187
+ && !insideUnclosedCodeFence(fullText)) {
5188
+ noteSoftCutFired();
5189
+ emitCotAnchorEvent(ctx, EVENT_SOFTCUT_TAKEN, {
5190
+ ...evidenceBase(payload?.sessionId, payload?.turn, payload?.step),
5191
+ cutClass: "heuristic",
5192
+ detector: "over-long-cot"
5193
+ });
5194
+ const anchorText = renderOverLongCoTAnchor(fullText.length, OVER_LONG_COT_THRESHOLD);
5195
+ return {
5196
+ kind: "cut",
5197
+ budgetClass: "heuristic",
5198
+ cutClass: "heuristic",
5199
+ contexts: [buildAnchorContext(anchorText,
5200
+ `cot-anchor: over-long-cot ${fullText.length}/${OVER_LONG_COT_THRESHOLD}`)]
5201
+ };
5202
+ }
5203
+
4837
5204
  // (4) A→"接下来我要…"→B transition inside one generation.
4838
5205
  // The cut is destructive, so it requires an EXPLICIT conclusion
4839
5206
  // ("所以/因此/综上/therefore …") already present — a density-only
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cot-anchor",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "思考锚点:从模型上一段思考中提取已确立结论,在工具结果后注入,减少重复推导;并可识别打转与伪工具调用",
5
5
  "keywords": [
6
6
  "dsh",