@mealsea/dsh-prompt-enhance 1.0.0 → 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.
package/test/host.mjs CHANGED
@@ -23,9 +23,17 @@ const textStream = (text) => async function* () {
23
23
  yield { type: 'finish', reason: { kind: 'stop' } }
24
24
  }
25
25
 
26
+ const allWfCalls = []
27
+ const allFsCalls = []
28
+ // 所有响应里的 context,供全局“totalTokens 从不超预算”不变量断言使用。
29
+ const contextObservations = []
30
+
26
31
  function makeCtx(options = {}) {
27
32
  const routes = []
28
33
  const calls = []
34
+ const wfCalls = []
35
+ const fsCalls = []
36
+ const gets = []
29
37
  const ctx = {
30
38
  effect(fn) { fn() },
31
39
  webServer: {
@@ -33,6 +41,7 @@ function makeCtx(options = {}) {
33
41
  register(route) { routes.push(route); return () => {} },
34
42
  },
35
43
  get(name) {
44
+ gets.push(name)
36
45
  if (name === 'agentDefaultModel') {
37
46
  return { currentSelection: () => options.selection === undefined ? { provider: 'deepseek', model: 'deepseek-chat' } : options.selection }
38
47
  }
@@ -72,10 +81,31 @@ function makeCtx(options = {}) {
72
81
  }
73
82
  return llm
74
83
  }
84
+ if (name === 'sessions') return options.sessions
85
+ if (name === 'sessionPersistence') return options.sessionPersistence
86
+ if (name === 'agents') return options.agents
87
+ if (name === 'commands') return options.commands
88
+ if (name === 'workspaceFiles' && options.workspaceFiles) {
89
+ const wf = options.workspaceFiles
90
+ const wrap = (key) => (typeof wf[key] === 'function'
91
+ ? (...args) => { wfCalls.push(key); allWfCalls.push(key); return wf[key](...args) }
92
+ : undefined)
93
+ return {
94
+ read: wrap('read'), search: wrap('search'), list: wrap('list'), stat: wrap('stat'),
95
+ write: wrap('write'), writeFile: wrap('writeFile'), remove: wrap('remove'),
96
+ delete: wrap('delete'), mkdir: wrap('mkdir'), rename: wrap('rename'),
97
+ }
98
+ }
99
+ if (name === 'fs' && options.fs) {
100
+ return {
101
+ resolve: (...args) => { fsCalls.push('resolve'); allFsCalls.push('resolve'); return options.fs.resolve(...args) },
102
+ contains: (...args) => { fsCalls.push('contains'); allFsCalls.push('contains'); return options.fs.contains(...args) },
103
+ }
104
+ }
75
105
  return undefined
76
106
  },
77
107
  }
78
- return { ctx, routes, calls }
108
+ return { ctx, routes, calls, wfCalls, fsCalls, gets }
79
109
  }
80
110
 
81
111
  function makeReq({ method = 'POST', headers = {}, body = '' } = {}) {
@@ -111,6 +141,8 @@ async function call(route, init = {}) {
111
141
  await done
112
142
  let json = null
113
143
  try { json = res.body ? JSON.parse(res.body) : null } catch { json = null }
144
+ // 记录所有返回的 context,用于全局预算不变量审计。
145
+ if (json && json.context && typeof json.context === 'object') contextObservations.push(json.context)
114
146
  return { status: res.status, headers: res.headers, json, raw: res.body }
115
147
  }
116
148
 
@@ -335,4 +367,577 @@ const routeOf = (options) => {
335
367
  const noCatalog = await call(routes[2], { method: 'GET', headers: {} })
336
368
  assert(noCatalog.status === 502 && noCatalog.json.code === 'model', 'llm 不提供目录时 502')
337
369
  }
370
+ // ---------------------------------------------------------------- 7. 工作区感知(只读上下文)
371
+ const T = (await import('../index.js')).__test__
372
+ const AW_ROOT = '/ws'
373
+
374
+ function fakeFs(config = {}) {
375
+ const contains = config.contains || ((root, target) => {
376
+ const base = String(root).replace(/\/$/, '')
377
+ return target === base || String(target).startsWith(base + '/')
378
+ })
379
+ return {
380
+ resolve(path, opts = {}) {
381
+ const norm = String(path).replace(/\\/g, '/')
382
+ if (norm.startsWith('/') || /^[A-Za-z]:\//.test(norm)) return Promise.resolve(norm)
383
+ const cwd = String(opts.cwd || AW_ROOT).replace(/\\/g, '/').replace(/\/$/, '')
384
+ return Promise.resolve(cwd + '/' + norm.replace(/^\.\//, ''))
385
+ },
386
+ contains(root, target) { return contains(root, target) },
387
+ }
388
+ }
389
+
390
+ function fakeWf(config = {}) {
391
+ const reads = []
392
+ return {
393
+ reads,
394
+ // 只读白名单:实现若调用任何写方法会立刻抛错,末尾还有零调用断言
395
+ async write() { throw new Error('workspaceFiles.write must not be called') },
396
+ async writeFile() { throw new Error('workspaceFiles.writeFile must not be called') },
397
+ async remove() { throw new Error('workspaceFiles.remove must not be called') },
398
+ async delete() { throw new Error('workspaceFiles.delete must not be called') },
399
+ async search() {
400
+ if (config.searchThrows) throw new Error('search boom')
401
+ const matches = (config.matches || []).map((path) => ({ type: 'file', path }))
402
+ return { matches, total: matches.length }
403
+ },
404
+ async read(scope, path, options) {
405
+ reads.push(path)
406
+ const code = (config.readThrowsFor && config.readThrowsFor[path]) || config.readThrows
407
+ if (code) throw Object.assign(new Error('not readable'), { code })
408
+ const page = (config.pages && config.pages[path]) || config.page
409
+ if (!page) throw Object.assign(new Error('missing'), { code: 'workspace-file/not-found' })
410
+ return { absolutePath: '/ws/' + String(path).replace(/^\.\//, ''), offset: options.offset, eof: true, lines: 1, text: '', ...page }
411
+ },
412
+ }
413
+ }
414
+
415
+ // 纯函数 / 归一化
416
+ {
417
+ assert(T && typeof T.estimateTokens === 'function', '导出内部测试入口 __test__')
418
+ assert(T.estimateTokens('abcdefg') === 2 && T.estimateTokens('') === 0, 'estimateTokens = ceil(len/3.5)')
419
+ const b = T.normalizeAwarenessRequest({ enabled: true, maxFiles: 99, maxLinesPerFile: 0, maxTokens: 999999 })
420
+ assert(b.enabled === true && b.maxFiles === 8 && b.maxLinesPerFile === 1 && b.maxTokens === 1200, '预算夹取到硬上限')
421
+ assert(T.normalizeAwarenessRequest(undefined).enabled === false, '缺省 awareness 关闭')
422
+ assert(T.normalizeCommandName('/Goal') === 'goal', '命令名去斜杠并小写')
423
+ assert(T.normalizeCommandName('a b') === '' && T.normalizeCommandName('x'.repeat(70)) === '', '非法命令名被拒绝')
424
+ const hints = T.extractContextHints('请改 src/app.js 里的 createServer,再看看 createServer 的日志')
425
+ assert(hints.length > 0 && hints.length <= 6, '提示最多 6 条')
426
+ assert(hints[0].kind === 'path' && hints[0].text === 'src/app.js', '路径提示排在最前')
427
+ assert(hints.some((h) => h.kind === 'term' && h.text === 'createserver'), '重复标识符作为术语提示')
428
+ const block = T.buildContextBlock({ enabled: true, files: [{ path: 'a.js', startLine: 1, endLine: 2 }] }, new Map([['a.js', 'const a = 1']]), 'zh')
429
+ assert(block.startsWith('<workspace-context>') && block.includes('<file path="a.js" lines="1-2">') && block.includes('const a = 1'), '上下文块形状')
430
+ assert(T.buildContextBlock({ enabled: false, files: [] }, new Map(), 'zh') === '', '无上下文时块为空')
431
+ }
432
+
433
+ // 默认关:不出现 context/symbols,且一次 workspaceFiles/fs 调用都不发生
434
+ {
435
+ const made = routeOf({ workspaceFiles: fakeWf({ matches: ['src/app.js'] }), fs: fakeFs() })
436
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js', sessionId: 's1' }))
437
+ assert(res.status === 200 && res.json.text === '你好世界', '旧请求(无 awareness)行为不变')
438
+ assert(!('context' in res.json) && !('symbols' in res.json) && !('command' in res.json), '旧请求不新增响应字段')
439
+ assert(Array.isArray(res.json.notes) && res.json.notes.length === 0, 'notes 为空数组')
440
+ assert(made.wfCalls.length === 0 && made.fsCalls.length === 0, 'awareness 关闭时零 IO')
441
+ }
442
+
443
+ // live 会话:搜索 → 双重围栏 → 行窗口 → 审计对象 + 符号
444
+ {
445
+ const pageText = 'export function createServer() {\n return 1\n}\n'
446
+ const made = routeOf({
447
+ sessions: { get: (id) => (id === 's1' ? { header: { cwd: AW_ROOT } } : undefined) },
448
+ workspaceFiles: fakeWf({ matches: ['src/app.js'], page: { text: pageText, lines: 3 } }),
449
+ fs: fakeFs(),
450
+ })
451
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js 里的 createServer', sessionId: 's1', awareness: { enabled: true } }))
452
+ assert(res.status === 200 && res.json.text === '你好世界', '开启感知后改写仍成功')
453
+ const c = res.json.context
454
+ assert(c.enabled === true && c.source === 'live' && c.sessionId === 's1' && c.workspaceRoot === AW_ROOT, 'context 基本字段')
455
+ assert(c.totalFiles === 1 && c.files.length === 1 && c.totalLines === 3, '收录一个文件并统计行数')
456
+ const f = c.files[0]
457
+ assert(f.path === 'src/app.js' && f.startLine === 1 && f.endLine === 3 && f.lines === 3, '文件窗口字段')
458
+ assert(f.tokens === T.estimateTokens(pageText) && c.totalTokens === f.tokens, 'token 估算一致')
459
+ assert(c.budget.maxFiles === 5 && c.budget.maxLinesPerFile === 80 && c.budget.maxTokens === 800, '预算回显默认值')
460
+ assert(c.skippedFiles === 0 && c.truncated === false, '无跳过、未截断')
461
+ assert(Array.isArray(res.json.symbols) && res.json.symbols.some((s) => s.name === 'createServer' && s.kind === 'function' && s.file === 'src/app.js' && s.line === 1), '符号带 kind/file/line')
462
+ const userText = made.calls[0].messages[0].content[0].text
463
+ assert(userText.startsWith('<workspace-context>'), '上下文块位于草稿之前')
464
+ assert(userText.includes('<file path="src/app.js" lines="1-3">'), '文件块带路径与行范围')
465
+ assert(userText.includes('<workspace-context>') && userText.includes('<draft>') && userText.includes('createServer'), '上下文块进入模型请求')
466
+ assert(made.wfCalls.includes('search') && made.wfCalls.includes('read'), '经 workspaceFiles 搜索+读取')
467
+ assert(made.fsCalls.every((m) => m === 'resolve' || m === 'contains'), 'fs 只用 resolve/contains(只读)')
468
+ assert(made.wfCalls.every((m) => ['read', 'search', 'list'].includes(m)), 'workspaceFiles 只用只读方法')
469
+ }
470
+
471
+ // 多文件:总计等于各文件求和(§10.1-2)
472
+ {
473
+ const made = routeOf({
474
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
475
+ workspaceFiles: fakeWf({
476
+ matches: ['a.js', 'b.js'],
477
+ pages: {
478
+ 'a.js': { text: 'const a = 1\n', lines: 1 },
479
+ 'b.js': { text: 'const b = 2\nconst c = 3\n', lines: 2 },
480
+ },
481
+ }),
482
+ fs: fakeFs(),
483
+ })
484
+ const res = await call(made.routes[0], json({ text: '看看 a.js 和 b.js', sessionId: 's1', awareness: { enabled: true } }))
485
+ const c = res.json.context
486
+ assert(c.files.length === 2 && c.totalLines === 3, '多文件 totalLines 为各文件求和')
487
+ assert(c.totalTokens === c.files.reduce((sum, file) => sum + file.tokens, 0), '多文件 totalTokens 为各文件求和')
488
+ }
489
+
490
+ // 有路径提示但没有匹配文件:上下文块为空,草稿逐字节等于原文(§10.1-14)
491
+ {
492
+ const made = routeOf({
493
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
494
+ workspaceFiles: fakeWf({ matches: [] }),
495
+ fs: fakeFs(),
496
+ })
497
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js 里的 createServer', sessionId: 's1', awareness: { enabled: true } }))
498
+ assert(res.status === 200 && made.calls[0].messages[0].content[0].text === '看看 src/app.js 里的 createServer', '无文件时模型输入逐字节等于原文')
499
+ }
500
+
501
+ // 非 live 会话:持久化快照的 cwd
502
+ {
503
+ const made = routeOf({
504
+ sessions: { get: () => undefined },
505
+ sessionPersistence: { stat: async () => ({ header: { cwd: AW_ROOT } }) },
506
+ workspaceFiles: fakeWf({ matches: ['src/app.js'], page: { text: 'const a = 1\n', lines: 1 } }),
507
+ fs: fakeFs(),
508
+ })
509
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js', sessionId: 's2', awareness: { enabled: true } }))
510
+ assert(res.status === 200 && res.json.context.source === 'persisted', 'live 取不到时用持久化 cwd')
511
+ assert(res.json.context.enabled === true && res.json.context.files.length === 1, '持久化路径也能采集')
512
+ }
513
+
514
+ // 缺 sessionId / 会话没有工作区根
515
+ {
516
+ const made = routeOf({ workspaceFiles: fakeWf({ matches: ['src/app.js'] }), fs: fakeFs() })
517
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js', awareness: { enabled: true } }))
518
+ assert(res.status === 200 && res.json.context.skipped === 'no-session', '缺 sessionId → no-session')
519
+ assert(res.json.context.error.code === 'awareness_denied' && res.json.context.enabled === false, 'no-session 审计字段')
520
+ assert(res.json.context.sessionId === null && made.wfCalls.length === 0, '无会话时不搜索')
521
+ assert(Array.isArray(res.json.symbols) && res.json.symbols.length === 0, 'no-session → symbols=[]')
522
+ assert(made.calls.length === 1 && made.calls[0].messages[0].content[0].text === '看看 src/app.js', 'no-session 仍正常改写且原文透传')
523
+ }
524
+ {
525
+ let listed = false
526
+ const made = routeOf({
527
+ sessions: { get: () => ({ header: {} }), list: () => { listed = true; return [] } },
528
+ sessionPersistence: { stat: async () => ({ header: {} }) },
529
+ workspaceFiles: fakeWf({ matches: ['src/app.js'] }),
530
+ fs: fakeFs(),
531
+ })
532
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js', sessionId: 's3', awareness: { enabled: true } }))
533
+ assert(res.status === 200 && res.json.context.skipped === 'no-workspace', '会话没有 cwd → no-workspace')
534
+ assert(res.json.context.error.code === 'awareness_denied' && made.wfCalls.length === 0, 'no-workspace 不触及 workspaceFiles')
535
+ assert(listed === false, 'no-workspace 不调用 sessions.list()')
536
+ assert(!made.gets.includes('sandboxPolicy') && !made.gets.includes('workspaceRegistry'), 'no-workspace 不以 sandboxPolicy/registry 兜底')
537
+ }
538
+
539
+ // 单个候选不可读时继续尝试其它候选(§10.1-9)
540
+ {
541
+ const made = routeOf({
542
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
543
+ workspaceFiles: fakeWf({
544
+ matches: ['secret.bin.js', 'huge.js', 'src/app.js'],
545
+ readThrowsFor: {
546
+ 'secret.bin.js': 'workspace-file/not-text',
547
+ 'huge.js': 'workspace-file/too-large',
548
+ },
549
+ pages: { 'src/app.js': { text: 'const ok = 1\n', lines: 1 } },
550
+ }),
551
+ fs: fakeFs(),
552
+ })
553
+ const res = await call(made.routes[0], json({ text: '看看 secret.bin.js、huge.js 和 src/app.js', sessionId: 's1', awareness: { enabled: true } }))
554
+ const c = res.json.context
555
+ assert(res.status === 200 && c.files.length === 1 && c.files[0].path === 'src/app.js', 'not-text/too-large 后继续读其它文件')
556
+ assert(c.skippedFiles === 2 && c.error === undefined, '不可读文件只计入 skippedFiles')
557
+ }
558
+
559
+ // 读取通道失败:skipped=read-failed,改写仍 200(§10.1-15 的失败降级)
560
+ {
561
+ const made = routeOf({
562
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
563
+ workspaceFiles: fakeWf({ matches: ['src/app.js'], readThrows: 'workspace-file/boom' }),
564
+ fs: fakeFs(),
565
+ })
566
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js', sessionId: 's1', awareness: { enabled: true } }))
567
+ const c = res.json.context
568
+ assert(res.status === 200 && res.json.text === '你好世界' && made.calls.length === 1, 'read-failed 仍改写并调用模型')
569
+ assert(c.files.length === 0 && c.skipped === 'read-failed' && c.skippedFiles === 1, '读取通道失败 → read-failed')
570
+ assert(c.error && c.error.code === 'awareness_failed', 'read-failed 审计字段 awareness_failed')
571
+ }
572
+
573
+ // 围栏:读前
574
+ {
575
+ const made = routeOf({
576
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
577
+ workspaceFiles: fakeWf({ matches: ['../outside.js'], page: { text: 'secret\n', lines: 1 } }),
578
+ fs: fakeFs({ contains: () => false }),
579
+ })
580
+ const res = await call(made.routes[0], json({ text: '看看 ../outside.js', sessionId: 's1', awareness: { enabled: true } }))
581
+ assert(res.status === 200 && res.json.context.skippedFiles === 1 && res.json.context.files.length === 0, '越界候选计入 skippedFiles')
582
+ assert(!made.wfCalls.includes('read'), '越界候选不读取')
583
+ }
584
+
585
+ // 围栏:读后复核 absolutePath
586
+ {
587
+ let guard = 0
588
+ const containTargets = []
589
+ const made = routeOf({
590
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
591
+ workspaceFiles: fakeWf({ matches: ['src/app.js'], page: { text: 'const a = 1\n', lines: 1 } }),
592
+ fs: fakeFs({ contains: (root, target) => { guard += 1; containTargets.push(target); return guard === 1 } }),
593
+ })
594
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js', sessionId: 's1', awareness: { enabled: true } }))
595
+ assert(res.status === 200 && res.json.context.skippedFiles === 1 && res.json.context.files.length === 0, '读后围栏用 absolutePath 复核')
596
+ assert(containTargets.length === 2 && containTargets[1] === '/ws/src/app.js', '读后围栏复核的是 workspaceFiles 返回的 absolutePath')
597
+ assert(res.json.context.enabled === false, '复核失败时 context 不启用')
598
+ }
599
+
600
+ // 不可读文件(非文本)只计数,不算通道失败
601
+ {
602
+ const made = routeOf({
603
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
604
+ workspaceFiles: fakeWf({ matches: ['secret.bin.js'], readThrows: 'workspace-file/not-text' }),
605
+ fs: fakeFs(),
606
+ })
607
+ const res = await call(made.routes[0], json({ text: '看看 secret.bin.js', sessionId: 's1', awareness: { enabled: true } }))
608
+ assert(res.status === 200 && res.json.context.skippedFiles === 1, '不可读文件计入 skippedFiles')
609
+ assert(res.json.context.error === undefined, 'not-text 不算通道失败')
610
+ }
611
+
612
+ // 二进制(NUL)与超大文件:只跳过,不进入上下文
613
+ {
614
+ const made = routeOf({
615
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
616
+ workspaceFiles: fakeWf({ matches: ['data.js'], page: { text: 'a\u0000b', lines: 1 } }),
617
+ fs: fakeFs(),
618
+ })
619
+ const res = await call(made.routes[0], json({ text: '看看 data.js', sessionId: 's1', awareness: { enabled: true } }))
620
+ assert(res.status === 200 && res.json.context.skippedFiles === 1 && res.json.context.files.length === 0, 'NUL 字节文件被拒绝')
621
+ }
622
+ {
623
+ const made = routeOf({
624
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
625
+ workspaceFiles: fakeWf({ matches: ['huge.js'], readThrows: 'workspace-file/too-large' }),
626
+ fs: fakeFs(),
627
+ })
628
+ const res = await call(made.routes[0], json({ text: '看看 huge.js', sessionId: 's1', awareness: { enabled: true } }))
629
+ assert(res.status === 200 && res.json.context.skippedFiles === 1 && res.json.context.error === undefined, 'too-large 只跳过')
630
+ }
631
+
632
+ // 预算:maxFiles 与 maxTokens
633
+ {
634
+ const made = routeOf({
635
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
636
+ workspaceFiles: fakeWf({
637
+ matches: ['a.js', 'b.js', 'c.js'],
638
+ pages: {
639
+ 'a.js': { text: 'const a = 1\n', lines: 1 },
640
+ 'b.js': { text: 'const b = 2\n', lines: 1 },
641
+ 'c.js': { text: 'const c = 3\n', lines: 1 },
642
+ },
643
+ }),
644
+ fs: fakeFs(),
645
+ })
646
+ const res = await call(made.routes[0], json({ text: '看看 a.js、b.js 和 c.js', sessionId: 's1', awareness: { enabled: true, maxFiles: 1 } }))
647
+ assert(res.status === 200 && res.json.context.files.length === 1 && res.json.context.truncated === true, 'maxFiles 截断且置 truncated')
648
+ assert(res.json.context.totalFiles === 1, 'totalFiles 反映收录数')
649
+ }
650
+ {
651
+ const made = routeOf({
652
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
653
+ workspaceFiles: fakeWf({ matches: ['src/big.js'], page: { text: 'x'.repeat(40) + '\n', lines: 1 } }),
654
+ fs: fakeFs(),
655
+ })
656
+ const res = await call(made.routes[0], json({ text: '看看 src/big.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 1 } }))
657
+ const c = res.json.context
658
+ assert(res.status === 200 && c.enabled === false && c.files.length === 0, '总预算不足时不收录文件')
659
+ assert(c.skipped === 'budget-exhausted' && c.truncated === true, '预算耗尽 → budget-exhausted + truncated')
660
+ }
661
+
662
+ // 预算裁剪:整页超预算时按行前缀裁剪,而不是整页丢弃
663
+ {
664
+ const bigText = Array.from({ length: 80 }, () => 'x'.repeat(50)).join('\n')
665
+ assert(T.estimateTokens(bigText) > 800, '裁剪用例的整页 token 确实超过默认预算')
666
+ const wf = fakeWf({ matches: ['src/big.js'], page: { text: bigText, lines: 80 } })
667
+ const made = routeOf({
668
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
669
+ workspaceFiles: wf,
670
+ fs: fakeFs(),
671
+ })
672
+ const res = await call(made.routes[0], json({ text: '看看 src/big.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 800 } }))
673
+ const c = res.json.context
674
+ const f = c.files[0] || {}
675
+ assert(res.status === 200 && c.enabled === true && c.files.length === 1, '整页超预算时裁剪后仍返回文件')
676
+ assert(c.totalTokens === f.tokens && c.totalTokens <= 800, '裁剪后 totalTokens 不超过设上限')
677
+ assert(c.truncated === true && f.lines >= 8 && f.lines < 80, '裁剪置 truncated 且至少保留 8 行')
678
+ assert(f.lines === f.endLine - f.startLine + 1 && f.startLine === 1, '裁剪后 lines/endLine 与窗口一致')
679
+ const userText = made.calls[0].messages[0].content[0].text
680
+ const tag = '<file path="src/big.js" lines="1-' + f.endLine + '">\n'
681
+ const at = userText.indexOf(tag)
682
+ const stop = at === -1 ? -1 : userText.indexOf('\n</file>', at)
683
+ let blockText = ''
684
+ if (at !== -1 && stop !== -1) blockText = userText.slice(at + tag.length, stop)
685
+ assert(blockText === bigText.slice(0, blockText.length), '上下文块是原文的整行前缀')
686
+ assert(blockText.split('\n').length === f.lines && T.estimateTokens(blockText) === f.tokens, '块内行数与 token 同审计字段一致')
687
+ assert(c.skipped === undefined && c.skippedFiles === 0 && c.error === undefined, '裁剪成功不算跳过/错误')
688
+ assert(wf.reads.length === 1, '裁剪只读一次文件')
689
+ }
690
+ {
691
+ // 三个 30 行 × 80 字符的候选:预算只够裁一个,其余跳过且总量不越界
692
+ const pages = {}
693
+ for (const name of ['a.js', 'b.js', 'c.js']) {
694
+ const line = ('// ' + name + ' ').padEnd(80, 'y')
695
+ pages[name] = { text: Array.from({ length: 30 }, () => line).join('\n'), lines: 30 }
696
+ }
697
+ const wf = fakeWf({ matches: ['a.js', 'b.js', 'c.js'], pages })
698
+ const made = routeOf({
699
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
700
+ workspaceFiles: wf,
701
+ fs: fakeFs(),
702
+ })
703
+ const res = await call(made.routes[0], json({ text: '看看 a.js、b.js 和 c.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 500 } }))
704
+ const c = res.json.context
705
+ assert(c.files.length === 1 && c.files[0].path === 'a.js', '预算只够一个文件时仍裁剪收录第一个候选')
706
+ assert(c.totalTokens <= 500, '多候选裁剪后 totalTokens 不超过设上限')
707
+ assert(c.skippedFiles >= 1 && c.skipped === undefined && c.error === undefined && c.truncated === true, '放不下的候选只计入 skippedFiles,files 非空不置 budget-exhausted')
708
+ assert(wf.reads.length >= 2 && new Set(wf.reads).size === wf.reads.length, '每个候选最多读取一次')
709
+ }
710
+ {
711
+ // 裁到 MIN_CONTEXT_LINES=8 行仍放不下:跳过该文件,继续下一个更小的候选
712
+ const bigText = Array.from({ length: 8 }, () => 'z'.repeat(100)).join('\n')
713
+ const smallText = Array.from({ length: 5 }, (_, i) => 's' + i + ' = 1').join('\n')
714
+ const wf = fakeWf({
715
+ matches: ['big.js', 'small.js'],
716
+ pages: {
717
+ 'big.js': { text: bigText, lines: 8 },
718
+ 'small.js': { text: smallText, lines: 5 },
719
+ },
720
+ })
721
+ const made = routeOf({
722
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
723
+ workspaceFiles: wf,
724
+ fs: fakeFs(),
725
+ })
726
+ const res = await call(made.routes[0], json({ text: '看看 big.js 和 small.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 100 } }))
727
+ const c = res.json.context
728
+ assert(c.files.length === 1 && c.files[0].path === 'small.js', '裁到 8 行仍放不下时跳过并继续下一个候选')
729
+ assert(c.skippedFiles === 1 && c.skipped === undefined && c.truncated === true, '跳过的候选计入 skippedFiles,不误置 budget-exhausted')
730
+ assert(c.totalTokens <= 100, '跳过后续文件的 totalTokens 仍不超上限')
731
+ assert(wf.reads.join(',') === 'big.js,small.js', '每个候选只读一次且顺序按路径分排序')
732
+ }
733
+ {
734
+ // 候选因裁剪下限被全员跳过且 files 为空:才标 budget-exhausted
735
+ const bigText = Array.from({ length: 8 }, () => 'q'.repeat(100)).join('\n')
736
+ const made = routeOf({
737
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
738
+ workspaceFiles: fakeWf({ matches: ['big.js'], page: { text: bigText, lines: 8 } }),
739
+ fs: fakeFs(),
740
+ })
741
+ const res = await call(made.routes[0], json({ text: '看看 big.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 100 } }))
742
+ const c = res.json.context
743
+ assert(c.enabled === false && c.files.length === 0 && c.totalTokens === 0, '裁剪下限都放不下且 files 为空 → enabled=false')
744
+ assert(c.skipped === 'budget-exhausted' && c.skippedFiles === 1 && c.truncated === true, 'files 为空且候选因预算被跳过 → budget-exhausted')
745
+ assert(c.error === undefined, '预算跳过不是采集错误')
746
+ }
747
+
748
+ // 验收原文:80 行 × 80 字符页面在 maxTokens=800 下必须裁剪收录且不越界
749
+ {
750
+ const page80 = Array.from({ length: 80 }, () => 'a'.repeat(80)).join('\n')
751
+ assert(T.estimateTokens(page80) > 800, '80×80 页面整页 token 超过 800')
752
+ const wf = fakeWf({ matches: ['src/page.js'], page: { text: page80, lines: 80 } })
753
+ const made = routeOf({
754
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
755
+ workspaceFiles: wf,
756
+ fs: fakeFs(),
757
+ })
758
+ const res = await call(made.routes[0], json({ text: '看看 src/page.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 800 } }))
759
+ const c = res.json.context
760
+ const f = c.files[0] || {}
761
+ assert(res.status === 200 && c.files.length === 1 && c.totalTokens <= 800, '80×80 页面裁剪后返回至少一个文件且不越界')
762
+ assert(f.lines >= 8 && f.lines < 80 && f.endLine === f.lines && f.startLine === 1, '80×80 页面裁剪为整行前缀窗口')
763
+ assert(c.truncated === true && c.skipped === undefined && c.error === undefined, '80×80 页面裁剪只置 truncated')
764
+ assert(wf.reads.length === 1, '80×80 页面只读一次')
765
+ }
766
+
767
+ // 对抗性边界 A:整页 token 恰好等于 maxTokens,不应裁剪也不应截断
768
+ {
769
+ const exact = 'e'.repeat(348) // ceil(348 / 3.5) === 100
770
+ assert(T.estimateTokens(exact) === 100, '边界用例文本恰好 100 token')
771
+ const wf = fakeWf({ matches: ['exact.js'], page: { text: exact, lines: 1 } })
772
+ const made = routeOf({
773
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
774
+ workspaceFiles: wf,
775
+ fs: fakeFs(),
776
+ })
777
+ const res = await call(made.routes[0], json({ text: '看看 exact.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 100 } }))
778
+ const c = res.json.context
779
+ assert(c.files.length === 1 && c.files[0].tokens === 100 && c.totalTokens === 100, '恰好等于上限时完整保留(不多不少)')
780
+ assert(c.totalTokens <= c.budget.maxTokens && c.budget.maxTokens === 100, '恰好等于上限时 totalTokens 不越界')
781
+ assert(c.truncated === false && c.skipped === undefined && c.skippedFiles === 0, '恰好等于上限不算裁剪/跳过')
782
+ assert(wf.reads.length === 1, '恰好等于上限只读一次')
783
+ }
784
+
785
+ // 对抗性边界 B:单行 token 就超过预算,裁到 8 行下限仍放不下 → 跳过且 budget-exhausted
786
+ {
787
+ const oneLongLine = 'L'.repeat(700) // 200 token,远大于 100 的预算
788
+ assert(T.estimateTokens(oneLongLine) > 100, '单行长文本 token 超过预算')
789
+ const wf = fakeWf({ matches: ['long.js'], page: { text: oneLongLine, lines: 1 } })
790
+ const made = routeOf({
791
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
792
+ workspaceFiles: wf,
793
+ fs: fakeFs(),
794
+ })
795
+ const res = await call(made.routes[0], json({ text: '看看 long.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 100 } }))
796
+ const c = res.json.context
797
+ assert(res.status === 200 && c.files.length === 0 && c.totalTokens === 0 && c.enabled === false, '单行超预算且不足 8 行 → 不收录')
798
+ assert(c.skipped === 'budget-exhausted' && c.skippedFiles === 1 && c.truncated === true, '单行超预算被跳过 → budget-exhausted')
799
+ assert(c.error === undefined && wf.reads.length === 1, '单行超预算是预算跳过而非错误')
800
+ }
801
+
802
+ // 对抗性边界 C:MIN_CONTEXT_LINES=8 恰好放下(9 行会超),且预算耗尽后停止读取后续候选
803
+ {
804
+ const line = 'w'.repeat(80)
805
+ const text = Array.from({ length: 80 }, () => line).join('\n')
806
+ const wf = fakeWf({ matches: ['min.js'], page: { text, lines: 80 } })
807
+ const made = routeOf({
808
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
809
+ workspaceFiles: wf,
810
+ fs: fakeFs(),
811
+ })
812
+ const res = await call(made.routes[0], json({ text: '看看 min.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 200 } }))
813
+ const c = res.json.context
814
+ const f = c.files[0] || {}
815
+ assert(c.files.length === 1 && f.lines === 8 && f.endLine === 8 && f.startLine === 1, '裁剪恰好停在 MIN_CONTEXT_LINES=8 行')
816
+ assert(f.tokens === T.estimateTokens(text.split('\n').slice(0, 8).join('\n')) && c.totalTokens === f.tokens && c.totalTokens <= 200, '8 行边界 token 重算且不越界')
817
+ assert(c.truncated === true && c.skipped === undefined && c.skippedFiles === 0 && c.error === undefined, '8 行裁剪只置 truncated')
818
+ assert(wf.reads.length === 1, '8 行边界只读一次')
819
+ }
820
+ {
821
+ // 首个候选恰好吃满预算,后续候选必须停止读取(不再 read,也不计入 skippedFiles)
822
+ const exact = 'p'.repeat(348) // 100 token
823
+ const wf = fakeWf({
824
+ matches: ['a.js', 'b.js', 'c.js'],
825
+ pages: {
826
+ 'a.js': { text: exact, lines: 1 },
827
+ 'b.js': { text: 'const b = 1\n', lines: 1 },
828
+ 'c.js': { text: 'const c = 1\n', lines: 1 },
829
+ },
830
+ })
831
+ const made = routeOf({
832
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
833
+ workspaceFiles: wf,
834
+ fs: fakeFs(),
835
+ })
836
+ const res = await call(made.routes[0], json({ text: '看看 a.js、b.js 和 c.js', sessionId: 's1', awareness: { enabled: true, maxTokens: 100 } }))
837
+ const c = res.json.context
838
+ assert(c.files.length === 1 && c.files[0].path === 'a.js' && c.totalTokens === 100, '预算吃满后保留首个候选')
839
+ assert(c.totalTokens <= c.budget.maxTokens && c.truncated === true, '预算吃满置 truncated 且 totalTokens 不越界')
840
+ assert(wf.reads.join(',') === 'a.js', '预算耗尽后停止读取后续候选')
841
+ assert(c.skippedFiles === 0 && c.skipped === undefined && c.error === undefined, '未读取的候选不计入 skippedFiles,files 非空不标 budget-exhausted')
842
+ }
843
+
844
+ // maxLinesPerFile 触顶:读到非 EOF 行窗口即置 truncated
845
+ {
846
+ const made = routeOf({
847
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
848
+ workspaceFiles: fakeWf({ matches: ['src/app.js'], page: { text: 'const a = 1\n', lines: 1, eof: false } }),
849
+ fs: fakeFs(),
850
+ })
851
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js', sessionId: 's1', awareness: { enabled: true, maxLinesPerFile: 1 } }))
852
+ assert(res.status === 200 && res.json.context.truncated === true && res.json.context.files.length === 1, 'maxLinesPerFile 触顶 → truncated')
853
+ }
854
+
855
+ // 符号抽取:class / function / 箭头函数,行号为文件内绝对行号(§10.1-11)
856
+ {
857
+ const symText = '\nfunction collectContext() {\n return 1\n}\n\nconst foo = () => 1\n\nclass Widget {}\n'
858
+ const made = routeOf({
859
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
860
+ workspaceFiles: fakeWf({ matches: ['src/app.js'], page: { text: symText, lines: 8 } }),
861
+ fs: fakeFs(),
862
+ })
863
+ const res = await call(made.routes[0], json({ text: '看看 src/app.js 的 collectContext', sessionId: 's1', awareness: { enabled: true } }))
864
+ const syms = res.json.symbols || []
865
+ const find = (name) => syms.find((s) => s.name === name)
866
+ assert(find('collectContext') && find('collectContext').kind === 'function' && find('collectContext').line === 2, 'function 符号与绝对行号')
867
+ assert(find('foo') && find('foo').kind === 'function' && find('foo').line === 6, '箭头函数符号与绝对行号')
868
+ assert(find('Widget') && find('Widget').kind === 'class' && find('Widget').line === 8, 'class 符号与绝对行号')
869
+ }
870
+
871
+ // 搜索失败:不影响改写
872
+ {
873
+ const made = routeOf({
874
+ sessions: { get: () => ({ header: { cwd: AW_ROOT } }) },
875
+ workspaceFiles: fakeWf({ matches: ['src/app.js'], searchThrows: true }),
876
+ fs: fakeFs(),
877
+ })
878
+ const res = await call(made.routes[0], json({ text: '看看 createServer 的日志', sessionId: 's1', awareness: { enabled: true } }))
879
+ assert(res.status === 200 && res.json.text === '你好世界', '搜索失败不影响改写(200)')
880
+ assert(made.calls.length === 1, '搜索失败仍调用模型')
881
+ assert(res.json.context.skipped === 'search-failed' && res.json.context.enabled === false, '搜索失败 → skipped=search-failed')
882
+ assert(res.json.context.error && res.json.context.error.code === 'awareness_failed', '搜索失败 → error=awareness_failed')
883
+ assert(!made.wfCalls.includes('read'), '搜索失败后不读取')
884
+ }
885
+
886
+ // /命令:注册表优先,缺失时用内置兜底语义
887
+ {
888
+ const made = routeOf({
889
+ agents: { get: (id) => ({ id }) },
890
+ commands: { list: () => [{ name: 'goal', description: '推进目标直到完成' }] },
891
+ })
892
+ const res = await call(made.routes[0], json({ text: '帮我规划下一步', sessionId: 's1', commandName: '/goal', locale: 'zh' }))
893
+ assert(res.status === 200 && res.json.command && res.json.command.name === 'goal', '命令描述来自注册表')
894
+ assert(res.json.command.description === '推进目标直到完成' && res.json.command.source === 'registry', 'registry 描述与来源')
895
+ assert(made.calls[0].system.includes('/goal') && made.calls[0].system.includes('推进目标直到完成'), '命令语义进入 system')
896
+ }
897
+ {
898
+ const made = routeOf({})
899
+ const res = await call(made.routes[0], json({ text: '帮我规划下一步', commandName: 'goal', locale: 'zh' }))
900
+ assert(res.status === 200 && res.json.command.source === 'fallback', '无命令注册表 → fallback')
901
+ assert(res.json.command.description === '命令说明不可用', 'fallback 用契约通用文案')
902
+ assert(!res.json.command.description.includes('目标模式') && !res.json.command.description.includes('goal'), 'fallback 描述不冒充注册表语义')
903
+ assert(made.calls[0].system.includes('目标模式'), '内置兜底表提供命令语义')
904
+ }
905
+ {
906
+ const made = routeOf({})
907
+ const res = await call(made.routes[0], json({ text: 'plan next', commandName: 'goal', locale: 'en' }))
908
+ assert(res.status === 200 && res.json.command.source === 'fallback', '无注册表且 en → fallback')
909
+ assert(res.json.command.description === 'Command description unavailable', 'fallback en 通用文案')
910
+ assert(made.calls[0].system.includes('Goal mode'), 'fallback en 命令语义进入 system')
911
+ }
912
+ {
913
+ const made = routeOf({
914
+ agents: { get: (id) => ({ id }) },
915
+ commands: { list: () => [{ name: 'plan', description: '计划模式' }] },
916
+ })
917
+ const res = await call(made.routes[0], json({ text: '帮我规划下一步', sessionId: 's1', commandName: 'goal', locale: 'zh' }))
918
+ assert(res.status === 200 && res.json.command.source === 'fallback' && res.json.command.description === '命令说明不可用', '注册表无对应 descriptor 时回退通用文案')
919
+ }
920
+ {
921
+ const made = routeOf({})
922
+ const res = await call(made.routes[0], json({ text: '你好', commandName: 'no such', locale: 'zh' }))
923
+ assert(res.status === 200 && !('command' in res.json), '非法命令名忽略')
924
+ }
925
+
926
+ // 全局只读审计:整个测试文件跑下来,workspaceFiles 从未调用写方法,fs 只做路径解析
927
+ assert(allWfCalls.length > 0 && allWfCalls.every((m) => ['read', 'search', 'list'].includes(m)), 'workspaceFiles 全程零写方法调用')
928
+ assert(allFsCalls.every((m) => m === 'resolve' || m === 'contains'), 'fs 全程只调用 resolve/contains')
929
+
930
+ // 全局预算不变量:任何一次返回的 context 都不得越过 maxTokens,且 totalTokens 等于 files 求和
931
+ assert(contextObservations.length >= 20, '全局预算审计覆盖到足够多的上下文响应')
932
+ for (const c of contextObservations) {
933
+ if (!c || !c.budget) continue
934
+ assert(c.totalTokens <= c.budget.maxTokens, `totalTokens 从不超预算(${c.totalTokens} <= ${c.budget.maxTokens})`)
935
+ assert(c.totalTokens === c.files.reduce((sum, f) => sum + f.tokens, 0), 'totalTokens 始终等于 files token 求和')
936
+ assert(c.files.every((f) => f.tokens <= c.budget.maxTokens), '单个文件 token 也不超总预算')
937
+ if (c.files.length > 0) assert(c.skipped !== 'budget-exhausted', 'files 非空时不得出现 budget-exhausted')
938
+ if (c.skipped === 'budget-exhausted') {
939
+ assert(c.files.length === 0 && c.truncated === true && c.skippedFiles >= 1, 'budget-exhausted 仅当 files 为空且确有预算跳过')
940
+ }
941
+ }
942
+
338
943
  console.log(`\n✅ host 通过:${passed} 项断言`)