wishforge-ide/apps/api/src/domain/wish-report.ts
eust-w 91ab5f91e6 🌐 Write run events, waiting details and agent replies in Chinese
The run page mixed English stage events and agent summaries into the
Chinese console. Messages are now written in Simplified Chinese at their
source (control plane, dispatcher, worker, POC build), keeping commands,
SHAs, branches and error codes verbatim; raw runtime errors get a Chinese
prefix. The agent prompt asks for the plan, summary and questions in
Chinese. File-change parsing accepts old and new messages, and the event
label table covers every event kind written.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-04 12:42:04 +08:00

359 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {
type Actor,
type CheckpointRecord,
type CodeReview,
type Evidence,
type Project,
type Release,
type Run,
type RunEvent,
type Wish,
} from '@wishforge/contracts';
import type { Store } from '../db/store.js';
import { must, projectAccess } from './control-plane.js';
import { redact } from './policy.js';
import { changedPathsOf } from './provider-events.js';
const STAGES: Record<string, string> = {
clarify: '澄清',
plan: '规划',
implement: '实现',
verify: '验证',
integrate: '合入',
build: '构建',
release: '发布',
accept: '验收',
};
const STATUSES: Record<string, string> = {
queued: '排队中',
running: '执行中',
waiting: '等待中',
paused: '已暂停',
succeeded: '已完成',
failed: '失败',
canceled: '已取消',
};
const EVIDENCE: Record<string, string> = {
verification: '验证',
integration: '合入',
build: '构建',
deployment: '部署',
};
const RELEASES: Record<string, string> = {
awaiting_approval: '等待批准',
ready: '待部署',
deploying: '部署中',
healthy: '已上线',
failed: '失败',
rolled_back: '已回滚',
unknown: '状态未知',
};
const REVIEWS: Record<string, string> = {
pending: '待审核',
approved: '已批准',
rejected: '已驳回',
invalidated: '已失效',
};
/** The code change, at most this long; the rest stays in the run's artifacts. */
const PATCH_LIMIT = 80_000;
const OUTPUT_LIMIT = 4000;
/** A time in China's time zone, where the deployment's people work. */
export function reportTime(value?: string) {
if (!value) return '—';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const local = new Date(date.getTime() + 8 * 3600_000).toISOString();
return `${local.slice(0, 10)} ${local.slice(11, 19)}`;
}
const duration = (ms: number) => {
const minutes = Math.floor(ms / 60_000);
const seconds = Math.round((ms % 60_000) / 1000);
return minutes ? `${minutes} 分 ${seconds} 秒` : `${seconds} 秒`;
};
/** Text inside a table cell: one line, no pipes. */
const cell = (value: unknown) =>
String(value ?? '—')
.replace(/\r?\n/g, ' ')
.replace(/\|/g, '\\|')
.trim() || '—';
/** A fence longer than any backtick run in the text, so the text cannot close it. */
export function fenced(text: string, language = '') {
const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map(match => match[0].length));
const fence = '`'.repeat(longest + 1);
return `${fence}${language}\n${text.replace(/\s+$/, '')}\n${fence}`;
}
const table = (head: string[], rows: unknown[][]) =>
rows.length
? [
`| ${head.join(' | ')} |`,
`| ${head.map(() => '---').join(' | ')} |`,
...rows.map(row => `| ${row.map(cell).join(' | ')} |`),
].join('\n')
: '';
const tail = (text: string, limit = OUTPUT_LIMIT) =>
text.length > limit ? `…(前面省略)\n${text.slice(-limit)}` : text;
/**
* Markdown someone else wrote, placed under a heading of the report: its headings move down so
* the biggest becomes `top`, and code blocks stay as they are.
*/
export function nested(text: string, top = 4) {
const levels = [...text.matchAll(/^(#{1,6})\s/gm)].map(match => match[1]!.length);
const shift = levels.length ? Math.max(0, top - Math.min(...levels)) : 0;
let fence = '';
return text
.split('\n')
.map(line => {
const marker = /^(`{3,}|~{3,})/.exec(line)?.[1];
if (marker && (!fence || marker.startsWith(fence))) fence = fence ? '' : marker;
if (fence || !shift) return line;
return line.replace(
/^(#{1,6})(\s)/,
(_, hashes: string, space: string) => '#'.repeat(Math.min(6, hashes.length + shift)) + space,
);
})
.join('\n');
}
/** A changed file as the agent reported it, relative to its workspace. */
const workspacePath = (file: string) => file.replace(/^.*\/executor\/[^/]+\/[^/]+-a\d+\//, '');
interface RunRecord {
run: Run;
events: RunEvent[];
evidence: Evidence[];
reviews: CodeReview[];
releases: Release[];
checkpoint?: CheckpointRecord;
}
function runSection(index: number, { run, events, evidence, reviews, releases, checkpoint }: RunRecord) {
const lines: string[] = [];
const title = run.revertOf ? `撤销运行` : run.revision > 1 ? `第 ${run.revision} 版` : '运行';
lines.push(
`## ${index}. ${title} \`${run.id.slice(0, 8)}\` · ${STATUSES[run.status] ?? run.status} · ${STAGES[run.stage] ?? run.stage}`,
);
lines.push(
table(
['项目', '内容'],
[
['运行 ID', run.id],
['状态', `${STATUSES[run.status] ?? run.status}${run.waitingReason ? `(${run.waitingReason})` : ''}`],
['当前阶段', STAGES[run.stage] ?? run.stage],
['提交人', run.requestedBy],
['执行器', run.provider],
['模型', run.providerModel ?? '执行器默认'],
['代码范围', run.frontendOnly === undefined ? '—' : run.frontendOnly ? '只改前端' : '前端和后端'],
['起始分支', run.sourceBranch ?? '目标分支'],
['开始时间', reportTime(run.createdAt)],
['最后更新', reportTime(run.updatedAt)],
['执行时长', duration(run.activeMilliseconds ?? 0)],
[
'Token(计入预算)',
`${run.usedTokens.toLocaleString('en-US')} / ${run.budget.maxTokens.toLocaleString('en-US')}`,
],
['修复轮次', `${run.repairCount} / ${run.budget.maxRepairRounds}`],
['基线提交', run.sourceCommit],
['验证通过的提交', run.verifiedCommit],
['合入的提交', run.integratedCommit],
...(run.error ? [['错误', run.error]] : []),
],
),
);
const transitions = events.filter(
event => event.type === 'run.transition' || event.type.startsWith('run.') || event.type === 'wish.submitted',
);
lines.push('### 阶段时间线');
lines.push(
table(
['时间', '阶段', '事件'],
transitions.map(event => [
reportTime(event.time),
STAGES[String(event.data?.stage ?? '')] ?? event.data?.stage ?? '',
event.message,
]),
) || '没有记录。',
);
lines.push('### AI 执行细节');
const plans = events.filter(event => event.type === 'provider.plan');
const plan = plans.at(-1);
if (plan) lines.push('#### 计划', plan.message);
const outputs = events.filter(event => event.type === 'provider.output');
if (outputs.length) {
lines.push('#### Agent 的回复');
for (const output of outputs)
lines.push(`${reportTime(output.time)}`, fenced(tail(String(output.data?.text ?? output.message)), 'text'));
}
const files = [
...new Set(
events
.filter(event => event.type === 'provider.file_change')
.flatMap(event => {
const paths = changedPathsOf(event.message);
return paths ? [workspacePath(paths)] : [];
}),
),
];
if (files.length) lines.push('#### Agent 改动的文件', files.map(file => `- \`${file}\``).join('\n'));
const commands = events.filter(event => event.type === 'provider.command');
if (commands.length)
lines.push(
'#### Agent 执行的命令',
table(
['时间', '命令', '退出码'],
commands.map(event => [
reportTime(event.time),
String(event.data?.command ?? event.message).slice(0, 300),
event.data?.exitCode,
]),
),
);
const usage = events.filter(event => event.type === 'provider.usage');
if (usage.length)
lines.push(
'#### 模型用量',
table(
['时间', '输入', '输出', '缓存创建', '缓存读取', '计入预算'],
usage.map(event => [
reportTime(event.time),
event.data?.input,
event.data?.output,
event.data?.cacheCreation ?? 0,
event.data?.cacheRead ?? 0,
event.data?.counted ?? event.data?.total ?? '—',
]),
),
);
if (!plan && !outputs.length && !files.length && !commands.length && !usage.length)
lines.push('执行器没有留下记录。');
if (run.implementationSummary) lines.push('### 实现总结', nested(run.implementationSummary));
const patch = typeof checkpoint?.checkpoint?.patch === 'string' ? (checkpoint.checkpoint.patch as string) : '';
if (patch.trim())
lines.push(
'### 代码改动',
patch.length > PATCH_LIMIT
? `${fenced(patch.slice(0, PATCH_LIMIT), 'diff')}\n\n改动共 ${patch.length.toLocaleString('en-US')} 个字符,这里只列出前 ${PATCH_LIMIT.toLocaleString('en-US')} 个;完整改动见运行的产物。`
: fenced(patch, 'diff'),
);
if (evidence.length) {
lines.push('### 验证证据');
for (const item of [...evidence].sort((a, b) => a.createdAt.localeCompare(b.createdAt))) {
lines.push(
`#### ${EVIDENCE[item.type] ?? item.type} · ${item.passed ? '通过' : '未通过'} · ${reportTime(item.createdAt)}`,
`提交 \`${item.sourceCommit}\`${item.checkSandbox ? `,检查隔离:${item.checkSandbox}` : ''}`,
);
if (item.backendPaths?.length)
lines.push(`改到了后端文件:${item.backendPaths.map(file => `\`${file}\``).join('、')}`);
for (const command of [...(item.installFailure ? [item.installFailure] : []), ...(item.commands ?? [])]) {
lines.push(
`- \`${command.argv.join(' ').slice(0, 300)}\` → 退出码 ${command.exitCode}${command.durationMs ? `,${duration(command.durationMs)}` : ''}`,
);
if (command.outputTail?.trim()) lines.push(fenced(tail(command.outputTail, 3000), 'text'));
}
}
}
if (run.lastFailure)
lines.push(
'### 失败与修复',
`最近一次失败(${run.lastFailure.kind})${run.lastFailure.argv ? `:\`${run.lastFailure.argv.join(' ')}\`` : ''}${run.lastFailure.exitCode !== undefined ? `,退出码 ${run.lastFailure.exitCode}` : ''}`,
fenced(tail(run.lastFailure.outputTail, 3000), 'text'),
);
if (reviews.length)
lines.push(
'### 代码审核',
table(
['时间', '状态', '审核人', '涉及路径', '意见'],
reviews.map(review => [
reportTime(review.decidedAt ?? review.createdAt),
REVIEWS[review.status] ?? review.status,
review.decidedBy,
review.paths.slice(0, 10).join(', '),
review.comment,
]),
),
);
if (releases.length)
lines.push(
'### 发布',
table(
['时间', '状态', '环境', '镜像', '提交', '需要批准的原因', '失败原因'],
releases.map(release => [
reportTime(release.deployedAt ?? release.createdAt),
RELEASES[release.status] ?? release.status,
release.environmentId,
release.imageDigest,
release.sourceCommit.slice(0, 12),
release.riskReasons.join(';'),
release.failureReason,
]),
),
);
lines.push(
'### 完整事件日志',
table(
['#', '时间', '类型', '内容'],
events.map(event => [event.seq, reportTime(event.time), event.type, event.message.slice(0, 500)]),
) || '没有事件。',
);
return lines.join('\n\n');
}
/** Every run of a wish, its stages and what the AI did, as one Markdown document. */
export class WishReports {
constructor(private store: Store) {}
async markdown(actor: Actor, wishId: string, exportedAt = new Date()) {
return this.store.read(actor.tenantId, async tx => {
const wish = await must<Wish>(tx, 'wish', wishId);
const project: Project = await projectAccess(tx, actor, wish.projectId);
const runs = (await tx.list<Run>('run', { projectId: wish.projectId }))
.filter(run => run.wishId === wishId)
.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
const records: RunRecord[] = [];
for (const run of runs)
records.push({
run,
events: await tx.events(run.id),
evidence: await tx.list<Evidence>('evidence', { runId: run.id }),
reviews: await tx.list<CodeReview>('code_review', { runId: run.id }),
releases: await tx.list<Release>('release', { runId: run.id }),
checkpoint: run.checkpointId ? await tx.get<CheckpointRecord>('checkpoint', run.checkpointId) : undefined,
});
const latest = runs.at(-1);
const goal = latest?.goal ?? wish.goal;
const criteria = latest?.acceptanceCriteria ?? wish.acceptanceCriteria;
const heading = goal.split('\n')[0]!.trim().slice(0, 80);
const document = [
`# 愿望报告:${heading}`,
table(
['项目', '内容'],
[
['项目', project.name],
['目标分支', project.targetBranch],
['愿望 ID', wish.id],
['提交时间', reportTime(wish.createdAt)],
['运行次数', runs.length],
['导出时间', reportTime(exportedAt.toISOString())],
['导出人', actor.displayName ?? actor.userId],
],
),
'时间均为北京时间(UTC+8)。Token 用量按计入预算的口径:输入、输出、缓存创建全额,缓存读取按 1/10。',
'## 愿望',
goal,
'### 验收标准',
criteria.map((criterion, i) => `${i + 1}. ${criterion}`).join('\n'),
...records.map((record, i) => runSection(i + 1, record)),
].join('\n\n');
const date = reportTime(exportedAt.toISOString()).slice(0, 10).replaceAll('-', '');
return { filename: `wish-${wish.id.slice(0, 8)}-${date}.md`, content: `${redact(document)}\n` };
});
}
}