Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

Merge origin/main + fix(i18n): schema 形状校验,收敛 workspace slot 新文案

Dashc08b2b45bb87
diff --cc apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index b0e74fe9bd,ec75d62885..f047f1be51
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@@ -2425,15 -2429,17 +2429,17 @@@
"unchanged": "其余 {{count}} 项权限不变",
"noChange": "权限无变化。",
"pick": "可请求你选择一个文件夹交给它",
- "pickDetail": "它发起请求时,Cindy 会弹出系统的选择文件夹窗口;选哪个、给不给,都由你亲手决定,取消则它什么都拿不到。",
- "workspace": "可请求为项目文件夹在侧边栏创建会话入口",
- "workspaceDetail": "它发起请求时,由你亲手选择文件夹,或在确认卡上看到完整路径后再决定;它正在处理你发起的调用时,当前会话工作目录内的子文件夹可直接使用,不再单独确认。文件夹已有会话时直接复用,不重复创建。创建的只是空会话,不会自动开始任何任务。",
- "sessionContext": "可获知当前会话正在使用的项目文件夹位置",
- "sessionContextDetail": "只在它为当前会话干活时告知位置信息(会话编号与项目文件夹路径),不包含文件内容,也不因此获得文件访问权。",
+ "pickDetail": "它发起请求时,Cindy 会弹出系统的选择文件夹窗口;选哪个、给不给,都由你亲手决定,取消则它什么都拿不到。",
++ "workspace": "可请求为项目文件夹在侧边栏创建对话入口",
++ "workspaceDetail": "它发起请求时,由你亲手选择文件夹,或在确认卡上看到完整路径后再决定;它正在处理你发起的调用时,当前对话工作目录内的子文件夹可直接使用,不再单独确认。文件夹已有对话时直接复用,不重复创建。创建的只是空对话,不会自动开始任何任务。",
+ "sessionContext": "可获知当前对话正在使用的项目文件夹位置",
+ "sessionContextDetail": "只在它为当前对话干活时告知位置信息(对话编号与项目文件夹路径),不包含文件内容,也不因此获得文件访问权。",
"preview": "可在右侧栏浏览器中打开以下网站的预览页面",
- "previewDetail": "只能打开下方列出的网站;每次打开都会提示是哪个插件打开的。",
+ "previewDetail": "只能打开下方列出的网站;每次打开都会提示是哪个插件打开的。",
"nodeChildSpawn": "Node 程序可请宿主再启动包内申报过的子进程",
- "nodeChildSpawnDetail": "只能启动它自己包里申报过的 JS 文件(与主程序同样的本机权限),不能执行任意命令;插件停用或退出时子进程一并关闭。",
+ "nodeChildSpawnDetail": "只能启动它自己包里申报过的 JS 文件(与主程序同样的本机权限),不能执行任意命令;插件停用或退出时子进程一并关闭。",
"skill": "为 AI 助手添加技能「{{name}}」",
- "skillDetail": "技能是一份指令文件,AI 会把它当作自己的指令加载执行,拥有你的全部权限,对 Claude Code 与 Codex、所有项目都生效——不受本插件沙箱约束。插件启用期间持续可用,停用或卸载即移除;仅对某个文件夹关闭本插件不会隐藏它。此处无法预览技能全文——请只安装你信任的插件。"
+ "skillDetail": "技能是一份指令文件,AI 会把它当作自己的指令加载执行,拥有你的全部权限,对 Claude Code 与 Codex、所有项目都生效——不受本插件沙箱约束。插件启用期间持续可用,停用或卸载即移除;仅对某个文件夹关闭本插件不会隐藏它。此处无法预览技能全文——请只安装你信任的插件。"
},
"connections": {
"confirmTitle": "添加连接地址",
@@@ -2521,7 -2527,8 +2527,8 @@@
"slotNetwork": "网络访问",
"slotNotify": "系统提示",
"slotFs": "写文件",
- "slotSkill": "Agent 技能"
+ "slotSkill": "Agent 技能",
- "slotWorkspace": "工作区会话"
++ "slotWorkspace": "工作区对话"
},
"commandPaletteTag": "插件指令",
"updateConfirm": {
@@@ -2533,6 -2540,10 +2540,10 @@@
"pick": {
"dialogTitle": "选择文件夹",
"dialogMessage": "插件「{{name}}」请求你选择一个文件夹"
+ },
+ "workspace": {
+ "dialogTitle": "选择项目文件夹",
- "dialogMessage": "插件「{{name}}」请求你选择一个项目文件夹,用于在侧边栏创建会话"
++ "dialogMessage": "插件「{{name}}」请求你选择一个项目文件夹,用于在侧边栏创建对话"
}
},
"mcp": {
@@@ -3226,12 -3237,20 +3237,20 @@@
"copyLinkFailed": "复制链接失败",
"crash": {
"crashedTitle": "页面崩溃",
- "crashedDesc": "网页进程意外终止,请重新加载",
+ "crashedDesc": "网页进程意外终止,请重新加载",
"unresponsiveTitle": "页面无响应",
- "unresponsiveDesc": "页面长时间未响应,可重新加载或稍候等待",
+ "unresponsiveDesc": "页面长时间未响应,可重新加载或稍候等待",
"navigationLoopTitle": "已停止重复跳转",
- "navigationLoopDesc": "页面在短时间内反复跳转,已暂停导航。请重新加载页面后重试",
+ "navigationLoopDesc": "页面在短时间内反复跳转,已暂停导航。请重新加载页面后重试",
+ "resourceKilledTitle": "页面占用内存过高",
- "resourceKilledDesc": "该页面占用内存过高,已被终止以保护应用运行。可重新加载",
++ "resourceKilledDesc": "该页面占用内存过高,已被终止以保护应用运行。可重新加载",
+ "forceKill": "强制终止",
"reload": "重新加载"
+ },
+ "resourceAlert": {
+ "cpuHint": "此页面占用大量系统资源",
+ "terminate": "终止页面",
- "dismiss": "忽略"
++ "dismiss": "关闭"
}
},
"terminal": {
@@@ -6155,13 -6174,14 +6174,14 @@@
"confirm": {
"title": "「{{name}}」请求使用你的文件",
"count": "{{count}} 个文件",
- "descriptionAttachments": "以下文件在当前会话的工作目录之外。允许后,这些文件会交给该插件处理(它只拿到内容指纹,拿不到路径)。",
- "descriptionDir": "以下目录/文件在当前会话的工作目录之外。允许后,其中的文件会交给该插件上传(它只拿到一次性票据,拿不到路径)。",
- "descriptionSaveDir": "以下目录在当前会话的工作目录之外。允许后,该插件可以把下载的文件存入其中(不会覆盖已有文件)。",
- "descriptionFsWrite": "该插件请求在当前会话的工作目录写入以下文件。允许后,本会话内它写同一目录不再询问。",
- "descriptionWorkspace": "该文件夹在当前会话的工作目录之外。允许后,Cindy 会以它为工作目录在侧边栏创建一个空会话(已有会话时直接复用),不会读取其中的文件。",
+ "descriptionAttachments": "以下文件在当前对话的工作目录之外。允许后,这些文件会交给该插件处理(它只拿到内容指纹,拿不到路径)。",
+ "descriptionDir": "以下目录/文件在当前对话的工作目录之外。允许后,其中的文件会交给该插件上传(它只拿到一次性票据,拿不到路径)。",
+ "descriptionSaveDir": "以下目录在当前对话的工作目录之外。允许后,该插件可以把下载的文件存入其中(不会覆盖已有文件)。",
+ "descriptionFsWrite": "该插件请求在当前对话的工作目录写入以下文件。允许后,本对话内它写同一目录不再询问。",
++ "descriptionWorkspace": "该文件夹在当前对话的工作目录之外。允许后,Cindy 会以它为工作目录在侧边栏创建一个空对话(已有对话时直接复用),不会读取其中的文件。",
"dirMeta": "{{count}} 个文件 · {{size}}",
"directory": "目录",
- "allowDirs": "同时允许这些文件所在目录(本会话内同目录媒体文件不再询问)",
+ "allowDirs": "同时允许这些文件所在目录(本对话内同目录媒体文件不再询问)",
"allow": "允许",
"deny": "拒绝"
}
diff --cc scripts/__tests__/glossary-rules.test.mjs
index 0e4a1ebf50,0000000000..4be2b88a95
mode 100644,000000..100644
--- a/scripts/__tests__/glossary-rules.test.mjs
+++ b/scripts/__tests__/glossary-rules.test.mjs
@@@ -1,542 -1,0 +1,570 @@@
+/**
+ * 术语表 guard 规则函数的单测。
+ *
+ * 这里每一条断言都对应一个真实踩过的坑或一条有数据依据的裁决,不是为覆盖率凑数:
+ * 误报会让门禁被绕过或被关掉,漏报会让门禁形同虚设,两边都要钉住。
+ */
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+
+import {
+ ELLIPSIS_LOCALES,
+ HALFWIDTH_PUNCT_LOCALES,
+ FULL_WIDTH_PUNCT,
+ findCaseMismatch,
+ findHalfWidthPunct,
+ hasAsciiEllipsis,
+ makeExemptChecker,
+ occursIn,
+ stripNonProse,
+ normalizeForPunctuation,
+} from '../shared/glossary-rules.mjs';
+import { validateAgainstSchema } from '../shared/json-schema-lite.mjs';
+import { renderGlossaryDoc } from '../shared/glossary-doc.mjs';
+
+const ROOT = path.resolve(fileURLToPath(new URL('../..', import.meta.url)));
+
+// ---------------------------------------------------------------------------
+// occursIn:词边界
+// ---------------------------------------------------------------------------
+
+test('occursIn: 连字符复合词不算命中(ssh-agent ≠ 产品 Agent)', () => {
+ // 这是引入 guard 时最大的一批假阳性来源:SSH 密钥代理与产品 Agent 同形但无关。
+ assert.equal(occursIn('密钥已加载到 ssh-agent', 'agent'), false);
+ assert.equal(occursIn('检查 user-agent 头', 'agent'), false);
+ assert.equal(occursIn('字段 agent_id 缺失', 'agent'), false);
+ // 独立成词时必须命中,否则门禁形同虚设。
+ assert.equal(occursIn('展开 agent 设置', 'agent'), true);
+});
+
+test('occursIn: 允许复数但不误伤更长的标识符', () => {
+ assert.equal(occursIn('更多 Plugin 操作', 'Plugin'), true);
+ assert.equal(occursIn('已安装 Plugins', 'Plugin'), true);
+ assert.equal(occursIn('PluginRegistry 初始化', 'Plugin'), false);
+});
+
+test('occursIn: 中文术语按子串匹配(无词边界概念)', () => {
+ assert.equal(occursIn('这是代理设置', '代理'), true);
+ assert.equal(occursIn('这是插件设置', '代理'), false);
+});
+
+test('occursIn: 大小写敏感 —— forbidden 区分 Plugin 与 plugin', () => {
+ assert.equal(occursIn('更多 plugin 操作', 'Plugin'), false);
+});
+
+// ---------------------------------------------------------------------------
+// stripNonProse:剥离非文案片段
+// ---------------------------------------------------------------------------
+
+test('stripNonProse: 剥离 i18next 插值,避免变量名与术语同形误报', () => {
+ // {{project}} 是变量名,不是展示给用户的「Project」字样。
+ assert.equal(occursIn(stripNonProse('在 {{project}} 中新建'), 'project'), false);
+ assert.equal(occursIn(stripNonProse('该 Project 下的会话'), 'Project'), true);
+});
+
+test('stripNonProse: 剥离 URL、邮箱与文件名', () => {
+ assert.equal(occursIn(stripNonProse('打开 https://x.com/agent/list'), 'agent'), false);
+ assert.equal(occursIn(stripNonProse('读取 project.json 失败'), 'project'), false);
+ assert.equal(occursIn(stripNonProse('联系 [email protected]'), 'agent'), false);
+});
+
+test('stripNonProse: 剥离 Trans 占位与 $t 引用', () => {
+ assert.equal(stripNonProse('前<0>中</0>后').includes('<0>'), false);
+ assert.equal(stripNonProse('$t(common.agent) 之后').includes('$t('), false);
+});
+
+// ---------------------------------------------------------------------------
+// findCaseMismatch:大小写形态
+// ---------------------------------------------------------------------------
+
+test('findCaseMismatch: 命中错误形态时返回实际拼写,正确时返回 null', () => {
+ assert.equal(findCaseMismatch('归档 worker', 'Worker'), 'worker');
+ assert.equal(findCaseMismatch('归档 Worker', 'Worker'), null);
+ assert.equal(findCaseMismatch('归档 WORKER', 'Worker'), 'WORKER');
+});
+
+test('findCaseMismatch: 复数形态归一后再比对,不误报 Workers', () => {
+ assert.equal(findCaseMismatch('所有 Workers 已停止', 'Worker'), null);
+ assert.equal(findCaseMismatch('所有 workers 已停止', 'Worker'), 'worker');
+});
+
+test('findCaseMismatch: 连字符复合词同样豁免', () => {
+ assert.equal(findCaseMismatch('service-worker 已注册', 'Worker'), null);
+});
+
+test('findCaseMismatch: 扫描全部匹配,不因首个正确就漏掉后面的错误形态', () => {
+ // #389 两位 reviewer 同标 P1:非全局 match 只看第一个匹配,首个正确即返回 null,
+ // 后面的错误形态永远进不了报告,能一路漏到 UI。
+ assert.equal(findCaseMismatch('创建 Worker 后,该 worker 会自动启动', 'Worker'), 'worker');
+ assert.equal(findCaseMismatch('Agent 与另一个 agent 协作', 'Agent'), 'agent');
+ // 全部正确时仍应返回 null,不能因为改成全局匹配就误报。
+ assert.equal(findCaseMismatch('创建 Worker 后,该 Worker 会自动启动', 'Worker'), null);
+});
+
+// ---------------------------------------------------------------------------
+// makeExemptChecker:豁免
+// ---------------------------------------------------------------------------
+
+test('makeExemptChecker: 完整路径精确匹配', () => {
+ const isExempt = makeExemptChecker(['desktop:settings.a.b']);
+ assert.equal(isExempt('desktop:settings.a.b'), true);
+ assert.equal(isExempt('desktop:settings.a.c'), false);
+});
+
+test('makeExemptChecker: 以点结尾的子树前缀豁免整段', () => {
+ const isExempt = makeExemptChecker(['desktop:settings.remote.']);
+ assert.equal(isExempt('desktop:settings.remote.keys.inAgent'), true);
+ assert.equal(isExempt('desktop:settings.remoteControl.hook'), false, '前缀必须含点,不能误伤 remoteControl');
+});
+
+test('makeExemptChecker: 不支持按末段 key 名匹配', () => {
+ // 按末段匹配会让任意同名嵌套 key 被静默放过,是 brand guard 明确记录过的教训。
+ const isExempt = makeExemptChecker(['title']);
+ assert.equal(isExempt('desktop:settings.a.title'), false);
+});
+
+test('makeExemptChecker: 空/缺省列表不豁免任何 key', () => {
+ assert.equal(makeExemptChecker(undefined)('desktop:any.key'), false);
+ assert.equal(makeExemptChecker([])('desktop:any.key'), false);
+});
+
+// ---------------------------------------------------------------------------
+// 标点规则
+// ---------------------------------------------------------------------------
+
+test('findHalfWidthPunct: 只在汉字后触发', () => {
+ assert.equal(findHalfWidthPunct('保存失败:原因'), ':');
+ assert.equal(findHalfWidthPunct('授权失败,请重试'), ',');
+ assert.equal(findHalfWidthPunct('保存失败:原因'), null);
+ // 英文/数字后的半角标点是正常排版,不能报。
+ assert.equal(findHalfWidthPunct('Error: not found'), null);
+ assert.equal(findHalfWidthPunct('共 1,000 项'), null);
+});
+
+test('findHalfWidthPunct: 覆盖分号与问号叹号', () => {
+ // 首轮只查了逗号冒号,清理时才发现分号 49 处、问号叹号 25 处是同类问题。
+ assert.equal(findHalfWidthPunct('加载失败;请重试'), ';');
+ assert.equal(findHalfWidthPunct('确定要删除吗?'), '?');
+ assert.equal(findHalfWidthPunct('操作成功!'), '!');
+ assert.equal(findHalfWidthPunct('加载失败;请重试'), null);
+ assert.equal(findHalfWidthPunct('确定要删除吗?'), null);
+});
+
+test('FULL_WIDTH_PUNCT: 覆盖全部受检半角标点', () => {
+ // 映射表缺项会让 hint 退化成「应使用全角「;」」这种自相矛盾的提示。
+ for (const mark of [',', ':', ';', '!', '?']) {
+ assert.ok(FULL_WIDTH_PUNCT[mark], `缺少 ${mark} 的全角映射`);
+ assert.equal(findHalfWidthPunct(`中文${mark}`), mark);
+ assert.equal(findHalfWidthPunct(`中文${FULL_WIDTH_PUNCT[mark]}`), null);
+ }
+});
+
+test('标点规则的 locale 适用范围有数据依据', () => {
+ // ja 实测半角冒号 124:78 才是主流(日文 UI 惯例),套用中文全角规则会制造大批假阳性。
+ assert.equal(HALFWIDTH_PUNCT_LOCALES.has('zh-CN'), true);
+ assert.equal(HALFWIDTH_PUNCT_LOCALES.has('ja'), false);
+ assert.equal(HALFWIDTH_PUNCT_LOCALES.has('ko'), false);
+ // 省略号三语一致以「…」为主流。
+ for (const locale of ['zh-CN', 'ja', 'ko']) {
+ assert.equal(ELLIPSIS_LOCALES.has(locale), true, `${locale} 应纳入省略号规则`);
+ }
+});
+
+test('hasAsciiEllipsis: 识别三点省略号', () => {
+ assert.equal(hasAsciiEllipsis('加载中...'), true);
+ assert.equal(hasAsciiEllipsis('加载中…'), false);
+});
+
+// ---------------------------------------------------------------------------
+// 术语表数据自身的完整性
+// ---------------------------------------------------------------------------
+
+const glossary = JSON.parse(fs.readFileSync(path.join(ROOT, 'i18n', 'glossary.json'), 'utf8'));
+
+test('glossary.json: id 唯一且格式合法', () => {
+ const ids = glossary.terms.map((t) => t.id);
+ assert.equal(new Set(ids).size, ids.length, '术语 id 必须唯一——baseline 用它做锚点');
+ for (const id of ids) {
+ assert.match(id, /^[a-z0-9-]+$/, `id "${id}" 必须是 kebab-case`);
+ }
+});
+
+test('glossary.json: 每条术语都有裁决理由', () => {
+ for (const term of glossary.terms) {
+ assert.ok(term.note?.trim(), `术语 ${term.id} 缺 note——没有理由的裁决会被后人反复推翻`);
+ }
+});
+
+test('glossary.json: decided 术语必须给出所有非源语言的译法', () => {
+ const targets = glossary.locales.filter((l) => l !== glossary.sourceLocale);
+ for (const term of glossary.terms.filter((t) => t.status === 'decided')) {
+ for (const locale of targets) {
+ assert.ok(
+ term.translations?.[locale]?.trim(),
+ `已裁决术语 ${term.id} 缺 ${locale} 译法;拿不准应留在 status=proposed`,
+ );
+ }
+ }
+});
+
+test('glossary.json: forbidden 不能与自己的标准译法冲突', () => {
+ for (const term of glossary.terms) {
+ for (const [locale, words] of Object.entries(term.forbidden ?? {})) {
+ const standard = term.translations?.[locale];
+ if (!standard) continue;
+ const texts = words.map((w) => (typeof w === 'string' ? w : w.text));
+ assert.ok(
+ !texts.includes(standard),
+ `术语 ${term.id} 在 ${locale} 把标准译法「${standard}」同时列为禁用,规则自相矛盾`,
+ );
+ }
+ }
+});
+
+test('glossary.json: 声明的译法必须是现状主流,否则要写明为何有意偏离', () => {
+ // 引入术语表时踩过的坑:ja/ko 的译法凭抽样几个 key 就定,结果 5 条是少数派,
+ // 其中 quota 的 ko「쿼터」全仓零出现——纯属凭空造词。更糟的是 automation 的 ja
+ // 把少数派同时写进 translations 与 forbidden,guard 于是输出「X 是禁用译法,应为 X」。
+ // 这条断言把「你凭什么违反数据」显式化:占比不足 35% 就必须给理由。
+ const MIN_RATIO = 0.35;
+ const load = (locale) => {
+ const out = new Map();
+ const flatten = (obj, prefix) => {
+ for (const [k, v] of Object.entries(obj)) {
+ const kp = prefix ? `${prefix}.${k}` : k;
+ if (v && typeof v === 'object' && !Array.isArray(v)) flatten(v, kp);
+ else if (typeof v === 'string') out.set(kp, v);
+ }
+ };
+ flatten(
+ JSON.parse(fs.readFileSync(path.join(ROOT, `apps/desktop/src/renderer/i18n/locales/${locale}/common.json`), 'utf8')),
+ '',
+ );
+ return out;
+ };
+
+ const corpus = Object.fromEntries(glossary.locales.map((l) => [l, load(l)]));
+ const problems = [];
+
+ for (const term of glossary.terms) {
+ if (term.status !== 'decided') continue;
+ const escaped = term.en.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const re = new RegExp(`(?<![A-Za-z0-9_-])${escaped}s?(?![A-Za-z0-9_-])`, 'i');
+ const keys = [...corpus[glossary.sourceLocale]].filter(([, v]) => re.test(v)).map(([k]) => k);
+ if (keys.length < 8) continue; // 样本太小,占比没有统计意义
+
+ for (const locale of glossary.locales) {
+ if (locale === glossary.sourceLocale) continue;
+ const declared = term.translations?.[locale];
+ if (!declared) continue;
+ // alsoAllowed 是同一裁决下的合法变体(Running 作谓语时用「正在运行」),
+ // 计算主流度时必须算进来,否则分场合译法越多、越会被误判成"声明不是主流"。
+ const accepted = [declared, ...(term.alsoAllowed?.[locale] ?? []).map((v) => v.text)];
+ const hit = keys.filter((k) => {
+ const value = corpus[locale].get(k);
+ return value && accepted.some((a) => value.includes(a));
+ }).length;
+ const ratio = hit / keys.length;
+ if (ratio >= MIN_RATIO) continue;
+ if (term.minorityByDesign?.[locale]?.trim()) continue;
+ problems.push(
+ `${term.id}/${locale}: 声明「${declared}」只覆盖 ${hit}/${keys.length} ` +
+ `(${Math.round(ratio * 100)}%),既非主流又没写 minorityByDesign 理由`,
+ );
+ }
+ }
+
+ assert.deepEqual(problems, [], `\n${problems.join('\n')}`);
+});
+
+test('glossary.json: 同一 locale 下 forbidden 词不跨术语重复', () => {
+ // 重复会让同一处违规被两个术语各报一次,baseline 也会存两条指纹。
+ // 一个词只归属一个术语,其余条目在 note 里交叉引用(如「代理」统一登记在 proxy 下)。
+ // 例外:带 whenEn 的条件禁用可以同词多登记——它们按英文源区分,替换目标唯一。
+ // 「代理」正是如此:Agent / Subagent / Proxy 三个来源各登记一条,统一挂在某一条下
+ // 反而会让自动替换无法确定该换成哪个词(2026-07 一次批量重放就因此产出「子 Proxy 模型」)。
+ const owner = new Map();
+ for (const term of glossary.terms) {
+ for (const [locale, words] of Object.entries(term.forbidden ?? {})) {
+ for (const entry of words) {
+ const word = typeof entry === 'string' ? entry : entry.text;
+ const scope = typeof entry === 'string' ? '' : `@${entry.whenEn}`;
+ const slot = `${locale}\t${word}${scope}`;
+ const prev = owner.get(slot);
+ assert.equal(
+ prev,
+ undefined,
+ `${locale} 的禁用词「${word}」同时登记在 ${prev} 与 ${term.id} 下,会造成重复报告`,
+ );
+ owner.set(slot, term.id);
+ }
+ }
+ }
+});
+
+test('glossary.json: exempt 路径带来源前缀,不是裸 key', () => {
+ for (const term of glossary.terms) {
+ for (const item of term.exempt ?? []) {
+ assert.match(
+ item,
+ /^(desktop|mobile\/[a-zA-Z]+):.+$/,
+ `术语 ${term.id} 的豁免 "${item}" 缺来源前缀(desktop: / mobile/<ns>:)`,
+ );
+ }
+ }
+});
+
+test('glossary.json: locales 与 desktop SUPPORTED_LOCALES 一致', () => {
+ const localeTs = fs.readFileSync(path.join(ROOT, 'apps/desktop/src/shared/locale.ts'), 'utf8');
+ const match = localeTs.match(/SUPPORTED_LOCALES\s*=\s*\[([^\]]*)\]/);
+ assert.ok(match, '无法从 locale.ts 解析 SUPPORTED_LOCALES');
+ const supported = [...match[1].matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]);
+ assert.deepEqual(
+ [...glossary.locales].sort(),
+ [...supported].sort(),
+ '术语表覆盖的语言必须与 SUPPORTED_LOCALES 一致,新增语言时两处一起改',
+ );
+});
+
+// ---------------------------------------------------------------------------
+// 文档同步
+// ---------------------------------------------------------------------------
+
+test('GLOSSARY.md 与 glossary.json 同步', () => {
+ const doc = fs.readFileSync(path.join(ROOT, 'i18n', 'GLOSSARY.md'), 'utf8');
+ assert.equal(
+ doc,
+ renderGlossaryDoc(glossary),
+ 'i18n/GLOSSARY.md 已过期,运行 pnpm i18n:glossary-doc 重新生成',
+ );
+});
+
+// ---------------------------------------------------------------------------
+// baseline 完整性
+// ---------------------------------------------------------------------------
+
+test('glossary-baseline.json: 条目格式合法且无重复', () => {
+ const baseline = JSON.parse(fs.readFileSync(path.join(ROOT, 'i18n', 'glossary-baseline.json'), 'utf8'));
+ const entries = baseline.entries ?? [];
+ assert.equal(new Set(entries).size, entries.length, 'baseline 不应有重复条目');
+ for (const entry of entries) {
+ const parts = entry.split('\t');
+ assert.equal(parts.length, 4, `baseline 条目 "${entry}" 应为 locale\\tkey\\trule\\tdetail 四段`);
+ assert.ok(glossary.locales.includes(parts[0]), `baseline 条目语言 "${parts[0]}" 不在术语表 locales 内`);
+ }
+});
+
+// ---------------------------------------------------------------------------
+// schema 校验器
+//
+// 子集校验器的价值全在「拼错字段能被抓住」和「schema 加了新关键字不会被静默忽略」
+// 这两条上。两条都塌了的话,它比没有更危险——看起来有校验,实际全绿放行。
+// ---------------------------------------------------------------------------
+
+test('validateAgainstSchema: 正本必须符合自己的 schema', () => {
+ const schema = JSON.parse(fs.readFileSync(path.join(ROOT, 'i18n', 'glossary.schema.json'), 'utf8'));
+ assert.deepEqual(validateAgainstSchema(glossary, schema), []);
+});
+
+test('validateAgainstSchema: 拼错的字段名被判为未知字段', () => {
+ const schema = {
+ type: 'object',
+ additionalProperties: false,
+ properties: { forbidden: { type: 'array', items: { type: 'string' } } },
+ };
+ const errors = validateAgainstSchema({ forbiden: ['会话'] }, schema);
+ assert.equal(errors.length, 1);
+ assert.match(errors[0], /forbiden/);
+});
+
+test('validateAgainstSchema: 校验 required / enum / pattern / oneOf', () => {
+ const schema = {
+ type: 'object',
+ required: ['id', 'status'],
+ additionalProperties: false,
+ properties: {
+ id: { type: 'string', pattern: '^[a-z0-9-]+$' },
+ status: { enum: ['decided', 'proposed'] },
+ forbidden: {
+ type: 'array',
+ items: {
+ oneOf: [
+ { type: 'string' },
+ {
+ type: 'object',
+ required: ['text', 'whenEn'],
+ additionalProperties: false,
+ properties: { text: { type: 'string' }, whenEn: { type: 'string' } },
+ },
+ ],
+ },
+ },
+ },
+ };
+ assert.deepEqual(validateAgainstSchema({ id: 'session', status: 'decided' }, schema), []);
+ assert.match(validateAgainstSchema({ id: 'session' }, schema).join(), /缺少必填字段 "status"/);
+ assert.match(validateAgainstSchema({ id: 'Session', status: 'decided' }, schema).join(), /不匹配/);
+ assert.match(validateAgainstSchema({ id: 'a', status: 'decied' }, schema).join(), /取值必须是/);
+ // 条件禁用少写 whenEn 时,两个 oneOf 分支都不匹配
+ assert.match(
+ validateAgainstSchema({ id: 'a', status: 'decided', forbidden: [{ text: '代理' }] }, schema).join(),
+ /oneOf/,
+ );
+});
+
+test('validateAgainstSchema: schema 用了未实现的关键字必须报错而非忽略', () => {
+ assert.throws(
+ () => validateAgainstSchema({}, { type: 'object', anyOf: [{ type: 'object' }] }),
+ /未实现的关键字 "anyOf"/,
+ );
+});
+
+// ---------------------------------------------------------------------------
+// 标点检查的插值边界
+//
+// stripNonProse 把 {{插值}} 换成空格,于是插值后面的半角标点前是空格而非汉字,
+// 整类违规被静默放过(reportCache 的 `{{total}},上限` 就是这样漏掉的)。
+// 标点检查必须走 normalizeForPunctuation。
+// ---------------------------------------------------------------------------
+
+test('normalizeForPunctuation: 插值后的半角标点能被检出', () => {
+ const raw = '已缓存 {{total}},上限 {{limit}};清掉后会重新拉取。';
+ assert.equal(findHalfWidthPunct(stripNonProse(raw)), null, '这正是原先漏检的成因');
+ assert.equal(findHalfWidthPunct(normalizeForPunctuation(raw)), ',');
+});
+
+test('normalizeForPunctuation: 两个插值之间的标点是格式分隔符,不判违规', () => {
+ // 该用半角还是全角取决于运行期填进去的值,静态扫描判不了,整类排除
+ for (const raw of ['二维码将在 {{minutes}}:{{seconds}} 后过期', '{{label}}: {{path}}']) {
+ assert.equal(findHalfWidthPunct(normalizeForPunctuation(raw)), null, raw);
+ }
+});
+
+test('normalizeForPunctuation: 文件名与 URL 里的冒号不算标点违规', () => {
+ // 这几类替换成空格而非汉字替身,否则 `config.json:` 的路径冒号会被误判
+ assert.equal(findHalfWidthPunct(normalizeForPunctuation('请检查 config.json:12 行')), null);
+ assert.equal(findHalfWidthPunct(normalizeForPunctuation('详见 https://a.example/b:8080 页面')), null);
+});
+
+test('glossary.schema.json: terms 不能为空——空表会让整套门禁静默消失', () => {
+ const schema = JSON.parse(fs.readFileSync(path.join(ROOT, 'i18n', 'glossary.schema.json'), 'utf8'));
+ const errors = validateAgainstSchema({ ...glossary, terms: [] }, schema);
+ assert.ok(
+ errors.some((e) => /terms.*至少需要 1 项|至少需要 1 项/.test(e)),
+ `空 terms 必须被拒绝,实际错误:${JSON.stringify(errors)}`,
+ );
+});
+
+test('stripNonProse: URL 后紧跟中文时,不能把后面的正文一起吞掉', () => {
+ // \S+ 收尾会连全角标点带整句正文一起吃掉,URL 之后的禁用词就永远扫不到
+ const stripped = stripNonProse('请访问 https://x.test,返回对话列表继续操作');
+ assert.ok(stripped.includes('返回对话列表继续操作'), `URL 之后的正文被吞了:${JSON.stringify(stripped)}`);
+ assert.ok(!stripped.includes('x.test'));
+});
+
+test('glossary.json: 语言键必须都在 locales 里', () => {
+ // 拼错的语言键(forbidden.zh_CN)不会被 schema 拦下——additionalProperties 只约束值的
+ // 形状,不能拿 locales 的内容去约束键名——而扫描只按 locales 迭代,规则就静默失效了
+ const locales = new Set(glossary.locales);
+ for (const term of glossary.terms) {
+ for (const field of ['translations', 'forbidden', 'alsoAllowed', 'minorityByDesign']) {
+ for (const locale of Object.keys(term[field] ?? {})) {
+ assert.ok(locales.has(locale), `术语 ${term.id} 的 ${field}.${locale} 语言键不在 locales 里`);
+ }
+ }
+ }
+});
+
+test('stripNonProse: 任意扩展名的文件名都要剥离,但不能吃掉数字', () => {
+ // 白名单式的扩展名列表补不全,plugin.py / worker.go 会被误判成正文里的产品术语
+ for (const [text, gone] of [
+ ['请编辑 plugin.py 后重试', 'plugin'],
+ ['运行 worker.go', 'worker'],
+ ['打开 Agent.java', 'Agent'],
+ ]) {
+ assert.ok(!stripNonProse(text).includes(gone), text);
+ }
+ // 版本号 / 小数不是文件名。若被当成文件名吃掉,「已用 1.5 GB」会变成「已用 」,
+ // 后续的术语与标点检查都在残缺文本上跑
+ assert.ok(stripNonProse('已用 1.5 GB').includes('1.5'));
+ assert.ok(stripNonProse('版本 v1.0 可用').includes('v1.0'));
+ // 若 1.5 被当成文件名吃掉,「已用 1.5 GB,缓存超限,请清理」里的「限,」就会连带丢失
+ assert.equal(findHalfWidthPunct(normalizeForPunctuation('已用 1.5 GB,缓存超限,请清理')), ',');
+});
+
+test('findHalfWidthPunct: 右括号等闭合符号也算中文正文的左边界', () => {
+ assert.equal(findHalfWidthPunct('可润色改写正文(直接替换),或用卡片替换'), ',');
+ assert.equal(findHalfWidthPunct('卸载「{{name}}」?'.replace('{{name}}', 'x')), '?');
+ // 右括号做边界后,英文括注也会命中。这不是问题:标点规则只对 zh-CN 生效
+ // (HALFWIDTH_PUNCT_LOCALES),而 zh-CN 文案里的英文括注同样该跟中文标点
+ assert.equal(findHalfWidthPunct('see (note), then continue'), ',');
+});
+
+// ---------------------------------------------------------------------------
+// 术语表的定位:参考,不是替换表
+// ---------------------------------------------------------------------------
+
+test('禁用译法的提示不给替换目标,只给英文源', () => {
+ // 「应为 X」读起来就是一条替换指令,会诱导机械替换——#389 由此产生约 35 处误译。
+ // 禁用译法的正确目标取决于英文源(同一个「额度」在 Balance / Quota / Credits 下答案
+ // 不同),工具给不出,也不该假装给得出。这条断言防止提示被改回「应为」句式。
+ const src = fs.readFileSync(path.join(ROOT, 'scripts', 'check-i18n-glossary.mjs'), 'utf8');
+ const forbiddenBlock = src
+ .slice(src.indexOf("rule: 'forbidden-term'"), src.indexOf("rule: 'term-case'"))
+ // 剔除注释行:注释里会引用旧的「应为」句式来解释为什么不再用它
+ .split('\n')
+ .filter((line) => !line.trim().startsWith('//'))
+ .join('\n');
+ assert.ok(forbiddenBlock.includes('hint:'), '未定位到 forbidden-term 的提示构造');
+ assert.ok(
+ !forbiddenBlock.includes('应为'),
+ 'forbidden-term 的提示不应给出替换目标——术语表是参考不是替换表',
+ );
+ assert.ok(forbiddenBlock.includes('英文源'), 'forbidden-term 的提示应附上英文源供判断语境');
+});
+
+test('GLOSSARY.md 必须声明「参考,不是替换表」', () => {
+ const doc = fs.readFileSync(path.join(ROOT, 'i18n', 'GLOSSARY.md'), 'utf8');
+ assert.ok(doc.includes('不是替换表'), 'GLOSSARY.md 缺少定位声明');
+ assert.ok(doc.includes('禁止拿本表做脚本批量替换'), 'GLOSSARY.md 缺少批量替换禁令');
+});
+
+test('validateAgainstSchema: schema 的 pattern 写坏时报可读错误而不是抛栈', () => {
+ // 直接 new RegExp 会把异常抛出校验流程,调用方拿不到带 path 的错误、
+ // check-i18n-glossary 会崩栈而不是走 fail()
+ const schema = { type: 'object', properties: { id: { type: 'string', pattern: '[' } } };
+ const errors = validateAgainstSchema({ id: 'x' }, schema);
+ assert.equal(errors.length, 1);
+ assert.match(errors[0], /\$\.id: schema 的 pattern 不是合法正则/);
+});
++
++test('validateAgainstSchema: 关键字的值形状写错必须报错而不是被曲解', () => {
++ // type: ["string","null"] 是合法 draft-07,但本模块只实现字符串形态——
++ // 拿数组去比对会永远不等,那条 type 约束就在「看似生效」的外表下彻底失效
++ assert.throws(
++ () => validateAgainstSchema({}, { type: 'object', properties: { a: { type: ['string', 'null'] } } }),
++ /"type" 应是 string,实际是 array/,
++ );
++ // properties 写成数组
++ assert.throws(
++ () => validateAgainstSchema({}, { type: 'object', properties: [] }),
++ /"properties" 应是 object,实际是 array/,
++ );
++ // required 写成字符串
++ assert.throws(
++ () => validateAgainstSchema({}, { type: 'object', required: 'id' }),
++ /"required" 应是 array,实际是 string/,
++ );
++ // additionalProperties 允许 boolean 与 schema 对象两种,其余报错
++ assert.doesNotThrow(() => validateAgainstSchema({}, { type: 'object', additionalProperties: false }));
++ assert.doesNotThrow(() =>
++ validateAgainstSchema({}, { type: 'object', additionalProperties: { type: 'string' } }),
++ );
++ assert.throws(
++ () => validateAgainstSchema({}, { type: 'object', additionalProperties: 'yes' }),
++ /additionalProperties 只支持 boolean 或 schema 对象/,
++ );
++});
diff --cc scripts/shared/json-schema-lite.mjs
index 799a0f9805,0000000000..b103651ee4
mode 100644,000000..100644
--- a/scripts/shared/json-schema-lite.mjs
+++ b/scripts/shared/json-schema-lite.mjs
@@@ -1,172 -1,0 +1,220 @@@
+/**
+ * JSON Schema draft-07 的**受限子集**校验器,零依赖。
+ *
+ * 为什么不用 ajv:本仓 scripts/ 一贯只用 node 内置模块(唯一例外是 ws)。ajv 目前能在
+ * 根 node_modules 里解析到,但它只是别的包提升上来的传递依赖——把 CI 阻断门禁架在
+ * 「碰巧被提升」的包上,lockfile 一变就会静默失效。
+ *
+ * 安全前提:**遇到不认识的关键字立即抛错**(compile 阶段),而不是忽略。
+ * 子集校验器最危险的失败模式是「schema 写了约束、校验器看不懂、于是默默放行」——
+ * 那正是本模块要解决的问题本身。宁可让加新关键字的人被迫来这里补实现。
+ */
+
+/**
+ * 本模块实现的关键字。不在此列的一律报错,详见文件头。
+ *
+ * 其中 $schema / $id / title / description 是纯注解,不产生约束;definitions 只被
+ * $ref 解引用时用到。它们列在这里是为了让 assertSupported 放行,校验逻辑本身
+ * 不需要看它们。
+ */
+const SUPPORTED = new Set([
+ '$schema',
+ '$id',
+ '$ref',
+ 'title',
+ 'description',
+ 'type',
+ 'required',
+ 'properties',
+ 'additionalProperties',
+ 'items',
+ 'enum',
+ 'pattern',
+ 'minItems',
+ 'minLength',
+ 'oneOf',
+ 'definitions',
+]);
+
- /** 递归检查 schema 自身只用了已实现的关键字。 */
++/**
++ * 每个关键字的值必须是什么形状。
++ *
++ * 只查「关键字名认不认得」是不够的:形状写错时,校验器会以自己那套(而非 JSON Schema 的)
++ * 方式去解释它,约束就变成了别的意思——这恰恰违背本模块「不静默忽略」的安全前提。
++ * 典型的是 `type: ["string", "null"]`(draft-07 合法),本实现只支持字符串形态,
++ * 拿数组去比对会永远不等,于是那条 type 约束在「看似生效」的外表下彻底失效。
++ */
++const KEYWORD_SHAPE = {
++ type: 'string',
++ pattern: 'string',
++ $ref: 'string',
++ $schema: 'string',
++ $id: 'string',
++ title: 'string',
++ description: 'string',
++ minItems: 'number',
++ minLength: 'number',
++ required: 'array',
++ enum: 'array',
++ oneOf: 'array',
++ properties: 'object',
++ definitions: 'object',
++ items: 'object',
++ // additionalProperties 可以是 boolean 或 schema 对象,单独判
++};
++
++function shapeOf(value) {
++ if (Array.isArray(value)) return 'array';
++ if (value === null) return 'null';
++ return typeof value;
++}
++
++/** 递归检查 schema 自身只用了已实现的关键字,且每个关键字的值形状也在支持范围内。 */
+function assertSupported(node, path = '#') {
+ if (node === true || node === false) return;
+ if (typeof node !== 'object' || node === null) {
+ throw new Error(`schema ${path} 不是对象`);
+ }
- for (const key of Object.keys(node)) {
++ for (const [key, value] of Object.entries(node)) {
+ if (!SUPPORTED.has(key)) {
+ throw new Error(
+ `schema ${path} 使用了未实现的关键字 "${key}"——请在 scripts/shared/json-schema-lite.mjs 里补上实现,` +
+ '不要让它被静默忽略',
+ );
+ }
++ if (key === 'additionalProperties') {
++ if (typeof value !== 'boolean' && shapeOf(value) !== 'object') {
++ throw new Error(
++ `schema ${path}/additionalProperties 只支持 boolean 或 schema 对象,实际是 ${shapeOf(value)}`,
++ );
++ }
++ continue;
++ }
++ const expected = KEYWORD_SHAPE[key];
++ if (expected && shapeOf(value) !== expected) {
++ throw new Error(
++ `schema ${path} 的 "${key}" 应是 ${expected},实际是 ${shapeOf(value)}——` +
++ '本模块只实现了 JSON Schema 的一个子集,形状不符时约束会被错误解释而非报错',
++ );
++ }
+ }
+ for (const [key, child] of Object.entries(node.properties ?? {})) {
+ assertSupported(child, `${path}/properties/${key}`);
+ }
+ for (const [key, child] of Object.entries(node.definitions ?? {})) {
+ assertSupported(child, `${path}/definitions/${key}`);
+ }
+ if (typeof node.additionalProperties === 'object') {
+ assertSupported(node.additionalProperties, `${path}/additionalProperties`);
+ }
+ if (node.items) assertSupported(node.items, `${path}/items`);
+ for (const [i, child] of (node.oneOf ?? []).entries()) {
+ assertSupported(child, `${path}/oneOf/${i}`);
+ }
+}
+
+function typeOf(value) {
+ if (Array.isArray(value)) return 'array';
+ if (value === null) return 'null';
+ if (Number.isInteger(value)) return 'integer';
+ return typeof value;
+}
+
+function matchesType(value, expected) {
+ if (expected === 'integer') return Number.isInteger(value);
+ if (expected === 'number') return typeof value === 'number';
+ return typeOf(value) === expected || (expected === 'number' && typeOf(value) === 'integer');
+}
+
+/**
+ * 校验 value 是否符合 schema,返回错误信息数组(空数组=通过)。
+ * root 用于解析 `$ref`,只支持 `#/definitions/X` 这一种形态——够用,且不引入
+ * 远程引用这类需要网络的能力。
+ */
+function validateNode(value, schema, root, path, errors) {
+ if (schema.$ref) {
+ const m = /^#\/definitions\/([^/]+)$/.exec(schema.$ref);
+ if (!m) throw new Error(`只支持 #/definitions/X 形式的 $ref,收到 ${schema.$ref}`);
+ const target = root.definitions?.[m[1]];
+ if (!target) throw new Error(`$ref 指向不存在的定义:${schema.$ref}`);
+ validateNode(value, target, root, path, errors);
+ return;
+ }
+
+ if (schema.type && !matchesType(value, schema.type)) {
+ errors.push(`${path}: 期望 ${schema.type},实际 ${typeOf(value)}`);
+ return;
+ }
+
+ if (schema.enum && !schema.enum.includes(value)) {
+ errors.push(`${path}: 取值必须是 ${schema.enum.join(' / ')} 之一,实际 ${JSON.stringify(value)}`);
+ }
+
+ if (typeof value === 'string') {
+ if (schema.pattern) {
+ // schema 里的 pattern 写坏时,new RegExp 会抛出去、整个校验流程中断,调用方拿不到
+ // 带 path 的可读错误(check-i18n-glossary 会直接崩栈而不是走 fail())。
+ // 转成普通校验错误,并明确指向是 schema 自身的问题而非数据的问题。
+ let re;
+ try {
+ re = new RegExp(schema.pattern);
+ } catch (err) {
+ errors.push(`${path}: schema 的 pattern 不是合法正则(${schema.pattern}):${err.message}`);
+ re = null;
+ }
+ if (re && !re.test(value)) {
+ errors.push(`${path}: "${value}" 不匹配 ${schema.pattern}`);
+ }
+ }
+ if (schema.minLength !== undefined && value.length < schema.minLength) {
+ errors.push(`${path}: 长度需 ≥ ${schema.minLength}`);
+ }
+ }
+
+ if (Array.isArray(value)) {
+ if (schema.minItems !== undefined && value.length < schema.minItems) {
+ errors.push(`${path}: 至少需要 ${schema.minItems} 项`);
+ }
+ if (schema.items) {
+ value.forEach((item, i) => validateNode(item, schema.items, root, `${path}[${i}]`, errors));
+ }
+ }
+
+ if (schema.oneOf) {
+ const passed = schema.oneOf.filter((branch) => {
+ const sub = [];
+ validateNode(value, branch, root, path, sub);
+ return sub.length === 0;
+ });
+ if (passed.length !== 1) {
+ errors.push(`${path}: 需恰好匹配 oneOf 的一个分支,实际匹配 ${passed.length} 个`);
+ }
+ }
+
+ if (typeOf(value) === 'object') {
+ for (const key of schema.required ?? []) {
+ if (!(key in value)) errors.push(`${path}: 缺少必填字段 "${key}"`);
+ }
+ const known = new Set(Object.keys(schema.properties ?? {}));
+ for (const [key, child] of Object.entries(value)) {
+ const childPath = `${path}.${key}`;
+ if (known.has(key)) {
+ validateNode(child, schema.properties[key], root, childPath, errors);
+ } else if (schema.additionalProperties === false) {
+ errors.push(
+ `${childPath}: 未知字段 "${key}"——拼错的字段名(如 forbiden)会让整条规则静默失效`,
+ );
+ } else if (typeof schema.additionalProperties === 'object') {
+ validateNode(child, schema.additionalProperties, root, childPath, errors);
+ }
+ }
+ }
+}
+
+/** 校验 data 是否符合 schema。返回人读错误信息数组,空数组=通过。 */
+export function validateAgainstSchema(data, schema) {
+ assertSupported(schema);
+ const errors = [];
+ validateNode(data, schema, schema, '$', errors);
+ return errors;
+}