dsh-plain-talk 0.1.14 → 0.1.15

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/dsh/check.js CHANGED
@@ -1,250 +1,325 @@
1
- // Reply checker for dsh-plain-talk.
2
- //
3
- // This is deliberately a checker, not a gate: it reports what a reader would
4
- // stumble on, with the exact replacement form. The model decides what to keep.
5
- //
6
- // Three principles learned from real sessions in this workspace:
7
- // - Common terms and project names are not errors. Only opaque codes the
8
- // reader has never seen (EXP-7, DEV-1K, run-3) need a first-use gloss.
9
- // - A pointer is not a citation: `file.py:42` alone sends the reader away.
10
- // - Cross-turn wording ("上述", "上一轮") is the main reason a report cannot
11
- // be read on its own.
12
-
13
- const ALLOW = new Set([
14
- 'api', 'json', 'jsonl', 'yaml', 'yml', 'html', 'css', 'http', 'https', 'url', 'uri',
15
- 'cli', 'ui', 'ux', 'gpu', 'cpu', 'ram', 'ssd', 'hdd', 'ai', 'llm', 'sdk', 'ide',
16
- 'csv', 'tsv', 'ts', 'js', 'py', 'sh', 'md', 'txt', 'png', 'jpg', 'jpeg', 'svg',
17
- 'gif', 'webp', 'sql', 'xml', 'toml', 'npm', 'pnpm', 'git', 'ssh', 'dns', 'tcp',
18
- 'udp', 'tls', 'ssl', 'jwt', 'oauth', 'cors', 'orm', 'crud', 'rest', 'grpc',
19
- 'wasm', 'dom', 'smtp', 'imap', 'vpn', 'utf8', 'utf-8', 'utf16', 'utf-16',
20
- 'sha1', 'sha256', 'sha-256', 'sha512', 'sha-512', 'md5', 'x86', 'x64', 'arm64',
21
- 'mp3', 'mp4', 'pdf', 'h264', 'hevc', 'ipv4', 'ipv6', 'k8s', 'i18n', 'l10n',
22
- '2d', '3d', '4k', 'v1', 'v2', 'v3', 'v4', 'ci', 'pr', 'id', 'ok', 'vs', 'iso',
23
- 'doi', 'arxiv', 'p50', 'p95', 'p99', '2x', '4x', '8x', '16x', 'gpt', 'llm',
24
- 'linux', 'windows', 'macos', 'node', 'react', 'github', 'python', 'javascript',
25
- 'typescript', 'docker', 'sqlite', 'postgres', 'redis',
26
- ])
27
-
28
- const MODEL_FAMILY = /^(?:gpt|claude|gemini|llama|qwen|deepseek|mistral|phi|o1|o3|o4|glm|kimi|mimo|hy)\d*[-.]?\d*/i
29
-
30
- const BACKREF_ZH = [
31
- '上述', '上面', '前述', '前文', '前面提到', '前面说', '之前提到', '之前说',
32
- '此前', '上一步', '上一轮', '前一轮', '刚才', '该方案', '该项', '该任务',
33
- '前者', '后者', '如上', '见上文', '先前', '那次', '前面', '之前',
34
- ]
35
- const BACKREF_EN = [
36
- 'as mentioned', 'aforementioned', 'as discussed', 'the above', 'previous step',
37
- 'earlier', 'previously', 'the former', 'the latter',
38
- ]
39
-
40
- const PLUMBING = [
41
- /\bsession[-_][0-9a-z-]{6,}/i,
42
- /子代理|子会话|父代理|父会话|\bsubagent\b|\bparent agent\b|report sent to/i,
43
- /\b(?:plain_talk_check|run_code|ops_bash|ops_grep|todo_write)\b/,
44
- ]
45
-
46
- const PREAMBLE = /^(好的|好|当然|没问题|收到|明白|我来|让我|让我先|我们先|首先,我|先看一[下看])/
47
- const CLOSER = /(需要我|要不要|如果你愿意|希望(这|以上)|随时告诉我|还需要我|要我继续)/
48
-
49
- const FILE_EXT = 'py|js|mjs|cjs|ts|tsx|json|jsonl|md|ya?ml|toml|sh|ps1|bat|csv|tsv|txt|ipynb|log|html|css|tex|bib|pdf|zip|sql|db|pt|pth|ckpt|npy|npz|parquet|docx|xlsx|pptx'
50
-
51
- const IDENT_PATTERNS = [
52
- ['file', new RegExp(`(?:[A-Za-z]:[\\\\/]|\\/)?[A-Za-z0-9_.-]+(?:[\\\\/][A-Za-z0-9_.-]+)*\\.(?:${FILE_EXT})\\b`, 'gi')],
53
- ['hash', /\b[0-9a-f]{7,40}\b/gi],
54
- ['snake', /\b[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+\b/g],
55
- ['camel', /\b[a-z]+[A-Z][A-Za-z0-9]*\b|\b(?:[A-Z][a-z0-9]+){2,}[A-Za-z0-9]*\b|\b[A-Z][a-z]+[A-Z]{2,}[A-Za-z0-9]*\b/g],
56
- ['acronym', /\b[A-Z]{2,8}\b/g],
57
- ['code', /\b[A-Za-z]{1,10}[-_.]?\d{1,6}[A-Za-z]?\b|\b\d{1,4}[A-Za-z]{1,6}\b/g],
58
- ]
59
-
60
- export const LIMITS = {
61
- boxChars: 300,
62
- boxLines: 12,
63
- listRun: 5,
64
- identifierWarns: 8,
65
- }
66
-
67
- const cjkCount = (s) => (s.match(/[\u4e00-\u9fff]/g) ?? []).length
68
- const latinCount = (s) => (s.match(/[A-Za-z]/g) ?? []).length
69
- const len = (s) => [...s].length
70
-
71
- function stripCode(text) {
72
- return text
73
- .replace(/```[\s\S]*?```/g, ' ')
74
- .replace(/`[^`\n]*`/g, ' ')
75
- }
76
-
77
- export function isCommonTerm(term) {
78
- const text = String(term ?? '').trim()
79
- if (!text) return false
80
- return ALLOW.has(text.toLowerCase()) || MODEL_FAMILY.test(text)
81
- }
82
-
83
- export function scanIdentifiers(input) { const text = stripCode(String(input ?? ''))
84
- const found = []
85
- for (const [kind, re] of IDENT_PATTERNS) {
86
- re.lastIndex = 0
87
- let m
88
- while ((m = re.exec(text))) {
89
- const raw = m[0].replace(/[.,;:]+$/, '')
90
- if (!raw) continue
91
- found.push({ kind, token: raw, start: m.index, end: m.index + raw.length })
92
- }
93
- }
94
- found.sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start))
95
- const accepted = []
96
- for (const item of found) {
97
- if (accepted.some((a) => item.start < a.end && item.end > a.start)) continue
98
- accepted.push(item)
99
- }
100
- return accepted
101
- }
102
-
103
- function isAllowed(token, known) {
104
- const lower = token.toLowerCase()
105
- if (ALLOW.has(lower)) return true
106
- if (MODEL_FAMILY.test(token)) return true
107
- // Durations and multipliers ("10m", "3s", "4x") are measurements, not names.
108
- if (/^\d+(?:ms|s|m|h|d|w|k|m|b|x)$/i.test(token)) return true
109
- // Product-style names (AcmeService_V2, DataHub_V3) are project vocabulary the
110
- // reader already holds; a lower-case internal key (tier_reaudit) is not.
111
- if (/^[A-Za-z0-9]+(?:_[A-Za-z0-9]+)+$/.test(token) && (token.match(/[A-Z]/g) ?? []).length >= 2) return true
112
- if (known && (known.has(token) || known.has(lower))) return true
113
- return false
114
- }
115
-
116
- function explainedAfter(text, end) {
117
- const after = text.slice(end, end + 60)
118
- const m = /^\s*[((]([^))]{4,})[))]/.exec(after)
119
- if (!m) return false
120
- return cjkCount(m[1]) >= 3 || latinCount(m[1]) >= 8
121
- }
122
-
123
- function knownFrom(text, known) {
124
- return { text, known }
125
- }
126
-
127
- /**
128
- * Analyze one reply draft.
129
- *
130
- * @param draft - the reply text the model is about to send.
131
- * @param options - `knownTokens` (project/user vocabulary) and `language`
132
- * (`zh` when the user writes Chinese).
133
- * @returns issues plus the measurements the README benchmark reports.
134
- */
135
- export function analyze(draft, options = {}) {
136
- const text = String(draft ?? '')
137
- const known = new Set((options.knownTokens ?? []).map((t) => String(t)))
138
- const knownLower = new Set([...known].map((t) => t.toLowerCase()))
139
- const language = options.language ?? 'unknown'
140
- const issues = []
141
-
142
- const add = (severity, rule, message, fix) => issues.push({ severity, rule, message, fix })
143
-
144
- const narrative = stripCode(text)
145
-
146
- // 1. Cross-turn wording.
147
- const backrefs = [
148
- ...BACKREF_ZH.filter((w) => narrative.includes(w)),
149
- ...BACKREF_EN.filter((w) => narrative.toLowerCase().includes(w)),
150
- ]
151
- if (backrefs.length) {
152
- add('error', 'backref', `出现回指词:${backrefs.slice(0, 5).join('、')}。`, '把指代的东西重新写一遍,读者没有前文可翻。')
153
- }
154
-
155
- // 2. Internal plumbing.
156
- const plumbing = PLUMBING.find((re) => re.test(narrative))
157
- if (plumbing) {
158
- add('error', 'internal', '出现会话号、子代理或工具名等内部信息。', '删掉;只写用户能看见的对象。')
159
- }
160
-
161
- // 3. Pointer-only citations.
162
- const pointers = []
163
- const pointerRe = new RegExp(`(?:[A-Za-z]:[\\\\/]|/)?[\\w.-]+(?:[\\\\/][\\w.-]+)*\\.(?:${FILE_EXT}):\\d+`, 'gi')
164
- pointerRe.lastIndex = 0
165
- let pm
166
- while ((pm = pointerRe.exec(text))) pointers.push(pm[0])
167
- if (pointers.length) {
168
- const unquoted = pointers.filter((pointer) => {
169
- const at = text.indexOf(pointer)
170
- const window = text.slice(Math.max(0, at - 220), at + pointer.length + 220)
171
- return !/「[^」]{4,}」|"[^"]{4,}"|『[^』]{4,}』|`[^`]{4,}`|```/.test(window)
172
- })
173
- if (unquoted.length) {
174
- add('error', 'citation', `只有位置没有原文:${unquoted.slice(0, 3).join('、')}。`, '把那几行原文贴出来,再标位置。')
175
- }
176
- }
177
-
178
- // 4. Unexplained opaque identifiers.
179
- const seen = new Set()
180
- const unknown = []
181
- for (const token of scanIdentifiers(narrative)) {
182
- if (seen.has(token.token)) continue
183
- seen.add(token.token)
184
- if (isAllowed(token.token, known) || isAllowed(token.token, knownLower)) continue
185
- if (explainedAfter(narrative, token.end)) continue
186
- unknown.push(token.token)
187
- }
188
- if (unknown.length) {
189
- add(
190
- 'warn',
191
- 'identifier',
192
- `有 ${unknown.length} 个代号没有说明:${unknown.slice(0, 6).join('、')}${unknown.length > 6 ? ' 等' : ''}。`,
193
- '第一次出现写成「EXP-7(一句话说明它是什么)」;用户在本对话用过的词和项目名不用解释。',
194
- )
195
- }
196
-
197
- // 5. Shape.
198
- const lines = text.split('\n').filter((l) => l.trim())
199
- const cjk = cjkCount(narrative)
200
- if (cjk > LIMITS.boxChars || lines.length > LIMITS.boxLines) {
201
- add('warn', 'length', `回复有 ${cjk} 个汉字、${lines.length} 行,超过默认的 ${LIMITS.boxChars} 字 / ${LIMITS.boxLines} 行。`, '删掉读者不决策所需的内容;用户要细节时再展开。')
202
- }
203
-
204
- let run = 0
205
- let maxRun = 0
206
- for (const line of text.split('\n')) {
207
- if (/^\s*(?:[-*+]|\d+[.)])\s+/.test(line)) { run++; maxRun = Math.max(maxRun, run) } else if (!line.trim()) { run = 0 }
208
- }
209
- if (maxRun > LIMITS.listRun) {
210
- add('warn', 'list', `有一段列表 ${maxRun} 条,超过 5 条。`, '合并或只留最要紧的五条。')
211
- }
212
-
213
- const first = lines[0] ?? ''
214
- if (PREAMBLE.test(first)) {
215
- add('warn', 'preamble', `开头是「${first.slice(0, 20)}」,属于寒暄或过程宣告。`, '第一行直接给结论。')
216
- }
217
- const tail = text.slice(-180)
218
- const closer = CLOSER.exec(tail)
219
- if (closer) {
220
- add('warn', 'closer', `结尾出现「${closer[0]}」,在征求额外任务。`, '删掉;需要下一步就只给一个具体动作。')
221
- }
222
-
223
- // 6. Language mismatch.
224
- const total = cjk + latinCount(narrative)
225
- const cjkRatio = total === 0 ? 0 : cjk / total
226
- if (language === 'zh' && cjkRatio < 0.2 && latinCount(narrative) > 40) {
227
- add('warn', 'language', '用户用中文提问,但这条回复几乎全是英文。', '用中文写;命令、路径、报错原文保持原样。')
228
- }
229
- const hasNext = /下一步|接下来要|接下来请|你可以先|建议你先|Next step/i.test(text)
230
- if (!hasNext && (cjk > 200 || lines.length > 10)) {
231
- add('warn', 'next', '回复较长,但没有给出一个明确的下一步。', '结尾补一个用户现在就能做的事;没有就写"没有待办"。')
232
- }
233
-
234
- return {
235
- ok: !issues.some((i) => i.severity === 'error'),
236
- issues,
237
- stats: {
238
- chars: text.length,
239
- cjk,
240
- lines: lines.length,
241
- cjkRatio: Number(cjkRatio.toFixed(3)),
242
- identifiers: unknown.length,
243
- backrefs: backrefs.length,
244
- maxListRun: maxRun,
245
- hasNext,
246
- },
247
- }
248
- }
249
-
250
- export { cjkCount, latinCount, len }
1
+ // Reply checker for dsh-plain-talk.
2
+ //
3
+ // Advisory, not a gate. It reports what a reader would stumble on and how to
4
+ // fix it; the model decides what to keep.
5
+ //
6
+ // What it deliberately does NOT judge: reply length, list count, whether a
7
+ // next step exists, whether a term is professional, and whether "此前" is
8
+ // legitimate. Those are only wrong when the reader genuinely lacks the context,
9
+ // which this checker cannot know.
10
+ //
11
+ // What it does report:
12
+ // - cross-turn wording that sends the reader to a message they may not have;
13
+ // - opaque codes the reader has never seen (EXP-7, DEV-1K, run-3);
14
+ // - pointer-only citations (a file:line with no finding);
15
+ // - internal plumbing (session ids, tool names) — a warning, because a user
16
+ // who asked for those details should get them.
17
+
18
+ const ALLOW = new Set([
19
+ 'api', 'json', 'jsonl', 'yaml', 'yml', 'html', 'css', 'http', 'https', 'url', 'uri',
20
+ 'cli', 'ui', 'ux', 'gpu', 'cpu', 'ram', 'ssd', 'hdd', 'ai', 'llm', 'sdk', 'ide',
21
+ 'csv', 'tsv', 'ts', 'js', 'py', 'sh', 'md', 'txt', 'png', 'jpg', 'jpeg', 'svg',
22
+ 'gif', 'webp', 'sql', 'xml', 'toml', 'npm', 'pnpm', 'git', 'ssh', 'dns', 'tcp',
23
+ 'udp', 'tls', 'ssl', 'jwt', 'oauth', 'cors', 'orm', 'crud', 'rest', 'grpc',
24
+ 'wasm', 'dom', 'smtp', 'imap', 'vpn', 'utf8', 'utf-8', 'utf16', 'utf-16',
25
+ 'sha1', 'sha256', 'sha-256', 'sha512', 'sha-512', 'md5', 'x86', 'x64', 'arm64',
26
+ 'mp3', 'mp4', 'pdf', 'h264', 'hevc', 'ipv4', 'ipv6', 'k8s', 'i18n', 'l10n',
27
+ '2d', '3d', '4k', 'v1', 'v2', 'v3', 'v4', 'ci', 'pr', 'id', 'ok', 'vs', 'iso',
28
+ 'doi', 'arxiv', 'p50', 'p95', 'p99', '2x', '4x', '8x', '16x', 'gpt', 'llm',
29
+ 'linux', 'windows', 'macos', 'node', 'react', 'github', 'python', 'javascript',
30
+ 'typescript', 'docker', 'sqlite', 'postgres', 'redis',
31
+ ])
32
+
33
+ const MODEL_FAMILY = /^(?:gpt|claude|gemini|llama|qwen|deepseek|mistral|phi|o1|o3|o4|glm|kimi|mimo|hy)\d*[-.]?\d*/i
34
+
35
+ const BACKREF_ZH = [
36
+ '上述', '上面', '前述', '前文', '前面提到', '前面说', '之前提到', '之前说',
37
+ '此前', '上一步', '上一轮', '前一轮', '刚才', '该方案', '该项', '该任务',
38
+ '前者', '后者', '如上', '见上文', '先前', '那次', '前面', '之前',
39
+ ]
40
+ const BACKREF_EN = [
41
+ 'as mentioned', 'aforementioned', 'as discussed', 'the above', 'previous step',
42
+ 'earlier', 'previously', 'the former', 'the latter',
43
+ ]
44
+
45
+ const PLUMBING = [
46
+ /\bsession[-_][0-9a-z-]{6,}/i,
47
+ /子代理|子会话|父代理|父会话|\bsubagent\b|\bparent agent\b|report sent to/i,
48
+ /\b(?:plain_talk_check|plain_talk_vocab|run_code|ops_bash|ops_grep|todo_write)\b/,
49
+ ]
50
+
51
+ const PREAMBLE = /^(好的|好|当然|没问题|收到|明白|我来|让我|让我先|我们先|首先,我|先看一[下看])/
52
+ const CLOSER = /(需要我|要不要|如果你愿意|希望(这|以上)|随时告诉我|还需要我|要我继续)/
53
+
54
+ // An explicit gloss right after the code: 是指 / 指的是 / 也就是 / —— / :
55
+ const GLOSS_MARKER = /^\s*(?:是指|指的是|意思是|也就是|即|——|--|:)\s*\S/
56
+
57
+ const FILE_EXT = 'py|js|mjs|cjs|ts|tsx|json|jsonl|md|ya?ml|toml|sh|ps1|bat|csv|tsv|txt|ipynb|log|html|css|tex|bib|pdf|zip|sql|db|pt|pth|ckpt|npy|npz|parquet|docx|xlsx|pptx'
58
+
59
+ const IDENT_PATTERNS = [
60
+ ['file', new RegExp(`(?:[A-Za-z]:[\\\\/]|\\/)?[A-Za-z0-9_.-]+(?:[\\\\/][A-Za-z0-9_.-]+)*\\.(?:${FILE_EXT})\\b`, 'gi')],
61
+ ['hash', /\b[0-9a-f]{7,40}\b/gi],
62
+ ['snake', /\b[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)+\b/g],
63
+ ['camel', /\b[a-z]+[A-Z][A-Za-z0-9]*\b|\b(?:[A-Z][a-z0-9]+){2,}[A-Za-z0-9]*\b|\b[A-Z][a-z]+[A-Z]{2,}[A-Za-z0-9]*\b/g],
64
+ ['acronym', /\b[A-Z]{2,8}\b/g],
65
+ ['code', /\b[A-Za-z]{1,10}[-_.]?\d{1,6}[A-Za-z]?\b|\b\d{1,4}[A-Za-z]{1,6}\b/g],
66
+ ]
67
+
68
+ export const LIMITS = {
69
+ // 篇幅与条数默认不设上限:长度不是质量指标(见 test/REPORT.md、ANALYSIS-0.1.11-to-0.1.14.md)。
70
+ // 需要阈值时,调用 analyze(draft, { limits: { boxChars: n, boxLines: n, listRun: n } })。
71
+ boxChars: Infinity,
72
+ boxLines: Infinity,
73
+ listRun: Infinity,
74
+ }
75
+
76
+ const cjkCount = (s) => (s.match(/[\u4e00-\u9fff]/g) ?? []).length
77
+ const latinCount = (s) => (s.match(/[A-Za-z]/g) ?? []).length
78
+ const len = (s) => [...s].length
79
+
80
+ /** Drop fenced code blocks: their contents are not prose and not identifiers. */
81
+ function stripFences(text) {
82
+ return String(text).replace(/```[\s\S]*?```/g, ' ')
83
+ }
84
+
85
+ /**
86
+ * Prose view: fenced blocks and inline code both removed. Inline code holds
87
+ * names, not sentences, so it must not trigger wording rules.
88
+ */
89
+ function proseOnly(text) {
90
+ return stripFences(text).replace(/`[^`\n]*`/g, ' ')
91
+ }
92
+
93
+ export function isCommonTerm(term) {
94
+ const text = String(term ?? '').trim()
95
+ if (!text) return false
96
+ return ALLOW.has(text.toLowerCase()) || MODEL_FAMILY.test(text)
97
+ }
98
+
99
+ /**
100
+ * Names in a draft. Inline code IS scanned: `EXP-7` and `rules.js` in backticks
101
+ * are exactly the names a reader may not know.
102
+ */
103
+ export function scanIdentifiers(input) {
104
+ const text = stripFences(String(input ?? ''))
105
+ const found = []
106
+ for (const [kind, re] of IDENT_PATTERNS) {
107
+ re.lastIndex = 0
108
+ let m
109
+ while ((m = re.exec(text))) {
110
+ const raw = m[0].replace(/[.,;:]+$/, '')
111
+ if (!raw) continue
112
+ found.push({ kind, token: raw, start: m.index, end: m.index + raw.length })
113
+ }
114
+ }
115
+ found.sort((a, b) => a.start - b.start || (b.end - b.start) - (a.end - a.start))
116
+ const accepted = []
117
+ for (const item of found) {
118
+ if (accepted.some((a) => item.start < a.end && item.end > a.start)) continue
119
+ accepted.push(item)
120
+ }
121
+ return accepted
122
+ }
123
+
124
+ function isAllowed(token, known) {
125
+ const lower = token.toLowerCase()
126
+ if (ALLOW.has(lower)) return true
127
+ if (MODEL_FAMILY.test(token)) return true
128
+ // Durations and multipliers ("10m", "3s", "4x") are measurements, not names.
129
+ if (/^\d+(?:ms|s|m|h|d|w|k|m|b|x)$/i.test(token)) return true
130
+ // Product-style names (AcmeService_V2, DataHub_V3) are project vocabulary the
131
+ // reader already holds; a lower-case internal key (tier_reaudit) is not.
132
+ if (/^[A-Za-z0-9]+(?:_[A-Za-z0-9]+)+$/.test(token) && (token.match(/[A-Z]/g) ?? []).length >= 2) return true
133
+ if (known && (known.has(token) || known.has(lower))) return true
134
+ return false
135
+ }
136
+
137
+ function looksLikeGloss(text) {
138
+ return cjkCount(text) >= 3 || latinCount(text) >= 8
139
+ }
140
+
141
+ // A name can also be introduced by a preceding clause: "为推理流程增加实例
142
+ // 验证的实验 EXP-7". Require a 的-noun right before the name so that merely
143
+ // mentioning a code is still reported.
144
+ const PREFIX_GLOSS = /的[^\s,。;、]{1,10}\s*$/
145
+
146
+ /** A gloss can sit before the name as well as after it, and need not be in parentheses. */
147
+ function isCjkGloss(value) {
148
+ const body = String(value || "")
149
+ if (cjkCount(body) < 4) return false
150
+ return !/[<>{}\[\]$;]|=>|::|\(\)/.test(body)
151
+ }
152
+
153
+ function explainedNear(text, start, end) {
154
+ const before = text.slice(Math.max(0, start - 32), start)
155
+ const mBefore = /[((]([^))]{4,})[))]\s*$/.exec(before)
156
+ if (mBefore && looksLikeGloss(mBefore[1])) return true
157
+ if (cjkCount(before) >= 4 && PREFIX_GLOSS.test(before)) return true
158
+
159
+ const after = text.slice(end, end + 60).replace(/^[`"'”」』))\]]+/, "")
160
+ const mAfter = /^\s*[((]([^))]{4,})[))]/.exec(after)
161
+ if (mAfter && (looksLikeGloss(mAfter[1]) || isCjkGloss(mAfter[1]))) return true
162
+ if (GLOSS_MARKER.test(after)) return true
163
+ return false
164
+ }
165
+
166
+ /**
167
+ * Analyze one reply draft.
168
+ *
169
+ * @param draft - the reply text the model is about to send.
170
+ * @param options - `knownTokens` (confirmed reader vocabulary) and `language`
171
+ * (`zh` when the user writes Chinese).
172
+ * @returns issues plus the measurements the README benchmark reports.
173
+ */
174
+ export function analyze(draft, options = {}) {
175
+ const limits = { ...LIMITS, ...(options.limits ?? {}) }
176
+ const text = String(draft ?? '')
177
+ const known = new Set((options.knownTokens ?? []).map((t) => String(t)))
178
+ const knownLower = new Set([...known].map((t) => t.toLowerCase()))
179
+ const language = options.language ?? 'unknown'
180
+ const issues = []
181
+
182
+ const add = (severity, rule, message, fix) => issues.push({ severity, rule, message, fix })
183
+
184
+ const narrative = proseOnly(text)
185
+
186
+ // 1. Cross-turn wording. A warning: it is only wrong when the referent is not
187
+ // in this reply, which the checker cannot decide.
188
+ const backrefs = [
189
+ ...BACKREF_ZH.filter((w) => narrative.includes(w)),
190
+ ...BACKREF_EN.filter((w) => narrative.toLowerCase().includes(w)),
191
+ ]
192
+ if (backrefs.length) {
193
+ add(
194
+ 'warn',
195
+ 'backref',
196
+ `出现可能依赖前文说法:${backrefs.slice(0, 5).join('、')}。`,
197
+ '如果指的是本轮回复里已经说明过的内容,可以保留;否则把指代的东西写出来。',
198
+ )
199
+ }
200
+
201
+ // 2. Internal plumbing. A warning: a user who asked for the session id,
202
+ // commit hash or tool list should get it verbatim.
203
+ const plumbing = PLUMBING.find((re) => re.test(narrative))
204
+ if (plumbing) {
205
+ add(
206
+ 'warn',
207
+ 'internal',
208
+ '出现会话号、子代理或工具名等内部信息。',
209
+ '用户没要求就删掉;用户明确要看会话号、提交号或工具调用情况时,照给。',
210
+ )
211
+ }
212
+
213
+ // 3. Pointer-only citations: a location with no finding.
214
+ const pointers = []
215
+ const pointerRe = new RegExp(`(?:[A-Za-z]:[\\\\/]|/)?[\\w.-]+(?:[\\\\/][\\w.-]+)*\\.(?:${FILE_EXT}):\\d+`, 'gi')
216
+ let pointer
217
+ while ((pointer = pointerRe.exec(text))) pointers.push(pointer[0])
218
+ if (pointers.length) {
219
+ const bare = pointers.filter((item) => {
220
+ const at = text.indexOf(item)
221
+ const window = text.slice(Math.max(0, at - 260), at + item.length + 260)
222
+ const lineStart = text.lastIndexOf('\n', at) + 1
223
+ const lineEndRaw = text.indexOf('\n', at + item.length)
224
+ const lineEnd = lineEndRaw < 0 ? text.length : lineEndRaw
225
+ const line = text.slice(lineStart, lineEnd)
226
+ const sentence = line
227
+ if (/(发现|原因|报错|错误|异常|结果|根因|日志|堆栈|表现为|是因为|error|exception|traceback|panic)/i.test(sentence)) return false
228
+ return !/「[^」]{4,}」|"[^"]{4,}"|『[^』]{4,}』|```/.test(window)
229
+ })
230
+ if (bare.length) {
231
+ add(
232
+ 'warn',
233
+ 'citation',
234
+ `只给了位置、没给发现:${bare.slice(0, 3).join('、')}。`,
235
+ '先说那里写了什么、说明什么都行;要贴原文时贴关键那几行。',
236
+ )
237
+ }
238
+ }
239
+
240
+ // 4. Unexplained opaque identifiers.
241
+ const seen = new Set()
242
+ const unknown = []
243
+ const scannable = stripFences(text)
244
+ for (const token of scanIdentifiers(text)) {
245
+ if (seen.has(token.token)) continue
246
+ seen.add(token.token)
247
+ if (isAllowed(token.token, known) || isAllowed(token.token, knownLower)) continue
248
+ if (explainedNear(scannable, token.start, token.end)) continue
249
+ unknown.push(token.token)
250
+ }
251
+ if (unknown.length) {
252
+ add(
253
+ 'warn',
254
+ 'identifier',
255
+ `有 ${unknown.length} 个代号没有说明:${unknown.slice(0, 6).join('、')}${unknown.length > 6 ? ' 等' : ''}。`,
256
+ '第一次出现时用一句话说明它是什么;用户已经知道的词不用解释。',
257
+ )
258
+ }
259
+
260
+ // 5. Optional shape limits. Off by default; a caller may set them. When a
261
+ // caller does, the result is a statistic (info), never an error: length is
262
+ // not a quality verdict.
263
+ const lines = text.split('\n').filter((l) => l.trim())
264
+ const cjk = cjkCount(narrative)
265
+ if (limits.boxChars !== Infinity || limits.boxLines !== Infinity) {
266
+ if (cjk > limits.boxChars || lines.length > limits.boxLines) {
267
+ add(
268
+ 'info',
269
+ 'length',
270
+ `回复有 ${cjk} 个汉字、${lines.length} 行,超过调用方设定的 ${limits.boxChars} 个汉字 / ${limits.boxLines} 行。`,
271
+ '这是调用方设的阈值,不是表达规则;只在确实该删的时候删。',
272
+ )
273
+ }
274
+ }
275
+
276
+ let run = 0
277
+ let maxRun = 0
278
+ for (const line of text.split('\n')) {
279
+ if (/^\s*(?:[-*+]|\d+[.)])\s+/.test(line)) {
280
+ run++
281
+ maxRun = Math.max(maxRun, run)
282
+ } else if (!line.trim()) {
283
+ run = 0
284
+ }
285
+ }
286
+ if (maxRun > limits.listRun) {
287
+ add('info', 'list', `有一段列表 ${maxRun} 条,超过调用方设定的 ${limits.listRun} 条。`, '这是调用方设的阈值,不是表达规则。')
288
+ }
289
+
290
+ const first = lines[0] ?? ''
291
+ if (PREAMBLE.test(first)) {
292
+ add('warn', 'preamble', `开头是「${first.slice(0, 20)}」,属于寒暄或过程宣告。`, '第一行直接给结论。')
293
+ }
294
+ const closer = CLOSER.exec(text.slice(-180))
295
+ if (closer) {
296
+ add('warn', 'closer', `结尾出现「${closer[0]}」,在征求额外任务。`, '需要下一步就只给一个具体动作;不需要就不用问。')
297
+ }
298
+
299
+ // 6. Language mismatch, judged against the user's latest message only.
300
+ const total = cjk + latinCount(narrative)
301
+ const cjkRatio = total === 0 ? 0 : cjk / total
302
+ if (language === 'zh' && cjkRatio < 0.2 && latinCount(narrative) > 40) {
303
+ add('warn', 'language', '用户用中文提问,但这条回复几乎全是英文。', '用中文写;命令、路径、报错原文保持原样。')
304
+ }
305
+
306
+ // No "missing next step" rule: a finished answer may legitimately have none.
307
+ const hasNext = /下一步|接下来要|接下来请|你可以先|建议你先|Next step/i.test(text)
308
+
309
+ return {
310
+ ok: !issues.some((issue) => issue.severity === 'error'),
311
+ issues,
312
+ stats: {
313
+ chars: text.length,
314
+ cjk,
315
+ lines: lines.length,
316
+ cjkRatio: Number(cjkRatio.toFixed(3)),
317
+ identifiers: unknown.length,
318
+ backrefs: backrefs.length,
319
+ maxListRun: maxRun,
320
+ hasNext,
321
+ },
322
+ }
323
+ }
324
+
325
+ export { cjkCount, latinCount, len }