dsh-goal-contract 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,66 @@
4
4
 
5
5
  本文件记录 `dsh-goal-contract` 的对外变化。每条先中文整段、再英文整段。
6
6
 
7
+ ## 0.2.6 — 2026-11-28
8
+
9
+ 中文 / English
10
+
11
+ ### 中文
12
+
13
+ 这一版修的是一个「该拦却拦不住」的缺陷,功能本身没有增加。
14
+
15
+ **思考通道以前完全不参与判据。** 那条判据只看正文,而 2026-11-28 那次事故里,重复全部发生在思考区——那一步进来 2400 个思考分片、正文分片是 0,计数器一个数都没吃到。现在思考与正文一样参与。
16
+
17
+ **原来的判据数不到真实的重复形态。** 旧判据是「同一个小碎片连续出现 30 次」,而真实形态是「同一小段循环几百遍」:拿那 2400 个真实分片喂给旧判据,最长只连了 2 次。新增「尾部同一单元连续重复」判据(单元 3~64 字符,默认阈值仍是 30),两条判据任一命中即拦截。**只认连续、不累计**:中间插进任何别的内容就归零重算,跨步跨块都不累加。
18
+
19
+ **拦下之后你能看见了。** 以前它只发一条模型可见的纠偏消息,聊天区不渲染,所以你什么都看不到。现在会在目标面板的「异常提醒(纯提醒,不用处理)」组里留一条记录,写明连续重复已达上限多少次、重复的是什么;它不挡收尾、不进未完结计数。
20
+
21
+ 真实日志回归:458 那轮连刷 699 次、459 那轮 920 次,都命中;460 那轮只连 24 次,正确地不命中。测试:1816 个全通过,进程退出码 0。
22
+
23
+ ### English
24
+
25
+ This release fixes a defect where the interruption failed to fire when it should have. No new capability was added.
26
+
27
+ **The reasoning channel never participated.** The check only looked at visible text, but in the incident on 2026-11-28 every repetition happened in the reasoning stream — that step received 2,400 reasoning deltas and zero text deltas, so the counter never saw a single one. Reasoning now takes part exactly like visible text.
28
+
29
+ **The old check also could not see the real shape.** It required the same small fragment 30 times in a row, while the real pattern was one short unit looping hundreds of times: fed the 2,400 real deltas, it never counted more than 2. A new "same unit repeating at the tail" check was added (unit length 3–64 characters, default threshold still 30); either check firing interrupts the turn. **Only contiguous runs count, never accumulated totals**: any different content in between resets the count, and it never adds up across steps or blocks.
30
+
31
+ **You can now see it happen.** Previously the interrupt only sent a steer message that the chat view does not render, so nothing was visible. It now leaves a record in the "anomaly reminders (informational only)" group of the goal panel, stating how many repetitions the run reached and what the repeated content was; it does not block completion and is not counted as an open debt.
32
+
33
+ Real-log regression: the 458 turn repeated 699 times and the 459 turn 920 times, both interrupted; the 460 turn repeated only 24 times and correctly was not. Tests: 1,816 passing, process exit code 0.
34
+
35
+ ## 0.2.5 — 2026-11-28
36
+
37
+ 中文 / English
38
+
39
+ ### 中文
40
+
41
+ 这一版没有改任何插件行为,只补了「一个正常仓库该有的东西」。起因是 0.2.4 推上去之后,看 npm 页面和 GitHub 首页才发现:README 只有中文、没有 CI、没有 issue 模板、GitHub 的 About 三项全空。
42
+
43
+ **新增英文版 README。** `README.en.md`,276 行,与中文版逐行对齐——15 个章节标题落在完全相同的行号,15 个工具名、模型选型的全部数字、16 个配置项都原样保留。两份 README 顶部互相加跳转:中文版写 `**中文** | [English](README.en.md)`,英文版写 `[中文](README.md) | **English**`。
44
+
45
+ **新增 CI。** `.github/workflows/ci.yml`:Ubuntu 和 Windows 两个平台、Node 22,每次 push 到 master 或提 PR 自动跑一千八百多个测试。两个细节是必需的——这个包没有 lock 文件,所以用 `npm install` 而不是 `npm ci`;有 5 个测试会读 `dist/client.js`,所以必须先跑 `npm run build:client` 再跑测试。
46
+
47
+ **新增协作文件。** `.github/ISSUE_TEMPLATE/` 下的 bug 与功能建议表单、`.github/pull_request_template.md`、`CONTRIBUTING.md`(怎么本地跑起来、提 PR 前要做什么、不接受什么)、`SECURITY.md`(双语;写清「模型能绕过这个插件」不算漏洞——它本来就不是安全边界)。
48
+
49
+ **补齐 GitHub 仓库 About。** description(和 npm 同一句)、homepage(指向 npm 页面)、8 个 topics(dsh / dsh-plugin / deepseek-harness / cordis / goal-tracking / agent-safety / ai-agent / autonomous-agent)。
50
+
51
+ 测试:1806 个全通过,进程退出码 0。
52
+
53
+ ### English
54
+
55
+ No plugin behaviour changed in this release. It only fills in what a normal repository is expected to have. After 0.2.4 shipped, looking at the npm page and the GitHub front page made the gaps obvious: the README was Chinese-only, there was no CI, no issue templates, and all three GitHub About fields were empty.
56
+
57
+ **English README added.** `README.en.md`, 276 lines, aligned with the Chinese version line by line — all 15 section headings land on exactly the same line numbers, and all 15 tool names, every number in the model benchmark table, and all 16 configuration keys are preserved verbatim. The two READMEs link to each other at the top.
58
+
59
+ **CI added.** `.github/workflows/ci.yml`: Ubuntu and Windows, Node 22, running the full suite of 1,800+ tests on every push to master and every pull request. Two details are load-bearing — this package has no lock file, so it uses `npm install` rather than `npm ci`; and five tests read `dist/client.js`, so `npm run build:client` has to run before the suite.
60
+
61
+ **Collaboration files added.** Bug and feature-request forms under `.github/ISSUE_TEMPLATE/`, `.github/pull_request_template.md`, `CONTRIBUTING.md` (how to run it locally, what to check before opening a PR, and what will be rejected), and `SECURITY.md` (bilingual; it states plainly that "the model can bypass this plugin" is not a vulnerability, because the plugin was never a security boundary).
62
+
63
+ **GitHub About filled in.** description (the same sentence as npm), homepage (pointing at the npm page), and 8 topics.
64
+
65
+ Tests: 1806 passing, process exit code 0.
66
+
7
67
  ## 0.2.4 — 2026-11-28
8
68
 
9
69
  ### 中文
package/README.en.md ADDED
@@ -0,0 +1,278 @@
1
+ # dsh-goal-contract
2
+
3
+ [中文](README.md) | **English**
4
+
5
+ Current version: 0.2.6
6
+
7
+ **While you are away, the AI's goal keeps moving forward — under control.**
8
+
9
+ Set a goal contract for a session (objective / allow / deny / acceptance), write every change into an append-only ledger, use deterministic rules to spot drift (edited a path you forbade, ran a command you forbade, changed the goal without a reason, no progress for a long time), and stop the AI when it goes in circles, fails repeatedly, repeats itself, or gets stuck.
10
+
11
+ > ⚠ This plugin is an **interrogator + bookkeeper**, not a security boundary.
12
+ > The model can only propose; the contract and its amendments are decided by you.
13
+
14
+ ## What it can do for you
15
+
16
+ ### 1. Your goal can't be quietly changed while you're away
17
+
18
+ Only you can change the goal — the model can only propose. When it says "I want to change the goal to X", that has to land first as a proposal with a reason, written into the contract and the ledger, so you can see it and reject it.
19
+
20
+ The "paths you must not touch" and "commands you must not run" you wrote into the contract: the call that steps outside them is refused on the spot, and you get back one line saying which boundary was crossed and what to do next.
21
+
22
+ Deleting an acceptance item, rewriting a milestone, rewriting the goal statement — all of those count as "downgrades". Without your explicit permission, every one of them is refused.
23
+
24
+ ### 2. Progress is computed, not self-reported
25
+
26
+ The progress on the panel comes from the milestones ticked off one by one in the ledger, not from the model's self-report.
27
+
28
+ Marking something done requires a **command you can re-run** (or a file location you can check); only exit code 0 counts. Evidence that doesn't meet the bar is refused.
29
+
30
+ "Done N/M" and the percentage are reduced from the ledger and match what the panel shows; they survive a page refresh and a DSH restart.
31
+
32
+ ### 3. It stops the AI before it goes in circles
33
+
34
+ The same tool failing again and again, the same call swinging back and forth, long repeated output — all three stuck signals are cut off on the spot.
35
+
36
+ Loops and being stuck are **hard blocks**: once they fire, there is no way through until you change the approach.
37
+
38
+ Several rounds on the same problem with no progress: it stops and reports the way you configured, or researches first and then reports. Running out of rounds is only a **soft hint** — one reminder, no block.
39
+
40
+ ### 4. You won't come back to "an idea nobody wrote down"
41
+
42
+ Every word you say gets filed: what fits an acceptance item gets attached to it, what doesn't go into "Outstanding Items", and **your exact words are always kept** — never rewritten into the model's own paraphrase.
43
+
44
+ Promises the AI makes like "I'll give you X later" are recorded as debts automatically, so it doesn't have to remember them. Before work starts you're reminded of the most important ones; the rest you can find on the panel.
45
+
46
+ Debts left open in a long task stay on the panel; when you want to wrap up or archive a session, open debts block it, and you get an itemized list of what is still owed.
47
+
48
+ ### 5. Every step is visible on the panel
49
+
50
+ In the "Goal Tracking" tab on the right of the session, the top bar shows the revision count, the run state and the progress; the acceptance list has a checkbox on every entry.
51
+
52
+ The top bar's "Change Log" is an overlay: every change to the goal and the contract is in there — what changed, why it changed, what it became.
53
+
54
+ How long something has been owed isn't written into the table; color says it: over 24 hours is yellow, over 72 hours is red.
55
+
56
+ ## Installation
57
+
58
+ ```bash
59
+ dsh plugin --profile <your profile name> add dsh-goal-contract
60
+ ```
61
+
62
+ Restart DSH after installing and it takes effect. The plugin has zero third-party dependencies; it only borrows DSH's own general services.
63
+
64
+ ## Five-minute start
65
+
66
+ Four steps and you can see it watching for you.
67
+
68
+ **Step 1 · Declare the goal.**
69
+ Just tell the AI "make this a goal, with the acceptance written as…" and it will call `goal_declare` to lay down a contract.
70
+ > What you'll see: a "Goal Tracking" tab appears on the right of the session; the top bar shows the revision count, the engine state and the rounds run (e.g. "1 revision · engine active · 3 rounds run").
71
+
72
+ **Step 2 · Watch the progress on the panel.**
73
+ Open "Goal Tracking": the left column is "Goal Milestone Details", the middle column is "Outstanding Items", the right column is "Goal and Milestone Change Ledger".
74
+ > What you'll see: every acceptance item has a checkbox, and the card says "Done N/M".
75
+
76
+ **Step 3 · Tick a milestone.**
77
+ Tick it on the panel, or let the AI call `goal_accept` with the re-runnable verification command attached.
78
+ > What you'll see: that milestone gets a strikethrough and turns grey, and "Done N/M" goes up.
79
+
80
+ **Step 4 · Read the change log.**
81
+ Click "Change Log" in the top bar.
82
+ > What you'll see: a three-column table — what changed / why / what it became, every row with a timestamp and a reason.
83
+
84
+ ## How to read the panel
85
+
86
+ The panel lives in the "Goal Tracking" tab on the right of the session. There is exactly one top-level tab and no sub-tabs inside it.
87
+
88
+ **Top bar**: two buttons on the left — "Goal Execution Doc" (opens the execution doc for this goal) and "Change Log" (an overlay); in the middle, the one-line goal, the run state and the progress (Done N/M); on the right, "Settings".
89
+
90
+ **Three-column dashboard**:
91
+
92
+ | Column | Title | What you see in it |
93
+ | --- | --- | --- |
94
+ | Left | Goal Milestone Details | The acceptance items, each with its milestones underneath, each one tickable; ticked items get a strikethrough and turn grey |
95
+ | Middle | Outstanding Items | Three groups: "I owe you" (debts owed), "Your pending items" (things you said that haven't been filed yet), "Notices (reminders only, nothing to act on)" |
96
+ | Right | Goal and Milestone Change Ledger | A three-column table: what changed / why / what it became |
97
+
98
+ **Acceptance items can be ticked off to close**: an item that is not fully ticked shows a grey line underneath saying how many milestones / stages are still unticked; once all of them are ticked, that line says they are all complete and the goal can be closed, and the item turns grey with a strikethrough.
99
+
100
+ **How to read the "Outstanding Items" table**:
101
+
102
+ - One row per item: a settlement checkbox first, then the type / item / created time / actions.
103
+ - The table does **not** have an "owed for how long" column — overdue is expressed with color: over 24 hours is yellow, over 72 hours is red.
104
+ - Under the "item" cell there is a line of small grey text with the evidence and the retrieval hints.
105
+ - Ticking = settled, and it can be undone; once settled, the item moves into the "Completed" section (collapsed by default, searchable, reopenable).
106
+ - "Waive" is a single button; clicking it opens a small box for you to write a reason (it can be left empty). Writing back only touches the debt, **not the goal contract**.
107
+ - Top right there is also "Waive all (N)", with a second confirmation.
108
+ - By default only this session's debts are listed; at the bottom there is a collapsed section "Outstanding Items from other sessions" you can expand to see what other sessions still owe.
109
+ - Source labels come in three kinds: automatically detected ones show the name of the check (e.g. "git has uncommitted changes"), ones the model records show "Recorded by me", ones the panel adds show "Added by me".
110
+ - If the write-back fails, the checkbox snaps back and the server's reason is shown right there on the row — you never get a "nothing happened" click.
111
+ - "Show original" expands the words from that round in place, without switching sessions.
112
+
113
+ **Debts come in four kinds**:
114
+
115
+ | Type | Meaning | Example |
116
+ | --- | --- | --- |
117
+ | Promise | Something you said you'd do, not done yet | "I'll fill in the README later" |
118
+ | Owed delivery | A deliverable promised to someone | "I'll bring you that draft by Wednesday" |
119
+ | Loose end | Small unfinished bits | "That switch isn't back where it was" "CI is still red" |
120
+ | Temp file | A temp file this session wrote and hasn't cleaned up | `.work/scratch.tmp` |
121
+
122
+ **What the panel can't do**:
123
+
124
+ - It can't change the goal contract — only the model can, via `goal_declare` (first declaration) or `goal_amend` (amendment, **which must state a reason**).
125
+ - It only sees the requester's own copy — other sessions' content never leaks into yours.
126
+
127
+ ## The 15 tools at a glance
128
+
129
+ These tools are for the AI to use; you normally don't call them by hand — what you say makes it call them.
130
+
131
+ | Tool | What it does | When you'll run into it |
132
+ | --- | --- | --- |
133
+ | `goal_declare` | Lay down the goal contract for the first time (goal / allow / deny / acceptance) | When you set a goal for a long job |
134
+ | `goal_amend` | Amend the goal contract; a reason is required | When you find the goal has to change, or acceptance items need adding/removing |
135
+ | `goal_ack` | Record one reconciliation: this round's work matches the goal | When you want to keep a trace of "still on track" |
136
+ | `goal_milestone` | Record one piece of progress, stating "what got done" (doesn't change the contract, doesn't take a revision number) | When there is a milestone result mid-way you want to keep |
137
+ | `goal_accept` | Mark an acceptance item or one of its milestones done; must attach re-runnable evidence | When you see something really finished and want to tick it off |
138
+ | `goal_history` | Read this goal's change ledger (append-only, history can't be changed) | When you want to see how many times the goal changed and why each time |
139
+ | `goal_complete` | Close the goal out; it checks the acceptance items and open debts and lists what is missing if it isn't done | When you think the job can be closed |
140
+ | `goal_owe` | Record a debt (promise / owed delivery / loose end / temp file); evidence required | When you or the AI say "I'll do X later" and want it pinned down |
141
+ | `goal_settle` | Settle one debt (clear it / in progress / reopen / waive) | When you actually finished something, or decide to stop chasing it |
142
+ | `goal_debts` | Read-only query of the debt list, filterable by type and status | When you want to ask "what is still owed" without clicking through the UI |
143
+ | `goal_contract_claim` | One call records a reconciliation, pulls the claim board, and registers the file range this round will touch | When several sessions edit one repo and you fear they will overwrite each other |
144
+ | `goal_round` | Record one round: what this round set out to solve, and how it turned out | Once a long task is running and you want traceable progress |
145
+ | `goal_route` | Decide where a sentence that fits no acceptance item goes: append to the goal / replace it wholesale / record it as an outstanding item / ignore it (a reason is required) | When you raise a new request and the AI can't tell where it belongs |
146
+ | `goal_settle_queue` | Clear one outstanding item directly (done / dropped, reason required) | When the outstanding items list gets long and you want to clear one |
147
+ | `goal_status` | Read-only dashboard: how far the goal got (completed count / percentage / milestone list) | When you want to know "where are we now" without clicking through the UI |
148
+
149
+ ## Configuration options
150
+
151
+ Want to change the behavior? Start with this table — every option has a default, and you get the default if you leave it empty.
152
+
153
+ | Option | Type | Default | What it does |
154
+ |---|---|---|---|
155
+ | `maxGoalRounds` | integer | `256` | **Maximum automatic continuation rounds** when syncing to a DSH native goal (automatic continuation itself is kept: the goal stays armed and keeps running on its own) |
156
+ | `requireContract` | boolean | `false` | **No-contract hard gate** (off by default since 2026-11-11): without a goal contract, actions that change things are no longer refused. Pass `true` explicitly to restore the old behavior |
157
+ | `card.provider` | string | `siliconflow` | The model route (provider) used by the **auto goal card** (= route extraction); by default DSH's configured SiliconFlow free model |
158
+ | `card.model` | string | `Qwen/Qwen3-8B` | The model name used by the **auto goal card** (= route extraction); by default Qwen3-8B (measured 83% accuracy / 827ms) |
159
+ | `card.timeoutMs` | integer | `15000` | Timeout for the **auto goal card**'s model call (on timeout → keep the old card, don't write dirty data) |
160
+ | `card.maxOutputTokens` | integer | `300` | Max output tokens for the **auto goal card**'s model call (six fields, enough) |
161
+ | `nativeGoal` | boolean | `false` | **Sync this session's goal to the DSH native goal**: changing the goal on the board also changes the native goal, and changing the native goal also raises an inconsistency notice (off by default; `NATIVE_GOAL_DEFAULT_ENABLED = false`) |
162
+ | `critic.enabled` | boolean | `false` | Review method: `false` = code check only (default, **calls no model at all**); `true` = add the second-pass model review (semantic assertions can only rely on it) |
163
+ | `critic.provider` | string | `deepseek-account` | The provider used for the second-pass review |
164
+ | `critic.model` | string | `deepseek-flash` | The model used for the second-pass review |
165
+ | `critic.timeoutMs` | integer | `15000` | Timeout for the second-pass review (ms); a timeout is treated as "not reviewed" |
166
+ | `critic.rounds` | integer | `10` | Second-pass throttle: at most one review per N rounds per session |
167
+ | `stuck.threshold` | integer | `2` | How many consecutive rounds without progress on the same problem count as "stuck" (min 1, max 10) |
168
+ | `stuck.action` | one of three | `research-after` | What is forced after being stuck: `report-only` = stop and report / `research` = go research / `research-after` = research, then report |
169
+ | `shortfall.threshold` | integer | `3` | The threshold for the round-count **soft hint** (min 1, max 10): after a few bad rounds in a row you get one reminder |
170
+
171
+ ★ **`stuck.*` is a hard gate, `shortfall.*` is a soft hint** — these two rows plus `stuck.action` are the **underlying mechanism behind the three "round control" items on the panel's "Settings" page** (what the panel changes is written into the plugin's own config file and takes priority over the options here).
172
+
173
+ How `maxGoalRounds` is interpreted:
174
+
175
+ - **Left empty** (the option isn't in the config) → use the default **256**.
176
+ - **A positive integer** (`5`, `64`, `1024`…) → use it as is.
177
+ - **`0` (or `null`)** → **no limit** on rounds (when creating/changing the native goal the field is **not passed**, and the native goals service decides for itself).
178
+ - **An invalid value** (negative, not an integer, NaN, a string that isn't a number) → **fall back to 256**, and **the plugin log states the reason for the fallback**.
179
+
180
+ How to change it: override the `config` section in the composition layer under `id: dsh-goal-contract` (whole-section replacement, no deep merge):
181
+
182
+ ```yaml
183
+ - insert:
184
+ - id: dsh-goal-contract
185
+ name: dsh-goal-contract
186
+ config:
187
+ maxGoalRounds: 5 # ← for example: at most 5 automatic rounds; leave this line out and it is 256
188
+ ```
189
+
190
+ It takes effect after you **restart DSH** (the config is read once at mount time).
191
+ You can check it on a real machine: after creating or changing a goal, the `maxGoalRounds` returned by the DSH native goal is the configured value.
192
+
193
+ ## If you want to switch models: measured reference
194
+
195
+ The plugin defaults to **deepseek-account / deepseek-flash** for the second-pass review and **siliconflow / Qwen/Qwen3-8B** for route extraction. If you want to switch, here are measured readings you can use as a reference.
196
+
197
+ There are three places in this plugin that use a model: mapping your words onto an acceptance item, the second-pass review, and giving "plan / progress" suggestions at the end of a round. All three are "**the model only extracts, the code decides**", so there is just one requirement for the model: **it must be able to emit valid JSON**.
198
+
199
+ **Measured data** (same batch of extraction tasks; accuracy = the share of outputs the code could use directly):
200
+
201
+ | Model | Accuracy | Single-call latency | Notes |
202
+ | --- | --- | --- | --- |
203
+ | **Qwen3-8B** (`enable_thinking:false`) | **83%** | **827ms** | 0 failures; **the current first choice** |
204
+ | GLM-4-9B-0414 | 75% | 2011ms | Accurate but 2.4× slower |
205
+ | Qwen2.5-7B-Instruct | 75% | 4316ms | Same accuracy, 5× the latency |
206
+ | DeepSeek-R1-0528 | 58% | 12916ms | **Reasoning model: slow and inaccurate**, not suitable |
207
+ | Qwen3.5-4B | — | All calls timed out | 4B is too small, dropped outright |
208
+ | XingChen 29B | 25% | — | Output **malformed JSON**; more parameters made it worse |
209
+
210
+ **★ The key point: parameter count is not a predictor.** 8B Qwen3 (83%) beats 29B XingChen (25%) —
211
+ a bigger model doesn't mean it speaks the format you want.
212
+
213
+ **Selection criteria** (filter by these four, ignore the rest for now):
214
+ 1. **Supports JSON output** (you can't dig fields out of prose with regex);
215
+ 2. **Can turn thinking off** (`enable_thinking:false`): for Qwen3 that is **14027ms → 694ms (about 20×)**;
216
+ 3. **≥7B** (4B timed out on every call in the test);
217
+ 4. **Not a reasoning model** (R1 measured 12916ms; among the **candidates that can actually produce JSON** it has the lowest accuracy — the 25% XingChen 29B emits malformed JSON and Qwen3.5-4B times out entirely, so neither counts as "a candidate that can actually produce JSON").
218
+
219
+ **★ Model + code fallback → 92%** (higher than the single model's 83%): the part the model gets wrong
220
+ is caught by the code fallback (grounding check / missing fields / invalid JSON all degrade to "nothing extracted" — no guessing, no inventing).
221
+
222
+ **Only two backends are kept**:
223
+ - **`dsh-builtin`** (including SiliconFlow's free models) — the default first choice, works out of the box;
224
+ - **`local-model`** — local weights, data never leaves the machine.
225
+
226
+ **The default model for route extraction (mapping your words onto an acceptance item) = `siliconflow` / `Qwen/Qwen3-8B`**:
227
+
228
+ - **Source**: **the SiliconFlow free model DSH has already configured** — the `siliconflow` provider and
229
+ the `Qwen/Qwen3-8B` model **are already in the host's llm config**, so it works out of the box (no extra
230
+ key to configure, no account to sign up for).
231
+ - **Why this one**: in the table above it has the **highest accuracy (83%) and the lowest latency (827ms)**, and it isn't a reasoning model
232
+ (so thinking can be turned off → 20× faster).
233
+ - **Where to change it**: panel "Settings" page → the "Second-Pass Review Settings" card has one more row, "**Route extraction model**".
234
+ Two sources to choose from: **DSH configured models** (both provider and model are picked from **DSH's model list**, **nothing hard-coded**)
235
+ / **local model** (local weights that aren't in the list → type the provider and model name in by hand).
236
+ - **Where it lands**: an **independent entry** in the plugin config, which does **not overwrite** the second-pass group
237
+ (provider / model / fallback / rounds).
238
+ - **Old configs need no change**: an old config without this entry **falls back to the default automatically**
239
+ (`siliconflow` / `Qwen/Qwen3-8B`), and works just as well.
240
+ - **The second pass's own defaults are untouched**: still `deepseek-account` / `deepseek-flash`.
241
+ - **Failures are always silent**: model unavailable / timeout / invalid JSON → that round **writes no card and no queue entry**
242
+ (the previous result is kept, and the panel keeps showing the last card) — **it never throws and never writes dirty data**.
243
+
244
+ **JEV is not adopted**: the free channel (classifier.dev) and Laya self-hosting were both checked,
245
+ but an independent evaluation put it at **62.6% on the phishing-email task, while regex rules got 91.8%** —
246
+ **measurably worse than a small local model**, so it is not integrated.
247
+
248
+ ## What it can't do (known limitations)
249
+
250
+ These are the things it can't do — better to say them up front than to find out later.
251
+
252
+ **It is not a security boundary. Only two things can really stop you: loop detection and stuck detection. Everything else is "stop for one round" or "just a reminder".**
253
+
254
+ | Mechanism | Default threshold | Hardness | What happens after it fires |
255
+ |---|---|---|---|
256
+ | Loop detection | 3 | **Truly hard** | Blocked for good; you have to change the approach |
257
+ | Stuck detection | 2 | **Truly hard** | It asks you directly (stop and report / go research / research then report) |
258
+ | Consecutive tool failures | 6 | Stops one round | Answering "continue" lets it through |
259
+ | Repeated text | 30 | Stops one round | Same |
260
+ | Round soft hint | 3 | **Purely soft** | Reminds only, doesn't block |
261
+ | Drift guard (forbidden paths / commands) | No threshold | Hard refusal | The call is refused outright |
262
+
263
+ - **Only tools that take a file path argument can be blocked.** Running a script on the command line that edits files gets around the lock — there is no physical enforcement layer here.
264
+ - **Members of the same session do not lock against each other.** The task graph already handles the ordering, otherwise it would deadlock itself.
265
+ - **The panel can't change the goal contract**; only the model can, via `goal_declare` / `goal_amend` (amendments must state a reason).
266
+ - **The panel only sees the requester's own copy**; other sessions' content never leaks into yours.
267
+ - **Temp file debts must have their file deleted before they can be settled** (settling checks whether the path is still there); if you don't want to delete it, waive it (leaves a trace, can be undone). The plugin **only records, it never deletes anything for you**.
268
+ - **Semantic judgments rely on code, not on the model.** The second review model (if you enabled it) only records, it never blocks; when the model is unavailable, times out, or returns invalid JSON, everything degrades gracefully — no blocking, no conviction. A reviewer that isn't sure is more dangerous than no reviewer.
269
+ - **When extraction isn't accurate, it is better to queue it than to attach it wrongly.** Your exact words are always kept, but the cost is that "Outstanding Items" may keep piling up.
270
+ - **"Show original" only expands inside the current panel**; it doesn't switch to another session.
271
+
272
+ ## Where the full docs are
273
+
274
+ For the details: implementation notes, design decisions and the change history live in `docs/`, where `docs/implementation-notes.md` is an internal developer memo. The plugin's origins and design intent are in [`ORIGIN.md`](./ORIGIN.md), and the version changes are in [`CHANGELOG.md`](./CHANGELOG.md).
275
+
276
+ ## Problems / feedback
277
+
278
+ The repository is at <https://github.com/Eason-22/dsh-goal-contract>; please open an issue for problems and suggestions: <https://github.com/Eason-22/dsh-goal-contract/issues>.
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # dsh-goal-contract
2
2
 
3
- 当前版本:0.2.4
3
+ **中文** | [English](README.en.md)
4
+
5
+ 当前版本:0.2.6
4
6
 
5
7
  **你走开的时候,AI 的目标还在(相对)受控地往前走。**
6
8
 
@@ -93,6 +95,8 @@ dsh plugin --profile <你的 profile 名> add dsh-goal-contract
93
95
  | 中 | 未完结事项 | 分三组:「我欠你的」(欠着的账)、「你说的待定」(你说过但还没归位的话)、「异常提醒(纯提醒,不用处理)」 |
94
96
  | 右 | 目标和里程碑变更台账 | 三列表:改了什么 / 为什么 / 变成什么样 |
95
97
 
98
+ **验收可勾选(结案)**:左列里没勾完的那条,下面灰字写「还差 N 个里程碑 / 阶段没勾」;全部勾完时那行字改成「全部里程碑 / 阶段已完成,可以结案了」,条目变删除线变灰。
99
+
96
100
  **「未完结事项」这张表怎么读**:
97
101
 
98
102
  - 一行一条,前面是结清勾选框,后面是类型 / 事项 / 产生时间 / 操作。
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- /* source-sha256: cbb0959b08e7f1f4 */
1
+ /* source-sha256: 9d57d7aa4307c0df */
2
2
  /* dsh-goal-contract 客户端产物(由 `node src/client.js` 从 src/client.js 生成,请勿手改) */
3
3
  window.__ModuleLoader__.load({
4
4
  id: 'dsh-goal-contract',
@@ -1618,6 +1618,11 @@ window.__ModuleLoader__.load({
1618
1618
  if (type === ANOMALY_KIND) return true;
1619
1619
  const check = String(debt.check ?? '').trim();
1620
1620
  if (check === TOOL_ANOMALY_CHECK_ID || check === ANOMALY_CHECK_ID) return true;
1621
+ // ★ 2026-11-28:文本重复被拦下的那条。**必须与服务端 src/debts.js 的
1622
+ // TEXT_REPEAT_ANOMALY_CHECK_ID 同步**(本文件自己写着「改一处就要改另一处」)。
1623
+ // 当前运行时前端拿到的是归约后的 type='anomaly',走上面第一条就命中;
1624
+ // 这里补登记是为了「前端将来直接读原始账本条目」时不会漏判。
1625
+ if (check === 'text-repeat-interrupted') return true;
1621
1626
  const content = String(debt.content ?? '');
1622
1627
  return content.includes('可能坏了') && (type === '' || type === 'loose-end');
1623
1628
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-goal-contract",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "type": "module",
5
5
  "description": "Helps keep an AI agent's goal under control while you are away. It cannot silently change the goal, completing a milestone needs a real command exit code, and it stops on repeated failures, loops or text repetition instead of grinding all night.",
6
6
  "license": "MIT",
package/src/client.js CHANGED
@@ -1612,6 +1612,11 @@ export function isAnomalyDebt(debt) {
1612
1612
  if (type === ANOMALY_KIND) return true;
1613
1613
  const check = String(debt.check ?? '').trim();
1614
1614
  if (check === TOOL_ANOMALY_CHECK_ID || check === ANOMALY_CHECK_ID) return true;
1615
+ // ★ 2026-11-28:文本重复被拦下的那条。**必须与服务端 src/debts.js 的
1616
+ // TEXT_REPEAT_ANOMALY_CHECK_ID 同步**(本文件自己写着「改一处就要改另一处」)。
1617
+ // 当前运行时前端拿到的是归约后的 type='anomaly',走上面第一条就命中;
1618
+ // 这里补登记是为了「前端将来直接读原始账本条目」时不会漏判。
1619
+ if (check === 'text-repeat-interrupted') return true;
1615
1620
  const content = String(debt.content ?? '');
1616
1621
  return content.includes('可能坏了') && (type === '' || type === 'loose-end');
1617
1622
  }
package/src/debts.js CHANGED
@@ -108,6 +108,18 @@ export const ANOMALY_CHECK_ID = 'tool-anomaly';
108
108
  */
109
109
  export const TOOL_ANOMALY_CHECK_ID = 'tool-failed-broken';
110
110
 
111
+ /**
112
+ * 「文本重复被拦下」那条**异常提醒**的 check id(2026-11-28)。
113
+ *
114
+ * ★ 为什么单独一个 id:这条不是「工具坏了」,是**轮次控制**拦下的输出重复 ——
115
+ * 共用旧 id 的话,面板上分不清是哪种异常。
116
+ * ★ 身份靠 `check` 认(见 {@link isAnomalyDebt} 与 `reduceDebts`):
117
+ * 所以这个 id **必须**在这两处的 check 白名单里登记 ——
118
+ * 不登记的话,这条读回来既不算异常提醒,又因为落盘时类型留空而**整条消失**
119
+ * (比看不见更糟:用户连「被拦过」都不知道)。
120
+ */
121
+ export const TEXT_REPEAT_ANOMALY_CHECK_ID = 'text-repeat-interrupted';
122
+
111
123
  /**
112
124
  * 异常提醒的**一句话说明**(面板分组标题 / 收尾文案共用)。
113
125
  */
@@ -141,6 +153,8 @@ export function isAnomalyDebt(debt) {
141
153
  if (type === ANOMALY_KIND) return true;
142
154
  const check = String(debt.check ?? '').trim();
143
155
  if (check === TOOL_ANOMALY_CHECK_ID || check === ANOMALY_CHECK_ID) return true;
156
+ // ★ 2026-11-28:文本重复被拦下的那条(专属 check id)也是异常提醒。
157
+ if (check === TEXT_REPEAT_ANOMALY_CHECK_ID) return true;
144
158
  const content = String(debt.content ?? '');
145
159
  return content.includes('可能坏了') && (type === '' || type === 'loose-end');
146
160
  }
@@ -224,6 +238,8 @@ export const AUTO_CHECK_LABELS = Object.freeze({
224
238
  'temp-leftover': '本会话写过的临时路径仍存在',
225
239
  'tool-failed': '最近有失败的工具调用',
226
240
  'tool-failed-broken': '工具异常提醒(这个工具可能坏了)',
241
+ // ★ 2026-11-28:文本重复被拦下的那条(专属 check id,见 TEXT_REPEAT_ANOMALY_CHECK_ID)。
242
+ 'text-repeat-interrupted': '文本重复被拦截(已截断本轮)',
227
243
  });
228
244
 
229
245
  /** 欠了多久开始**标黄**(24 小时)。 */
@@ -444,6 +460,9 @@ export function reduceDebts(entries) {
444
460
  const anomaly = rawType === ANOMALY_KIND
445
461
  || rawCheck === TOOL_ANOMALY_CHECK_ID
446
462
  || rawCheck === ANOMALY_CHECK_ID
463
+ // ★ 2026-11-28:文本重复被拦下的那条(专属 check id)同样归 anomaly ——
464
+ // 不登记的话,这条读回来既不是异常提醒,又因类型留空被整条丢掉。
465
+ || rawCheck === TEXT_REPEAT_ANOMALY_CHECK_ID
447
466
  || (rawContent.includes('可能坏了') && (rawType === '' || rawType === 'loose-end'));
448
467
  const type = anomaly ? ANOMALY_KIND : (isDebtKind(rawType) ? rawType : '');
449
468
  if (type === '') continue;
package/src/index.js CHANGED
@@ -123,7 +123,12 @@ import {
123
123
  resolveMaxGoalRounds,
124
124
  } from './tools.js';
125
125
  import {
126
+ // ★ 2026-11-28:文本重复被拦下时写一条「异常提醒」——
127
+ // 用户原话「代码原本的设计是拦截了要暴露在前端」,而 steer 发的是
128
+ // source:{kind:'system'} 的消息(DSH 0.1.7 起聊天区不渲染 ⇒ 看不见)。
129
+ ANOMALY_KIND,
126
130
  AUTO_CHECK_IDS,
131
+ TEXT_REPEAT_ANOMALY_CHECK_ID,
127
132
  buildDebtBriefing,
128
133
  classifyErrorClass,
129
134
  describeDebt,
@@ -1753,7 +1758,7 @@ export const name = 'dsh-goal-contract';
1753
1758
  export const SERVICE_NAME = 'goalContract';
1754
1759
 
1755
1760
  /** 版本号。必须与 package.json 的 version 一致(测试会核对这两处不漂)。 */
1756
- export const PLUGIN_VERSION = '0.2.4';
1761
+ export const PLUGIN_VERSION = '0.2.6';
1757
1762
 
1758
1763
  // ── 配置声明(挂进 DSH 设置页) ─────────────────────────────────────────────
1759
1764
  //
@@ -4011,6 +4016,46 @@ export function buildDebtCompletionReminder({
4011
4016
  };
4012
4017
  }
4013
4018
 
4019
+ /**
4020
+ * 造「文本重复被拦下」那条**异常提醒**的载荷(纯函数,零依赖)。
4021
+ *
4022
+ * ★ 为什么单独拎出来(2026-11-28,用户原话「代码原本的设计是拦截了要暴露在前端」):
4023
+ * ① 记录**怎么写**与**怎么写进账本**分开 —— 写进账本那一段在 `apply()` 里(要账本服务),
4024
+ * 这一段是纯计算,可以被直接验(临时脚本 / 真机都能调)。
4025
+ * ② 写进账本之后它会出现在面板的「异常提醒(纯提醒,不用处理)」那一组
4026
+ * (client.js 的 DASHBOARD_ANOMALY_GROUP_TITLE)—— 这是**唯一**一条
4027
+ * 「拦了但聊天区看不见」的闸的可见出口。
4028
+ *
4029
+ * ★ detail 的字段**可能缺**(`count` / `unit` / `kind` 都可能没有)——
4030
+ * 一律容错,绝不因为字段缺失抛错(抛错会连累流内截断)。
4031
+ *
4032
+ * @param {{count?: number, unit?: string, kind?: string}} [detail] 命中详情。
4033
+ * @returns {{type: string, content: string, evidence: string, dueHint: string, check: string}}
4034
+ */
4035
+ export function buildTextRepeatAnomalyRecord(detail) {
4036
+ const rawCount = Number(detail?.count);
4037
+ const countText = Number.isFinite(rawCount) && rawCount > 0
4038
+ ? String(Math.floor(rawCount))
4039
+ : '?';
4040
+ const rawUnit = typeof detail?.unit === 'string' ? detail.unit : '';
4041
+ const unitText = rawUnit.trim() === '' ? '' : rawUnit.slice(0, 40);
4042
+ const kindText = String(detail?.kind ?? '').trim();
4043
+ const content = `文本重复被拦截(已截断本轮):同一段输出连续重复已达上限 ${countText} 次(到这个数就截断,不是总共只重复了这么多次)`
4044
+ + (unitText !== '' ? `,重复内容「${unitText}」` : '')
4045
+ + '。'
4046
+ + '这条是纯提醒:不用清账、不挡收尾;想处理可以自行处理。';
4047
+ const evidence = `llm/stream(文本重复检测):连续重复已达上限 ${countText} 次(配置阈值)`
4048
+ + (unitText !== '' ? `,样本「${unitText}」` : '')
4049
+ + (kindText !== '' ? `,类型 ${kindText}` : '');
4050
+ return {
4051
+ type: ANOMALY_KIND,
4052
+ content,
4053
+ evidence,
4054
+ dueHint: '',
4055
+ check: TEXT_REPEAT_ANOMALY_CHECK_ID,
4056
+ };
4057
+ }
4058
+
4014
4059
  export function apply(ctx, config = {}) {
4015
4060
  const logger = ctx?.logger ?? console;
4016
4061
  // ★ 配置里的可写叶子在宿主那边是「易失盒子」({ get() }),**不是值本身** ——
@@ -9084,8 +9129,86 @@ const rememberAction = (sessionId, execution) => {
9084
9129
  ? stuckState.interrupt : {};
9085
9130
  return (raw.textRepeat && typeof raw.textRepeat === 'object') ? raw.textRepeat : {};
9086
9131
  };
9132
+ // ★★★ 2026-11-28(用户原话:「代码原本的设计是拦截了要暴露在前端」):
9133
+ // 文本重复被拦下时,除了给模型发纠偏提示,还要给**用户**留一条看得见的痕迹。
9134
+ // 病根(本文件 :9060 那段注释自证):steer 发的是 `source:{kind:'system'}` 的消息,
9135
+ // 而 DSH 0.1.7 起聊天区**不渲染 context 类消息** ⇒ 提示写了也看不见 ⇒ 拦了等于静默。
9136
+ // 另外两条闸(toolFail / loop)走 `{kind:'deny', reason:…}`,屏幕上能看到 ——
9137
+ // **只有 textRepeat 这条是看不见的**。
9138
+ // 做法:走**已有的异常提醒通道**(type=anomaly,纯提醒、不用清账、不挡收尾),
9139
+ // 面板上会落在「异常提醒(纯提醒,不用处理)」那一组(client.js 的 DASHBOARD_ANOMALY_GROUP_TITLE)。
9140
+ //
9141
+ // ★ onBreak 只拿得到 agent(拿不到 sessionId)⇒ 用 agent 反查会话 id。
9142
+ // WeakMap:不拦强引用,agent 被回收后这条映射自动消失。
9143
+ /** @type {WeakMap<object, string>} */
9144
+ const agentSessionIds = new WeakMap();
9145
+ /**
9146
+ * 文本重复被拦下 → 写一条**异常提醒**(用户看得见;纯提醒,不用清账)。
9147
+ *
9148
+ * ★ 写失败**绝不能连累截断**:全程 try/catch,失败只 warn。
9149
+ *
9150
+ * @param {any} agent 被拦下那一轮的 agent(用来反查会话 id)。
9151
+ * @param {{count?: number, unit?: string, kind?: string}} detail 命中详情(字段可能缺)。
9152
+ * @returns {Promise<void>}
9153
+ */
9154
+ const noteTextRepeatAnomaly = async (agent, detail) => {
9155
+ try {
9156
+ const sid = (agent && typeof agent === 'object')
9157
+ ? (agentSessionIds.get(agent) ?? '')
9158
+ : '';
9159
+ if (sid === '') {
9160
+ logger.warn?.(`[${name}] 文本重复已命中,但反查不到会话 id,没能记异常提醒(不影响截断)`);
9161
+ return;
9162
+ }
9163
+ if (!debts || typeof debts.add !== 'function') {
9164
+ logger.warn?.(`[${name}] 欠账服务不可用,没能记异常提醒(不影响截断)`);
9165
+ return;
9166
+ }
9167
+ // ★ 载荷怎么写见 {@link buildTextRepeatAnomalyRecord}(纯函数;字段缺失也容错,不许抛错)。
9168
+ const record = buildTextRepeatAnomalyRecord(detail);
9169
+ const content = record.content;
9170
+ // ★ 同一会话里**一模一样**的那条不重复记(免得刷屏)——
9171
+ // 读清单失败时**照写不误**(读失败只是没法去重,不许因此丢掉这条提醒)。
9172
+ try {
9173
+ const existing = await debts.list(sid);
9174
+ const duplicated = (Array.isArray(existing) ? existing : []).some((one) => one
9175
+ && String(one.check ?? '') === TEXT_REPEAT_ANOMALY_CHECK_ID
9176
+ && String(one.content ?? '') === content
9177
+ && String(one.status ?? 'open') !== 'done');
9178
+ if (duplicated) {
9179
+ logger.info?.(`[${name}] 同一条文本重复提醒已经在账本里,不重复记(${TEXT_REPEAT_ANOMALY_CHECK_ID})`);
9180
+ return;
9181
+ }
9182
+ } catch (error) {
9183
+ logger.debug?.(`[${name}] 读账本去重失败(照写不误):${error?.message ?? error}`);
9184
+ }
9185
+ const result = await debts.add({
9186
+ sessionId: sid,
9187
+ type: record.type,
9188
+ content: record.content,
9189
+ evidence: record.evidence,
9190
+ dueHint: record.dueHint,
9191
+ check: record.check,
9192
+ source: 'auto',
9193
+ anchor: null,
9194
+ });
9195
+ if (result?.ok === true) {
9196
+ logger.info?.(`[${name}] 已记一条异常提醒(${TEXT_REPEAT_ANOMALY_CHECK_ID}):${content}`);
9197
+ } else {
9198
+ logger.warn?.(`[${name}] 异常提醒没记上(不影响截断):${result?.error ?? '未知原因'}`);
9199
+ }
9200
+ } catch (error) {
9201
+ logger.warn?.(`[${name}] 异常提醒写入失败(不影响截断):${error?.message ?? error}`);
9202
+ }
9203
+ };
9087
9204
  const streamBreaker = createStreamBreaker({
9088
- getAgent: (sid) => resolveAgentOfSession(null, sid),
9205
+ getAgent: (sid) => {
9206
+ const resolved = resolveAgentOfSession(null, sid);
9207
+ if (resolved && typeof resolved === 'object') {
9208
+ agentSessionIds.set(resolved, String(sid ?? ''));
9209
+ }
9210
+ return resolved;
9211
+ },
9089
9212
  // ★ 判据照抄 dsh-loop-guard 的 `TextRepetitionDetector`:
9090
9213
  // **连续 N 个规范化后完全相同的 text-delta** 才算重复。
9091
9214
  // 不用行级判据 —— 流式输出常常是碎片(「好。」「执行。」轮转),
@@ -9106,6 +9229,14 @@ const rememberAction = (sessionId, execution) => {
9106
9229
  // 下一轮很可能照旧重复,等于没修。
9107
9230
  // 形状沿用 session.append 用过、宿主已经接受的那一份 UserMessage。
9108
9231
  onBreak: (agent, detail) => {
9232
+ // ① 用户可见的那一份:**异常提醒**(写账本 ⇒ 面板「异常提醒」组里看得见)。
9233
+ // ★ 写失败绝不能连累截断 —— try/catch 包住,失败只 warn。
9234
+ try {
9235
+ void noteTextRepeatAnomaly(agent, detail);
9236
+ } catch (error) {
9237
+ logger.warn?.(`[${name}] 异常提醒写入失败(不影响截断):${error?.message ?? error}`);
9238
+ }
9239
+ // ② 给模型的纠偏提示(原有行为,一个字没改)—— 让模型别再重复下去。
9109
9240
  if (!agent || typeof agent.steer !== 'function') return;
9110
9241
  agent.steer({
9111
9242
  id: randomUUID(),
@@ -9114,7 +9245,7 @@ const rememberAction = (sessionId, execution) => {
9114
9245
  content: [{
9115
9246
  type: 'text',
9116
9247
  text: '【轮次控制】刚才那段输出被判定为**连续重复**,已截断本轮。\n'
9117
- + `依据:同一段内容连续出现 ${detail?.count ?? '?'} 次`
9248
+ + `依据:同一段内容连续重复已达上限 ${detail?.count ?? '?'} 次(到这个数就截断,不是总次数)`
9118
9249
  + (detail?.unit ? `(「${String(detail.unit).slice(0, 40)}」)` : '')
9119
9250
  + '\n'
9120
9251
  + '\n'
@@ -11,6 +11,12 @@
11
11
  // 一个 delta 里根本不含换行,按行切永远等不到「整行重复」。
12
12
  // 对方实测过:行级/字符级各有盲区,先照抄它验证过的那一条,不自行发挥。
13
13
  //
14
+ // **2026-11-28 补一条**:抄来的那条只看「整条 delta 规范化后完全相同」,而这次事故
15
+ // 是模型在 **reasoning 通道**里把同一个 8~9 字符单元连续刷了 699 次 —— reasoning 的
16
+ // 分片碎成 1~5 个字符,规范化后多半是空串,那条判据一个都没吃到。
17
+ // 所以补了「尾部连续周期重复」这条(见下面 detectCycleRepeat / createCycleDetector),
18
+ // 并把 reasoning-delta 也纳入计数。两条判据任一命中即算命中。
19
+ //
14
20
  // 三条硬约束(全部来自实测踩坑,见 docs/llm-stream-break-contract.md):
15
21
  // ① 有 tool-call 块开着时**不许切** —— 闭合它会提交半截调用并被执行;
16
22
  // 不闭合,BlockAssembler 也会从 delta 组装出同样的半截调用。两种都会跑一个
@@ -46,6 +52,23 @@ export function normalizeDelta(text) {
46
52
  return text.replace(/\s+/g, ' ').trim();
47
53
  }
48
54
 
55
+ /**
56
+ * 把阈值解析成可用的数字。**两条判据共用这一份口径。**
57
+ *
58
+ * ★ 显式关闭(Infinity)和「值无效」必须走两条路。
59
+ * 前者是 index.js 在开关关掉时**主动**传下来的(见 index.js「关着时给 Infinity ⇒ 永不命中」),
60
+ * 必须原样保留成 Infinity;若走兜底分支,`Number.isFinite(Infinity) === false`
61
+ * 会把它当成「没配」并填 DEFAULT_DELTA_REPEAT_MAX,于是**开关关掉了却照样会截断**。
62
+ *
63
+ * @param {unknown} max
64
+ * @returns {number} `Infinity`(显式关闭)或一个 ≥1 的整数
65
+ */
66
+ function resolveRepeatLimit(max) {
67
+ if (max === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY;
68
+ if (Number.isFinite(max) && max >= 1) return Math.floor(max);
69
+ return DEFAULT_DELTA_REPEAT_MAX;
70
+ }
71
+
49
72
  /**
50
73
  * 连续相同 delta 的计数器。
51
74
  *
@@ -53,13 +76,8 @@ export function normalizeDelta(text) {
53
76
  * 每次喂一个 delta,相同就 +1、不同就归 1;返回是否达到阈值。
54
77
  */
55
78
  export function createDeltaCounter(max) {
56
- // ★ 显式关闭(Infinity)和「值无效」必须走两条路。
57
- // 前者是 index.js 在开关关掉时**主动**传下来的(见 index.js「关着时给 Infinity ⇒ 永不命中」),
58
- // 必须原样保留成 Infinity;若走下面的兜底分支,`Number.isFinite(Infinity) === false`
59
- // 会把它当成「没配」并填 DEFAULT_DELTA_REPEAT_MAX,于是**开关关掉了却照样会截断**。
60
- const limit = max === Number.POSITIVE_INFINITY
61
- ? Number.POSITIVE_INFINITY
62
- : (Number.isFinite(max) && max >= 1 ? Math.floor(max) : DEFAULT_DELTA_REPEAT_MAX);
79
+ // ★ 显式关闭(Infinity)和「值无效」必须走两条路 —— 口径见 resolveRepeatLimit。
80
+ const limit = resolveRepeatLimit(max);
63
81
  let last = null;
64
82
  let count = 0;
65
83
  return {
@@ -79,6 +97,107 @@ export function createDeltaCounter(max) {
79
97
  };
80
98
  }
81
99
 
100
+ // ── 尾部「连续周期重复」判据(2026-11-28 新增) ──────────────────────────
101
+ //
102
+ // 事故复盘:模型在 **reasoning 通道**里把 `\n\n**做。**` 这个 8~9 字符的单元
103
+ // 连续重复了 699 次(turn 458 step 1,2400 个 reasoning 分片,text 分片 0 个),
104
+ // 而旧判据只看「整条 delta 规范化后完全相同」—— reasoning 的分片碎成 1~5 个字符,
105
+ // 规范化后多半是空串,旧判据一个都没吃到。
106
+ //
107
+ // 这条判据换个问法:**只看尾巴** —— 末尾是不是同一个 L 字符单元连续重复了 N 次?
108
+ // L 取 3..64(单元下限 3:单字符刷屏交给原判据;上限 64:再长就不像「一个单元」了)。
109
+ //
110
+ // ★ 只认连续,绝不累计:中间插进任何不匹配的内容,周期立刻断掉重新数;
111
+ // 计数不跨 delta、跨 block、跨 step。
112
+
113
+ /** 周期判据的单元长度下限:单字符刷屏(「0」「|」)归原判据管。 */
114
+ export const MIN_CYCLE_UNIT_LEN = 3;
115
+ /** 周期判据的单元长度上限。 */
116
+ export const MAX_CYCLE_UNIT_LEN = 64;
117
+ /** 报给模型 / 写进日志的重复单元最多留多少字符。 */
118
+ export const MAX_CYCLE_UNIT_PREVIEW = 40;
119
+
120
+ /**
121
+ * 在一段文本的**尾部**找「同一个 L 字符单元连续重复」的段。
122
+ *
123
+ * 判据:末尾能凑出 `minCount` 个完全相同的 L 字符块 ⇒ 命中。
124
+ * 只取**最小**的 L(最小周期):`ABCABCABC` 报出来的是 `ABC` 而不是 `ABCABC`。
125
+ *
126
+ * @param {string} text
127
+ * @param {{minCount?: number, minLen?: number, maxLen?: number}} [options]
128
+ * minCount:至少要连续几个单元(默认 2)。
129
+ * @returns {{count: number, unit: string, kind: 'cycle'} | null}
130
+ */
131
+ export function detectCycleRepeat(text, options = {}) {
132
+ if (typeof text !== 'string' || text === '') return null;
133
+ const minCount = Number.isFinite(options.minCount) && options.minCount >= 1
134
+ ? Math.floor(options.minCount) : 2;
135
+ const minLen = Number.isFinite(options.minLen) && options.minLen >= 1
136
+ ? Math.floor(options.minLen) : MIN_CYCLE_UNIT_LEN;
137
+ const maxLen = Number.isFinite(options.maxLen) && options.maxLen >= minLen
138
+ ? Math.floor(options.maxLen) : MAX_CYCLE_UNIT_LEN;
139
+ const len = text.length;
140
+ for (let p = minLen; p <= maxLen; p += 1) {
141
+ const need = minCount * p;
142
+ // p 越大 need 越大;长度不够就不用往下试了。
143
+ if (len < need) break;
144
+ // 末尾 need 个字符是不是以 p 为周期?错的 p 几乎第一格就露馅(成本 O(1))。
145
+ let ok = true;
146
+ for (let j = len - 1; j >= len - need + p; j -= 1) {
147
+ if (text[j] !== text[j - p]) { ok = false; break; }
148
+ }
149
+ if (!ok) continue;
150
+ // 命中:往回找周期后缀的起点 → 真实的连续次数 + 重复单元。
151
+ let start = len - 1;
152
+ while (start >= p && text[start] === text[start - p]) start -= 1;
153
+ // 关系在 start 处断了 ⇒ 周期段从 start-p+1 开始(起点允许是半个单元)。
154
+ const regionStart = start >= p ? start - p + 1 : 0;
155
+ const count = Math.floor((len - regionStart) / p);
156
+ // 单元取**末尾这 p 个字符**:模型最后正在重复的那一段(不是某次旋转)。
157
+ const unit = text.slice(len - p).slice(0, MAX_CYCLE_UNIT_PREVIEW);
158
+ return { count, unit, kind: 'cycle' };
159
+ }
160
+ return null;
161
+ }
162
+
163
+ /**
164
+ * 造一个「尾部连续周期重复」检测器(**每个 block 一个**)。
165
+ *
166
+ * 它只维护该 block 已输出文本的**尾部窗口**(最近 `limit * MAX_CYCLE_UNIT_LEN`
167
+ * 个字符,不无限增长),每次喂一段文本就问一遍:
168
+ * 「末尾是不是同一个 L 字符单元连续重复了 ≥ limit 次?」
169
+ *
170
+ * @param {number} [max] 阈值;`Infinity` 表示显式关闭 ⇒ 永不命中。
171
+ * @returns {{push(text: string): {count: number, unit: string, kind: 'cycle'} | null,
172
+ * count: number, unit: string, limit: number}}
173
+ */
174
+ export function createCycleDetector(max) {
175
+ const limit = resolveRepeatLimit(max);
176
+ const windowSize = Number.isFinite(limit)
177
+ ? Math.max(limit * MAX_CYCLE_UNIT_LEN, MAX_CYCLE_UNIT_LEN)
178
+ : MAX_CYCLE_UNIT_LEN;
179
+ let tail = '';
180
+ let hit = null;
181
+ return {
182
+ /** 喂一段文本;命中返回 { count, unit, kind: 'cycle' },没命中返回 null。 */
183
+ push(text) {
184
+ if (hit !== null) return hit; // 已命中就不再重算
185
+ if (limit === Number.POSITIVE_INFINITY) return null; // 显式关闭 ⇒ 永不命中
186
+ if (typeof text !== 'string' || text === '') return null;
187
+ tail += text;
188
+ if (tail.length > windowSize) tail = tail.slice(tail.length - windowSize);
189
+ const found = detectCycleRepeat(tail, { minCount: limit });
190
+ if (found !== null) hit = found;
191
+ return hit;
192
+ },
193
+ /** 命中时的连续次数(没命中过是 0)。 */
194
+ get count() { return hit === null ? 0 : hit.count; },
195
+ /** 命中时的重复单元(没命中过是空串)。 */
196
+ get unit() { return hit === null ? '' : hit.unit; },
197
+ get limit() { return limit; },
198
+ };
199
+ }
200
+
82
201
  /**
83
202
  * 造一个 `llm/stream` 监听器。
84
203
  *
@@ -87,8 +206,10 @@ export function createDeltaCounter(max) {
87
206
  * @param {number} [deps.max] 连续相同 delta 的阈值,缺省 60
88
207
  * @param {(options: any) => boolean} [deps.isAgentLoopRequest]
89
208
  * 可选精确过滤器;缺省时退化为「有 sessionId」。
90
- * @param {(agent: any, detail: {count: number, unit: string}) => void} [deps.onBreak]
209
+ * @param {(agent: any, detail: {count: number, unit: string, kind: 'cycle' | 'same'}) => void} [deps.onBreak]
91
210
  * 截断成功后回调,用来给模型发纠偏提示。
211
+ * `kind` 区分命中的是哪条判据:`'same'` = 整条 delta 规范化后连续相同;
212
+ * `'cycle'` = 尾部同一单元连续周期重复(这次事故的形态)。
92
213
  * @param {object} [deps.logger]
93
214
  * @returns {(options: any, next: () => AsyncIterable<any>) => AsyncIterable<any>}
94
215
  */
@@ -105,19 +226,25 @@ export function createStreamBreaker({ getAgent, max, isAgentLoopRequest, onBreak
105
226
  return (async function* guarded() {
106
227
  /** index → { blockType, text },顺序即流顺序。 */
107
228
  const open = new Map();
108
- /** 本步的连续相同 delta 计数器。`max` 允许是函数 —— 这样改配置不用重启。 */
109
- const counter = createDeltaCounter(typeof max === 'function' ? max() : max);
229
+ /**
230
+ * index → 该 block 的两条判据。
231
+ *
232
+ * ★ 按 block 分开记:用户口径「不许跨 block 累加总数」——
233
+ * reasoning 块和 text 块各记各的,混着来不算连续。
234
+ */
235
+ const judges = new Map();
236
+ /** 阈值。`max` 允许是函数 —— 这样改配置不用重启(每条流开始时求值一次)。 */
237
+ const limit = resolveRepeatLimit(typeof max === 'function' ? max() : max);
110
238
 
111
239
  for await (const chunk of next()) {
112
240
  // 记录 block 生命周期,供命中时闭合用。
113
241
  if (chunk?.type === 'block-start') {
114
242
  open.set(chunk.index, { blockType: String(chunk.blockType ?? 'text'), text: '' });
243
+ judges.delete(chunk.index);
115
244
  } else if (chunk?.type === 'block-end') {
116
245
  open.delete(chunk.index);
117
- } else if (chunk?.type === 'text-delta') {
118
- const block = open.get(chunk.index);
119
- if (block !== undefined) block.text += chunk.text ?? '';
120
- } else if (chunk?.type === 'reasoning-delta') {
246
+ judges.delete(chunk.index);
247
+ } else if (chunk?.type === 'text-delta' || chunk?.type === 'reasoning-delta') {
121
248
  const block = open.get(chunk.index);
122
249
  if (block !== undefined) block.text += chunk.text ?? '';
123
250
  }
@@ -125,25 +252,38 @@ export function createStreamBreaker({ getAgent, max, isAgentLoopRequest, onBreak
125
252
  // 先把这一块原样交给下游 —— 已产生的输出一律保留。
126
253
  yield chunk;
127
254
 
128
- // 只在可见文本 delta 上判(reasoning 合理会复述计划,不参与这条判据)。
129
- if (chunk?.type !== 'text-delta') continue;
255
+ // ★ text-delta 与 reasoning-delta **都参与**判据。
256
+ // 旧实现只判 text-delta(注释写「reasoning 合理会复述计划」),
257
+ // 漏掉了这次事故的真实形态:模型在 reasoning 通道里把同一个单元刷了几百次。
258
+ if (chunk?.type !== 'text-delta' && chunk?.type !== 'reasoning-delta') continue;
130
259
 
131
- if (!counter.push(chunk.text)) continue;
260
+ let judge = judges.get(chunk.index);
261
+ if (judge === undefined) {
262
+ judge = { same: createDeltaCounter(limit), cycle: createCycleDetector(limit) };
263
+ judges.set(chunk.index, judge);
264
+ }
265
+ // 两条判据任一命中即算命中;周期判据优先(它能报出「在重复哪一段」)。
266
+ const cycleHit = judge.cycle.push(chunk.text);
267
+ const sameHit = judge.same.push(chunk.text);
268
+ let hit = null;
269
+ if (cycleHit !== null) hit = cycleHit;
270
+ else if (sameHit) hit = { count: judge.same.count, unit: judge.same.unit ?? '', kind: 'same' };
271
+ if (hit === null) continue;
132
272
 
133
273
  const tail = buildTerminal(open);
134
274
  if (tail === null) {
135
275
  // 有非 text/reasoning 的块开着 —— 切不安全,本轮放弃。
136
- logger?.warn?.(`[轮次控制] 文本重复命中,但有非文本块开着,放弃截断(连续 ${counter.count} 次相同)`);
276
+ logger?.warn?.(`[轮次控制] 文本重复命中,但有非文本块开着,放弃截断(连续 ${hit.count} 次,判据 ${hit.kind})`);
137
277
  continue;
138
278
  }
139
279
  for (const out of tail) yield out;
140
- logger?.info?.(`[轮次控制] 已截断本轮(连续 ${counter.count} 个相同 delta,阈值 ${counter.limit})`);
280
+ logger?.info?.(`[轮次控制] 已截断本轮(连续 ${hit.count} 次${hit.kind === 'cycle' ? '同一单元' : '相同 delta'},阈值 ${limit})`);
141
281
  // ★ 截断之后必须告诉模型「为什么停、接下来做什么」。
142
282
  // 没有这一步,截断就只是把话掐断:模型不知道自己被拦了,下一轮很可能照旧重复。
143
283
  // 失败绝不连累流(steer 收到的形状不对时宿主会抛),只记一笔。
144
284
  if (typeof onBreak === 'function') {
145
285
  try {
146
- onBreak(agent, { count: counter.count, unit: counter.unit ?? '' });
286
+ onBreak(agent, { count: hit.count, unit: hit.unit ?? '', kind: hit.kind });
147
287
  } catch (error) {
148
288
  logger?.warn?.(`[轮次控制] 纠偏提示发送失败(不影响截断):${error?.message ?? error}`);
149
289
  }