dsh-progress-union 0.7.0-rc.1 → 0.7.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,20 @@
2
2
 
3
3
  本项目的所有值得记录的变更都写在这里。版本号遵循语义化版本。
4
4
 
5
+ ## 0.7.0-rc.2 (2026-12-04)
6
+
7
+ **feat(gloss+ui):下载子进度条落到输入框迷你条,工序可解释三层上线(R2 展示面 + R5)——真值全部自解析,零跨插件依赖。**
8
+
9
+ - **子进度条(client.js)**:`ProgressDock` 在主条行(`.pb-dock-row`)之后、展开列表之前渲染 `downloadRow(snapshot.download, t)`。两档形态严格对应后端 `basis`:`stdout` / `board` 才画实际填充宽度并显示百分比;`elapsed`(只有动作记录、没有真值)走 `indeterminate` 斜条纹 + 已用时长,**绝不拿随机数或驻留 100% 假扮百分比**。后台下载追加 warn 色徽标(`.pb-badge-bg`),悬停 title 拼「动作 · 目标 · 字节 · 耗时 · 真值来源」。
10
+ - **窄屏与动效**:`@media (max-width: 760px)` 去掉左缩进、限名称宽、隐去时长;`520px` 整行收起,不给主条添高度。条纹动画受 `prefers-reduced-motion: reduce` 关闭。配色全部走 `--dsw-alias-*` 宿主令牌(含 `color-mix`),无硬编 hex/rgb,皮肤切换不失配(延续 0.6.x 的 `--dsw-alias-bg-base` 前景区分纪律)。
11
+ - **关板不渲染**:`downloadRow` 首行 `if (!dl || dl.active !== true) return null` —— 后端在板关闭、`download.showSubBar=false` 或记录过期时不下发 `download`,浏览器半不留空行,迷你条高度逐字等于 0.6.x。
12
+ - **R5 层 1(可解释规则表)**:新增导出纯函数 `describeToolStep(name, argsRaw, maxLen)` 与 `glossCommand(command)`。命令型工具按**首段首词**二跳分派(`git clone`→克隆仓库、`npm ci && npm test`→按锁文件装依赖、`docker build`→构建镜像、`npx create-vite`→临时跑 create-vite),另有约 70 条首词表覆盖 ls/cat/grep/curl 等;文件类走参数名并只留路径末段;`apply_patch` 从 `*** Update File:` / `+++ b/x` 反推被改文件;`run_code` 递归解 `tools.xxx(` 出「PTC 内层 shell+read」;`act` 包装先 `unwrapAct` 解一层。猜不出退回 `key=value`(单值截 24),全空返回空串——沿用 `filePathOf` 的「拿不到就不记」纪律,不写「执行了一个操作」这类空话。
13
+ - **R5 层 2(结果回显)**:`recordTool` 给 `o.tools[]` 附 `gloss` 与 `cid`;`tool/result` 到达时 `attachToolResult()` 按 callId 对齐(缺失则退化为 120s 窗口内最后一条未挂结果的动作)写 `result = resultDigest(text, failed)`(≤60 字,区分 `结果:` / `失败:` / `失败(无输出)`,且不覆盖 `lastToolError`)。观察块「最近动作」行、todo 校对输入、助手审查输入三处统一走 `toolLabel()`,形如 `Bash 跑测试 → 结果:188 passed in 6.4s`。
14
+ - **R5 层 3(叙述纪律)**:`systemPrompt.context` 观察块尾部追加一行静态纪律 `▸ 每步工具前用一行写清「▸ <动作> → <本步目的>」`,`toolGloss.softNarrate=false` 可关;**不做 pre-step 逐条注入、不注册 act、不挂 tools.guard、不做 autoEventize**(grep 复核),与 dsh-better-tooluse 无任何运行期关系、零新增依赖。
15
+ - **退回保证**:`toolGloss.enabled=false` 时三处渲染逐字退回 0.6.x 的 `name×count → name` 串(新用例按 0.6.x 原算法重算后逐字节比较)。
16
+ - **locales**:client.js 内联 zh/en 两份字典各补 11 个 `dl*` 键(`dlDownload/dlInstall/dlClone/dlPull/dlUnnamed/dlBackground/dlSecUnit/dlMinUnit/dlBasisStdout/dlBasisBoard/dlBasisElapsed`),用例断言两字典成对出现。
17
+ - **测试**:新增 `test/tool-gloss.test.mjs`(11 例)+ `test/client.test.mjs` 扩 5 例(子条三档形态与关板门控走**真调用**:从源码抠出 `downloadRow` 在 stub `h/t` 下实际渲染,而非只做源码正则);`npm test` 204 pass / 0 fail(rc.1 的 188 → +16),零回归。
18
+
5
19
  ## 0.7.0-rc.1 (2026-12-04)
6
20
 
7
21
  **feat(download):下载类软感知与进度真值数据面(R1 + R2 后端)——只识别与催办,绝不拦截工具。**
package/client.js CHANGED
@@ -24,7 +24,7 @@ window.__ModuleLoader__.load({
24
24
  var REPO_URL = "https://github.com/drscrewdriver/dsh-progress-union";
25
25
  var STAR_NS = "progress-union";
26
26
  var STAR_GEN = "v4"; /* ladder:gen */
27
- var STAR_VERSION = "0.7.0-rc.1"; /* ladder:ver */
27
+ var STAR_VERSION = "0.7.0-rc.2"; /* ladder:ver */
28
28
  var LANGS = ["zh", "en", "ja", "ko", "fr", "de", "it", "ru", "es", "pt"];
29
29
 
30
30
  // 三代共享:GitHub 单色 mark(octicon 轮廓,fill 随 currentColor)。
@@ -397,6 +397,18 @@ window.__ModuleLoader__.load({
397
397
  dockEdit: '编辑',
398
398
  dockOpenFull: '打开完整进度板',
399
399
  dockAllDone: '全部完成',
400
+ // v0.7.0 R2:下载子条(只读展示,不拦截)
401
+ dlDownload: '下载',
402
+ dlInstall: '安装',
403
+ dlClone: '克隆',
404
+ dlPull: '拉取',
405
+ dlUnnamed: '未具名',
406
+ dlBackground: '后台',
407
+ dlSecUnit: '秒',
408
+ dlMinUnit: '分钟',
409
+ dlBasisStdout: '输出实测',
410
+ dlBasisBoard: '板项百分比',
411
+ dlBasisElapsed: '仅计时(无真值)',
400
412
  dockPause: '暂停',
401
413
  dockResume: '继续',
402
414
  dockPauseHint: '暂停这个长程目标(进度板目标,独立于宿主的 /goal):立即停止当前回合,之后不再自动续轮',
@@ -569,6 +581,18 @@ window.__ModuleLoader__.load({
569
581
  dockEdit: 'Edit',
570
582
  dockOpenFull: 'Open full board',
571
583
  dockAllDone: 'All done',
584
+ // v0.7.0 R2: download sub-bar (read-only, never blocks the tool)
585
+ dlDownload: 'download',
586
+ dlInstall: 'install',
587
+ dlClone: 'clone',
588
+ dlPull: 'pull',
589
+ dlUnnamed: 'unnamed',
590
+ dlBackground: 'bg',
591
+ dlSecUnit: 's',
592
+ dlMinUnit: 'min',
593
+ dlBasisStdout: 'parsed from output',
594
+ dlBasisBoard: 'board percent',
595
+ dlBasisElapsed: 'elapsed only (no real value)',
572
596
  dockPause: 'Pause',
573
597
  dockResume: 'Resume',
574
598
  dockPauseHint: 'Pause this long goal (board goal — separate from the host /goal): stop the live turn now and stop auto-continuing',
@@ -894,6 +918,33 @@ window.__ModuleLoader__.load({
894
918
  .pb-dock-item-title { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 12px; }
895
919
  .pb-dock-item-meta { flex: none; color: var(--dsw-alias-label-secondary); font-size: 11px; font-variant-numeric: tabular-nums; }
896
920
  .pb-dock-more { border: 0; background: transparent; color: var(--dsw-alias-brand-primary); padding: 4px 1px; font: inherit; font-size: 11px; text-align: left; cursor: pointer; }
921
+ /* v0.7.0 R2:下载子进度条(主条下方单独一行)。有真值才画宽度,没真值只画条纹——
922
+ 宁可显示「不知道多少」,也不拿随机数冒充百分比。颜色全走 --dsw-alias-* 令牌。 */
923
+ .pb-dock-dl {
924
+ display: flex; align-items: center; gap: 7px; margin: 3px 0 0 43px;
925
+ color: var(--dsw-alias-label-secondary); font-size: 11px; line-height: 1.3;
926
+ }
927
+ .pb-dock-dl-ico { flex: none; color: var(--dsw-alias-brand-primary); }
928
+ .pb-dock-dl-bar {
929
+ flex: none; width: 64px; height: 4px; border-radius: 999px; overflow: hidden;
930
+ background: var(--dsw-alias-bg-layer-2);
931
+ }
932
+ .pb-dock-dl-bar > i { display: block; height: 100%; border-radius: inherit; background: var(--dsw-alias-brand-primary); transition: width .25s ease; }
933
+ .pb-dock-dl-bar.indeterminate > i {
934
+ width: 200%; background-image: repeating-linear-gradient(115deg, var(--dsw-alias-brand-primary) 0 5px, color-mix(in srgb, var(--dsw-alias-brand-primary) 30%, transparent) 5px 10px);
935
+ animation: pb-dock-dl-slide 1.2s linear infinite;
936
+ }
937
+ @keyframes pb-dock-dl-slide { from { transform: translateX(-50%) } to { transform: translateX(0) } }
938
+ @media (prefers-reduced-motion: reduce) { .pb-dock-dl-bar.indeterminate > i { animation: none } }
939
+ .pb-dock-dl-pct { flex: none; min-width: 30px; font-variant-numeric: tabular-nums; }
940
+ .pb-dock-dl-name { min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
941
+ .pb-dock-dl-time { flex: none; color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); font-variant-numeric: tabular-nums; }
942
+ /* 后台徽标:与「长时间无输出」同档(warn 色),不起新色板 */
943
+ .pb-badge-bg {
944
+ flex: none; padding: 0 4px; border-radius: 4px; font-size: 10px;
945
+ border: 1px solid color-mix(in srgb, var(--dsw-alias-state-warn-primary) 45%, var(--dsw-alias-border-l1));
946
+ color: var(--dsw-alias-state-warn-primary);
947
+ }
897
948
  .pb-side {
898
949
  box-sizing: border-box; height: 100%; overflow: auto; padding: 14px 14px 28px;
899
950
  color: var(--dsw-alias-label-primary); background: var(--dsw-alias-bg-base);
@@ -952,6 +1003,9 @@ window.__ModuleLoader__.load({
952
1003
  @media (max-width: 760px) {
953
1004
  .pb-dock-bar { display: none; }
954
1005
  .pb-dock-sub { max-width: 42vw; }
1006
+ .pb-dock-dl { margin-left: 0; }
1007
+ .pb-dock-dl-name { max-width: 26vw; }
1008
+ .pb-dock-dl-time { display: none; }
955
1009
  .pb-root { padding: 20px 16px 44px; }
956
1010
  .pb-head { flex-direction: column; gap: 10px; }
957
1011
  .pb-overview-top { align-items: flex-start; flex-direction: column; gap: 10px; }
@@ -967,6 +1021,10 @@ window.__ModuleLoader__.load({
967
1021
  .pb-side-task-head { flex-wrap: wrap; }
968
1022
  .pb-side-task-head .pb-status { width: 100%; }
969
1023
  }
1024
+ /* 极窄(手机抽屉宽度):子条整行收起,不给主条添高度 */
1025
+ @media (max-width: 520px) {
1026
+ .pb-dock-dl { display: none; }
1027
+ }
970
1028
  `
971
1029
 
972
1030
  function makeT(props) {
@@ -1596,6 +1654,32 @@ window.__ModuleLoader__.load({
1596
1654
  return timing
1597
1655
  }
1598
1656
 
1657
+ // v0.7.0 R2:下载子条。形态由 basis 定:stdout/board(有真值)画实际宽度,
1658
+ // elapsed(只有动作记录)走 indeterminate 条纹 + 已用时长。**不拿随机数假扮百分比**。
1659
+ // 后端不下发 download(关板 / showSubBar=false / 过期)时整行不渲染。
1660
+ function downloadRow(dl, t) {
1661
+ if (!dl || dl.active !== true) return null
1662
+ const basis = String(dl.basis || '')
1663
+ const raw = Number(dl.percent)
1664
+ const pct = Number.isFinite(raw) ? Math.min(100, Math.max(0, Math.round(raw))) : null
1665
+ const known = (basis === 'stdout' || basis === 'board') && pct !== null
1666
+ const verbKey = dl.kind === 'install' ? 'dlInstall' : (dl.kind === 'clone' ? 'dlClone' : (dl.kind === 'pull' ? 'dlPull' : 'dlDownload'))
1667
+ const secs = Math.max(0, Math.round(Number(dl.elapsedSec) || 0))
1668
+ const spent = secs >= 60 ? `${Math.round(secs / 60)} ${t('dlMinUnit')}` : `${secs} ${t('dlSecUnit')}`
1669
+ const basisKey = basis === 'stdout' ? 'dlBasisStdout' : (basis === 'board' ? 'dlBasisBoard' : 'dlBasisElapsed')
1670
+ const tip = [t(verbKey), dl.target || t('dlUnnamed'), dl.bytes, spent, t(basisKey)].filter(Boolean).join(' \u00b7 ')
1671
+ return h(
1672
+ 'div',
1673
+ { className: 'pb-dock-dl', title: tip },
1674
+ h('span', { className: 'pb-dock-dl-ico' }, '\u2b07'),
1675
+ h('span', { className: known ? 'pb-dock-dl-bar' : 'pb-dock-dl-bar indeterminate' }, known ? h('i', { style: { width: `${pct}%` } }) : h('i')),
1676
+ known ? h('span', { className: 'pb-dock-dl-pct' }, `${pct}%`) : null,
1677
+ h('span', { className: 'pb-dock-dl-name' }, `${t(verbKey)} ${(dl.target || t('dlUnnamed'))}`),
1678
+ dl.background ? h('span', { className: 'pb-badge-bg' }, t('dlBackground')) : null,
1679
+ h('span', { className: 'pb-dock-dl-time' }, dl.bytes || spent),
1680
+ )
1681
+ }
1682
+
1599
1683
  function ProgressDock(props) {
1600
1684
  const t = makeT(props)
1601
1685
  const { sessionId } = props
@@ -1782,6 +1866,7 @@ window.__ModuleLoader__.load({
1782
1866
  ),
1783
1867
  ),
1784
1868
  ),
1869
+ downloadRow(snapshot.download, t),
1785
1870
  expanded
1786
1871
  ? h(
1787
1872
  'div',
package/dsh.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-progress-union",
3
- "version": "0.7.0-rc.1",
3
+ "version": "0.7.0-rc.2",
4
4
  "main": "./index.js",
5
5
  "description": "进度结合原型:board 槽位真相源(用户可编辑、diff+ack 增量同步、staleness nudge)× 鲸程时间引擎(step 计数、ETA 三档 board>todo>local>prior、悬浮迷你条),向压缩插件暴露只读三层进度锚点 progressAnchor(board 语义锚 + time 时间锚 + userEdits 未确认改动,service 与 HTTP 双平面),并在 0.6.0 起每回合落一版会话归档(handoff 规则摘要 + 重启注入一次)。",
6
6
  "engines": {
package/index.js CHANGED
@@ -429,8 +429,180 @@ function isDownloadItem(item) {
429
429
  return DOWNLOAD_TITLE_RE.test(String(item.title || ''))
430
430
  }
431
431
 
432
+ // ── R5 工序可解释(层 1):把一次工具调用翻成一句人话。纯规则表,不做语义推断。
433
+ // 与 classifyDownload 共用同一批词表(SHELL_TOOL_NAMES / INSTALLERS / DOWNLOADERS / git 子动词),
434
+ // 保证「认出这是下载」和「说出这步在干什么」不会各说各话。
435
+ // 纪律同 filePathOf:猜不出返回 '',调用方逐字退回旧的 name×count——宁可不说,
436
+ // 也不写「处理中 / 执行命令」这种没有信息量的空话。
437
+ const GIT_SUB_GLOSS = new Map([
438
+ ['clone', '克隆仓库'], ['fetch', '拉取远端'], ['pull', '拉取更新'], ['push', '推送远端'],
439
+ ['commit', '提交改动'], ['add', '暂存改动'], ['restore', '撤销改动'], ['checkout', '切换分支'],
440
+ ['switch', '切换分支'], ['branch', '看分支'], ['status', '看仓库状态'], ['diff', '看差异'],
441
+ ['log', '看提交记录'], ['show', '看提交'], ['init', '初始化仓库'], ['rebase', '变基'],
442
+ ['merge', '合并分支'], ['stash', '暂存工作区'], ['tag', '打标签'], ['submodule', '拉子模块'],
443
+ ['worktree', '开工作树'], ['blame', '追改动来源'],
444
+ ])
445
+ // 包管理器二级动词(head 命中 INSTALLERS 时二跳取它)。
446
+ const PKG_SUB_GLOSS = new Map([
447
+ ['install', '装依赖'], ['i', '装依赖'], ['isntall', '装依赖'], ['add', '加依赖'], ['ci', '按锁文件装依赖'],
448
+ ['update', '更新依赖'], ['upgrade', '更新依赖'], ['remove', '移除依赖'], ['rm', '移除依赖'],
449
+ ['uninstall', '移除依赖'], ['run', '跑脚本'], ['test', '跑测试'], ['build', '构建'],
450
+ ['start', '起服务'], ['dev', '起开发服务'], ['exec', '跑子命令'], ['pip', '装 Python 包'],
451
+ ['sync', '同步锁文件'], ['lock', '生成锁文件'], ['deps', '拉项目依赖'], ['restore', '还原依赖'],
452
+ ['tool', '装工具链'], ['fetch', '拉包缓存'], ['download', '下载包'], ['wheel', '构建 wheel'],
453
+ ['require', '加依赖'], ['publish', '发包'], ['pack', '打包'], ['link', '软链包'], ['global', '全局装'],
454
+ ])
455
+ const CONTAINER_SUB_GLOSS = new Map([
456
+ ['pull', '拉镜像'], ['build', '构建镜像'], ['run', '起容器'], ['exec', '进容器执行'],
457
+ ['compose', '编排容器'], ['logs', '看容器日志'], ['ps', '看容器列表'], ['push', '推镜像'],
458
+ ])
459
+ // 命令首词 → 人话动词。表外的一律返回 ''(不编「执行 X」)。
460
+ const HEAD_GLOSS = new Map([
461
+ ['ls', '列目录'], ['dir', '列目录'], ['cd', '切目录'], ['cat', '看文件'], ['head', '看文件头'],
462
+ ['tail', '看文件尾'], ['less', '看文件'], ['more', '看文件'], ['sed', '按行改文本'],
463
+ ['awk', '按列算文本'], ['sort', '排序输出'], ['uniq', '去重'], ['wc', '数行列'], ['cut', '切字段'],
464
+ ['jq', '处理 JSON'], ['mkdir', '建目录'], ['rmdir', '删目录'], ['touch', '新建文件'],
465
+ ['rm', '删文件'], ['del', '删文件'], ['mv', '移动文件'], ['cp', '复制文件'], ['ln', '建链接'],
466
+ ['chmod', '改权限'], ['chown', '改归属'], ['find', '找文件'], ['fd', '找文件'], ['grep', '搜文本'],
467
+ ['rg', '搜文本'], ['tar', '解打包'], ['zip', '打包'], ['unzip', '解压'], ['gzip', '压缩'],
468
+ ['ps', '看进程'], ['kill', '杀进程'], ['pkill', '杀进程'], ['killall', '杀进程'], ['df', '看磁盘'],
469
+ ['du', '算目录体积'], ['free', '看内存'], ['top', '看负载'], ['env', '看环境变量'],
470
+ ['which', '找可执行文件'], ['whereis', '找可执行文件'], ['node', '跑 Node'], ['python', '跑 Python'],
471
+ ['python3', '跑 Python'], ['pytest', '跑测试'], ['vitest', '跑测试'], ['jest', '跑测试'],
472
+ ['make', '构建'], ['cmake', '构建'], ['docker', '操作容器'], ['podman', '操作容器'],
473
+ ['kubectl', '操作集群'], ['curl', '发 HTTP 请求'], ['wget', '下载文件'], ['ssh', '连远端'],
474
+ ['scp', '传文件'], ['rsync', '同步文件'], ['echo', '打印'], ['printf', '打印'],
475
+ ['export', '设环境变量'], ['source', '载入脚本'], ['git', '跑 git'], ['gh', '操作 GitHub'],
476
+ ['aws', '调 AWS'], ['brew', '装软件'], ['cargo', '跑 Rust 工程'], ['go', '跑 Go 工程'],
477
+ ['dotnet', '跑 .NET'], ['mix', '跑 Elixir'], ['composer', '跑 PHP 依赖'],
478
+ ])
479
+
480
+ function argText(o, keys) {
481
+ for (const key of keys) {
482
+ const v = o && o[key]
483
+ if (typeof v === 'string' && v.trim()) return v.trim()
484
+ }
485
+ return ''
486
+ }
487
+
488
+ // 路径只留末段:模型对 `src/a/b.ts` 与 `b.ts` 的判断力差别不大,token 省一半。
489
+ function baseName(raw) {
490
+ const s = String(raw || '').replace(/[\\/]+$/, '')
491
+ const seg = s.split(/[\\/]/).filter(Boolean)
492
+ return seg.length ? seg[seg.length - 1] : s.slice(0, 40)
493
+ }
494
+
495
+ function hostOf(url) {
496
+ const m = /^[a-z][\w+.:-]*:\/\/([^\/?#]+)/i.exec(String(url || ''))
497
+ return m ? m[1] : ''
498
+ }
499
+
500
+ // apply_patch / unified diff 没有 path 参数,目标文件名只能从补丁头反推。
501
+ function patchFilesOf(text) {
502
+ const out = []
503
+ const re = /\*\*\*\s*(?:Update|Add|Delete)\s+File:\s*(\S+)|^\+\+\+\s+b\/(\S+)|^---\s+a\/(\S+)/gmi
504
+ let m
505
+ while ((m = re.exec(String(text || '')))) {
506
+ const f = baseName(m[1] || m[2] || m[3])
507
+ if (f && !out.includes(f)) out.push(f)
508
+ if (out.length >= 3) break
509
+ }
510
+ return out
511
+ }
512
+
513
+ // 一条 shell 命令的人话:只看第一段(复合命令里首段才是本轮意图)。
514
+ function glossCommand(command) {
515
+ const segs = commandSegments(command)
516
+ if (!segs.length) return ''
517
+ const words = segs[0]
518
+ const head = headWord(words)
519
+ if (!head) return ''
520
+ const at = words.findIndex((w) => w.toLowerCase() === head)
521
+ const sub = String(words[at + 1] || '').toLowerCase().replace(/^-+/, '')
522
+ if (head === 'git') return GIT_SUB_GLOSS.get(sub) || ''
523
+ if (head === 'docker' || head === 'podman' || head === 'nerdctl') return CONTAINER_SUB_GLOSS.get(sub) || ''
524
+ if (head === 'npx' || head === 'pnpx' || head === 'dlx' || head === 'uvx') {
525
+ const pkg = cleanTarget(firstOperand(words, at + 1)).replace(/@[^@]+$/, '')
526
+ return pkg ? '临时跑 ' + pkg : ''
527
+ }
528
+ const inst = INSTALLERS.get(head)
529
+ if (inst) {
530
+ const sub2 = String(words[at + 2] || '').toLowerCase()
531
+ const verb = inst.verbs.has(sub) ? sub : (inst.verbs.has(sub2) ? sub2 : sub)
532
+ return PKG_SUB_GLOSS.get(verb) || ''
533
+ }
534
+ return HEAD_GLOSS.get(head) || ''
535
+ }
536
+
537
+ /**
538
+ * v0.7.0 R5 层 1:一次工具调用 → 一句人话(≤maxLen 字)。猜不出返回 ''。
539
+ * 只做名字/参数映射,不调 LLM、不拦截;与 tools.guard 无关。
540
+ */
541
+ function describeToolStep(name, argsRaw, maxLen) {
542
+ const u = unwrapAct(name, argsRaw)
543
+ const key = String(u.name || '').toLowerCase()
544
+ if (!key) return ''
545
+ let o = null
546
+ try { const v = JSON.parse(String(u.argsRaw || '')); if (isObject(v)) o = v } catch (_err) {}
547
+ const cap = Math.max(8, Number(maxLen) || 46)
548
+ let out = ''
549
+ if (SHELL_TOOL_NAMES.has(key) || BACKGROUND_TOOL_NAMES.has(key)) {
550
+ const cmd = argText(o, ['command', 'cmd', 'input', 'text']) || (typeof u.argsRaw === 'string' ? u.argsRaw : '')
551
+ out = glossCommand(cmd)
552
+ } else if (FETCH_TOOL_NAMES.has(key)) {
553
+ const tgt = baseName(argText(o, ['url', 'path', 'output', 'dest']))
554
+ out = tgt ? '下载 ' + tgt : ''
555
+ } else if (/^(?:read|read_file|open_file|view_file|list_dir)$/.test(key)) {
556
+ const f = baseName(argText(o, ['path', 'file_path', 'filePath', 'filename', 'file', 'dir_path']))
557
+ out = f ? (key === 'list_dir' ? '列目录 ' + f : '读文件 ' + f) : ''
558
+ } else if (/^(?:write|write_file|create_file|new_file|save_file)$/.test(key)) {
559
+ const f = baseName(argText(o, ['path', 'file_path', 'filePath', 'filename', 'file']))
560
+ out = f ? '写文件 ' + f : ''
561
+ } else if (/^(?:edit|edit_file|str_replace_editor|str_replace|multi_edit|multiline_edit|apply_patch|patch)$/i.test(key)) {
562
+ const verb = String(o?.command || '').toLowerCase()
563
+ const f = baseName(argText(o, ['path', 'file_path', 'filePath', 'filename']))
564
+ || patchFilesOf(argText(o, ['input', 'patch', 'content', 'new_text', 'text']))[0] || ''
565
+ if (f) out = (verb === 'view' || verb === 'read') ? '读文件 ' + f : (verb === 'create' ? '写文件 ' + f : '改文件 ' + f)
566
+ } else if (/^(?:grep|search|glob|find_files|code_search|ripgrep|list_files|files_search)$/i.test(key)) {
567
+ const pat = argText(o, ['pattern', 'query', 'glob_pattern', 'glob', 'regex'])
568
+ out = pat ? '搜 ' + pat.slice(0, 24) : ''
569
+ } else if (/^(?:webfetch|web_fetch|fetch_url|browse|open_url|read_url)$/i.test(key)) {
570
+ const host = hostOf(argText(o, ['url', 'href', 'link']))
571
+ out = host ? '抓网页 ' + host : ''
572
+ } else if (/^(?:websearch|web_search|search_web|tavily_search|exa_search)$/i.test(key)) {
573
+ const q = argText(o, ['query', 'q', 'search_query'])
574
+ out = q ? '搜网页 ' + q.slice(0, 24) : ''
575
+ } else if (/^(?:subagent|spawn_teammate|task|delegate|agents)$/i.test(key)) {
576
+ const role = baseName(argText(o, ['agent', 'agent_type', 'subagent_type', 'role', 'name']))
577
+ out = role ? '派子代理 ' + role : '派子代理'
578
+ } else if (/^(?:todo_write|todo|todos|write_todos|task_create)$/i.test(key)) {
579
+ const list = o && (Array.isArray(o.todos) ? o.todos : (Array.isArray(o.items) ? o.items : null))
580
+ out = list && list.length ? `更新官方清单 ×${list.length}` : '更新官方清单'
581
+ } else if (/^(?:run_code|code_exec|python_exec|repl|script)$/i.test(key)) {
582
+ // PTC 会话外层只有 run_code,内层真身在 `tools.xxx(` 里——能解出来就说内层。
583
+ const code = argText(o, ['code', 'script', 'source'])
584
+ const inner = [...String(code).matchAll(/tools\.([a-z_][\w]*)\s*\(/gi)].map((mm) => mm[1])
585
+ out = inner.length ? 'PTC 内层 ' + inner.slice(0, 3).join('+') : (code ? '跑代码' : '')
586
+ }
587
+ if (!out && o) {
588
+ // 猜不出时退回「第一个非空标量参数」:这是事实而非空话(plan:key=value 兜底)。
589
+ for (const [k, v] of Object.entries(o)) {
590
+ if (typeof v === 'string' && v.trim()) { out = `${k}=${v.trim().slice(0, 24)}`; break }
591
+ if (typeof v === 'number' || typeof v === 'boolean') { out = `${k}=${v}`; break }
592
+ }
593
+ }
594
+ return out.length > cap ? out.slice(0, cap - 1) + '…' : out
595
+ }
596
+
597
+ // 结果回显(层 2 的后半):工具完成后把动作升级成「动作 → 结果:<摘要 ≤60 字>」。
598
+ function resultDigest(text, failed) {
599
+ const s = String(text || '').replace(/\s+/g, ' ').trim()
600
+ if (!s) return failed ? '失败(无输出)' : ''
601
+ return ((failed ? '失败:' : '结果:') + (s.length > 54 ? s.slice(0, 54) + '…' : s)).slice(0, 60)
602
+ }
603
+
432
604
  // 纯解析函数导出(仅供 test/plan.test.mjs 单测;不在 dsh 契约面上,勿在插件间消费)。
433
- export { parseChecklistMarkdown, parseSpecOutline, normalizeStatus, planDirCandidates, pickPlanDir, classifyDownload, parseProgress, unwrapAct, isDownloadItem }
605
+ export { parseChecklistMarkdown, parseSpecOutline, normalizeStatus, planDirCandidates, pickPlanDir, classifyDownload, parseProgress, unwrapAct, isDownloadItem, describeToolStep, glossCommand, resultDigest }
434
606
 
435
607
  const PROGRESS_POLICY = `## 进度板
436
608
  progress_update 维护用户可见的实时进度板。每项含 title/status/percent/current/next/approach/note。
@@ -1632,7 +1804,7 @@ export async function apply(ctx, config) {
1632
1804
  '官方 todo(外部改动):',
1633
1805
  ...todoLines,
1634
1806
  lastOutput ? `最近输出:${lastOutput.text}` : '最近输出:—',
1635
- o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
1807
+ o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map(toolLabel).join(' → ')}` : '最近动作:—',
1636
1808
  ]
1637
1809
  try {
1638
1810
  const raw = await callAssistant({ system: TODO_RECONCILE_SYSTEM, user: lines.join('\n'), a })
@@ -2535,20 +2707,34 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2535
2707
  return s.length > 90 ? s.slice(0, 90) + '…' : s
2536
2708
  }
2537
2709
 
2710
+ // 动作标签:工具有人话就说「name 人话(→ 结果)」,猜不出或关了工具解释时
2711
+ // 逐字退回 0.6.x 的 `name` / `name×count`(新用例断言两者字节一致)。
2712
+ function toolLabel(x) {
2713
+ const head = x && x.count > 1 ? `${x.name}×${x.count}` : String(x && x.name || '')
2714
+ if (!cfg.toolGloss.enabled) return head
2715
+ const gloss = String(x.gloss || '')
2716
+ const tail = x.result ? ' → ' + String(x.result) : ''
2717
+ return head + (gloss ? ' ' + gloss : '') + tail
2718
+ }
2719
+
2538
2720
  function recordTool(sid, data) {
2539
2721
  const d = data || {}
2540
2722
  if (typeof d.name !== 'string' || !d.name) return
2541
2723
  const o = obsOf(sid)
2542
2724
  const at = now()
2543
2725
  const brief = briefArgs(d.arguments)
2726
+ // R5 层 1:规则表出人话(开关关掉时完全不算,o.tools 里就不会出现 gloss)。
2727
+ const gloss = cfg.toolGloss.enabled ? describeToolStep(d.name, d.arguments, cfg.toolGloss.maxLen) : ''
2544
2728
  // PTC 一步可能派发几十条同名工具(实测某会话单会话 86 次 shell),全量 push 会把
2545
2729
  // 真实动作挤出 o.tools 窗口。同 name+brief 与末条相同时只推进时间戳。
2546
2730
  const last = o.tools[o.tools.length - 1]
2547
2731
  if (last && last.name === d.name && last.brief === brief) {
2548
2732
  last.at = at
2549
2733
  last.count = (last.count || 1) + 1
2734
+ if (gloss && !last.gloss) last.gloss = gloss
2735
+ last.result = ''
2550
2736
  } else {
2551
- o.tools.push({ at, name: d.name, brief, count: 1 })
2737
+ o.tools.push({ at, name: d.name, brief, count: 1, gloss, result: '', cid: String(d.callId || '') })
2552
2738
  if (o.tools.length > 8) o.tools.splice(0, o.tools.length - 8)
2553
2739
  }
2554
2740
  // 文件改动(事实级):任何带路径类参数的工具调用都记一笔,同路径去重留最新
@@ -2569,10 +2755,27 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2569
2755
  }
2570
2756
  }
2571
2757
 
2758
+ // R5 层 2 回显:把结果摘要挂到对应那条动作上(callId 优先,无 id 退到末条且未回显)。
2759
+ // 失败只写自己的尾巴,不动既有 lastToolError(观察块的「最近失败」行另有其人)。
2760
+ function attachToolResult(o, at, callId, digest) {
2761
+ if (!cfg.toolGloss.enabled || !digest) return
2762
+ let target = null
2763
+ if (callId) {
2764
+ for (let i = o.tools.length - 1; i >= 0; i -= 1) {
2765
+ if (o.tools[i].cid === callId) { target = o.tools[i]; break }
2766
+ }
2767
+ }
2768
+ if (!target) {
2769
+ const x = o.tools[o.tools.length - 1]
2770
+ if (x && !x.result && at - x.at < 120000) target = x
2771
+ }
2772
+ if (target) target.result = digest
2773
+ }
2774
+
2572
2775
  /**
2573
- * v0.7.0 R2:工具结果里抽真实进度(后台下载轮询日志、curl/wget/pip 末行)。
2574
- * 只留末条、截 400 字、不进归档事件环(归档侧的 interesting 白名单刻意不收 tool/result,
2575
- * 就是怕把工具输出这种大 payload 常驻内存)。
2776
+ * v0.7.0 R2 + R5 层 2:一次 tool/result —— 既喂下载真值(downloadGuess),
2777
+ * 也给末条动作补上「→ 结果:…」尾巴。只留末条、截 400 字、不进归档事件环
2778
+ * (归档侧的 interesting 白名单刻意不收 tool/result,就是怕工具输出这种大 payload 常驻内存)。
2576
2779
  */
2577
2780
  function recordToolResult(sid, data) {
2578
2781
  const d = data || {}
@@ -2580,7 +2783,11 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2580
2783
  const raw = textOf(msg)
2581
2784
  if (!raw) {
2582
2785
  const o = obsOf(sid)
2583
- if (msg.isError === true || d.error) o.lastResult = { at: now(), name: '', callId: String(msg.toolCallId || ''), text: '', failed: true }
2786
+ if (msg.isError === true || d.error) {
2787
+ const at0 = now()
2788
+ o.lastResult = { at: at0, name: '', callId: String(msg.toolCallId || ''), text: '', failed: true }
2789
+ attachToolResult(o, at0, String(msg.toolCallId || d.callId || ''), resultDigest('', true))
2790
+ }
2584
2791
  return
2585
2792
  }
2586
2793
  const o = obsOf(sid)
@@ -2589,7 +2796,9 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2589
2796
  const flat = raw.replace(/[\r\t]+/g, ' ').replace(/ {2,}/g, ' ').trim()
2590
2797
  const tail = flat.length > 400 ? flat.slice(-400) : flat
2591
2798
  const callId = String(msg.toolCallId || d.callId || '')
2592
- o.lastResult = { at, name: String(msg.toolName || ''), callId, text: tail, failed: msg.isError === true || Boolean(d.error) }
2799
+ const failed = msg.isError === true || Boolean(d.error)
2800
+ o.lastResult = { at, name: String(msg.toolName || ''), callId, text: tail, failed }
2801
+ attachToolResult(o, at, callId, resultDigest(tail, failed))
2593
2802
  const ld = o.lastDownload
2594
2803
  if (!ld || !cfg.download.enabled) return
2595
2804
  const ttl = Math.max(1000, Number(cfg.download.ttlMs) || 480000)
@@ -2801,7 +3010,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2801
3010
  `目标:${state.goal && state.goal.phase === 'active' ? JSON.stringify(state.goal.objective) : '(无)'}`,
2802
3011
  ...renderChecklist(state, cfg.observer.maxItems),
2803
3012
  lastOutput ? `最近输出:${lastOutput.text}` : '最近输出:—',
2804
- o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
3013
+ o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map(toolLabel).join(' → ')}` : '最近动作:—',
2805
3014
  files.length ? `最近改动:${files.join(' · ')}` : '最近改动:—',
2806
3015
  ]
2807
3016
  // plan 文档是**助手细化板的主原料**:用户明确要求让任务管理 LLM 读 spec/tasks/checklist。
@@ -3023,7 +3232,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3023
3232
  const lastOutput = o.outputs[o.outputs.length - 1]
3024
3233
  if (lastOutput) lines.push(`最近输出:「${lastOutput.text}」`)
3025
3234
  const tools = o.tools.slice(-cfg.observer.maxTools)
3026
- if (tools.length) lines.push(`最近动作:${tools.map((x) => (x.count > 1 ? `${x.name}×${x.count}` : x.name)).join(' → ')}`)
3235
+ if (tools.length) lines.push(`最近动作:${tools.map(toolLabel).join(' → ')}`)
3027
3236
  if (o.lastToolError) lines.push(`最近失败:${o.lastToolError.name}${o.lastToolError.message ? ' · ' + o.lastToolError.message : ''}`)
3028
3237
  // v0.7.0 R1:下载感知(软:只提醒 + 催办,绝不拦截工具)。关板/全完成在上面已 return。
3029
3238
  const dl = downloadView(state, at)
@@ -3046,6 +3255,10 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3046
3255
  if (o.assistantError) lines.push(`助手审查失败:${o.assistantError}(仅影响审查建议,不阻断主流程)`)
3047
3256
  const planRow = planLine(sid)
3048
3257
  if (planRow) lines.push(planRow)
3258
+ // R5 层 3:静态叙述纪律(只提一行、不逐条 pre-step 注入,softNarrate:false 可关)。
3259
+ if (cfg.toolGloss.enabled && cfg.toolGloss.softNarrate) {
3260
+ lines.push('▸ 每步工具前用一行写清「▸ <动作> → <本步目的>」(例:▸ 读 index.js → 确认字段名再改),不复述整段计划。')
3261
+ }
3049
3262
  return `<progress-observer revision="${state.revision}" synced="${synced}">\n${lines.join('\n')}\n</progress-observer>`
3050
3263
  }
3051
3264
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-progress-union",
3
- "version": "0.7.0-rc.1",
3
+ "version": "0.7.0-rc.2",
4
4
  "type": "module",
5
5
  "description": "进度结合原型:dsh-progress-board 槽位真相源 × 鲸程 widget 时间/ETA 引擎;向压缩插件暴露只读三层进度锚点(service + HTTP 双平面);0.6.0 起每回合落一版会话归档(handoff + 重启注入一次)。基于 l3j3y3/dsh-progress-board (MIT) 与 uuhihj/task-progress-bar dsh-progress-widget (MIT)。",
6
6
  "license": "MIT",
@@ -188,3 +188,87 @@ test('0.6.3:提示卡与用量条间距成体系,且不再出现负 margin',
188
188
  assert.match(src, /\.pb-side > \.pb-usage \{[^}]*margin: 0 0 12px/, '用量条上边距必须归零')
189
189
  assert.match(src, /\.pb-side > \.pb-llm \+ \.pb-side-error \{ margin-top: 12px; \}/, '同类块相邻补 12px')
190
190
  })
191
+
192
+ // ── 0.7.0 rc.2 / Phase 4:下载子进度条(R2 展示面)──────────────────────
193
+
194
+ // 把 client.js 里的 downloadRow 抠出来在 vm 外单跑一次:源码正则只能证明「写了」,
195
+ // 真调用才能证明「关板时返回 null、无真值时不吐假百分比」。
196
+ function loadDownloadRow() {
197
+ const src = fs.readFileSync(clientFile, 'utf8').replace(/\r\n/g, '\n')
198
+ const start = src.indexOf('function downloadRow(dl, t) {')
199
+ assert.ok(start > 0, 'downloadRow 助手必须存在')
200
+ const end = src.indexOf('\n }\n', start)
201
+ assert.ok(end > start, 'downloadRow 函数体必须能定界')
202
+ // eslint-disable-next-line no-new-func
203
+ return new Function('h', 't', `${src.slice(start, end + 6)}\nreturn downloadRow`)(
204
+ (...args) => ({ __el: args }),
205
+ (key) => key,
206
+ )
207
+ }
208
+
209
+ test('rc.2:子条渲染门控——后端不下发 download 时整行不渲染', () => {
210
+ const downloadRow = loadDownloadRow()
211
+ const t = (k) => k
212
+ assert.equal(downloadRow(undefined, t), null, 'snapshot 无 download 键(关板/showSubBar=false/过期)必须不渲染')
213
+ assert.equal(downloadRow(null, t), null)
214
+ assert.equal(downloadRow({ active: false, basis: 'stdout', percent: 50 }, t), null, 'active=false 必须不渲染')
215
+ })
216
+
217
+ test('rc.2:真值档(stdout/board)画实际宽度并显示百分比', () => {
218
+ const downloadRow = loadDownloadRow()
219
+ const row = downloadRow({ active: true, basis: 'stdout', percent: 42.6, kind: 'install', target: 'zod', elapsedSec: 8 }, (k) => k)
220
+ assert.ok(row && row.__el, '子条必须产出元素')
221
+ const [, attrs, ...kids] = row.__el
222
+ assert.equal(attrs.className, 'pb-dock-dl')
223
+ assert.match(String(attrs.title), /dlInstall \u00b7 zod/, '悬停提示需带动作与目标')
224
+ const cls = (n) => (n && n.__el ? String(n.__el[1].className) : '')
225
+ const bar = kids.find((n) => cls(n).indexOf('pb-dock-dl-bar') === 0)
226
+ assert.ok(bar, '必须画进度条')
227
+ assert.equal(cls(bar), 'pb-dock-dl-bar', '有真值时不得加 indeterminate')
228
+ assert.equal(bar.__el[2].__el[1].style.width, '43%', '填充宽度取整百分比')
229
+ const pctNode = kids.find((n) => cls(n) === 'pb-dock-dl-pct')
230
+ assert.ok(pctNode && pctNode.__el[2] === '43%', '百分比文本只在真值档出现')
231
+ })
232
+
233
+ test('rc.2:elapsed 档禁假百分比,走 indeterminate 条纹 + 已用时长;后台加徽标', () => {
234
+ const downloadRow = loadDownloadRow()
235
+ const row = downloadRow({ active: true, basis: 'elapsed', kind: 'clone', target: 'repo.git', elapsedSec: 125, background: true }, (k) => k)
236
+ const [, , ...kids] = row.__el
237
+ const cls = (n) => (n && n.__el ? String(n.__el[1].className) : '')
238
+ const bar = kids.find((n) => cls(n).indexOf('pb-dock-dl-bar') === 0)
239
+ assert.equal(cls(bar), 'pb-dock-dl-bar indeterminate', '无真值必须走条纹档')
240
+ assert.equal(bar.__el[2].__el[1], undefined, '无真值不得写内联 style(假百分比)')
241
+ assert.equal(kids.some((n) => cls(n) === 'pb-dock-dl-pct'), false, '无真值不得出现百分比')
242
+ const badge = kids.find((n) => cls(n) === 'pb-badge-bg')
243
+ assert.ok(badge && badge.__el[2] === 'dlBackground', 'background=true 必须出徽标')
244
+ const time = kids.find((n) => cls(n) === 'pb-dock-dl-time')
245
+ assert.equal(time.__el[2], '2 dlMinUnit', '>=60s 换算成分钟')
246
+ })
247
+
248
+ test('rc.2:子条样式全走宿主令牌,且挂在主条行之后、展开区之前', () => {
249
+ const src = fs.readFileSync(clientFile, 'utf8').replace(/\r\n/g, '\n')
250
+ const cssStart = src.indexOf('.pb-dock-dl {')
251
+ const cssEnd = src.indexOf('.pb-side {')
252
+ assert.ok(cssStart > 0 && cssEnd > cssStart, '子条样式块必须在侧栏样式之前')
253
+ const css = src.slice(cssStart, cssEnd)
254
+ assert.doesNotMatch(css, /#[0-9a-fA-F]{3,6}/, '子条样式不得硬编十六进制色')
255
+ assert.doesNotMatch(css, /rgba?\(/, '子条样式不得硬编 rgb 色(皮肤切换会失配)')
256
+ assert.match(css, /var\(--dsw-alias-brand-primary\)/, '填充色必须用主色令牌')
257
+ assert.match(css, /\.pb-badge-bg \{[^}]*var\(--dsw-alias-state-warn-primary\)/, '后台徽标必须用 warn 令牌')
258
+ assert.match(css, /@media \(prefers-reduced-motion: reduce\)/, '条纹动画必须尊重「减少动效」')
259
+ assert.match(src, /\.pb-dock-dl \{ margin-left: 0; \}/, '760px 段需去掉左缩进')
260
+ assert.match(src, /@media \(max-width: 520px\) \{\s*\.pb-dock-dl \{ display: none; \}/, '极窄屏整行收起')
261
+ const rowIdx = src.indexOf("{ className: 'pb-dock-row' }")
262
+ const dlIdx = src.indexOf('downloadRow(snapshot.download, t),')
263
+ const expIdx = src.indexOf('expanded\n ? h(', dlIdx)
264
+ assert.ok(rowIdx > 0 && rowIdx < dlIdx && dlIdx < expIdx, '子条必须渲染在主条行之后、展开列表之前')
265
+ })
266
+
267
+ test('rc.2:子条文案 zh/en 成对(本仓 client 只有内联 zh/en 两份字典)', () => {
268
+ const src = fs.readFileSync(clientFile, 'utf8').replace(/\r\n/g, '\n')
269
+ const keys = ['dlDownload', 'dlInstall', 'dlClone', 'dlPull', 'dlUnnamed', 'dlBackground', 'dlSecUnit', 'dlMinUnit', 'dlBasisStdout', 'dlBasisBoard', 'dlBasisElapsed']
270
+ for (const k of keys) {
271
+ const hits = src.match(new RegExp(`\\n\\s+${k}: '[^']+',`, 'g')) || []
272
+ assert.equal(hits.length, 2, `${k} 必须在 zh/en 各出现一次(实得 ${hits.length})`)
273
+ }
274
+ })
@@ -0,0 +1,137 @@
1
+ /**
2
+ * 0.7.0 rc.2 验收:R5 工序可解释。
3
+ * 层 1 = describeToolStep 规则表;层 2 = o.tools 的 gloss + tool/result 回显;
4
+ * 层 3 = 观察块末尾的静态叙述纪律行(softNarrate)。
5
+ * 硬约束:toolGloss.enabled=false 时观察块输出与 0.6.x 逐字一致。
6
+ */
7
+ import assert from 'node:assert/strict'
8
+ import fs from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+ import test from 'node:test'
12
+
13
+ process.env.DSH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'union-test-'))
14
+ const { SESSION, createHarness, jsonReq, callRoute } = await import('./harness.mjs')
15
+ const { describeToolStep, glossCommand, resultDigest } = await import('../index.js')
16
+
17
+ async function booted(config) {
18
+ const harness = createHarness({ config })
19
+ await harness.run()
20
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
21
+ await harness.toolMap.get('progress_update').definition.execute({ changes: [{ title: '改造接口', status: 'doing' }] }, { agent: harness.agent })
22
+ return harness
23
+ }
24
+
25
+ function observerText(harness) {
26
+ const fn = harness.contexts.get('progress-union-observer')
27
+ assert.ok(fn, 'progress-union-observer 上下文必须注册')
28
+ return fn()
29
+ }
30
+
31
+ function actionLine(text) {
32
+ const line = String(text).split('\n').find((l) => l.startsWith('最近动作:'))
33
+ return line || ''
34
+ }
35
+
36
+ // ── 层 1:规则表(纯函数)────────────────────────────────────────────────
37
+
38
+ test('glossCommand:git/docker/包管理器二跳与首词表', () => {
39
+ assert.equal(glossCommand('git clone https://x/y.git'), '克隆仓库')
40
+ assert.equal(glossCommand('git commit -m "msg"'), '提交改动')
41
+ assert.equal(glossCommand('docker build -t img .'), '构建镜像')
42
+ assert.equal(glossCommand('npm test'), '跑测试')
43
+ assert.equal(glossCommand('pnpm add zod'), '加依赖')
44
+ assert.equal(glossCommand('uv pip install ruff'), '装 Python 包')
45
+ assert.equal(glossCommand('ls -la'), '列目录')
46
+ assert.equal(glossCommand('npx --yes create-vite@3 app'), '临时跑 create-vite')
47
+ // 首段才是本轮意图:复合命令不再被后段带偏
48
+ assert.equal(glossCommand('npm ci && npm test'), '按锁文件装依赖')
49
+ // 表外词:返回空串,不编「执行 x」
50
+ assert.equal(glossCommand('myCustomTool --run'), '')
51
+ })
52
+
53
+ test('describeToolStep:文件类与检索类工具走参数名,路径只留末段', () => {
54
+ assert.equal(describeToolStep('read', JSON.stringify({ file_path: 'src/deep/nested/mod.ts' })), '读文件 mod.ts')
55
+ assert.equal(describeToolStep('write', JSON.stringify({ path: 'a/b/out.md' })), '写文件 out.md')
56
+ assert.equal(describeToolStep('edit', JSON.stringify({ filePath: 'a/b/c.py' })), '改文件 c.py')
57
+ assert.equal(describeToolStep('str_replace_editor', JSON.stringify({ command: 'view', path: 'x/y.ts' })), '读文件 y.ts')
58
+ assert.equal(describeToolStep('apply_patch', JSON.stringify({ input: '*** Begin Patch\n*** Update File: pkg/lib/entry.js\n@@' })), '改文件 entry.js')
59
+ assert.equal(describeToolStep('grep', JSON.stringify({ pattern: 'unwrapLive' })), '搜 unwrapLive')
60
+ assert.equal(describeToolStep('webfetch', JSON.stringify({ url: 'https://docs.example.com/a/b?x=1' })), '抓网页 docs.example.com')
61
+ assert.equal(describeToolStep('websearch', JSON.stringify({ query: 'cordis volatile schema' })), '搜网页 cordis volatile schema')
62
+ assert.equal(describeToolStep('todo_write', JSON.stringify({ todos: [1, 2, 3].map((i) => ({ content: 't' + i })) })), '更新官方清单 ×3')
63
+ assert.equal(describeToolStep('run_code', JSON.stringify({ code: 'tools.shell(1); tools.read(2)' })), 'PTC 内层 shell+read')
64
+ })
65
+
66
+ test('describeToolStep:act 透传后仍出人话(不记成 act)', () => {
67
+ const raw = JSON.stringify({ tool: 'bash', input: { command: 'git push origin main' } })
68
+ assert.equal(describeToolStep('act', raw), '推送远端')
69
+ })
70
+
71
+ test('describeToolStep:猜不出退回 key=value,全空则空串(不写空话)', () => {
72
+ assert.equal(describeToolStep('frobnicate', JSON.stringify({ widget: 'fluxcapacitor-mark-ii' })), 'widget=fluxcapacitor-mark-ii')
73
+ // 兼容兜底也要有界:单值截 24
74
+ assert.equal(describeToolStep('frobnicate', JSON.stringify({ widget: 'supercalifragilisticexpialidocious' })), 'widget=supercalifragilisticexpi')
75
+ assert.equal(describeToolStep('frobnicate', '{}'), '')
76
+ assert.equal(describeToolStep('frobnicate', ''), '')
77
+ // 命令型但参数不是命令:同样不硬编
78
+ assert.equal(describeToolStep('bash', JSON.stringify({ cwd: '/tmp' })), 'cwd=/tmp')
79
+ })
80
+
81
+ test('describeToolStep:maxLen 生效且截断带省略号', () => {
82
+ const out = describeToolStep('search', JSON.stringify({ pattern: 'a'.repeat(80) }), 20)
83
+ assert.ok(out.length <= 20, `长度 ${out.length} 应 ≤20`)
84
+ assert.ok(out.endsWith('…'), '截断必须带省略号')
85
+ })
86
+
87
+ test('resultDigest:≤60 字、区分成败、无输出不写空话', () => {
88
+ const long = 'x'.repeat(200)
89
+ const ok = resultDigest(long, false)
90
+ assert.ok(ok.startsWith('结果:'))
91
+ assert.ok(ok.length <= 60, `长度 ${ok.length} 应 ≤60`)
92
+ assert.equal(resultDigest(' built 42 frames ', true), '失败:built 42 frames')
93
+ assert.equal(resultDigest('', true), '失败(无输出)')
94
+ assert.equal(resultDigest('', false), '')
95
+ })
96
+
97
+ // ── 层 2/3:接进观察者(真事件流)──────────────────────────────────────
98
+
99
+ test('层 2:最近动作带人话,tool/result 追加结果尾巴', async () => {
100
+ const harness = await booted()
101
+ harness.emit('tool/call', { name: 'Bash', callId: 'c1', arguments: JSON.stringify({ command: 'npm test' }) })
102
+ assert.match(actionLine(observerText(harness)), /^最近动作:Bash 跑测试$/)
103
+ harness.emit('tool/result', { message: { toolCallId: 'c1', isError: false, content: [{ type: 'text', text: '188 passed in 6.4s' }] } })
104
+ assert.match(actionLine(observerText(harness)), /^最近动作:Bash 跑测试 → 结果:188 passed in 6\.4s$/)
105
+ })
106
+
107
+ test('层 2:连续同名同参仍走 ×N,且新动作会让上一条的结果尾巴作废', async () => {
108
+ const harness = await booted()
109
+ for (let i = 0; i < 3; i++) harness.emit('tool/call', { name: 'Bash', callId: 'c' + i, arguments: JSON.stringify({ command: 'npm test' }) })
110
+ assert.match(actionLine(observerText(harness)), /^最近动作:Bash×3 跑测试$/)
111
+ })
112
+
113
+ test('层 3:softNarrate 默认开,出静态「▸ 动作 → 本步目的」纪律行', async () => {
114
+ const harness = await booted()
115
+ const text = observerText(harness)
116
+ assert.match(text, /^▸ 每步工具前用一行写清「▸ <动作> → <本步目的>」/m)
117
+ })
118
+
119
+ test('softNarrate:false 只撤纪律行,人话动作保留', async () => {
120
+ const harness = await booted({ toolGloss: { softNarrate: false } })
121
+ harness.emit('tool/call', { name: 'Bash', callId: 'c1', arguments: JSON.stringify({ command: 'git status' }) })
122
+ const text = observerText(harness)
123
+ assert.doesNotMatch(text, /▸ 每步工具前/, '关掉后不得再推叙述纪律')
124
+ assert.equal(actionLine(text), '最近动作:Bash 看仓库状态')
125
+ })
126
+
127
+ test('enabled:false:最近动作逐字退回 0.6.x 的 name×count,且不算 gloss', async () => {
128
+ const harness = await booted({ toolGloss: { enabled: false } })
129
+ harness.emit('tool/call', { name: 'Bash', callId: 'c1', arguments: JSON.stringify({ command: 'npm test' }) })
130
+ harness.emit('tool/call', { name: 'Bash', callId: 'c2', arguments: JSON.stringify({ command: 'npm test' }) })
131
+ harness.emit('tool/call', { name: 'Read', callId: 'c3', arguments: JSON.stringify({ file_path: 'a/b.ts' }) })
132
+ harness.emit('tool/result', { message: { toolCallId: 'c3', isError: false, content: [{ type: 'text', text: 'export const x = 1' }] } })
133
+ // 0.6.x 原算法重算一遍:name(同名连续计数)+ ' → ' 连接,无人话、无结果尾巴、无纪律行
134
+ const legacy = '最近动作:' + ['Bash×2', 'Read'].join(' → ')
135
+ assert.equal(actionLine(observerText(harness)), legacy)
136
+ assert.doesNotMatch(observerText(harness), /▸ 每步工具前/)
137
+ })