@mealsea/dsh-prompt-enhance 1.0.1 → 1.1.0

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.
@@ -0,0 +1,1253 @@
1
+ # 工作区感知 / 命令感知 / 语义 diff / 悬浮位置 —— 实现契约
2
+
3
+ - 版本:1.0(2026-12-06)
4
+ - 适用仓库:`D:\prompt_enhance`
5
+ - 适用文件:`index.js`(Host 半)、`client.js`(Client 半)、`test/host.mjs`、`test/smoke.mjs`
6
+ - 本文是 host-dev 与 client-dev 的唯一接口来源。两人只凭本文即可并行编码,不需要再互相确认字段。
7
+ - 与 `docs/dev/context-facts.md` 冲突时:**以本文为准**。`context-facts.md` §4.4「Client slot 拿不到 sessionId」已被 live Cordis Inspect 纠正:`conversation.input.left` 的 standardProps 明确带 `sessionId: SessionId`,本契约直接使用该 prop,不做被动 input source、不做「最近会话」兜底。
8
+
9
+ ---
10
+
11
+ ## 0. 硬约束(先读这一节,违反即返工)
12
+
13
+ 1. **只读**:Host 只允许调用 `workspaceFiles.read/list/search/stat` 与 `fs.resolve/contains`。禁止调用任何 `fs.writeText/editText/patchText/deleteFile/moveFile`,禁止任何 `workspaceFiles` 写操作(该服务本身也没有写方法)。不得为了「省事」用 Node `fs` 直接读文件。
14
+ 2. **隐私围栏**:`workspaceFiles.read` 允许工作区外绝对路径,服务不围栏。每次读取前必须用 `fs.resolve(workspaceRoot)` + `fs.resolve(relativePath)` + `fs.contains(root, target)` 预围栏;读取后再用返回的 `absolutePath` 做一次 `fs.contains` 复核。越界 → 不读、计入 `context.skippedFiles`。**绝不**降级到其它会话的工作区。
15
+ 3. **会话解析只有两条路**:`ctx.get('sessions').get(sessionId)?.header.cwd`(live)→ `await ctx.get('sessionPersistence').stat(sessionId)` 的 `header.cwd`(非 live)。两条都失败 → `context.enabled=false, context.skipped='no-workspace'`。**禁止**用 `sessions.list()` 取「最近会话」、禁止用 `sandboxPolicy.workspaceRoot` 猜当前会话根。
16
+ 4. **sessionId 来源**:Client 直接使用 slot standard prop `sessionId`,随 `conversation.input.left` 的 slotProps 传入(`EnhanceTrigger` 已收到全部 slotProps)。开启感知时 `sessionId` 必须随请求发送;缺失时 Host 只能降级为 `no-session`,不能猜。
17
+ 5. **预算双层**:Host 强制 `maxFiles / maxLinesPerFile / maxTokens` 三个上限;Client 只负责把设置值传下去并展示结果。任一上限触顶 → 立即停止,`context.truncated=true`。
18
+ 6. **token 估算唯一公式**:`estimateTokens(text) = Math.ceil(String(text).length / 3.5)`。Host、测试、文档统一使用它,Client 不重新估算。
19
+ 7. **命令名来源**:Client 只用 `InputState.claim.name`;**禁止**拆 `claim.token`(内建命令 token 是本地化词,例如 zh 的 `/目标`,字符串无法可靠还原)。Host 用 `ctx.get('commands').list(ctx.get('agents').get(sessionId))` 取描述;Client 不额外调 `remote.commands`。
20
+ 8. **感知失败不阻断改写**:`awareness_denied` / `awareness_failed` 只写入 `context.error`,HTTP 仍为 200,照常返回 `{text}`。它们不加入 `ERROR_CODES`,不产生 `panel.error.*` 文案。
21
+ 9. **悬浮提示不改变写回文本**:`SymbolText` 只用于预览渲染;`applyNow` / `undo` 仍然使用 `state.res.text` 纯字符串,任何 span 包装都不得进入写回内容。
22
+ 10. **文件所有权**:host-dev 只改 `index.js` 与 `test/host.mjs`;client-dev 只改 `client.js` 与 `test/smoke.mjs`。除本文外不得互相改文件;`package.json`、`cordis.patch.yml`、`locale/*.json` 不变。
23
+
24
+ ---
25
+
26
+ ## 1. 常量与共享定义
27
+
28
+ ### 1.1 Host 常量(`index.js` 顶部,模块作用域)
29
+
30
+ ```js
31
+ const CONTEXT_DEFAULTS = Object.freeze({ maxFiles: 5, maxLinesPerFile: 80, maxTokens: 800 })
32
+ const CONTEXT_LIMITS = Object.freeze({ maxFiles: 8, maxLinesPerFile: 160, maxTokens: 1200 })
33
+ const CONTEXT_MAX_HINTS = 6 // 每次最多用 6 个提示词
34
+ const CONTEXT_MAX_READ_CANDIDATES = 16 // 最多预读 16 个候选文件
35
+ const CONTEXT_MAX_SYMBOLS = 100 // 响应中 symbols 上限
36
+ const CONTEXT_TIMEOUT_MS = 2500 // 感知采集独立预算,超时降级,不影响模型改写
37
+ const CONTEXT_EXTENSIONS = new Set([
38
+ '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json', '.md',
39
+ '.css', '.scss', '.html', '.vue', '.svelte',
40
+ '.py', '.go', '.rs', '.java', '.kt', '.rb', '.php', '.cs',
41
+ '.c', '.h', '.cpp', '.hpp', '.sh', '.yml', '.yaml', '.toml',
42
+ ])
43
+ const CONTEXT_EXCLUDED_PREFIXES = [
44
+ '.git/', 'node_modules/', 'dist/', 'build/', 'coverage/',
45
+ '.next/', '.cache/', 'vendor/', '.agent-teams/',
46
+ ]
47
+ ```
48
+
49
+ `estimateTokens` 与 `contextFileScore` 必须是纯函数,便于单测。
50
+
51
+ ```js
52
+ /** 唯一 token 估算公式;参数会被 String() 化。 */
53
+ function estimateTokens(text) {
54
+ return Math.ceil(String(text == null ? '' : text).length / 3.5)
55
+ }
56
+ ```
57
+
58
+ ### 1.2 相对路径规范
59
+
60
+ 所有对外路径 `path` 一律是 **工作区相对、POSIX 分隔、无前导 `./`**:
61
+
62
+ ```js
63
+ function normalizeRelPath(path) {
64
+ return String(path == null ? '' : path).replace(/\\/g, '/').replace(/^\.\//, '')
65
+ }
66
+ ```
67
+
68
+ - `context.files[].path`、`symbols[].file`、`command` 里的路径全部使用该规范。
69
+ - `context.files[].absolutePath` 保留 Host 返回的原始绝对路径,仅用于审计展示。
70
+ - 绝对路径、以 `/` 开头的路径、包含 `..` 段的候选一律不进入读取(预围栏会再拒绝一次)。
71
+
72
+ ---
73
+
74
+ ## 2. A) 请求契约:`POST /api/prompt-enhance/enhance`
75
+
76
+ 路由不变,仍为 `ROUTE_PATHS`(`/api/prompt-enhance/enhance` 与 `/x-prompt-enhance/enhance`)。请求体是 JSON,在现有字段上**只增不改**:
77
+
78
+ ```jsonc
79
+ {
80
+ // ---- 旧字段,语义完全不变 ----
81
+ "text": "要改写的草稿正文(必填,trim 后非空,≤ 8000 字符)",
82
+ "locale": "zh | en | zh-CN | en-US | ...(可选,缺省按 zh)",
83
+ "provider": "deepseek(可选,必须与 model 同时出现)",
84
+ "model": "deepseek-chat(可选,必须与 provider 同时出现)",
85
+
86
+ // ---- 新字段,全部可选;旧 Client 不传时行为与当前完全一致 ----
87
+ "sessionId": "当前会话 id;awareness.enabled=true 时必填",
88
+ "awareness": {
89
+ "enabled": true, // 缺省 false;只有严格 true 才启用
90
+ "maxFiles": 5, // 缺省 5,夹到 [1, 8] 的整数
91
+ "maxLinesPerFile": 80, // 缺省 80,夹到 [1, 160] 的整数
92
+ "maxTokens": 800 // 缺省 800,夹到 [1, 1200] 的整数
93
+ },
94
+ "commandName": "goal" // 可选;无前导斜杠、小写、[a-z0-9][a-z0-9_-]{0,63}
95
+ }
96
+ ```
97
+
98
+ ### 2.1 Host 归一化规则(必须逐字实现)
99
+
100
+ ```js
101
+ function clampInt(value, fallback, min, max) {
102
+ const n = Number(value)
103
+ if (!Number.isFinite(n)) return fallback
104
+ return Math.min(max, Math.max(min, Math.floor(n)))
105
+ }
106
+
107
+ function normalizeAwarenessRequest(raw) {
108
+ const source = raw && typeof raw === 'object' ? raw : {}
109
+ return {
110
+ enabled: source.enabled === true,
111
+ maxFiles: clampInt(source.maxFiles, CONTEXT_DEFAULTS.maxFiles, 1, CONTEXT_LIMITS.maxFiles),
112
+ maxLinesPerFile: clampInt(source.maxLinesPerFile, CONTEXT_DEFAULTS.maxLinesPerFile, 1, CONTEXT_LIMITS.maxLinesPerFile),
113
+ maxTokens: clampInt(source.maxTokens, CONTEXT_DEFAULTS.maxTokens, 1, CONTEXT_LIMITS.maxTokens),
114
+ }
115
+ }
116
+
117
+ function normalizeCommandName(raw) {
118
+ if (typeof raw !== 'string') return ''
119
+ const name = raw.trim().replace(/^\/+/, '').toLowerCase()
120
+ return /^[a-z0-9][a-z0-9_-]{0,63}$/.test(name) ? name : ''
121
+ }
122
+ ```
123
+
124
+ - `awareness` 缺失、为 `null`、不是对象 → 等价于 `{ enabled: false }`。
125
+ - `enabled` 只认布尔 `true`;字符串 `"true"`、数字 `1` 都视为 false(防御性)。
126
+ - `sessionId`:`typeof === 'string'` 且 `trim()` 后非空且长度 ≤ 256 才有效;否则视为缺失(返回 `null`,不截断、不伪造):
127
+ ```js
128
+ const sessionId = typeof payload.sessionId === 'string'
129
+ && payload.sessionId.trim()
130
+ && payload.sessionId.trim().length <= 256
131
+ ? payload.sessionId.trim()
132
+ : null
133
+ ```
134
+ - `commandName` 归一化失败 → 视为未提供;不报错。
135
+ - 请求体仍是 64 KiB 上限;新字段很小,不会触发 `too_large`。
136
+
137
+ ### 2.2 旧字段兼容性判定(Host 测试必须覆盖)
138
+
139
+ 请求不含 `awareness` 时:
140
+
141
+ - 用户消息文本必须与当前实现**逐字节一致**(`rewrite` 收到的 `text` 就是原 `text`);
142
+ - 响应不得出现 `context`、`symbols`;
143
+ - 其它行为(模型选择、错误码、超时、清洗)保持现状。
144
+
145
+ ---
146
+
147
+ ## 3. B) 响应契约
148
+
149
+ 成功响应仍是 HTTP 200:
150
+
151
+ ```jsonc
152
+ {
153
+ "text": "改写后的正文",
154
+ "notes": [], // 保留字段;Host 目前恒为空数组,Client 兼容缺省
155
+
156
+ "context": { /* 3.1;仅当请求 awareness.enabled === true 时出现 */ },
157
+ "symbols": [ /* 3.2;与 context 同时出现,context 不出现时也不出现 */ ],
158
+ "command": { /* 3.3;仅当请求 commandName 有效时出现,与 awareness 无关 */ }
159
+ }
160
+ ```
161
+
162
+ - `awareness.enabled !== true` → **不出现** `context` 与 `symbols`。这样旧 Client 完全不受影响。
163
+ - `commandName` 有效 → 即使 awareness 关闭也返回 `command`(命令感知独立于文件感知)。
164
+ - 模型改写失败仍走现有 502 / 499 / 503 错误响应;感知失败**不改变** HTTP 状态。
165
+
166
+ ### 3.1 `context` 对象(字段全部唯一定义)
167
+
168
+ ```ts
169
+ interface ContextFile {
170
+ path: string // 工作区相对 POSIX 路径
171
+ absolutePath: string // 审计用绝对路径(已通过 fs.contains 围栏)
172
+ startLine: number // 本次纳入的起始行,1 基;v1 恒为 1(读取 offset=1)
173
+ endLine: number // startLine + lines - 1
174
+ lines: number // 本次纳入的行数,等于 workspaceFiles.read 返回的 page.lines
175
+ tokens: number // estimateTokens(page.text)
176
+ score: number // 见 §4.6,整数
177
+ }
178
+
179
+ interface ContextBudget {
180
+ maxFiles: number
181
+ maxLinesPerFile: number
182
+ maxTokens: number
183
+ }
184
+
185
+ interface ContextError {
186
+ code: 'awareness_denied' | 'awareness_failed'
187
+ message: string // 可读诊断,截断到 200 字符
188
+ }
189
+
190
+ interface ContextResult {
191
+ enabled: boolean // 严格等于 files.length > 0
192
+ skipped?: 'no-session' | 'no-workspace' | 'search-failed' | 'read-failed' | 'budget-exhausted'
193
+ error?: ContextError
194
+ sessionId: string | null // 解析成功时是请求里的 sessionId,否则 null
195
+ workspaceRoot: string | null // 解析成功时是会话 cwd,否则 null
196
+ source: 'live' | 'persisted' | 'none'
197
+ skippedFiles: number // 因越界、非文本、过大、读取异常而跳过的候选文件数(预算拒绝不计)
198
+ truncated: boolean // 任一上限触顶(见 §4.8)
199
+ files: ContextFile[] // 按 score 降序、path 升序
200
+ totalFiles: number // files.length
201
+ totalLines: number // sum(files[].lines)
202
+ totalTokens: number // sum(files[].tokens)
203
+ budget: ContextBudget // 回显归一化后的预算
204
+ }
205
+ ```
206
+
207
+ 字段存在性规则(必须严格):
208
+
209
+ | 情况 | `enabled` | `skipped` | `error` | 其它 |
210
+ |---|---|---|---|---|
211
+ | awareness 未开启 | 不出现整个 `context` | — | — | 不出现 `symbols` |
212
+ | `sessionId` 缺失 | `false` | `'no-session'` | `{code:'awareness_denied', message:'sessionId required'}` | `sessionId=null`、`workspaceRoot=null`、`source='none'` |
213
+ | 会话存在但没有 cwd | `false` | `'no-workspace'` | `{code:'awareness_denied', message:'session workspace not found'}` | 同上 |
214
+ | 搜索/列表全部失败 | `false` | `'search-failed'` | `{code:'awareness_failed', message:...}` | `workspaceRoot/source` 保留已解析值 |
215
+ | 所有候选读取失败 | `false` | `'read-failed'` | `{code:'awareness_failed', message:...}` | 同上 |
216
+ | 预算装不下第一个文件 | `false` | `'budget-exhausted'` | 不出现 | `truncated=true`、`files=[]` |
217
+ | 草稿里没有可用提示词,或没有候选文件 | `false` | 不出现 | 不出现 | `files=[]`、`truncated=false`,Client 显示「无匹配文件」 |
218
+ | 至少纳入一个文件 | `true` | 不出现 | 部分搜索/读取异常时才有 `awareness_failed` | `truncated` 按 §4.8 |
219
+
220
+ - `skipped` 的取值集合**严格限定**为上表 5 个(不新增 `disabled`、`no-hints` 等值);未开启时整个 `context` 不出现;无匹配文件时省略 `skipped`。
221
+ - `error.code` 与 `skipped` 的对应关系:
222
+ - `no-session` / `no-workspace` → `awareness_denied`
223
+ - `search-failed` / `read-failed` → `awareness_failed`
224
+ - `budget-exhausted` → 无 error
225
+ - 部分成功(`files.length > 0`)但搜索或读取过程中抛过异常:`enabled=true`、`skipped` 不出现、`error={code:'awareness_failed'}`;每个被跳过的文件同时计入 `skippedFiles`。
226
+ - `context` 出现时,所有非可选字段必须出现(含 `sessionId/workspaceRoot/source/skippedFiles/truncated/totalFiles/totalLines/totalTokens/budget`),不得省略。
227
+
228
+ ### 3.2 `symbols` 数组
229
+
230
+ ```ts
231
+ interface SymbolRef {
232
+ name: string // 标识符原文
233
+ kind: 'function' | 'variable' | 'class'
234
+ file: string // 与 context.files[].path 完全一致
235
+ line: number // 1 基,文件内绝对行号
236
+ endLine?: number // v1 永不输出;字段保留
237
+ }
238
+ ```
239
+
240
+ - 仅当 `context` 出现时 `symbols` 才出现;`context.enabled=false` 时 `symbols=[]`。
241
+ - 最多 100 条。去重键 `file + '\0' + name`(保留首次出现的行)。
242
+ - 排序:`file` 字典升序 → `line` 升序 → `name` 字典升序。
243
+ - 提取规则见 §4.9。
244
+
245
+ ### 3.3 `command` 对象
246
+
247
+ ```ts
248
+ interface CommandInfo {
249
+ name: string // 归一化后的命令名(无斜杠、小写)
250
+ description: string // registry 描述,或本地化 fallback 文案
251
+ source: 'registry' | 'fallback'
252
+ }
253
+ ```
254
+
255
+ - 仅当 `normalizeCommandName(payload.commandName)` 非空时出现。
256
+ - `source='registry'`:`ctx.get('agents').get(sessionId)` 返回 Agent,且 `ctx.get('commands').list(agent)` 中存在 `name.toLowerCase() === 请求名` 的 descriptor,且 `description.trim()` 非空。
257
+ - 否则 `source='fallback'`,`description` 为:
258
+ - `locale === 'zh'`:`'命令说明不可用'`
259
+ - `locale === 'en'`:`'Command description unavailable'`
260
+ - `commands.list` 抛错、没有 Agent、`sessionId` 缺失,都只降级为 fallback,不产生 `context.error`。
261
+ - 名称以 descriptor 的 `name` 为准(保留大小写);fallback 时用归一化后的请求名。
262
+
263
+ ---
264
+
265
+ ## 4. Host 实现规范(`index.js`)
266
+
267
+ ### 4.1 导出与内部函数清单(名字固定,便于 review 与单测)
268
+
269
+ ```js
270
+ // 纯函数 / 可单测
271
+ function estimateTokens(text)
272
+ function normalizeAwarenessRequest(raw)
273
+ function normalizeCommandName(raw)
274
+ function resolveWorkspace(ctx, sessionId, signal) // async
275
+ function extractContextHints(text)
276
+ function contextFileScore(hint, relPath)
277
+ function countOccurrences(haystack, needle)
278
+ function extractSymbols(files, texts) // texts: Map<string,string>
279
+ function buildContextBlock(context, texts, locale)
280
+ function resolveCommand(ctx, sessionId, commandName, locale)
281
+ function collectContext(ctx, scope, prompt, budget, signal) // async,永不 throw;scope 可带 source
282
+
283
+ // 路由流程
284
+ async function handle(ctx, req, res)
285
+ async function rewrite(ctx, selection, text, locale, signal, contextBlock)
286
+ ```
287
+
288
+ 末尾新增测试出口(不影响 DSH 只读取 `inject` / `apply`):
289
+
290
+ ```js
291
+ export const __test__ = {
292
+ estimateTokens,
293
+ normalizeAwarenessRequest,
294
+ normalizeCommandName,
295
+ resolveWorkspace,
296
+ extractContextHints,
297
+ contextFileScore,
298
+ countOccurrences,
299
+ extractSymbols,
300
+ buildContextBlock,
301
+ resolveCommand,
302
+ collectContext,
303
+ CONTEXT_DEFAULTS,
304
+ CONTEXT_LIMITS,
305
+ }
306
+ ```
307
+
308
+ ### 4.2 `resolveWorkspace(ctx, sessionId, signal)`
309
+
310
+ ```ts
311
+ type ResolveOk = { ok: true, sessionId: string, workspaceRoot: string, source: 'live' | 'persisted' }
312
+ type ResolveFail = { ok: false, skipped: 'no-session' | 'no-workspace' }
313
+
314
+ async function resolveWorkspace(ctx, sessionId, signal): Promise<ResolveOk | ResolveFail>
315
+ ```
316
+
317
+ 精确逻辑:
318
+
319
+ ```js
320
+ async function resolveWorkspace(ctx, sessionId, signal) {
321
+ if (typeof sessionId !== 'string' || !sessionId.trim()) return { ok: false, skipped: 'no-session' }
322
+ const id = sessionId.trim()
323
+ let live
324
+ try {
325
+ const sessions = ctx.get('sessions')
326
+ live = sessions && typeof sessions.get === 'function' ? sessions.get(id) : undefined
327
+ } catch (err) {
328
+ live = undefined
329
+ }
330
+ const liveCwd = live && live.header && typeof live.header.cwd === 'string' && live.header.cwd.trim()
331
+ ? live.header.cwd
332
+ : ''
333
+ if (liveCwd) return { ok: true, sessionId: id, workspaceRoot: liveCwd, source: 'live' }
334
+
335
+ let persistedCwd = ''
336
+ try {
337
+ const persistence = ctx.get('sessionPersistence')
338
+ const snapshot = persistence && typeof persistence.stat === 'function'
339
+ ? await persistence.stat(id, { signal })
340
+ : undefined
341
+ if (snapshot && snapshot.header && typeof snapshot.header.cwd === 'string' && snapshot.header.cwd.trim()) {
342
+ persistedCwd = snapshot.header.cwd
343
+ }
344
+ } catch (err) {
345
+ persistedCwd = ''
346
+ }
347
+ if (persistedCwd) return { ok: true, sessionId: id, workspaceRoot: persistedCwd, source: 'persisted' }
348
+ return { ok: false, skipped: 'no-workspace' }
349
+ }
350
+ ```
351
+
352
+ - 不读 `sessions.list()`,不读 `workspaceRegistry`,不读 `sandboxPolicy.workspaceRoot`。
353
+ - `signal.aborted` 时直接返回当前已解析结果;已解析到 cwd 仍可用。
354
+
355
+ ### 4.3 `extractContextHints(text)`
356
+
357
+ 返回 `Array<{ kind: 'path' | 'term', text: string, lower: string }>`,最多 6 条,顺序即搜索优先级。
358
+
359
+ ```js
360
+ const HINT_STOPWORDS = new Set([
361
+ 'the','and','for','with','this','that','from','into','when','then','than','have','has','are','was','were',
362
+ 'will','would','should','could','please','help','make','sure','code','file','files','function','error','bug',
363
+ 'fix','use','using','need','want','issue','problem','test','change','update','add','remove','about','your',
364
+ 'you','our','their','there','here','what','why','how','not','but','all','any','can','may','just','like',
365
+ 'get','set','new','old','good','bad','more','less','only','also','very','some','such','each','other',
366
+ 'which','where','while','after','before','between','over','under','again','still','same','different',
367
+ '帮我','一下','代码','这个','那个','文件','函数','怎么','可以','需要','使用','问题','修复','优化','修改',
368
+ '增加','删除','看看','这段','下面','上面','然后','就是','还是','已经','没有','一个','我们','你们','他们',
369
+ '什么','为什么','如何','这里','那里','现在','之前','之后','因为','所以','但是','如果','或者','以及','并且',
370
+ ])
371
+ ```
372
+
373
+ 1. **路径提示**:用 `/[A-Za-z0-9_.@/\\-]+\.[A-Za-z0-9]{1,8}/g` 抽取;取最后一个 `.` 后的扩展名(小写)必须在 `CONTEXT_EXTENSIONS` 内;长度 3..240;拒绝以 `/` 开头或以盘符开头的绝对路径;`normalizeRelPath` 后去重。最多 6 条,先到先得。
374
+ 2. **术语提示**:
375
+ - ASCII 标识符:`/[A-Za-z_$][A-Za-z0-9_$]{2,}/g`;
376
+ - 中文串:`/[\u3400-\u9FFF]{2,8}/g`;
377
+ - 全部 `toLowerCase()`,去重,排除 `HINT_STOPWORDS`、纯数字、长度 < 3 的项;
378
+ - 按「出现次数降序 → 长度降序 → 字典升序」排序,补足到总数 6 条。
379
+ 3. 没有提示词 → 返回 `[]`;调用方据此得到「无匹配文件」状态(不写 `skipped`)。
380
+
381
+ ### 4.4 候选发现(`workspaceFiles.search` / `workspaceFiles.list`)
382
+
383
+ `collectContext` 的入参 `scope` 可以带 `source`,但调用 `workspaceFiles` 时必须构造纯对象 `const wfScope = { sessionId: scope.sessionId, workspaceRoot: scope.workspaceRoot }`,不得把 `source` 等额外字段传给服务。`ctx.get('workspaceFiles')` 缺失 → `collectContext` 返回 `read-failed` 降级(v1 不做 `fs` 读降级,避免绕过围栏)。
384
+
385
+ 对每条 hint 调:
386
+
387
+ ```js
388
+ await workspaceFiles.search(wfScope, {
389
+ query: hint.text,
390
+ excludedPaths: [],
391
+ includeHidden: false,
392
+ respectGitignore: true,
393
+ }, signal)
394
+ ```
395
+
396
+ 返回值形状:`{ matches: Array<{ path: string, type: string }>, truncated: boolean, incomplete: boolean }`。
397
+
398
+ - 只保留 `type === 'file'` 的 `match.path`;`normalizeRelPath` 后去重;
399
+ - 客户端侧过滤(不依赖服务端):
400
+ - 命中 `CONTEXT_EXCLUDED_PREFIXES` 任意前缀 → 丢弃;
401
+ - 扩展名不在 `CONTEXT_EXTENSIONS` → 丢弃;
402
+ - basename 以 `.min.js` / `.min.css` 结尾 → 丢弃;
403
+ - 含 `..` 段、以 `/` 开头 → 不直接丢弃,保留为候选但不读取;交给 §4.5 预围栏拒绝并计入 `skippedFiles`。
404
+ - 路径提示(`kind === 'path'`)本身直接作为候选加入(其路径分固定按 §4.6 的 150 分支计算),不依赖 `search` 是否返回;仍要经过扩展名/排除规则与预围栏。
405
+ - 搜索调用失败:计数 `searchFailures += 1`,继续其它 hint;全部 hint 都失败且没有任何候选 → `search-failed`。
406
+ - `search` 不存在时:用 `workspaceFiles.list(wfScope, '.', signal)` 兜底一次:
407
+ - 只取 `entries[].type === 'file'`,`path = entry.name`;
408
+ - 同样应用扩展名/排除规则;
409
+ - `listing.truncated === true` → 最终 `truncated=true`;
410
+ - `list` 也失败 → `search-failed`。
411
+ - 没有候选 → 返回「无匹配文件」状态(`enabled=false`、无 `skipped`、无 `error`、`files=[]`、`truncated=false`)。
412
+
413
+ ### 4.5 预围栏(读取前)
414
+
415
+ ```js
416
+ async function fence(ctx, workspaceRoot, relPath) {
417
+ const fs = ctx.get('fs')
418
+ if (!fs || typeof fs.resolve !== 'function' || typeof fs.contains !== 'function') return null
419
+ const root = await fs.resolve(workspaceRoot)
420
+ const target = await fs.resolve(relPath, { cwd: workspaceRoot })
421
+ return fs.contains(root, target) ? target : undefined
422
+ }
423
+ ```
424
+
425
+ - 返回 `null`:`fs` 不可用,无法安全围栏 → 整个采集降级为 `read-failed` / `awareness_failed`(`skippedFiles` 加上候选数),不做任何读取。
426
+ - 返回 `undefined`:越界 → 跳过该候选,`skippedFiles += 1`。
427
+ - 返回 `FsTarget`:继续读取;读取后再用 `page.absolutePath` 复核:
428
+
429
+ ```js
430
+ const targetAfter = await fs.resolve(page.absolutePath)
431
+ if (!fs.contains(root, targetAfter)) { skippedFiles += 1; continue }
432
+ ```
433
+
434
+ - Windows 大小写、8.3 短名、符号链接一律交给 `fs.resolve` + `fs.contains`,禁止自己写 `startsWith`。
435
+
436
+ ### 4.6 读取、评分与排序
437
+
438
+ 对每个候选:
439
+
440
+ ```js
441
+ const page = await workspaceFiles.read(wfScope, relPath, {
442
+ offset: 1,
443
+ limit: budget.maxLinesPerFile,
444
+ }, signal)
445
+ ```
446
+
447
+ `page` 形状:`{ absolutePath, version, bytes?, offset, text, lines, eof }`。
448
+
449
+ - `page.lines === 0` 或 `page.text` 非字符串 → 跳过(不计 `skippedFiles`;非字符串按读取异常处理,见下表)。
450
+ - `startLine = Number.isFinite(page.offset) ? page.offset : 1`。
451
+ - `tokens = estimateTokens(page.text)`。
452
+ - 内容命中分:对每条 hint 统计 `countOccurrences(page.text.toLowerCase(), hint.lower)`,单条最多计 20 次;`contentScore = Math.min(40, totalHits * 2)`。
453
+ - 路径分 `contextFileScore(hint, relPath)`:
454
+
455
+ | 条件(按顺序短路) | 分值 |
456
+ |---|---|
457
+ | `hint.kind === 'path'` 且 `relPath === hint.text` 或 `relPath.endsWith('/' + hint.text)` 或 `relPath.endsWith(hint.text)` | 150 |
458
+ | basename 去扩展名后 === `hint.lower` | 100 |
459
+ | basename 去扩展名后包含 `hint.lower` | 60 |
460
+ | 整个 `relPath.toLowerCase()` 包含 `hint.lower` | 25 |
461
+ | 其它(被 search 命中但路径不含 hint) | 5 |
462
+
463
+ - 一条候选的路径分 = 所有 hint 的 `contextFileScore` 之和。
464
+ - 预读候选:按路径分降序、path 升序取前 `min(CONTEXT_MAX_READ_CANDIDATES, budget.maxFiles * 2)` 个。
465
+ - 读取后最终 `score = 路径分 + contentScore`;按 `score` 降序、`path` 升序重排。
466
+
467
+ 读取异常处理:
468
+
469
+ | 异常 code | 处理 |
470
+ |---|---|
471
+ | `workspace-file/not-text` / `workspace-file/not-regular-file` / `workspace-file/too-large` / `FS_NOT_TEXT` / `FS_TOO_LARGE` | `skippedFiles += 1`,继续下一个 |
472
+ | `workspace-file/outside-workspace` | `skippedFiles += 1`,继续 |
473
+ | 其它异常 | `skippedFiles += 1`,`readFailures += 1`,继续 |
474
+ | `signal.aborted` | 立即停止;按「已读到的文件」返回;若一个都没有 → `read-failed` |
475
+
476
+ - 只有「读取抛异常」(上表“其它异常”)才增加 `readFailures`;`not-text` / `too-large` / `outside-workspace` 只增加 `skippedFiles`。因此若所有候选都只是二进制/过大而被跳过,最终是「无匹配文件 + 跳过 N 个」而不是 `read-failed`。
477
+
478
+ ### 4.7 预算执行(唯一循环)
479
+
480
+ 按最终 `score` 降序遍历:
481
+
482
+ ```js
483
+ const files = []
484
+ const texts = new Map()
485
+ let totalTokens = 0
486
+ let truncated = false
487
+
488
+ for (const candidate of ranked) {
489
+ if (files.length >= budget.maxFiles) { truncated = true; break }
490
+ if (totalTokens + candidate.tokens > budget.maxTokens) { truncated = true; break }
491
+ if (candidate.eof === false) truncated = true
492
+ files.push(candidate.file)
493
+ texts.set(candidate.file.path, candidate.text)
494
+ totalTokens += candidate.tokens
495
+ }
496
+ ```
497
+
498
+ - `maxLinesPerFile` 由 `read` 的 `limit` 强制;`page.eof === false` 表示该文件被行数上限截断 → `truncated=true`,但文件仍纳入。
499
+ - `page.lines === 0`(空文件或无可读行)→ 视为候选不可用,直接 `continue`,不计 `readFailures`、不计 `skippedFiles`。
500
+ - `maxFiles` 触顶或 `maxTokens` 装不下下一个文件 → 停止,`truncated=true`。
501
+ - 预算拒绝的文件**不计入** `skippedFiles`。
502
+ - 若 `files.length === 0` 且原因是 token 预算装不下第一个文件(第一个候选 `tokens > maxTokens`)→ `skipped='budget-exhausted'`、`truncated=true`、`enabled=false`。
503
+ - `totalFiles = files.length`;`totalLines = sum(lines)`;`totalTokens = sum(tokens)`(不要用拼接后的整块文本重新估算)。
504
+
505
+ ### 4.8 `truncated` 判定汇总
506
+
507
+ 只有以下情况置 `true`:
508
+
509
+ 1. `files.length` 达到 `budget.maxFiles` 且还有候选未处理;
510
+ 2. `totalTokens + next.tokens > budget.maxTokens`;
511
+ 3. 任一已纳入文件 `page.eof === false`;
512
+ 4. 使用 `workspaceFiles.list` 兜底且 `listing.truncated === true`。
513
+
514
+ `search` 的 `truncated` / `incomplete` 不置 `context.truncated`(它表示发现阶段被截断,不代表纳入结果被预算截断);但会在 `context.error` 的 message 中记录(如果同时有搜索异常)。
515
+
516
+ ### 4.9 `extractSymbols(files, texts)`
517
+
518
+ 逐文件、逐行扫描;每行按下列顺序命中第一条即停止:
519
+
520
+ ```js
521
+ const SYMBOL_RULES = [
522
+ { kind: 'class', re: /^\s*(?:export\s+)?(?:default\s+)?class\s+([A-Za-z_$][\w$]*)/ },
523
+ { kind: 'function', re: /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/ },
524
+ { kind: 'function', re: /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/ },
525
+ { kind: 'function', re: /^\s*(?:static\s+)?(?:async\s+)?\*?\s*([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{/ },
526
+ { kind: 'variable', re: /^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b/ },
527
+ ]
528
+ ```
529
+
530
+ - `line = file.startLine + localLineIndex`(localLineIndex 从 0 开始)。
531
+ - 排除名字:`if, for, while, switch, catch, return, function, const, let, var, new, typeof, await, async, class, else`。
532
+ - 去重键 `file + '\0' + name`,保留首次(行号最小)。
533
+ - 排序:`file` 升序 → `line` 升序 → `name` 升序;截断到 `CONTEXT_MAX_SYMBOLS`。
534
+ - `endLine` 不输出。
535
+ - `context.enabled === false` → `symbols = []`。
536
+
537
+ ### 4.10 `buildContextBlock(context, texts, locale)`
538
+
539
+ ```js
540
+ const header = locale === 'en'
541
+ ? 'Read-only context from the current workspace. Use it only to resolve references in the draft; do not modify these files and do not answer or repeat this content.'
542
+ : '以下是当前工作区的只读上下文,仅用于理解草稿中的指代;不要修改这些文件,也不要回答或复述这些内容。'
543
+
544
+ const body = context.files.map((file) => {
545
+ const text = String(texts.get(file.path) || '').replace(/\n$/, '')
546
+ const path = file.path.replace(/"/g, '&quot;')
547
+ return '<file path="' + path + '" lines="' + file.startLine + '-' + file.endLine + '">\n' + text + '\n</file>'
548
+ }).join('\n\n')
549
+
550
+ return '<workspace-context>\n' + header + '\n\n' + body + '\n</workspace-context>'
551
+ ```
552
+
553
+ - `context.enabled === false` 时调用方不生成块,`contextBlock = ''`。
554
+ - 文件内容只进入模型请求,**不进入** HTTP 响应;响应只给路径、行数、token 与符号。
555
+
556
+ ### 4.11 `rewrite` 的上下文注入
557
+
558
+ `rewrite` 签名扩展为:
559
+
560
+ ```js
561
+ async function rewrite(ctx, selection, text, locale, signal, contextBlock)
562
+ ```
563
+
564
+ 用户消息文本:
565
+
566
+ ```js
567
+ const userText = contextBlock
568
+ ? contextBlock + '\n\n<draft>\n' + text + '\n</draft>'
569
+ : text
570
+ ```
571
+
572
+ - `contextBlock` 为空字符串时,`userText === text`(保证旧行为逐字节一致)。
573
+ - system prompt(`SYSTEM[locale]`)不变;`buildContextBlock` 的 header 已包含「不要回答/复述」约束。
574
+
575
+ ### 4.12 `handle` 流程(顺序固定)
576
+
577
+ 1. 方法 / Origin 检查(不变)。
578
+ 2. 读 body + JSON 解析(不变)。
579
+ 3. `text` 校验(不变)。
580
+ 4. `resolveSelection`(不变)。
581
+ 5. `const locale = localeOf(payload.locale)`。
582
+ 6. `const awareness = normalizeAwarenessRequest(payload.awareness)`。
583
+ 7. `const command = resolveCommand(ctx, sessionId, payload.commandName, locale)`(`sessionId` 先按 §2.1 归一化)。
584
+ 8. 创建外层 `controller`(模型取消/超时)与 `CALL_TIMEOUT_MS` 计时器;同时声明 `let context, symbols = [], texts = new Map()`。
585
+ 9. 若 `awareness.enabled`:
586
+ - 建独立 `awarenessCtrl`,`setTimeout(() => awarenessCtrl.abort(), CONTEXT_TIMEOUT_MS)`;外层 `controller.signal` abort 时联动 abort `awarenessCtrl`。
587
+ - `const resolved = await resolveWorkspace(ctx, sessionId, awarenessCtrl.signal)`。
588
+ - 成功 → `const collected = await collectContext(ctx, { sessionId, workspaceRoot, source }, text, awareness, awarenessCtrl.signal)`;`collectContext` 契约上不 throw,但 handler 用 try/catch 兜底成 `read-failed`。
589
+ - 失败 → 构造完整 `context`:
590
+ ```js
591
+ context = {
592
+ enabled: false,
593
+ skipped: resolved.skipped,
594
+ error: {
595
+ code: 'awareness_denied',
596
+ message: resolved.skipped === 'no-session' ? 'sessionId required' : 'session workspace not found',
597
+ },
598
+ sessionId: resolved.skipped === 'no-session' ? null : sessionId,
599
+ workspaceRoot: null,
600
+ source: 'none',
601
+ skippedFiles: 0,
602
+ truncated: false,
603
+ files: [],
604
+ totalFiles: 0,
605
+ totalLines: 0,
606
+ totalTokens: 0,
607
+ budget: awareness,
608
+ }
609
+ symbols = []
610
+ texts = new Map()
611
+ ```
612
+ - `clearTimeout(awarenessTimer)`;解除外层联动。
613
+ 10. `const contextBlock = context && context.enabled ? buildContextBlock(context, texts, locale) : ''`。
614
+ 11. `const raw = await rewrite(ctx, selection, text, locale, controller.signal, contextBlock)`。
615
+ 12. `send(res, 200, { text: output, notes: [], ...(context ? { context, symbols } : {}), ...(command ? { command } : {}) })`。
616
+ 13. 现有 catch/finally 保持:499 / 502 等错误映射不变;清理两个计时器与监听。
617
+
618
+ - `collectContext` 内部对 abort 的处理:搜索阶段 abort → `search-failed`;读取阶段 abort → `read-failed`;已有文件则按部分结果返回(`enabled=true`、`error.awareness_failed`)。
619
+ - 任何情况下都不得因为感知问题返回 4xx/5xx。
620
+
621
+ ### 4.13 `collectContext` 返回类型
622
+
623
+ ```ts
624
+ interface CollectedContext {
625
+ context: ContextResult
626
+ symbols: SymbolRef[]
627
+ texts: Map<string, string> // path -> page.text,仅 Host 内部使用
628
+ }
629
+ ```
630
+
631
+ - `texts` 不序列化,不写日志,不返回 Client。
632
+ - `collectContext` 必须在任何分支都返回完整 `context`(非可选字段齐全)。
633
+ - `collectContext` 内部第一件事:`const wfScope = { sessionId: scope.sessionId, workspaceRoot: scope.workspaceRoot }`;之后所有 `workspaceFiles.*` 调用只用 `wfScope`。
634
+ - 局部状态固定为 `let searchFailures = 0, readFailures = 0, skippedFiles = 0, truncated = false`。最终 `skipped` 的判定顺序(仅当 `files.length === 0` 时):
635
+ 1. `readFailures > 0` → `'read-failed'`(已有候选但均读取失败);
636
+ 2. 否则 `searchFailures > 0` → `'search-failed'`(没有候选且搜索/列表失败);
637
+ 3. 否则预算装不下第一个文件 → `'budget-exhausted'`;
638
+ 4. 否则省略 `skipped`(无提示词 / 无候选 / 全是空文件)。
639
+ - `files.length > 0` 且 `searchFailures + readFailures > 0` → `error={code:'awareness_failed', message:'partial context'}`;`files.length > 0` 时绝不写 `skipped`。
640
+
641
+ ---
642
+
643
+ ## 5. C) 设置项(`client.js`)
644
+
645
+ ### 5.1 默认值与白名单
646
+
647
+ ```js
648
+ const DEFAULT_SETTINGS = {
649
+ fontSize: 'follow',
650
+ language: 'auto',
651
+ mode: 'auto',
652
+ timeoutSec: 20,
653
+ debug: false,
654
+ awareness: 'off',
655
+ contextTokens: 800,
656
+ contextLines: 80,
657
+ contextFiles: 5,
658
+ }
659
+
660
+ const AWARENESS_MODES = new Set(['off', 'on'])
661
+ const CONTEXT_TOKENS = new Set([400, 800, 1200])
662
+ const CONTEXT_LINES = new Set([40, 80, 160])
663
+ const CONTEXT_FILES = new Set([3, 5, 8])
664
+ ```
665
+
666
+ `SETTINGS_KEY` 保持 `'prompt-enhance:settings'`,**不新增、不改名**。
667
+
668
+ ### 5.2 `normalizeSettings` 精确规则
669
+
670
+ ```js
671
+ function normalizeSettings(raw) {
672
+ const next = { ...DEFAULT_SETTINGS }
673
+ if (!raw || typeof raw !== 'object') return next
674
+ if (FONT_SIZES.has(raw.fontSize)) next.fontSize = raw.fontSize
675
+ if (LANGUAGE_MODES.has(raw.language)) next.language = raw.language
676
+ if (ENHANCE_MODES.has(raw.mode)) next.mode = raw.mode
677
+ if (TIMEOUT_SECONDS.has(Number(raw.timeoutSec))) next.timeoutSec = Number(raw.timeoutSec)
678
+ if (typeof raw.debug === 'boolean') next.debug = raw.debug
679
+ if (AWARENESS_MODES.has(raw.awareness)) next.awareness = raw.awareness
680
+ if (CONTEXT_TOKENS.has(Number(raw.contextTokens))) next.contextTokens = Number(raw.contextTokens)
681
+ if (CONTEXT_LINES.has(Number(raw.contextLines))) next.contextLines = Number(raw.contextLines)
682
+ if (CONTEXT_FILES.has(Number(raw.contextFiles))) next.contextFiles = Number(raw.contextFiles)
683
+ return next
684
+ }
685
+ ```
686
+
687
+ - 非法值(`'yes'`、`500`、`null`、字符串数字 `"800"` 等)一律回落默认值。
688
+ - `Number(raw.contextX)` 允许旧数据里是数字字符串;但集合校验保证只接受三档。
689
+ - `readSettings` / `persistSettings` / `updateSettings` / `resetSettings` 结构不变;`updateSettings({ awareness: 'on' })` 必须持久化。
690
+ - 旧 localStorage 数据(没有新键)读入后自动补齐 `awareness:'off'` 与三个默认档位。
691
+
692
+ ### 5.3 设置页 UI 结构
693
+
694
+ 在 `SettingsView` 中,`settings.detail` 区块之后、`reset` 行之前插入:
695
+
696
+ 1. `h('div', { className: 'pe-section' }, t('settings.context.title'))`
697
+ 2. `SettingRow`:
698
+ - `label: t('settings.context.enabledLabel')`
699
+ - `hint: t('settings.context.enabledHint')`
700
+ - `control: h('input', { type: 'checkbox', className: 'pe-check', checked: conf.awareness === 'on', onChange: (e) => updateSettings({ awareness: e.target.checked ? 'on' : 'off' }) })`
701
+ 3. 仅当 `conf.awareness === 'on'`,依次渲染三行 `SettingRow` + `SettingsSeg`:
702
+ - `settings.context.filesLabel`,options `CONTEXT_FILE_OPTIONS` = `[{value:3,labelKey:'settings.context.files3'},{value:5,...files5},{value:8,...files8}]`
703
+ - `settings.context.linesLabel`,options `CONTEXT_LINE_OPTIONS` = `40/80/160`
704
+ - `settings.context.tokensLabel`,options `CONTEXT_TOKEN_OPTIONS` = `400/800/1200`
705
+ - 分别 `updateSettings({ contextFiles: value })` / `contextLines` / `contextTokens`。
706
+ 4. 常量名固定:`CONTEXT_FILE_OPTIONS`、`CONTEXT_LINE_OPTIONS`、`CONTEXT_TOKEN_OPTIONS`。
707
+
708
+ `settings.resetHint` 文案改为同时提到工作区上下文(见 §6)。
709
+
710
+ ### 5.4 设置到请求的映射
711
+
712
+ 在 `EnhancePanel` 内构造(只构造一次,传给 `enhance`):
713
+
714
+ ```js
715
+ const awareness = {
716
+ enabled: conf.awareness === 'on',
717
+ maxFiles: conf.contextFiles,
718
+ maxLinesPerFile: conf.contextLines,
719
+ maxTokens: conf.contextTokens,
720
+ }
721
+ ```
722
+
723
+ - 即使 `enabled=false` 也把这个对象放进请求;Host 会忽略并**不返回** `context`。
724
+ - `sessionId` 来自 slot prop,原样传递;`typeof sessionId !== 'string'` 时不要伪造空字符串,省略该字段(Host 降级 `no-session`)。
725
+ - `commandName` 来自当前快照的 `view.commandName`;为空则省略。
726
+
727
+ ---
728
+
729
+ ## 6. D) 文案键(zh / en 成对,扁平点分 key)
730
+
731
+ 所有 key 必须同时加入 `ZH_NESTED` 与 `EN_NESTED`;按点号嵌套写入(例如 `settings.context.title` 写成 `settings: { context: { title: ... } }`),`flattenDict` 后不得有对象值。不得复用不存在的 key。
732
+
733
+ > 下表反引号只是 Markdown 标记,**不是文案内容**;实现时字符串里不要带反引号。
734
+
735
+ ### 6.1 `settings.context.*`
736
+
737
+ | key | zh | en |
738
+ |---|---|---|
739
+ | `settings.context.title` | 工作区上下文 | Workspace context |
740
+ | `settings.context.enabledLabel` | 读取工作区上下文 | Read workspace context |
741
+ | `settings.context.enabledHint` | 只读当前会话工作区的文件(不写入、不改动);读取清单会随结果展示,便于审计。 | Read-only: reads files from the current session's workspace (nothing is written or modified); the read list is shown with the result for auditing. |
742
+ | `settings.context.filesLabel` | 最多文件数 | Max files |
743
+ | `settings.context.files3` | 3 个文件 | 3 files |
744
+ | `settings.context.files5` | 5 个文件 | 5 files |
745
+ | `settings.context.files8` | 8 个文件 | 8 files |
746
+ | `settings.context.linesLabel` | 每文件行数 | Lines per file |
747
+ | `settings.context.lines40` | 40 行 | 40 lines |
748
+ | `settings.context.lines80` | 80 行 | 80 lines |
749
+ | `settings.context.lines160` | 160 行 | 160 lines |
750
+ | `settings.context.tokensLabel` | 总 token 上限 | Total token budget |
751
+ | `settings.context.tokens400` | 400 tokens | 400 tokens |
752
+ | `settings.context.tokens800` | 800 tokens | 800 tokens |
753
+ | `settings.context.tokens1200` | 1200 tokens | 1200 tokens |
754
+
755
+ `settings.resetHint` 替换为:
756
+
757
+ | key | zh | en |
758
+ |---|---|---|
759
+ | `settings.resetHint` | 字号、语言、增强方式、超时、调试开关与工作区上下文参数一起复位。 | Resets font size, language, enhancement mode, timeout, diagnostics, and workspace-context settings. |
760
+
761
+ ### 6.2 `panel.context.*`
762
+
763
+ | key | zh | en |
764
+ |---|---|---|
765
+ | `panel.context.title` | 读取的工作区上下文 | Workspace context |
766
+ | `panel.context.file` | `{path} · {lines} 行 · {tokens} tokens` | `{path} · {lines} lines · {tokens} tokens` |
767
+ | `panel.context.total` | `共 {files} 个文件 · {lines} 行 · {tokens} tokens` | `{files} files · {lines} lines · {tokens} tokens` |
768
+ | `panel.context.workspace` | `工作区:{root}` | `Workspace: {root}` |
769
+ | `panel.context.source.live` | 当前会话 | Live session |
770
+ | `panel.context.source.persisted` | 历史会话 | Stored session |
771
+ | `panel.context.truncated` | 已达上限,清单为部分结果 | Limit reached; the list is partial |
772
+ | `panel.context.skippedFiles` | `跳过 {count} 个文件(越界、非文本或过大)` | `{count} file(s) skipped (outside workspace, binary, or too large)` |
773
+ | `panel.context.empty` | 草稿中没有可匹配的文件 | No files matched the draft |
774
+ | `panel.context.skip.noSession` | 未找到会话,未读取上下文 | No session found; context was not read |
775
+ | `panel.context.skip.noWorkspace` | 会话没有工作区,未读取上下文 | The session has no workspace; context was not read |
776
+ | `panel.context.skip.searchFailed` | 文件搜索失败,未读取上下文 | File search failed; context was not read |
777
+ | `panel.context.skip.readFailed` | 文件读取失败,未读取上下文 | File read failed; context was not read |
778
+ | `panel.context.skip.budgetExhausted` | 上下文预算不足,未纳入文件 | Context budget too small; no files included |
779
+ | `panel.context.error.awarenessDenied` | 上下文访问被拒绝,已按无上下文继续 | Context access was denied; continuing without context |
780
+ | `panel.context.error.awarenessFailed` | 上下文读取异常,已按无上下文继续 | Context reading failed; continuing without context |
781
+
782
+ ### 6.3 `panel.diff.*`(新增项;`original` / `enhanced` 已有,不改)
783
+
784
+ | key | zh | en |
785
+ |---|---|---|
786
+ | `panel.diff.legend` | 差异图例 | Diff legend |
787
+ | `panel.diff.legend.add` | 新增 | Added |
788
+ | `panel.diff.legend.del` | 删除 | Removed |
789
+ | `panel.diff.legend.equal` | 未变 | Unchanged |
790
+
791
+ ### 6.4 `panel.hover.*`
792
+
793
+ | key | zh | en |
794
+ |---|---|---|
795
+ | `panel.hover.position` | `≈ {file}:{line}(附近 ±3 行)` | `≈ {file}:{line} (±3 lines)` |
796
+
797
+ ### 6.5 `panel.command.*`
798
+
799
+ | key | zh | en |
800
+ |---|---|---|
801
+ | `panel.command.label` | 命令 | Command |
802
+
803
+ > `panel.command.note` 已存在,保持不变;命令描述行追加在它附近,不替换。
804
+
805
+ ---
806
+
807
+ ## 7. E) 语义 diff 规格(`client.js`)
808
+
809
+ ### 7.1 对外纯函数
810
+
811
+ ```js
812
+ function computeSemanticDiff(before, after) // -> { mode: 'token'|'line', hunks: DiffHunk[] }
813
+ ```
814
+
815
+ ```ts
816
+ interface DiffHunk {
817
+ type: 'equal' | 'add' | 'del'
818
+ text: string
819
+ chinese?: true // 仅当 text 含 CJK 时出现;不含时省略该字段
820
+ }
821
+ ```
822
+
823
+ 不引入第三方 diff 库;纯手写 LCS。
824
+
825
+ ### 7.2 token 化(`mode='token'`)
826
+
827
+ 按 Unicode code point 扫描(`Array.from(text)`),分类:
828
+
829
+ 1. **空白**:`/\s/` 连续的空白合并为一个 token;token 文本保留原始空白串。
830
+ 2. **CJK**:`/[\u2E80-\u9FFF\uF900-\uFAFF\uFF00-\uFFEF]/` 的每个字符各自一个 token(无中文分词器,逐字是唯一确定的行为)。
831
+ 3. **标识符**:`/[A-Za-z0-9_$]/` 连续字符合并为一个 token。
832
+ 4. **标点/其它**:其余每个字符一个 token。
833
+
834
+ token 形状内部为 `{ kind: 'space'|'cjk'|'ident'|'punct', text: string }`;LCS 比较只看 `text`。
835
+
836
+ ### 7.3 LCS 与 hunk 合并
837
+
838
+ 1. 标准 DP:`dp[i][j]` = `a[i..]` 与 `b[j..]` 的 LCS 长度。
839
+ 2. 回溯规则:
840
+ - `a[i].text === b[j].text` → `equal`,`i++`、`j++`;
841
+ - 否则若 `dp[i+1][j] >= dp[i][j+1]` → `del`,`i++`;
842
+ - 否则 → `add`,`j++`。
843
+ - **平局优先 `del`**,保证结果确定。
844
+ 3. 连续同类型 hunk 合并。
845
+ 4. hunk 文本拼接后做空白折叠:
846
+ - `/[ \t]+/g` → `' '`;
847
+ - `/\n{2,}/g` → `'\n'`;
848
+ - 折叠后为空字符串的 hunk 丢弃。
849
+ 5. `chinese`:`text` 命中 CJK 正则时设为 `true`,否则省略。
850
+
851
+ ### 7.4 降级为行级
852
+
853
+ - 若 `beforeTokens.length > 400` 或 `afterTokens.length > 400` → `mode='line'`。
854
+ - 行 token:`String(text).split('\n')`,每个元素一个 token(空行也保留)。
855
+ - 仍走同一 LCS + hunk 合并;`mode='line'` 时不执行空白折叠(保留原行内容);`chinese` 规则相同。
856
+ - 两个空字符串 → `{ mode: 'token', hunks: [] }`。
857
+
858
+ ### 7.5 渲染
859
+
860
+ `SemanticDiff` 组件:
861
+
862
+ - props:`{ before: string, after: string, symbols: SymbolRef[], labelOf: (symbol) => string }`
863
+ - 先 `const { hunks } = computeSemanticDiff(before, after)`;
864
+ - 创建 `const seen = new Set()`,整块只创建一次,传给每个 hunk 的 `SymbolText`(保证「同一 symbol 只保留首个 title」跨 hunk 生效);
865
+ - 返回 `h('span', { className: 'pe-diff' }, hunks.map((hunk, i) => ...))`:
866
+ - `equal` / `add`:`h('span', { key: 'hunk-' + i, className: 'pe-diff-hunk pe-diff-' + hunk.type + (hunk.chinese ? ' pe-diff-cjk' : '') }, h(SymbolText, { text: hunk.text, symbols, seen, labelOf }))`
867
+ - `del`:同样 className,但子节点是纯文本 `hunk.text`(删除内容不参与悬浮匹配)。
868
+ - hunk 全部 `display: inline`,不换块;容器保留 `white-space: pre-wrap; overflow-wrap: anywhere`。
869
+ - `add` 背景高亮、`del` 删除线(CSS 见 §9.4);`equal` 无额外样式。
870
+ - `Diff` 组件保留并改造为:
871
+
872
+ ```js
873
+ function Diff({ t, before, after, symbols }) {
874
+ const labelOf = (symbol) => positionLabel(t, symbol)
875
+ return h('div', null,
876
+ h('div', { className: 'pe-diff-label' }, t('panel.diff.original')),
877
+ h('div', { className: 'pe-block pe-block-original' }, before),
878
+ h('div', { className: 'pe-diff-label', style: { marginTop: 8 } }, t('panel.diff.enhanced')),
879
+ h('div', { className: 'pe-block pe-block-enhanced' }, h(SemanticDiff, { before, after, symbols, labelOf })),
880
+ h(DiffLegend, { t }),
881
+ )
882
+ }
883
+ ```
884
+
885
+ - `Diff` 的 `before` 传 `snapRef.current.view.body`,`after` 传 `state.res.text`;命令前缀不参与 diff(面板已有 `panel.command.note` 说明)。
886
+ - 悬浮匹配按 hunk 进行;被 hunk 边界切断的 symbol 不包装(明确接受,不报错)。
887
+
888
+ ---
889
+
890
+ ## 8. F) 悬浮位置(`SymbolText`)
891
+
892
+ ### 8.1 边界定义
893
+
894
+ ```js
895
+ function isSymbolChar(ch) {
896
+ return /^[A-Za-z0-9_$]$/.test(ch)
897
+ }
898
+ ```
899
+
900
+ - 只有前后字符都**不是** `isSymbolChar` 时才算整词匹配;中文字符、标点、空白都自然成为边界。
901
+ - 因此 `把collectContext函数` 能匹配 `collectContext`(前 `把`、后 `函` 均非 symbol 字符)。
902
+ - 不使用 `\b`(它会把 CJK 当非词边界的行为与 JS 实现细节绑定),必须用上面的显式判断。
903
+
904
+ ### 8.2 匹配算法
905
+
906
+ ```js
907
+ function matchSymbols(text, symbols, seen) // -> Array<{ text: string, symbol: SymbolRef | null, first: boolean }>
908
+ ```
909
+
910
+ 1. 过滤 `symbols`:`name` 非空字符串、`kind ∈ {'function','variable','class'}`、`file` 字符串、`line` 正整数;按 `name` 去重(数组顺序首个胜出)。
911
+ 2. 候选按 `name.length` 降序、`name` 字典升序排列(长名优先,避免 `foo` 抢在 `foobar` 前面)。
912
+ 3. 从左到右扫描 `text`(UTF-16 index):
913
+ - 若当前位置前一个字符是 `isSymbolChar` → 不匹配,前进 1;
914
+ - 依次尝试候选:`text.startsWith(name, i)` 且 `i + name.length` 位置的下一个字符不是 `isSymbolChar` → 命中;
915
+ - 命中后:`first = !seen.has(name)`;`seen.add(name)`;产出 segment,`i += name.length`;
916
+ - 未命中:并入当前普通文本 segment,`i += 1`。
917
+ 4. 相邻普通字符合并成一个 segment;返回数组顺序与 text 一致。
918
+
919
+ ### 8.3 `SymbolText` 渲染
920
+
921
+ - props:`{ text: string, symbols: SymbolRef[], seen: Set<string>, labelOf: (symbol) => string }`。
922
+ - 对每个 segment:
923
+ - 普通文本:`segment.text`;
924
+ - 命中:`h('span', { key: ..., className: 'pe-sym' + (segment.first ? '' : ' pe-sym-repeat'), title: segment.first ? label : undefined, 'aria-label': segment.first ? label : undefined, 'data-pe-symbol': segment.first ? segment.symbol.name : undefined }, segment.text)`。
925
+ - `label = labelOf(segment.symbol)`;`SymbolText` 不接收 `t`,不自己拼文案。`labelOf` 由 `SemanticDiff` 以闭包 `(symbol) => positionLabel(t, symbol)` 传入:
926
+
927
+ ```js
928
+ function positionLabel(t, symbol) {
929
+ return interpolate(t('panel.hover.position'), { file: symbol.file, line: symbol.line })
930
+ }
931
+
932
+ function interpolate(template, vars) {
933
+ return String(template).replace(/\{(\w+)\}/g, (all, key) =>
934
+ Object.prototype.hasOwnProperty.call(vars, key) ? String(vars[key]) : all)
935
+ }
936
+ ```
937
+
938
+ - `title` 与 `aria-label` 文案完全一致:`≈ src/index.js:120(附近 ±3 行)` / `≈ src/index.js:120 (±3 lines)`。
939
+ - 同一 symbol 后续出现:**不加** `title`/`aria-label`/`data-pe-symbol`,只加 `pe-sym-repeat`(下划线样式)。
940
+ - 首个出现也不加下划线;重复出现加下划线(§9.4 CSS)。
941
+ - 所有 span 都是 `display: inline`,不插入额外空白,不改变文本内容;`textContent` 与原文逐字符一致。
942
+
943
+ ### 8.4 写回不受影响(硬约束)
944
+
945
+ - `SymbolText` 只出现在 `Diff` / `SemanticDiff` 的预览树中。
946
+ - `applyNow` / `applyAnyway` / `undo` 仍然使用 `state.res.text` / `appliedRef.current.before` 字符串;不得从 DOM 取 `textContent`,不得对 `state.res.text` 做任何 span 化处理。
947
+ - 测试必须断言:`normalizeModelResult(...).text` 与 `state.res.text` 不包含 `pe-sym`、`<span` 等标记。
948
+
949
+ ---
950
+
951
+ ## 9. G) Client 集成与文件分工(`client.js`)
952
+
953
+ ### 9.1 slot props 与数据流
954
+
955
+ 1. `EnhanceTrigger(props)` 从 `props` 解构 `sessionId`(`conversation.input.left` 的 standard prop);不新增 `inject`。
956
+ 2. 读取 `const claimName = useInput((s) => (s.claim && s.claim.name) || '')`;`claimToken` 保留原逻辑。
957
+ 3. `analyzeDraft({ draft, phase, claimToken, claimName, occurrences })`;返回值新增 `commandName`:
958
+ - `kind === 'command'` 且 `normalizeCommandName(claimName)` 非空 → `commandName` 为该归一化名称;
959
+ - 其它情况 → `commandName: null`;
960
+ - 不得从 `claimToken` 推导。
961
+ 4. `EnhanceTrigger` 把 `sessionId`、`claimName` 传给 `EnhancePopover`,再传给 `EnhancePanel`。
962
+ 5. `EnhancePanel` 的 `snapRef` 增加字段:
963
+
964
+ ```js
965
+ const snapRef = React.useRef({ text: draft, rev, view: draftView, sessionId })
966
+ ```
967
+
968
+ - 打开面板、`regenerate` 时都写入当前 `sessionId`;
969
+ - `enhance({ ..., sessionId: snapRef.current.sessionId, awareness, commandName: snapRef.current.view.commandName })`。
970
+
971
+ 6. `EnhancePanel` 用 `useSettings()` 的 `conf` 构造 §5.4 的 `awareness` 对象。
972
+ 7. `Diff` 调用改为 `h(Diff, { t, before: snapRef.current.view.body, after: state.res.text, symbols: state.res.symbols || [] })`。
973
+ 8. `ContextList` 放在 `Diff` 之后,条件:
974
+
975
+ ```js
976
+ state.res && (state.res.context || state.res.command) && (state.kind === 'preview' || state.kind === 'conflict')
977
+ ? h(ContextList, { t, context: state.res.context, command: state.res.command })
978
+ : null
979
+ ```
980
+
981
+ ### 9.2 引擎层扩展
982
+
983
+ ```js
984
+ async function enhance({ text, locale, mode, signal, selection, timeoutMs, onPartial, sessionId, awareness, commandName })
985
+ async function enhanceWithModel(text, locale, signal, selection, extras)
986
+ async function enhanceViaHttp(text, locale, signal, selection, extras)
987
+ async function postEnhance(endpoint, text, locale, signal, selection, extras)
988
+ async function runModel(text, locale, signal, selection, timeoutMs, extras)
989
+ function buildEnhanceBody(text, locale, selection, extras)
990
+ function normalizeModelResult(res)
991
+ ```
992
+
993
+ - `extras = { sessionId, awareness, commandName }`;只在 model / auto 的模型调用里传递。
994
+ - `buildEnhanceBody` 精确输出:
995
+
996
+ ```js
997
+ function buildEnhanceBody(text, locale, selection, extras) {
998
+ const body = { text, locale }
999
+ if (selection && selection.provider && selection.model) {
1000
+ body.provider = selection.provider
1001
+ body.model = selection.model
1002
+ }
1003
+ if (extras && typeof extras.sessionId === 'string' && extras.sessionId) body.sessionId = extras.sessionId
1004
+ if (extras && extras.awareness) {
1005
+ body.awareness = {
1006
+ enabled: extras.awareness.enabled === true,
1007
+ maxFiles: extras.awareness.maxFiles,
1008
+ maxLinesPerFile: extras.awareness.maxLinesPerFile,
1009
+ maxTokens: extras.awareness.maxTokens,
1010
+ }
1011
+ }
1012
+ if (extras && typeof extras.commandName === 'string' && extras.commandName) {
1013
+ body.commandName = extras.commandName
1014
+ }
1015
+ return body
1016
+ }
1017
+ ```
1018
+
1019
+ - `postEnhance` 用 `JSON.stringify(buildEnhanceBody(...))` 作为 body;`enhanceWithModel` 的 remote/host.call 分支也传同一个 request 对象。
1020
+ - `mode === 'rules'` 不构造、不发送感知字段(规则通道完全本地,不读文件)。
1021
+ - `onPartial` 的首个规则结果不带 `context/symbols`;模型结果到达后由 `accept` 替换。
1022
+
1023
+ ### 9.3 `normalizeModelResult` 扩展
1024
+
1025
+ ```js
1026
+ function normalizeModelResult(res) {
1027
+ const text = cleanModelText(res && res.text)
1028
+ if (!text) throw new EnhanceError('model')
1029
+ const notes = /* 现有逻辑不变 */
1030
+ const out = { text, notes }
1031
+
1032
+ const c = res && res.context
1033
+ if (c && typeof c === 'object' && typeof c.enabled === 'boolean' && Array.isArray(c.files)
1034
+ && c.budget && typeof c.budget === 'object') {
1035
+ const files = c.files.filter((f) => f && typeof f.path === 'string'
1036
+ && Number.isFinite(f.startLine) && Number.isFinite(f.endLine)
1037
+ && Number.isFinite(f.lines) && Number.isFinite(f.tokens) && Number.isFinite(f.score))
1038
+ .map((f) => ({
1039
+ path: f.path,
1040
+ absolutePath: typeof f.absolutePath === 'string' ? f.absolutePath : '',
1041
+ startLine: f.startLine, endLine: f.endLine,
1042
+ lines: f.lines, tokens: f.tokens, score: f.score,
1043
+ }))
1044
+ out.context = {
1045
+ enabled: c.enabled,
1046
+ files,
1047
+ totalFiles: Number.isFinite(c.totalFiles) ? c.totalFiles : files.length,
1048
+ totalLines: Number.isFinite(c.totalLines) ? c.totalLines : files.reduce((n, f) => n + f.lines, 0),
1049
+ totalTokens: Number.isFinite(c.totalTokens) ? c.totalTokens : files.reduce((n, f) => n + f.tokens, 0),
1050
+ budget: {
1051
+ maxFiles: c.budget.maxFiles, maxLinesPerFile: c.budget.maxLinesPerFile, maxTokens: c.budget.maxTokens,
1052
+ },
1053
+ skippedFiles: Number.isFinite(c.skippedFiles) ? c.skippedFiles : 0,
1054
+ truncated: c.truncated === true,
1055
+ sessionId: typeof c.sessionId === 'string' ? c.sessionId : null,
1056
+ workspaceRoot: typeof c.workspaceRoot === 'string' ? c.workspaceRoot : null,
1057
+ source: c.source === 'live' || c.source === 'persisted' ? c.source : 'none',
1058
+ }
1059
+ if (typeof c.skipped === 'string') out.context.skipped = c.skipped
1060
+ if (c.error && typeof c.error.code === 'string') out.context.error = { code: c.error.code, message: String(c.error.message || '') }
1061
+ }
1062
+
1063
+ if (Array.isArray(res && res.symbols)) {
1064
+ out.symbols = res.symbols.filter((s) => s && typeof s.name === 'string' && s.name
1065
+ && (s.kind === 'function' || s.kind === 'variable' || s.kind === 'class')
1066
+ && typeof s.file === 'string' && Number.isFinite(s.line) && s.line >= 1)
1067
+ .map((s) => ({ name: s.name, kind: s.kind, file: s.file, line: s.line }))
1068
+ }
1069
+
1070
+ const cmd = res && res.command
1071
+ if (cmd && typeof cmd.name === 'string' && typeof cmd.description === 'string'
1072
+ && (cmd.source === 'registry' || cmd.source === 'fallback')) {
1073
+ out.command = { name: cmd.name, description: cmd.description, source: cmd.source }
1074
+ }
1075
+ return out
1076
+ }
1077
+ ```
1078
+
1079
+ - 形状不合法 → 丢弃该字段,不抛错、不影响 `text`。
1080
+ - `context` 合法但 `files` 过滤后为空:仍然保留 `context`(`enabled` 以 Host 字段为准;Client 展示降级/空状态)。
1081
+ - `notes` 逻辑保持原样。
1082
+
1083
+ ### 9.4 CSS(新增类名固定)
1084
+
1085
+ ```css
1086
+ .pe-context { display: flex; flex-direction: column; gap: 2px; padding: 6px 8px;
1087
+ border: 0.5px solid var(--dsw-alias-border-l2); border-radius: var(--dsw-radius-md);
1088
+ background: var(--dsw-alias-bg-layer-1); }
1089
+ .pe-context-head { display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
1090
+ color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); line-height: 16px; font-weight: 500; }
1091
+ .pe-context-workspace { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%;
1092
+ color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); }
1093
+ .pe-context-list { display: flex; flex-direction: column; gap: 1px; }
1094
+ .pe-context-row { color: var(--dsw-alias-label-secondary); font-size: calc(12px * var(--pe-scale));
1095
+ line-height: 18px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
1096
+ .pe-context-total { color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); line-height: 16px; }
1097
+ .pe-context-note { color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); line-height: 16px; }
1098
+ .pe-context-note.pe-context-warn { color: var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-secondary)); }
1099
+
1100
+ .pe-command { display: flex; align-items: center; gap: 6px; flex-wrap: wrap;
1101
+ color: var(--dsw-alias-label-secondary); font-size: calc(12px * var(--pe-scale)); line-height: 18px; }
1102
+ .pe-command-name { color: var(--dsw-alias-label-primary); font-weight: 500; }
1103
+
1104
+ .pe-diff { white-space: pre-wrap; overflow-wrap: anywhere; }
1105
+ .pe-diff-hunk { display: inline; }
1106
+ .pe-diff-add { background: var(--dsw-alias-interactive-bg-hover);
1107
+ background: color-mix(in srgb, var(--dsw-alias-state-success-primary) 18%, transparent);
1108
+ border-radius: 2px; }
1109
+ .pe-diff-del { text-decoration: line-through; opacity: .65; }
1110
+ .pe-diff-cjk { letter-spacing: 0; }
1111
+ .pe-diff-legend { display: flex; align-items: center; gap: 8px; margin-top: 4px;
1112
+ color: var(--dsw-alias-label-tertiary); font-size: calc(11px * var(--pe-scale)); line-height: 16px; }
1113
+ .pe-diff-legend-item { display: inline-flex; align-items: center; gap: 3px; }
1114
+ .pe-diff-legend-swatch { display: inline-block; width: 8px; height: 8px; border-radius: 2px; }
1115
+ .pe-diff-legend-swatch[data-kind='add'] { background: var(--dsw-alias-state-success-primary); opacity: .45; }
1116
+ .pe-diff-legend-swatch[data-kind='del'] { background: var(--dsw-alias-label-tertiary); opacity: .45; }
1117
+
1118
+ .pe-sym { cursor: help; }
1119
+ .pe-sym-repeat { text-decoration: underline; text-decoration-style: dotted; text-underline-offset: 2px; }
1120
+ ```
1121
+
1122
+ - `pe-diff-add` 必须同时写 `background` 普通值与 `color-mix` 覆盖,保证旧主题变量缺失时仍有高亮。
1123
+ - 不新增全局样式,不修改现有 `.pe-block-*` 规则。
1124
+
1125
+ ### 9.5 组件清单(名字固定)
1126
+
1127
+ ```js
1128
+ function ContextList({ t, context, command })
1129
+ function SemanticDiff({ before, after, symbols, labelOf })
1130
+ function SymbolText({ text, symbols, seen, labelOf })
1131
+ function DiffLegend({ t })
1132
+ function positionLabel(t, symbol)
1133
+ function interpolate(template, vars)
1134
+ function computeSemanticDiff(before, after)
1135
+ function matchSymbols(text, symbols, seen)
1136
+ function buildEnhanceBody(text, locale, selection, extras)
1137
+ function normalizeModelResult(res)
1138
+ ```
1139
+
1140
+ `SemanticDiff` 的 `labelOf` 由 `Diff` 传入:`(symbol) => positionLabel(t, symbol)`;`SymbolText` 不直接依赖 `t`。
1141
+
1142
+ ### 9.6 `ContextList` 渲染规则
1143
+
1144
+ 辅助函数:`interpolate(template, vars)`(§8.3)。所有路径/数字都通过模板替换,不得手写拼接。
1145
+
1146
+ 1. `context` 与 `command` 都不存在 → 返回 `null`。
1147
+ 2. 容器 `h('div', { className: 'pe-context' }, ...)`。
1148
+ 3. 若 `command` 存在,第一行:
1149
+
1150
+ ```js
1151
+ h('div', { className: 'pe-command' },
1152
+ h('span', null, t('panel.command.label')),
1153
+ h('span', { className: 'pe-command-name' }, command.name),
1154
+ h('span', { className: 'pe-context-note' }, command.description))
1155
+ ```
1156
+
1157
+ 4. 若 `context` 存在:
1158
+ - 标题行:`h('div', { className: 'pe-context-head' }, t('panel.context.title'), source 标签)`;
1159
+ - `source === 'live'` → `panel.context.source.live`;`persisted` → `panel.context.source.persisted`;`none` 不显示。
1160
+ - `workspaceRoot` 非空 → `h('div', { className: 'pe-context-workspace' }, interpolate(t('panel.context.workspace'), { root: context.workspaceRoot }))`。
1161
+ - `enabled && files.length > 0`:
1162
+ - `h('div', { className: 'pe-context-list' }, context.files.map((f) => h('div', { key: f.path, className: 'pe-context-row' }, interpolate(t('panel.context.file'), { path: f.path, lines: f.lines, tokens: f.tokens }))))`
1163
+ - 总计行:`interpolate(t('panel.context.total'), { files: context.totalFiles, lines: context.totalLines, tokens: context.totalTokens })`,className `pe-context-total`。
1164
+ - `truncated === true` → `h('div', { className: 'pe-context-note' }, t('panel.context.truncated'))`。
1165
+ - `skippedFiles > 0` → `h('div', { className: 'pe-context-note' }, interpolate(t('panel.context.skippedFiles'), { count: context.skippedFiles }))`。
1166
+ - `!enabled && !skipped && !error && files.length === 0` → `h('div', { className: 'pe-context-note' }, t('panel.context.empty'))`。
1167
+ - `skipped` 存在 → 映射 key:
1168
+ | skipped | key |
1169
+ |---|---|
1170
+ | `no-session` | `panel.context.skip.noSession` |
1171
+ | `no-workspace` | `panel.context.skip.noWorkspace` |
1172
+ | `search-failed` | `panel.context.skip.searchFailed` |
1173
+ | `read-failed` | `panel.context.skip.readFailed` |
1174
+ | `budget-exhausted` | `panel.context.skip.budgetExhausted` |
1175
+ 渲染为 `pe-context-note`。
1176
+ - `error` 存在 → code 映射 `awareness_denied` → `panel.context.error.awarenessDenied`;`awareness_failed` → `panel.context.error.awarenessFailed`;追加 `pe-context-note pe-context-warn`。两行可同时出现(例如 `skipped=no-workspace` + `error=awareness_denied`)。
1177
+
1178
+ ### 9.7 诊断行与 BUILD
1179
+
1180
+ - `BUILD` 常量改为 `'2026-12-06.1'`,便于确认真机加载的是新 Client。
1181
+ - `debugInfo()` 不变;不把文件内容、绝对路径写入 `TRACE`。
1182
+
1183
+ ---
1184
+
1185
+ ## 10. 验收测试(两人都必须补)
1186
+
1187
+ ### 10.1 Host(`test/host.mjs`)
1188
+
1189
+ 新增 fake 服务时保持 `ctx.get(name)` 对未知 name 返回 `undefined`,旧测试必须继续通过。最少覆盖:
1190
+
1191
+ 1. **旧请求兼容**:`json({ text: '帮我写个函数', locale: 'zh' })` → 模型收到的 `messages[0].content[0].text` 仍等于原文;响应无 `context/symbols`。
1192
+ 2. **live 会话**:`sessions.get(id)` 返回 `header.cwd` → `context.source='live'`、`workspaceRoot` 正确、`files.length>0`、`totalLines/totalTokens` 等于各文件求和。
1193
+ 3. **非 live**:`sessions.get` 返回 undefined、`sessionPersistence.stat` 返回 header → `source='persisted'`。
1194
+ 4. **no-session**:awareness 开启但不传 `sessionId` → 200、`context.enabled=false`、`skipped='no-session'`、`error.code='awareness_denied'`、`symbols=[]`。
1195
+ 5. **no-workspace**:会话存在但无 cwd、persistence 也无线索 → `skipped='no-workspace'`、`error.code='awareness_denied'`;断言没有调用 `sessions.list()`/`sandboxPolicy`。
1196
+ 6. **预围栏**:fake `workspaceFiles.search` 返回 `../outside.js`;fake `fs.contains` 返回 false → 不调用 `read`,`skippedFiles=1`。
1197
+ 7. **后围栏**:fake `read` 返回工作区外 `absolutePath` → 文件不进入 `context.files`,`skippedFiles` 增加。
1198
+ 8. **只读断言**:fake `fs` 记录调用,断言只出现 `resolve/contains`;fake `workspaceFiles` 只出现 `read/list/search`,绝不出现写方法。
1199
+ 9. **二进制/过大**:fake `read` 抛 `workspace-file/not-text` / `too-large` → 跳过并继续其它文件。
1200
+ 10. **预算**:`maxFiles:1` 且 3 个候选 → `files.length===1`、`truncated===true`;`maxTokens:1` → `skipped='budget-exhausted'`、`truncated===true`、`files=[]`。
1201
+ 11. **符号**:包含 `function collectContext(`、`const foo = () =>`、`class A` 的文本 → `symbols` 的 `kind/line/file` 正确,`line` 是文件绝对行号。
1202
+ 12. **命令 registry**:fake `agents.get` + `commands.list` → `command.source='registry'`、description 来自 descriptor。
1203
+ 13. **命令 fallback**:无 Agent / 无 commands / descriptor 不存在 → `source='fallback'`,zh/en description 分别为 `'命令说明不可用'` / `'Command description unavailable'`。
1204
+ 14. **上下文块**:awareness 有文件时,模型收到的 user 文本以 `<workspace-context>` 开头、含 `<file path="..." lines="1-...">` 和 `<draft>`;无文件时逐字节等于原文。
1205
+ 15. **失败不阻断**:fake `workspaceFiles.search` 抛错 → 200、模型仍被调用、`skipped='search-failed'`、`error.code='awareness_failed'`。
1206
+
1207
+ ### 10.2 Client(`test/smoke.mjs`)
1208
+
1209
+ `__test__` 追加导出:`buildEnhanceBody`、`normalizeModelResult`、`computeSemanticDiff`、`matchSymbols`、`positionLabel`、`interpolate`。最少覆盖:
1210
+
1211
+ 1. **设置**:`normalizeSettings({ awareness:'on', contextTokens:1200, contextLines:160, contextFiles:8 })` 全保留;非法 `'yes'/500/999` 回落到 `off/800/80/5`;旧数据 `{fontSize:'compact'}` 得到新默认值;`SETTINGS_KEY` 仍为 `prompt-enhance:settings`。
1212
+ 2. **请求体**:`buildEnhanceBody` 在无 extras 时只含 `{text,locale}`;有 extras 时含 `sessionId/awareness/commandName`;`selection` 只在与 provider+model 同时存在时写入。
1213
+ 3. **响应归一化**:带 `context/symbols/command` 的响应完整保留;非法 `context` 被丢弃但 `text` 仍返回;`symbols` 非法条目被过滤。
1214
+ 4. **语义 diff**:`before='const a = 1'`、`after='const b = 1'` → 有 `del`/`add` hunk;空白折叠;`chinese` 只在含 CJK 的 hunk 出现;>400 token 输入走 `mode='line'`;完全相同时只有一个 `equal` hunk。
1215
+ 5. **悬浮匹配**:`matchSymbols('把collectContext函数和 collectContext 再看一次', symbols, new Set())` → 两处命中;第一处 `first=true`、第二处 `false`;长名 `foobar` 优先于 `foo`;`collectContextExtra` 不被 `collectContext` 误命中(前后都是 symbol 字符)。
1216
+ 6. **位置文案**:`positionLabel` zh/en 分别得到 `≈ src/index.js:12(附近 ±3 行)` 与 `≈ src/index.js:12 (±3 lines)`。
1217
+ 7. **写回不受影响**:预览 `state.res.text` 不含 `pe-sym`/`<span`;`planWrite` 仍按原逻辑工作。
1218
+ 8. **命令名**:`analyzeDraft({ claimName:'goal', claimToken:'/目标 ', ... })` → `commandName='goal'`;只有 token 时 `commandName=null`,不得猜成 `目标`。
1219
+
1220
+ 运行命令(必须都通过):
1221
+
1222
+ ```bash
1223
+ node test/host.mjs
1224
+ node test/smoke.mjs
1225
+ # 或
1226
+ node --test test/host.mjs test/smoke.mjs # 仅当两人决定改成 node:test 时;默认仍用上面两条
1227
+ ```
1228
+
1229
+ > 说明:当前 `test/host.mjs` 与 `test/smoke.mjs` 是自定义断言 + 顶层 `await` 的脚本,直接 `node test/host.mjs` / `node test/smoke.mjs` 即可;不要引入测试框架依赖。
1230
+
1231
+ ---
1232
+
1233
+ ## 11. 明确不做(防止范围蔓延)
1234
+
1235
+ - 不做工作区写回、不做文件编辑、不做 patch 预览。
1236
+ - 不做 `@文件` 引用注入;Client 只从 `claim.name` 取命令名,不从 `occurrences` 反推引用文件。
1237
+ - 不做「最近会话」兜底、不做跨会话读取、不做 `sandboxPolicy.workspaceRoot` 猜测。
1238
+ - 不做中文分词;CJK 按单字 token 处理。
1239
+ - 不做 diff 交互(接受/拒绝单块);diff 纯展示。
1240
+ - 不新增依赖、不新增构建步骤、不新增 HTTP 路由(仍走 `/enhance`)。
1241
+ - 不改 `locale/*.json`、`README`、`CHANGELOG`、`package.json`(由 captain / 集成者统一处理)。
1242
+
1243
+ ---
1244
+
1245
+ ## 12. 变更记录
1246
+
1247
+ - 2026-12-06 v1.0:基于 `docs/dev/context-facts.md` 与 captain 的 live Cordis Inspect 修正,冻结本契约。关键修正:
1248
+ 1. `sessionId` 直接来自 `conversation.input.left` 的 slot standardProps;
1249
+ 2. 会话解析只允许 live → persisted,失败即 `no-workspace`,禁止 `sessions.list()` / `sandboxPolicy` 兜底;
1250
+ 3. `workspaceFiles` 读路径必须 `fs.contains` 双重围栏;
1251
+ 4. 预算三层硬上限 + `estimateTokens = ceil(len/3.5)`;
1252
+ 5. 命令描述只由 Host 提供,Client 不调 `remote.commands`;
1253
+ 6. `context.skipped` 严格限定为 `no-session | no-workspace | search-failed | read-failed | budget-exhausted`。