🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(cli): check acceptance report language before publishing (#20857)
YuTengjingdff0ca1844f0
diff --git a/apps/cli/src/commands/acceptanceFlow.ts b/apps/cli/src/commands/acceptanceFlow.tsindex 84832201b56..7f552eef777 100644--- a/apps/cli/src/commands/acceptanceFlow.ts+++ b/apps/cli/src/commands/acceptanceFlow.ts@@ -5,6 +5,7 @@ import pc from 'picocolors';import { getTrpcClient } from '../api/client';import { confirm, outputJson } from '../utils/format';+import { assertReportLanguage, flowLanguageFields } from './acceptanceLanguage';/** Agent entry point: author a graph before exercising the product, then append real visits. */export function attachAcceptanceFlowCommands(acceptance: Command) {@@ -17,6 +18,9 @@ export function attachAcceptanceFlowCommands(acceptance: Command) {.action(async (id: string, options: { file: string }) => {const client = await getTrpcClient();const input = JSON.parse(await readFile(options.file, 'utf8'));+ // Planning is the earliest write in a flow-first acceptance: catching the+ // wrong language here saves executing and recording a whole round in it.+ await assertReportLanguage(client, flowLanguageFields(input.definition));outputJson(await client.acceptance.publishFlow.mutate({ ...input, id }));});flow.command('view <acceptanceId>').action(async (id: string) => {@@ -70,6 +74,7 @@ export function attachAcceptanceFlowCommands(acceptance: Command) {.action(async (id: string, options: { file: string }) => {const client = await getTrpcClient();const input = JSON.parse(await readFile(options.file, 'utf8'));+ await assertReportLanguage(client, [{ path: 'observation', text: input.observation }]);outputJson(await client.acceptance.recordFlowStep.mutate({ ...input, id }));});flowdiff --git a/apps/cli/src/commands/acceptanceLanguage.test.ts b/apps/cli/src/commands/acceptanceLanguage.test.tsnew file mode 100644index 00000000000..45e23f221fa--- /dev/null+++ b/apps/cli/src/commands/acceptanceLanguage.test.ts@@ -0,0 +1,268 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { log } from '../utils/logger';+import {+ assertReportLanguage,+ findLanguageViolations,+ flowLanguageFields,+ ingestLanguageFields,+ ReportLanguageError,+ reportLanguageFor,+} from './acceptanceLanguage';++vi.mock('../settings', () => ({+ resolveServerUrl: () => 'https://user:[email protected]',+}));++const clientFor = (responseLanguage?: string) => ({+ user: {+ getUserState: {+ query: vi.fn(async () => ({ settings: { general: { responseLanguage } } })),+ },+ },+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('reportLanguageFor', () => {+ it('enforces scripts distinguishable from Latin', () => {+ expect(reportLanguageFor('zh-CN')).toMatchObject({ locale: 'zh-CN', status: 'enforced' });+ expect(reportLanguageFor('ja-JP')).toMatchObject({ status: 'enforced' });+ expect(reportLanguageFor('ru-RU')).toMatchObject({ status: 'enforced' });+ });++ it('does not script-check Latin languages', () => {+ expect(reportLanguageFor('en-US')).toEqual({ locale: 'en-US', status: 'unchecked' });+ expect(reportLanguageFor('pt-BR')).toEqual({ locale: 'pt-BR', status: 'unchecked' });+ });++ it('treats "Follow System" (empty or missing) as unset', () => {+ expect(reportLanguageFor('')).toEqual({ status: 'unset' });+ expect(reportLanguageFor(undefined)).toEqual({ status: 'unset' });+ });+});++describe('findLanguageViolations', () => {+ const zh = reportLanguageFor('zh-CN');+ const rule = zh.status === 'enforced' ? zh.rule : undefined!;++ it('flags a field with no character of the target script', () => {+ expect(+ findLanguageViolations([{ path: 'summary.conclusion', text: 'All checks passed.' }], rule),+ ).toEqual([{ path: 'summary.conclusion', text: 'All checks passed.' }]);+ });++ it('accepts target-language prose that mixes in identifiers, code and links', () => {+ expect(+ findLanguageViolations(+ [+ { path: 'a', text: '修复了 `useFoo` 在 Safari 下的问题' },+ { path: 'b', text: '```ts\nconst a = 1;\n```\n结论:通过' },+ { path: 'c', text: '见 [PR 页面](https://github.com/lobehub/lobehub/pull/1)' },+ { path: 'd', text: 'URL:https://example.com,页面已通过' },+ ],+ rule,+ ),+ ).toEqual([]);+ });++ it('ignores absent fields and fields with no prose at all', () => {+ expect(+ findLanguageViolations(+ [+ { path: 'a', text: undefined },+ { path: 'b', text: '`bun run check`' },+ { path: 'c', text: 'https://app.lobehub.com/acceptance/1' },+ { path: 'd', text: '200 / 200' },+ { path: 'e', text: '~~~ts\nconst retry = true;\n~~~' },+ { path: 'f', text: 'https://example.com/café' },+ ],+ rule,+ ),+ ).toEqual([]);+ });++ it('keeps a longer fence open across a shorter fence inside it', () => {+ expect(+ findLanguageViolations(+ [+ { path: 'a', text: '````md\n```bash\nnpm test\n```\n````' },+ { path: 'b', text: '````md\n```\n````\n修复了问题\n```bash\nnpm test\n```' },+ ],+ rule,+ ),+ ).toEqual([]);+ });++ it('does not count target-script characters inside a URL as prose', () => {+ expect(+ findLanguageViolations(+ [{ path: 'a', text: 'All checks passed. https://example.com/中文' }],+ rule,+ ),+ ).toEqual([{ path: 'a', text: 'All checks passed. https://example.com/中文' }]);+ });++ it('accepts kana for Japanese', () => {+ const ja = reportLanguageFor('ja-JP');+ if (ja.status !== 'enforced') throw new Error('ja should be enforced');+ expect(findLanguageViolations([{ path: 'a', text: 'ボタンを押した' }], ja.rule)).toEqual([]);+ });+});++describe('assertReportLanguage', () => {+ it('names the configured language and every offending field', async () => {+ const error = await assertReportLanguage(clientFor('zh-CN'), [+ { path: 'title', text: '结账恢复' },+ { path: 'cases[screen].observation', text: 'The page showed the retry button.' },+ ]).catch((e: unknown) => e);++ expect(error).toBeInstanceOf(ReportLanguageError);+ const message = (error as Error).message;+ expect(message).toContain('response language (settings.general.responseLanguage) is "zh-CN"');+ expect(message).toContain('cases[screen].observation: "The page showed the retry button."');+ expect(message).not.toContain('title:');+ expect(message).toContain('https://app.lobehub.com/settings/appearance');+ expect(message).not.toContain('secret');+ });++ it('warns and skips the check when no response language is set', async () => {+ const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});++ await expect(+ assertReportLanguage(clientFor(''), [{ path: 'title', text: 'English title' }]),+ ).resolves.toEqual({ status: 'unset' });+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('no response language set'));+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('https://app.lobehub.com/settings/appearance'),+ );+ });+});++describe('flowLanguageFields', () => {+ it('collects the flow title and inline check wording', () => {+ const paths = flowLanguageFields({+ nodes: [+ {+ check: {+ definition: {+ expected: 'e',+ preconditions: ['p'],+ steps: [{ expected: 'se', id: 's1', instruction: 'i' }],+ },+ description: 'd',+ id: 'c1',+ title: 't',+ },+ id: 'n1',+ },+ { criterionId: 'existing', id: 'n2' },+ ],+ edges: [{ condition: 'when declined', id: 'e1', trigger: 'submit' }],+ title: 'flow',+ }).map((field) => field.path);++ expect(paths).toEqual([+ 'definition.title',+ 'nodes[c1].check.title',+ 'nodes[c1].check.description',+ 'nodes[c1].check.definition.expected',+ 'nodes[c1].check.definition.preconditions[0]',+ 'nodes[c1].check.definition.steps[s1].instruction',+ 'nodes[c1].check.definition.steps[s1].expected',+ 'edges[e1].trigger',+ 'edges[e1].condition',+ ]);+ });+});++describe('ingestLanguageFields', () => {+ it('covers plan descriptions and definition wording, not only titles', () => {+ const paths = ingestLanguageFields({+ cases: [],+ plan: [+ {+ category: 'c',+ definition: {+ expected: 'e',+ preconditions: ['p'],+ steps: [{ expected: 'se', id: 's1', instruction: 'i' }],+ },+ description: 'd',+ id: 'screen',+ title: 't',+ verifierConfig: {+ expected: 'x',+ method: 'm',+ requiredEvidence: [{ hint: 'h', type: 'screenshot' }],+ },+ },+ ],+ }).map((field) => field.path);++ expect(paths).toEqual(+ expect.arrayContaining([+ 'plan[screen].category',+ 'plan[screen].requiredEvidence[0].hint',+ 'plan[screen].description',+ 'plan[screen].definition.expected',+ 'plan[screen].definition.preconditions[0]',+ 'plan[screen].definition.steps[s1].instruction',+ 'plan[screen].definition.steps[s1].expected',+ ]),+ );+ });+});++describe('ingestLanguageFields evidence and visualization captions', () => {+ it('covers chapter, comparison and visualization prose but not data cells', () => {+ const paths = ingestLanguageFields({+ cases: [+ {+ case: {+ datasets: [{ fields: [{ key: 'model', label: 'Model' }], id: 'd', rows: [] }],+ evidence: [+ {+ chapters: [{ kind: 'step', label: 'Open page', note: 'Shows result', t: 0 }],+ comparison: { id: 'p', label: 'Retry', role: 'before' },+ description: '描述',+ path: 'a.png',+ },+ ],+ visualizations: [+ {+ context: 'ctx',+ encoding: {+ series: [{ field: 'v', label: 'Latency' }],+ valueLabel: 'ms',+ xLabel: 'Request',+ yLabel: 'Latency',+ },+ title: 't',+ },+ ],+ },+ checkItemId: 'screen',+ },+ ],+ }).map((field) => field.path);++ expect(paths).toEqual(+ expect.arrayContaining([+ 'cases[screen].evidence[0].chapters[0].label',+ 'cases[screen].evidence[0].chapters[0].note',+ 'cases[screen].evidence[0].comparison.label',+ 'cases[screen].datasets[0].fields[0].label',+ 'cases[screen].visualizations[0].title',+ 'cases[screen].visualizations[0].context',+ 'cases[screen].visualizations[0].encoding.series[0].label',+ 'cases[screen].visualizations[0].encoding.xLabel',+ 'cases[screen].visualizations[0].encoding.yLabel',+ 'cases[screen].visualizations[0].encoding.valueLabel',+ ]),+ );+ expect(paths.some((path) => path.includes('rows'))).toBe(false);+ });+});diff --git a/apps/cli/src/commands/acceptanceLanguage.ts b/apps/cli/src/commands/acceptanceLanguage.tsnew file mode 100644index 00000000000..61930bf19e9--- /dev/null+++ b/apps/cli/src/commands/acceptanceLanguage.ts@@ -0,0 +1,346 @@+import { resolveServerUrl } from '../settings';+import { log } from '../utils/logger';++/**+ * Acceptance pages are read by the account owner, so every human-readable+ * field has to be in their reply language. Agents get this wrong when they+ * infer "the user's language" from a delegation prompt instead of the+ * conversation, and a rule in the skill alone cannot stop that — so the CLI+ * checks the text before anything is published.+ *+ * Only scripts that are unambiguous against Latin are enforced: a Chinese+ * field with no Han character is certainly wrong, while English vs Portuguese+ * cannot be told apart reliably by script.+ */+interface ScriptRule {+ /** Shown in errors: "must be written in Chinese". */+ languageName: string;+ /** Matches at least one character of the target writing system. */+ pattern: RegExp;+}++const HAN = { languageName: 'Chinese', pattern: /\p{Script=Han}/u } satisfies ScriptRule;+const CYRILLIC = { languageName: 'Cyrillic script', pattern: /\p{Script=Cyrillic}/u };+const ARABIC = { languageName: 'Arabic script', pattern: /\p{Script=Arabic}/u };++/** Keyed by the primary language subtag of `responseLanguage` (`zh-CN` → `zh`). */+const SCRIPT_RULES: Record<string, ScriptRule> = {+ ar: { ...ARABIC, languageName: 'Arabic' },+ be: CYRILLIC,+ bg: { ...CYRILLIC, languageName: 'Bulgarian' },+ el: { languageName: 'Greek', pattern: /\p{Script=Greek}/u },+ fa: { ...ARABIC, languageName: 'Persian' },+ he: { languageName: 'Hebrew', pattern: /\p{Script=Hebrew}/u },+ hi: { languageName: 'Hindi', pattern: /\p{Script=Devanagari}/u },+ ja: {+ languageName: 'Japanese',+ pattern: /[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,+ },+ kk: CYRILLIC,+ ko: { languageName: 'Korean', pattern: /\p{Script=Hangul}/u },+ mn: CYRILLIC,+ ru: { ...CYRILLIC, languageName: 'Russian' },+ sr: CYRILLIC,+ th: { languageName: 'Thai', pattern: /\p{Script=Thai}/u },+ uk: { ...CYRILLIC, languageName: 'Ukrainian' },+ zh: HAN,+};++export type ReportLanguage =+ | { locale: string; rule: ScriptRule; status: 'enforced' }+ /** A Latin-script language: set, but not distinguishable by script. */+ | { locale: string; status: 'unchecked' }+ /** "Follow system" in Settings stores nothing the server can read. */+ | { status: 'unset' };++export interface LanguageField {+ path: string;+ text: unknown;+}++interface UserStateClient {+ user: { getUserState: { query: () => Promise<unknown> } };+}++export const responseLanguageSettingsUrl = () => {+ const url = new URL('/settings/appearance', resolveServerUrl());+ // The server URL may embed credentials; this link is printed to logs.+ url.username = '';+ url.password = '';+ return url.toString();+};++export function reportLanguageFor(responseLanguage: string | undefined): ReportLanguage {+ const locale = responseLanguage?.trim();+ if (!locale) return { status: 'unset' };+ const rule = SCRIPT_RULES[locale.split(/[-_]/)[0]!.toLowerCase()];+ return rule ? { locale, rule, status: 'enforced' } : { locale, status: 'unchecked' };+}++export async function resolveReportLanguage(client: UserStateClient): Promise<ReportLanguage> {+ const state = (await client.user.getUserState.query()) as {+ settings?: { general?: { responseLanguage?: unknown } };+ };+ const value = state?.settings?.general?.responseLanguage;+ return reportLanguageFor(typeof value === 'string' ? value : undefined);+}++/**+ * Code, links and paths are legitimately English inside any report; strip them+ * so "修复了 `useFoo` 的问题" passes and a bare `npm test` field is judged on+ * nothing rather than on the identifier.+ */+const stripNonProse = (text: string) =>+ text+ // A fence closes only on the same delimiter run, so a ```` fence can hold a ``` example.+ .replaceAll(/(`{3,}|~{3,})[\s\S]*?\1/g, ' ')+ .replaceAll(/`[^`\n]*`/g, ' ')+ .replaceAll(/!?\[[^\]]*\]\([^)]*\)/g, (match) => match.replace(/\([^)]*\)$/, ''))+ // A URL may contain non-ASCII path segments (`/中文`, `/café`), so it runs to+ // whitespace — but stops at full-width punctuation, which never belongs to a+ // URL and is how Chinese prose usually continues after one.+ .replaceAll(/https?:\/\/[^\s<>"'`,。!?、;:()【】「」《》]+/g, ' ');++/**+ * A field fails when it contains letters but none in the target script — the+ * whole field is in another language. Mixed text with identifiers passes.+ */+export function findLanguageViolations(fields: LanguageField[], rule: ScriptRule) {+ return fields.flatMap((field) => {+ if (typeof field.text !== 'string') return [];+ const prose = stripNonProse(field.text);+ if (!/\p{L}/u.test(prose) || rule.pattern.test(prose)) return [];+ return [{ path: field.path, text: field.text }];+ });+}++interface IngestTextInput {+ cases: { case: Record<string, any>; checkItemId: string }[];+ conclusion?: string;+ goal?: string;+ plan?: {+ /** Rendered as the checklist group heading. */+ category?: string;+ definition?: unknown;+ description?: string;+ id: string;+ title: string;+ verifierConfig?: unknown;+ }[];+ proposal?: string;+ report?: string;+ requirement?: string;+ title?: unknown;+}++/** Prose in a check definition: its outcome, preconditions and step wording. */+function checkDefinitionFields(at: string, definition: unknown): LanguageField[] {+ const value = (definition ?? {}) as {+ expected?: unknown;+ preconditions?: unknown;+ steps?: unknown;+ };+ const preconditions = Array.isArray(value.preconditions) ? value.preconditions : [];+ const steps = Array.isArray(value.steps) ? value.steps : [];+ return [+ { path: `${at}.expected`, text: value.expected },+ ...preconditions.map((text: unknown, index: number) => ({+ path: `${at}.preconditions[${index}]`,+ text,+ })),+ ...steps.flatMap((step: any) => [+ { path: `${at}.steps[${String(step?.id)}].instruction`, text: step?.instruction },+ { path: `${at}.steps[${String(step?.id)}].expected`, text: step?.expected },+ ]),+ ];+}++/**+ * Video step/claim captions and the before/after caption band. Shared by+ * `ingest` and `evidence upload --metadata`, which persist the same shape.+ */+export function evidenceCaptionFields(at: string, metadata: unknown): LanguageField[] {+ const value = (metadata ?? {}) as { chapters?: unknown; comparison?: { label?: unknown } };+ const chapters = Array.isArray(value.chapters) ? value.chapters : [];+ return [+ ...chapters.flatMap((chapter: any, i: number) => [+ { path: `${at}.chapters[${i}].label`, text: chapter?.label },+ { path: `${at}.chapters[${i}].note`, text: chapter?.note },+ ]),+ { path: `${at}.comparison.label`, text: value.comparison?.label },+ ];+}++/** Every `ingest` field that renders as prose on the acceptance page. */+export function ingestLanguageFields(input: IngestTextInput): LanguageField[] {+ const fields: LanguageField[] = [+ { path: 'title', text: input.title },+ { path: 'focus', text: input.goal },+ { path: 'requirement', text: input.requirement },+ { path: 'summary.conclusion', text: input.conclusion },+ { path: 'report.md', text: input.report },+ { path: 'proposal.md', text: input.proposal },+ ];+ for (const item of input.plan ?? []) {+ const config = (item.verifierConfig ?? {}) as {+ expected?: unknown;+ method?: unknown;+ requiredEvidence?: unknown;+ };+ const evidenceSpecs = Array.isArray(config.requiredEvidence) ? config.requiredEvidence : [];+ fields.push(+ { path: `plan[${item.id}].title`, text: item.title },+ { path: `plan[${item.id}].category`, text: item.category },+ { path: `plan[${item.id}].method`, text: config.method },+ { path: `plan[${item.id}].expected`, text: config.expected },+ { path: `plan[${item.id}].description`, text: item.description },+ ...checkDefinitionFields(`plan[${item.id}].definition`, item.definition),+ // Rendered as the evidence chip tooltip.+ ...evidenceSpecs.map((spec: any, index: number) => ({+ path: `plan[${item.id}].requiredEvidence[${index}].hint`,+ text: spec?.hint,+ })),+ );+ }+ for (const { case: c, checkItemId } of input.cases) {+ fields.push(+ { path: `cases[${checkItemId}].name`, text: c.name ?? c.case ?? c.title },+ {+ path: `cases[${checkItemId}].observation`,+ text: c.keyObservation ?? c.observation ?? c.note,+ },+ { path: `cases[${checkItemId}].suggestion`, text: c.suggestion },+ );+ const evidence = Array.isArray(c.evidence) ? c.evidence : [c.evidence];+ evidence.forEach((entry: any, index: number) => {+ if (!entry || typeof entry !== 'object') return;+ const at = `cases[${checkItemId}].evidence[${index}]`;+ fields.push(+ { path: `${at}.description`, text: entry.description ?? entry.desc },+ ...evidenceCaptionFields(at, entry),+ );+ });+ fields.push(...visualizationFields(`cases[${checkItemId}]`, c));+ }+ return fields;+}++/**+ * Visualization prose: titles, context and axis/series labels. Categories and+ * table cells are data (model names, file names, ids) and legitimately Latin,+ * so they are not checked — a false rejection has no bypass.+ */+function visualizationFields(at: string, c: Record<string, any>): LanguageField[] {+ const datasets = Array.isArray(c.datasets) ? c.datasets : [];+ const views = Array.isArray(c.visualizations) ? c.visualizations : [];+ return [+ ...datasets.flatMap((dataset: any, d: number) =>+ (Array.isArray(dataset?.fields) ? dataset.fields : []).map((field: any, f: number) => ({+ path: `${at}.datasets[${d}].fields[${f}].label`,+ text: field?.label,+ })),+ ),+ ...views.flatMap((view: any, v: number) => {+ const series = Array.isArray(view?.encoding?.series) ? view.encoding.series : [];+ return [+ { path: `${at}.visualizations[${v}].title`, text: view?.title },+ { path: `${at}.visualizations[${v}].context`, text: view?.context },+ // Explicit axis/value captions override the field labels when set.+ ...['xLabel', 'yLabel', 'valueLabel'].map((key) => ({+ path: `${at}.visualizations[${v}].encoding.${key}`,+ text: view?.encoding?.[key],+ })),+ ...series.map((entry: any, i: number) => ({+ path: `${at}.visualizations[${v}].encoding.series[${i}].label`,+ text: entry?.label,+ })),+ ];+ }),+ ];+}++const preview = (text: string) => {+ const line = text.replaceAll(/\s+/g, ' ').trim();+ return line.length > 80 ? `${line.slice(0, 77)}...` : line;+};++export class ReportLanguageError extends Error {+ constructor(+ readonly locale: string,+ readonly violations: { path: string; text: string }[],+ languageName: string,+ ) {+ super(+ [+ `Report language check failed: your account's response language (settings.general.responseLanguage) is "${locale}", so every human-readable field must be written in ${languageName}.`,+ `These ${violations.length} field(s) contain no ${languageName} text:`,+ ...violations.map((v) => ` - ${v.path}: "${preview(v.text)}"`),+ `Rewrite them in ${languageName} and retry. If "${locale}" is not the language you read, change Response Language at ${responseLanguageSettingsUrl()} first.`,+ ].join('\n'),+ );+ this.name = 'ReportLanguageError';+ }+}++export const unsetLanguageWarning = () =>+ `Report language not checked: your account has no response language set (Response Language is "Follow System" at ${responseLanguageSettingsUrl()}). Set it so acceptance text is checked against the language you read.`;++/**+ * Throws `ReportLanguageError` before any remote write when a field is in the+ * wrong script. There is intentionally no bypass flag: an agent that hits the+ * error would just add it.+ */+export async function assertReportLanguage(+ client: UserStateClient,+ fields: LanguageField[],+ language?: ReportLanguage,+): Promise<ReportLanguage> {+ const resolved = language ?? (await resolveReportLanguage(client));+ if (resolved.status === 'unset') {+ log.warn(unsetLanguageWarning());+ return resolved;+ }+ if (resolved.status !== 'enforced') return resolved;+ const violations = findLanguageViolations(fields, resolved.rule);+ if (violations.length > 0) {+ throw new ReportLanguageError(resolved.locale, violations, resolved.rule.languageName);+ }+ return resolved;+}++/** JSON-safe view of the resolved language for `--json` output. */+export const languageSummary = (language: ReportLanguage) => ({+ enforced: language.status === 'enforced',+ locale: language.status === 'unset' ? null : language.locale,+ ...(language.status === 'enforced' ? { languageName: language.rule.languageName } : {}),+ status: language.status,+});++/**+ * Prose in a flow definition: its title, every inline check's wording, and+ * edge triggers/conditions, which render as graph labels.+ */+export function flowLanguageFields(definition: unknown): LanguageField[] {+ const flow = (definition ?? {}) as { edges?: unknown; nodes?: unknown; title?: unknown };+ const fields: LanguageField[] = [{ path: 'definition.title', text: flow.title }];+ const nodes = Array.isArray(flow.nodes) ? flow.nodes : [];+ for (const node of nodes) {+ const check = (node as { check?: any })?.check;+ if (!check || typeof check !== 'object') continue;+ const at = `nodes[${String(check.id ?? (node as { id?: unknown }).id)}].check`;+ fields.push(+ { path: `${at}.title`, text: check.title },+ { path: `${at}.description`, text: check.description },+ ...checkDefinitionFields(`${at}.definition`, check.definition),+ );+ }+ const edges = Array.isArray(flow.edges) ? flow.edges : [];+ for (const edge of edges) {+ const value = (edge ?? {}) as { condition?: unknown; id?: unknown; trigger?: unknown };+ fields.push(+ { path: `edges[${String(value.id)}].trigger`, text: value.trigger },+ { path: `edges[${String(value.id)}].condition`, text: value.condition },+ );+ }+ return fields;+}diff --git a/apps/cli/src/commands/acceptanceRun.test.ts b/apps/cli/src/commands/acceptanceRun.test.tsindex 4ec68b77237..a2d75fd8e9f 100644--- a/apps/cli/src/commands/acceptanceRun.test.ts+++ b/apps/cli/src/commands/acceptanceRun.test.ts@@ -39,6 +39,7 @@ describe('acceptance publication with missing evidence', () => {uploadEvidence: { mutate: vi.fn() },upsertReport: { mutate: vi.fn() },},+ user: { getUserState: { query: vi.fn() } },workspace: { getById: { query: vi.fn() } },};let dir: string;@@ -65,6 +66,9 @@ describe('acceptance publication with missing evidence', () => {id: `result-${input.checkItemId}`,}));client.verify.uploadEvidence.mutate.mockResolvedValue({ id: 'evidence-1' });+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'en-US' } },+ });dir = await mkdtemp(path.join(tmpdir(), 'lh-evidence-'));await writeFile(path.join(dir, "screen's shot.png"), 'image fixture');await writeFile(path.join(dir, 'scroll.mp4'), 'video fixture');@@ -844,4 +848,153 @@ describe('acceptance publication with missing evidence', () => {verdict: 'failed',});});++ describe('report language', () => {+ const englishReport = async () => {+ await writeFile(+ path.join(dir, 'result.json'),+ JSON.stringify({+ cases: [{ id: 'screen', name: '用户能看到处理结果', observation: 'The page shows it.' }],+ plan: [{ expected: '页面显示结果', id: 'screen', title: '用户能看到处理结果' }],+ summary: { conclusion: '通过', verdict: 'passed' },+ title: '处理结果展示',+ }),+ );+ await writeFile(path.join(dir, 'report.md'), 'All checks passed.');+ };++ it('rejects a report in the wrong language before any remote write', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });+ await englishReport();++ const error = await run('ingest', dir).catch((e: unknown) => e);++ expect(String(error)).toContain('responseLanguage) is "zh-CN"');+ expect(String(error)).toContain('cases[screen].observation');+ expect(String(error)).toContain('report.md');+ expect(String(error)).not.toContain('plan[screen].title');+ expect(client.acceptance.ensure.mutate).not.toHaveBeenCalled();+ expect(client.verify.createRun.mutate).not.toHaveBeenCalled();+ });++ it('validates a plan-only report with --dry-run without publishing', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });+ await writeFile(+ path.join(dir, 'result.json'),+ JSON.stringify({+ plan: [{ id: 'screen', method: 'Open the page', title: '用户能看到处理结果' }],+ title: '处理结果展示',+ }),+ );++ await expect(run('ingest', dir, '--dry-run')).rejects.toThrow('plan[screen].method');++ await writeFile(+ path.join(dir, 'result.json'),+ JSON.stringify({+ plan: [{ id: 'screen', method: '打开页面', title: '用户能看到处理结果' }],+ title: '处理结果展示',+ }),+ );+ await run('ingest', dir, '--dry-run', '--json');++ expect(result()).toMatchObject({+ dryRun: true,+ language: { enforced: true, locale: 'zh-CN', status: 'enforced' },+ planItems: 1,+ });+ expect(client.acceptance.ensure.mutate).not.toHaveBeenCalled();+ expect(client.verify.createRun.mutate).not.toHaveBeenCalled();+ });++ it('rejects an English category, which renders as the checklist group heading', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });+ await writeFile(+ path.join(dir, 'result.json'),+ JSON.stringify({+ plan: [{ category: 'Task hierarchy', id: 'screen', title: '用户能看到处理结果' }],+ title: '处理结果展示',+ }),+ );++ await expect(run('ingest', dir, '--dry-run')).rejects.toThrow('plan[screen].category');+ });++ it('rejects an English required-evidence hint, shown as the evidence tooltip', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });+ await writeFile(+ path.join(dir, 'result.json'),+ JSON.stringify({+ plan: [+ {+ id: 'screen',+ requiredEvidence: [{ hint: 'Capture checkout result', type: 'screenshot' }],+ title: '用户能看到处理结果',+ },+ ],+ title: '处理结果展示',+ }),+ );++ await expect(run('ingest', dir, '--dry-run')).rejects.toThrow(+ 'plan[screen].requiredEvidence[0].hint',+ );+ });++ it('rejects English captions in `evidence upload --metadata` before uploading', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });++ await expect(+ run(+ 'evidence',+ 'upload',+ '--check',+ 'result-screen',+ '--content',+ '日志',+ '--type',+ 'text',+ '--desc',+ '执行记录',+ '--metadata',+ JSON.stringify({+ chapters: [{ kind: 'step', label: 'Open checkout', t: 0 }],+ comparison: { id: 'pair', label: '重试前', role: 'before' },+ }),+ ),+ ).rejects.toThrow('--metadata.chapters[0].label');+ expect(client.verify.uploadEvidence.mutate).not.toHaveBeenCalled();+ });++ it('rejects `run create` with a title in the wrong language', async () => {+ client.user.getUserState.query.mockResolvedValue({+ settings: { general: { responseLanguage: 'zh-CN' } },+ });++ await expect(+ run('create', '--title', 'Checkout recovery', '--goal', '验证重试'),+ ).rejects.toThrow('--title');+ expect(client.verify.createRun.mutate).not.toHaveBeenCalled();+ });++ it('warns and still publishes when the account has no response language', async () => {+ client.user.getUserState.query.mockResolvedValue({ settings: { general: {} } });+ await englishReport();++ await run('ingest', dir, '--json');++ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('no response language set'));+ expect(client.verify.createRun.mutate).toHaveBeenCalledOnce();+ });+ });});diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.tsindex d4e5c7b0b41..4df49542c3d 100644--- a/apps/cli/src/commands/acceptanceRun.ts+++ b/apps/cli/src/commands/acceptanceRun.ts@@ -22,6 +22,12 @@ import {uploadAcceptanceFile,uploadReportEvidence,} from './acceptanceEvidence';+import {+ assertReportLanguage,+ evidenceCaptionFields,+ ingestLanguageFields,+ languageSummary,+} from './acceptanceLanguage';import {type Decision,DECISIONS,@@ -213,6 +219,10 @@ interface RunCreateOptions {async function runCreateAction(options: RunCreateOptions): Promise<void> {const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--title', text: options.title },+ { path: '--goal', text: options.goal },+ ]);const created = await client.verify.createRun.mutate({goal: options.goal,operationId: options.operation,@@ -295,6 +305,11 @@ interface ResultIngestOptions {async function resultIngestAction(options: ResultIngestOptions): Promise<void> {const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--title', text: options.title },+ { path: '--evidence', text: options.evidence },+ { path: '--suggestion', text: options.suggestion },+ ]);const created = await client.verify.ingestResult.mutate({checkItemId: options.check,checkItemIndex: options.index ? Number.parseInt(options.index, 10) : undefined,@@ -368,6 +383,10 @@ async function submitAction(options: SubmitOptions): Promise<void> {process.exit(1);}const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--title', text: options.title },+ { path: '--desc', text: options.desc },+ ]);let fileId: string | undefined;let inlineContent = options.content;if (options.file) {@@ -446,6 +465,10 @@ async function evidenceUploadAction(options: EvidenceUploadOptions): Promise<voi}const metadata: unknown = options.metadata ? JSON.parse(options.metadata) : undefined;const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--desc', text: options.desc },+ ...evidenceCaptionFields('--metadata', metadata),+ ]);let fileId = options.fileId;let inlineContent = options.content;if (options.file) {@@ -525,6 +548,10 @@ interface ReportUpsertOptions {async function reportUpsertAction(options: ReportUpsertOptions): Promise<void> {const num = (s?: string) => (s === undefined ? undefined : Number.parseInt(s, 10));const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--summary', text: options.summary },+ { path: '--content', text: options.content },+ ]);const created = await client.verify.upsertReport.mutate({content: options.content,failedChecks: num(options.failed),@@ -557,6 +584,8 @@ async function reportGetAction(runId: string, options: { json?: boolean | stringinterface IngestReportOptions {acceptance?: string;+ /** Run every local check, including the report language, then stop before publishing. */+ dryRun?: boolean;goal?: string;json?: boolean | string;open?: boolean;@@ -739,6 +768,45 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption: undefined;const client = await getTrpcClient();+ // Before the first remote mutation: a round in the wrong language cannot be+ // fixed in place, only replaced by another immutable round.+ const language = await assertReportLanguage(+ client,+ ingestLanguageFields({+ cases,+ conclusion,+ goal,+ plan,+ proposal,+ report: content,+ requirement,+ title,+ }),+ );+ if (options.dryRun) {+ const checked =+ language.status === 'enforced'+ ? `report language ${language.locale} ✓`+ : language.status === 'unchecked'+ ? `report language ${language.locale} (not script-checked)`+ : 'report language not set';+ if (options.json !== undefined) {+ outputJson(+ {+ cases: cases.length,+ dryRun: true,+ language: languageSummary(language),+ planItems: plan?.length ?? 0,+ },+ typeof options.json === 'string' ? options.json : undefined,+ );+ return;+ }+ console.log(+ `${pc.green('✓ Dry run passed')} — ${cases.length} case(s), ${plan?.length ?? 0} plan item(s), ${checked}. Nothing was published.`,+ );+ return;+ }let acceptance;let bundle;if (requestedAcceptanceId) {@@ -1226,6 +1294,10 @@ function withIngestReportOptions(cmd: Command): Command {'Acceptance requirement recorded when the aggregate is first created',).option('--open', 'Print the in-app URL to open the report')+ .option(+ '--dry-run',+ 'Validate the report (including its language) without publishing; works on a plan-only result.json',+ ).option('--json [fields]', 'Output JSON');}diff --git a/apps/cli/src/commands/verify.test.ts b/apps/cli/src/commands/verify.test.tsindex f756d04bfb6..9353e4bcddc 100644--- a/apps/cli/src/commands/verify.test.ts+++ b/apps/cli/src/commands/verify.test.ts@@ -30,6 +30,11 @@ import { evidenceDescriptionForFile } from './verifyHelpers';const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {+ user: {+ getUserState: {+ query: vi.fn(async () => ({ settings: { general: { responseLanguage: 'en-US' } } })),+ },+ },verify: {createRubric: { mutate: vi.fn() },deleteRun: { mutate: vi.fn() },diff --git a/apps/cli/src/commands/verifyAcceptance.create.test.ts b/apps/cli/src/commands/verifyAcceptance.create.test.tsindex e8b36f78e5e..308343dd36d 100644--- a/apps/cli/src/commands/verifyAcceptance.create.test.ts+++ b/apps/cli/src/commands/verifyAcceptance.create.test.ts@@ -18,6 +18,7 @@ const ensure = vi.fn();const publishFlow = vi.fn();const createRun = vi.fn();const attachRun = vi.fn();+const getUserState = vi.fn();let output: ReturnType<typeof vi.spyOn>;const run = async (args: string[]) => {@@ -36,9 +37,11 @@ beforeEach(() => {publishFlow: { mutate: publishFlow },attachRun: { mutate: attachRun },},+ user: { getUserState: { query: getUserState } },verify: { createRun: { mutate: createRun } },} as unknown as Awaited<ReturnType<typeof getTrpcClient>>);ensure.mockImplementation(async (input) => ({ ...input, id: acceptanceId, status: 'pending' }));+ getUserState.mockResolvedValue({ settings: { general: { responseLanguage: 'en-US' } } });});afterEach(() => {@@ -157,3 +160,40 @@ describe('acceptance create', () => {}});});++describe('acceptance create report language', () => {+ it('rejects a requirement in the wrong language before creating anything', async () => {+ getUserState.mockResolvedValue({ settings: { general: { responseLanguage: 'zh-CN' } } });++ await expect(run(['create', '--requirement', requirement, '--json'])).rejects.toThrow(+ '--requirement',+ );+ expect(ensure).not.toHaveBeenCalled();+ });++ it('rejects a flow whose checks are in the wrong language before publishing', async () => {+ getUserState.mockResolvedValue({ settings: { general: { responseLanguage: 'zh-CN' } } });+ const dir = await mkdtemp(path.join(tmpdir(), 'lh-flow-language-'));+ const file = path.join(dir, 'flow.json');+ await writeFile(+ file,+ JSON.stringify({+ definition: {+ edges: [],+ entryNodeId: 'n1',+ nodes: [{ check: { definition: {}, id: 'c1', title: 'Retry payment' }, id: 'n1' }],+ title: '支付恢复',+ },+ }),+ );++ try {+ await expect(run(['flow', 'publish', acceptanceId, '--file', file])).rejects.toThrow(+ 'nodes[c1].check.title',+ );+ expect(publishFlow).not.toHaveBeenCalled();+ } finally {+ await rm(dir, { force: true, recursive: true });+ }+ });+});diff --git a/apps/cli/src/commands/verifyAcceptance.ts b/apps/cli/src/commands/verifyAcceptance.tsindex d09c247cbd1..bb4516f6d75 100644--- a/apps/cli/src/commands/verifyAcceptance.ts+++ b/apps/cli/src/commands/verifyAcceptance.ts@@ -13,6 +13,13 @@ import { outputJson, printTable, timeAgo, truncate } from '../utils/format';import { log } from '../utils/logger';import { collectCommentFeedback } from './acceptanceCommentFeedback';import { attachAcceptanceFlowCommands } from './acceptanceFlow';+import {+ assertReportLanguage,+ languageSummary,+ resolveReportLanguage,+ responseLanguageSettingsUrl,+ unsetLanguageWarning,+} from './acceptanceLanguage';import { attachAcceptanceRunCommands } from './acceptanceRun';import type { ReviewAnnotationRegion } from './verifyHelpers';import { formatAnnotationRegion, formatDisputedChapter, parseSubjectRef } from './verifyHelpers';@@ -77,6 +84,41 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecatattachAcceptanceFlowCommands(acceptance);+ acceptance+ .command('preflight')+ .description(+ 'Check that the CLI is authenticated and print the language every acceptance text must be written in. ' ++ 'Run it before authoring anything, and pass the language to any subagent you delegate to.',+ )+ .option('--json [fields]', 'Output JSON')+ .action(async (options: { json?: boolean | string }) => {+ const client = await getTrpcClient();+ // An auth failure throws here, which is the signal to stop before authoring.+ const language = await resolveReportLanguage(client);+ const instruction =+ language.status === 'unset'+ ? 'No response language is set on this account, so the language is not checked. Write in the language the user converses in.'+ : `Write every human-readable acceptance field (title, plan, case names and observations, evidence descriptions, conclusion, report.md, proposal.md) in ${language.locale}${language.status === 'enforced' ? `, i.e. ${language.rule.languageName}` : ''}. Pass this language explicitly to any subagent you delegate to.`;+ if (options.json !== undefined) {+ outputJson(+ {+ authenticated: true,+ instruction,+ language: languageSummary(language),+ settingsUrl: responseLanguageSettingsUrl(),+ },+ typeof options.json === 'string' ? options.json : undefined,+ );+ return;+ }+ if (language.status === 'unset') log.warn(unsetLanguageWarning());+ console.log(`${pc.green('✓')} Authenticated`);+ console.log(+ `${pc.bold('report language')}: ${language.status === 'unset' ? pc.yellow('not set') : language.locale}${language.status === 'unchecked' ? pc.dim(' (not script-checked)') : ''}`,+ );+ console.log(instruction);+ });+acceptance.command('create').summary('Create or reuse an acceptance without creating a verification round or results')@@ -125,6 +167,10 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat}const client = await getTrpcClient();+ await assertReportLanguage(client, [+ { path: '--requirement', text: requirement },+ { path: '--title', text: title },+ ]);const result = await client.acceptance.ensure.mutate({ ...subject, requirement, title });const acceptanceUrl = new URL(`/acceptance/${encodeURIComponent(result.id)}`,