refactor(pi-bridge): 定下 lib/ 与 test/lib/ 的边界 —— 三个测试侧模块原来会随部署进 /opt

pi 复核后指出:`lib/` 会被 `cp -a "$SRC/." "$STAGING/"` **整份打进生产快照**
(排除清单只有 `test/`、`.git`、`node_modules/.cache`),而我们那三个测试侧模块
(`tmp-space.mjs`、`env-error.mjs`、`session-fixtures.mjs`)都住在 `lib/` 里。
后果不是几 KB,而是"漂移 N 处"这个数字**虚高**、哈希清单变长 ——
而"手抄哈希清单"正是我们刚定性为会过期的东西。

## 规则写成**可判定的**,不写成约定

    lib/      = 从生产入口可达的模块(会进快照)
    test/lib/ = 只被测试引用的模块(test/ 不部署、也不被注册进套件)

`test/lib/reach.mjs` 真去走一遍 import 闭包(种子 = `src/index.mjs` +
源码里 `new URL('./x.mjs', import.meta.url)` 这类**按路径 fork 的子进程入口**)。

★ 顺带纠正 pi 的规则表述:他写的是"被 `src/` import",但实测 22 个 `lib/` 模块里
有 4 个 `src` **直接**引用数是 0 —— `addressing.js`(被 `lib/inbox-format.js` 引)、
`user-question.js`(走前缀动态 import)、`mail-session-id.js`、`crash-notify.mjs`。
**直接引用数不是可达性**,所以判据真走图而不是 grep。
★ 也纠正他的排除清单名字:脚本里没有 `EXCLUDE_DIRS` 这个变量,就是一条 `rm -rf`。

## 本规则多抓到一个 pi 没发现的

`lib/user-question.js` 也是**只被测试引用**(只有 `test/user-question.test.mjs` 用它)
⇒ 同样会进快照。已一并移到 `test/lib/`。剩下 `mail-session-id.js` 与
`crash-notify.mjs` 是**谁都不用**(生产与测试都不可达)—— 那是遗留物,
不动它们(不属本次范围),但记录在此。

## 新增:因果**无关**的运行期判据

`test/lib/run-suite.mjs`:跑套件并从**同一次运行的 TAP**里数结果行,任何用例名
出现两次就红。为什么需要:静态那条(测试文件不许互相 import)只能发现**已知成因**。
实测跨文件重名**不会被 runner 拦**:两个文件各写一个同名用例 ⇒
`# tests 2 / # pass 2 / # fail 0`,两句 `ok`,零警告。

判据锚在 `^(ok|not ok) <n> - <名字>`(**结果行**),不是"名字出现过"——
pi 先前那条 `grep -c '<名字>'` 给 4 是因为 TAP 里名字既出现在 `# Subtest:` 头、
又出现在结果行,**2 倍效应 + 2 倍噪声恰好同值**,若行种类是 3 就会把两次读成三次。
本脚本自带 `--self-check`(干净样本放行 / 重复样本点名 / 只出现在头里的不算重复 /
名字含 `#` 不被截断)。

`package.json` 的 `test` 改为:
    node test/lib/env-preflight.mjs && node test/lib/run-suite.mjs

## 判据全进套件

`test/layout-boundaries.test.mjs`(新):生产可达性不碰 `test/`、`test/lib/` 里不许藏
运行时模块、测试文件不许互相 import、`npm test` 必须接上 run-suite 那一层。
原来放在 `env-guard.test.mjs` 里那条"夹具不在测试文件里"已移到这里(集中边界判据)。

## 变异自检(两条都实测红了才留下)

- 造一个与巨行用例**同名**的探针文件 ⇒ `npm test` exit 1 并点名
  `2× ★巨大的 message 行不进内存也不影响解析`;
- 往 `src/gateway.mjs` 加一行指向 `test/lib/run-suite.mjs` 的真 import ⇒
  边界判据红并指出 `生产可达了测试代码:test/lib/run-suite.mjs`。
  两条探针均已删除、`src/gateway.mjs` 用 `git checkout` 还原并 `cmp` 校验一致。

顺带修一处路径:`env-guard.test.mjs` 里 `PREFLIGHT` 仍指向旧的 `test/env-preflight.mjs`
(前置脚本已移入 `test/lib/`)。

验证:`npm test` **462/462**、结果行重复检查 0 个重名、set 全绿。
This commit is contained in:
2026-09-14 20:00:16 +08:00
parent d735e674e1
commit fb85a8728d
12 changed files with 396 additions and 42 deletions

View File

@ -1,176 +0,0 @@
/**
* `ask_user_question` ↔ AgentMail 询问邮件 的双向映射(纯函数)。
*
* # 为什么需要它
*
* DSH 的 `ask_user_question` 走 `ctx.userQuestions` 这个 UI seam,而邮件驱动的
* 会话**没有本地 UI**。不桥接的后果是模型主动提问后永久挂死:`ask()` 的
* promise 永远不 resolve,那一轮工具调用卡在那里,人却什么也看不到。
*
* # 两个模型的形状差异
*
* DSH:`{ questions: [{ id, question, header?, options?: [{label, description?}],
* multiSelect? }] }` → `{ answers: [{ id, selected[], custom? }] }`
* - 一次可以问**多个**问题,每个问题可有自己的选项与多选语义
* - 答案按问题 id 回填,选项用 label 字符串
*
* AgentMail:一封询问邮件 = 一个问题 + 一个选项列表 + 一个 multi_select 标志
* - 只有单问题结构,因此多问题时必须摊平
*
* # 摊平策略(多问题时)
*
* 选项取所有问题 label 的并集(去重、保持首次出现顺序),并把每个问题的
* 原文、选项与说明枚举进 context 正文。回信时按「label 属于哪个问题」把
* 选择分配回去。这比「一问一封邮件」简单得多 —— 后者要等人分别回复多封
* 才能凑齐一次 `ask()` 的答案,而 `ask()` 是**单次**调用,凑不齐就还是挂死。
*
* # fail closed
*
* 认不出的答案一律不猜测;没有匹配到任何选项的问题返回空选择 + 把自由文本
* 放进 custom,而不是随便挑一个 label 放行。
*/
/** 问题是否带可选项。 */
export function hasOptions(question) {
return Array.isArray(question?.options) && question.options.length > 0;
}
/** 一个 DSH 问题的可选项 label 列表(保序)。 */
export function optionLabels(question) {
if (!hasOptions(question)) return [];
return question.options
.map((o) => (typeof o === 'string' ? o : o?.label))
.filter((l) => typeof l === 'string' && l.length > 0);
}
/** 一个问题的展示标题:header 有就用它做前缀,否则只用 question。 */
export function questionTitle(question) {
const header = typeof question?.header === 'string' ? question.header.trim() : '';
const text = typeof question?.question === 'string' ? question.question.trim() : '';
if (header && text) return `${header}: ${text}`;
return header || text || '(未提供问题)';
}
/**
* 把 DSH 的 questions 摊平成一封 AgentMail 询问邮件的正文与元数据。
*
* @param {Array<object>} questions DSH AskUserQuestionItem[]
* @returns {{ question: string, options: string[], context: string, multiSelect: boolean }}
*/
export function flattenQuestions(questions) {
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
if (list.length === 0) {
throw new Error('ask_user_question 至少需要一个 question');
}
const lines = [];
const options = [];
const seen = new Set();
let anyMulti = false;
list.forEach((q, i) => {
const title = questionTitle(q);
lines.push(`${i + 1}. ${title}`);
const detail = typeof q?.detail === 'string' ? q.detail.trim() : '';
if (detail) lines.push(` ${detail}`);
const labels = optionLabels(q);
if (labels.length > 0) {
lines.push(` 可选项:${labels.join(' / ')}${q.multiSelect ? '(可多选)' : ''}`);
for (const label of labels) {
if (!seen.has(label)) {
seen.add(label);
options.push(label);
}
}
} else {
lines.push(' (请直接填写回答)');
}
if (q?.multiSelect === true) anyMulti = true;
});
// 多问题时必须允许多选:不同问题的选项要能一起勾选。
const multiSelect = list.length > 1 ? options.length > 0 : anyMulti;
const question = list.length === 1 ? questionTitle(list[0]) : `${list.length} 个问题待回答`;
const context = [
list.length === 1 ? '' : '模型提出了多个问题,请在「回复」里一并回答:',
...lines,
'',
options.length > 0
? '可直接勾选下方的选项;补充说明写在备注里。'
: '这题没有预设选项,请把回答写在备注里。',
].filter((l) => l !== '').join('\n');
return { question, options, context, multiSelect };
}
/**
* 把人类的决策回写成 DSH 的 answers[]。
*
* @param {Array<object>} questions 原始 DSH questions(回填 id 用)
* @param {string} decision 人类选的选项原文(多选时前端用换行分隔)
* @param {string} [note] 自由文本/备注
* @returns {{ answers: Array<{id: string, selected: string[], custom?: string}> }}
*/
export function answersFromDecision(questions, decision, note) {
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
const labels = String(decision || '')
.split('\n')
.map((s) => s.trim())
.filter(Boolean);
const custom = typeof note === 'string' ? note.trim() : '';
// 单问题:忠实映射(选项 → selected,备注 → custom)。
if (list.length === 1) {
const q = list[0];
const id = String(q?.id ?? '0');
if (!hasOptions(q)) {
// 无选项题:人类把答案写在决策文本或备注里,都属于「自由文本回答」。
const text = custom || labels.join('\n');
return { answers: [{ id, selected: [], ...(text ? { custom: text } : {}) }] };
}
return {
answers: [{
id,
selected: labels,
...(custom ? { custom } : {}),
}],
};
}
// 多问题:按 label 归属把选择分配给各自的问题;备注归给第一个问题。
let customUsed = false;
const answers = list.map((q, i) => {
const id = String(q?.id ?? String(i));
const labels_q = optionLabels(q);
const selected = labels.filter((l) => labels_q.includes(l));
let qCustom;
if (custom && !customUsed) {
qCustom = custom;
customUsed = true;
}
// 无选项题且人没写备注:退而把决策文本整段给它(否则它的答案永远是空的)。
if (qCustom === undefined && !hasOptions(q) && note === undefined) {
const text = labels.join('\n');
if (text) qCustom = text;
}
return { id, selected, ...(qCustom ? { custom: qCustom } : {}) };
});
return { answers };
}
/**
* 决策是否「什么都没答」——用来在提交前拦住空回答(不把空答案喂给模型)。
*
* 允许多选时空 selected 但有 custom 也算答了;两者都空才算没答。
*/
export function isBlankAnswer(questions, decision, note) {
const labels = String(decision || '').split('\n').map((s) => s.trim()).filter(Boolean);
const custom = typeof note === 'string' ? note.trim() : '';
if (labels.length > 0 || custom) return false;
// 全部问题都没有选项、人也没写字 → 确实什么都没答
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
return list.some((q) => hasOptions(q)) || list.length === 0;
}