✨ Learn project skills from runs, and export a wish's report

- Skills: per-project know-how the platform proposes from each succeeded
  run (in the background, or on request from a run), people confirm,
  edit, disable, delete or write; active ones enter later prompts
- Export one skill as SKILL.md, or all as a zip with a directory per
  skill, as .claude/skills/ expects
- A wish's report: every run, its stage timeline, the agent's plan,
  replies, commands, changed files and model usage, the change, the
  checks, failures, reviews and releases, and the full event log, as
  Markdown, or laid out for printing to PDF

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
eust-w 2026-11-02 03:57:24 +08:00
parent d210875107
commit 4cffd71be8
24 changed files with 1856 additions and 3 deletions

View File

@ -52,6 +52,7 @@ import { providerProxyConfigured } from './provider-proxy.js';
import { assertVerificationProfile, verificationPolicyDigest } from './verification-policy.js';
import { IntegrationLeases } from './integration-lease.js';
import { captureLesson, projectLessons } from './lessons.js';
import { projectSkills } from './skills.js';
import { describeProviderEvent } from './provider-events.js';
import { backendDefined, personWishScope, requirePermission, wishScopeOf } from './permissions.js';
@ -1397,6 +1398,7 @@ export class ControlPlane {
connectionId: connection?.id ?? null,
bundleConfig: await resolveBundle(tx, run.bundleVersion),
lessons: await projectLessons(tx, run.projectId),
skills: await projectSkills(tx, run.projectId),
delivery: {
release,
verificationEvidenceId: current('verification'),

View File

@ -0,0 +1,423 @@
import { crc32 } from 'node:zlib';
import { z } from 'zod';
import { askClaude } from '@wishforge/runtime';
import { SKILL_LIMIT, type PromptSkill } from '@wishforge/agent';
import {
DomainError,
SKILL_CONTENT_LIMIT,
skillInput,
skillName,
skillUpdateInput,
type Actor,
type CodeReview,
type Project,
type Run,
type Skill,
type SkillHarvest,
} from '@wishforge/contracts';
import type { Store, Transaction } from '../db/store.js';
import { must, projectAccess, record, touch } from './control-plane.js';
import { nativeClaudeEnabled } from './local-execution.js';
import { wishScopeOf } from './permissions.js';
import { redact, requireHuman } from './policy.js';
const recentlyChanged = (a: Skill, b: Skill) => b.updatedAt.localeCompare(a.updatedAt);
/** Active skills of a project, most recently changed first, as they enter prompts. */
export async function projectSkills(tx: Transaction, projectId: string): Promise<PromptSkill[]> {
return (await tx.list<Skill>('skill', { projectId, status: 'active' }))
.sort(recentlyChanged)
.slice(0, SKILL_LIMIT)
.map(({ name, description, content }) => ({ name, description, content }));
}
/** A skill as Claude Code and other agents read it: SKILL.md with its name and purpose up front. */
export function skillMarkdown(skill: Pick<Skill, 'name' | 'description' | 'content'>) {
const description = skill.description.replace(/\s+/g, ' ').trim();
return `---\nname: ${skill.name}\ndescription: ${JSON.stringify(description)}\n---\n\n${skill.content.trim()}\n`;
}
/** A zip archive of text files, stored without compression: the format every system opens. */
export function zipFiles(files: { path: string; content: string }[], at = new Date()): Buffer {
const time = ((at.getHours() << 11) | (at.getMinutes() << 5) | (at.getSeconds() >> 1)) & 0xffff;
const date = (((at.getFullYear() - 1980) << 9) | ((at.getMonth() + 1) << 5) | at.getDate()) & 0xffff;
const locals: Buffer[] = [];
const centrals: Buffer[] = [];
let offset = 0;
for (const file of files) {
const name = Buffer.from(file.path, 'utf8');
const data = Buffer.from(file.content, 'utf8');
const checksum = crc32(data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0x0800, 6); // UTF-8 names
local.writeUInt16LE(0, 8);
local.writeUInt16LE(time, 10);
local.writeUInt16LE(date, 12);
local.writeUInt32LE(checksum, 14);
local.writeUInt32LE(data.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(name.length, 26);
local.writeUInt16LE(0, 28);
const central = Buffer.alloc(46);
central.writeUInt32LE(0x02014b50, 0);
central.writeUInt16LE(20, 4);
central.writeUInt16LE(20, 6);
central.writeUInt16LE(0x0800, 8);
central.writeUInt16LE(0, 10);
central.writeUInt16LE(time, 12);
central.writeUInt16LE(date, 14);
central.writeUInt32LE(checksum, 16);
central.writeUInt32LE(data.length, 20);
central.writeUInt32LE(data.length, 24);
central.writeUInt16LE(name.length, 28);
central.writeUInt32LE(offset, 42);
locals.push(local, name, data);
centrals.push(central, name);
offset += local.length + name.length + data.length;
}
const directory = Buffer.concat(centrals);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(files.length, 8);
end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(directory.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...locals, directory, end]);
}
export const HARVEST_RULES = `你是一名资深工程师,负责为一个软件项目沉淀"技能"(skill):以后在这个项目里做类似工作时,编码 Agent 可以直接照做的、可复用的做法。你会拿到一次已完成的工作记录(需求、验收标准、实现总结、改动的文件、遇到的失败和审核意见)以及项目里已有的技能。
1. 只提炼以后还会用到的、对这个项目具体有用的做法:例如这个项目里某类改动该改哪些地方、按什么步骤、要注意什么坑、怎么验证。不要把这一次的具体改动本身写成技能。
2. 通用常识(写测试、读代码、遵守代码风格之类)不算技能。已有技能已经覆盖的不要重复。没有值得沉淀的就返回空数组,这完全正常。
3. 最多返回 2 个。name 用小写英文单词和连字符,例如 lazy-load-page-css;description 用一两句话写"什么时候用它";content 用 Markdown 写做法:适用场景、步骤、注意事项、如何验证,具体到这个项目的目录、文件和命令,不超过 3000 字。
4. 只写工作记录里有依据的内容,不要编造文件、命令或结论。
5. 用和需求相同的语言写 description 和 content。`;
const proposal = z
.object({
name: skillName,
description: z.string().trim().min(1).max(500),
content: z.string().trim().min(1).max(8000),
})
.strip();
const harvestSchema = {
type: 'object',
properties: {
skills: {
type: 'array',
maxItems: 2,
description: '值得沉淀的技能,可以为空',
items: {
type: 'object',
properties: {
name: { type: 'string', description: '小写英文单词和连字符' },
description: { type: 'string', description: '什么时候用它,一两句话' },
content: { type: 'string', description: 'Markdown 写的做法:适用场景、步骤、注意事项、如何验证' },
},
required: ['name', 'description', 'content'],
additionalProperties: false,
},
},
},
required: ['skills'],
additionalProperties: false,
};
/** The changed files a run's agent reported, relative to its workspace. */
function changedFiles(events: { type: string; message: string }[]) {
const files = new Set<string>();
for (const event of events)
if (event.type === 'provider.file_change') {
const match = /^Changed (.+)$/.exec(event.message);
const file = match?.[1]?.replace(/^.*\/executor\/[^/]+\/[^/]+-a\d+\//, '');
if (file) files.add(file);
}
return [...files].slice(0, 100);
}
/** At most this many proposals are worked out at once on the deployment's Claude account. */
const CONCURRENCY = 1;
let running = 0;
/**
* A project's skills: proposed by the platform from finished runs, confirmed, edited, disabled,
* deleted and exported by the people who wish for the project.
*/
export class Skills {
constructor(
private store: Store,
private env = process.env,
private ask = askClaude,
) {}
async list(actor: Actor, projectId: string) {
return this.store.read(actor.tenantId, async tx => {
await projectAccess(tx, actor, projectId);
return (await tx.list<Skill>('skill', { projectId })).sort(recentlyChanged);
});
}
async create(actor: Actor, projectId: string, input: unknown) {
const data = skillInput.parse(input);
return this.store.transaction(actor.tenantId, async tx => {
const project = await projectAccess(tx, actor, projectId);
this.authorize(actor, project);
await this.uniqueName(tx, projectId, data.name);
const skill: Skill = {
...record(actor.tenantId),
projectId,
name: data.name,
description: redact(data.description),
content: redact(data.content),
status: 'active',
sourceRunIds: [],
createdBy: actor.userId,
};
await tx.put('skill', skill);
return skill;
});
}
/** Edits a skill; confirming a proposal is setting it active. */
async update(actor: Actor, id: string, input: unknown) {
const data = skillUpdateInput.parse(input);
return this.store.transaction(actor.tenantId, async tx => {
const skill = await must<Skill>(tx, 'skill', id);
this.authorize(actor, await projectAccess(tx, actor, skill.projectId));
if (data.name && data.name !== skill.name) await this.uniqueName(tx, skill.projectId, data.name, id);
const next: Skill = {
...touch(skill),
...(data.name ? { name: data.name } : {}),
...(data.description ? { description: redact(data.description) } : {}),
...(data.content ? { content: redact(data.content) } : {}),
...(data.status ? { status: data.status } : {}),
updatedBy: actor.userId,
};
await tx.put('skill', next);
return next;
});
}
async remove(actor: Actor, id: string) {
return this.store.transaction(actor.tenantId, async tx => {
const skill = await must<Skill>(tx, 'skill', id);
this.authorize(actor, await projectAccess(tx, actor, skill.projectId));
await tx.remove('skill', id);
return { deleted: true };
});
}
/** One skill as SKILL.md. */
async exportOne(actor: Actor, id: string) {
return this.store.read(actor.tenantId, async tx => {
const skill = await must<Skill>(tx, 'skill', id);
await projectAccess(tx, actor, skill.projectId);
return { filename: `${skill.name}.SKILL.md`, content: skillMarkdown(skill) };
});
}
/**
* The project's skills, proposals left out unless asked for, as a zip with a directory per skill
* holding its SKILL.md: what .claude/skills/ expects.
*/
async exportAll(actor: Actor, projectId: string, includeProposed = false) {
return this.store.read(actor.tenantId, async tx => {
const project = await projectAccess(tx, actor, projectId);
const skills = (await tx.list<Skill>('skill', { projectId }))
.filter(skill => skill.status === 'active' || (includeProposed && skill.status === 'proposed'))
.sort((a, b) => a.name.localeCompare(b.name));
if (!skills.length) throw new DomainError('NO_SKILLS', 'This project has no skills to export', 404);
const slug = project.name
.normalize('NFKD')
.replace(/[^A-Za-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.toLowerCase();
return {
filename: `${slug || 'project'}-skills.zip`,
content: zipFiles(skills.map(skill => ({ path: `${skill.name}/SKILL.md`, content: skillMarkdown(skill) }))),
};
});
}
available(tenantId: string) {
return nativeClaudeEnabled(this.env, tenantId);
}
/** A person asks for proposals from a finished run, even one looked at before. */
async suggest(actor: Actor, runId: string) {
const run = await this.store.read(actor.tenantId, async tx => {
const run = await must<Run>(tx, 'run', runId);
this.authorize(actor, await projectAccess(tx, actor, run.projectId));
return run;
});
if (!['succeeded', 'failed', 'canceled'].includes(run.status) && !run.implementationSummary)
throw new DomainError('RUN_NOT_FINISHED', 'Skills are learned from a run once its work is done', 409);
if (!this.available(actor.tenantId))
throw new DomainError(
'SKILLS_UNAVAILABLE',
'Learning skills needs the Claude CLI account of this deployment',
503,
);
if (running >= CONCURRENCY)
throw new DomainError('SKILLS_BUSY', 'Skills are being learned from another run; try again in a moment', 429);
return this.harvest(actor.tenantId, runId);
}
/**
* Looks for skills in one run and stores what it finds as proposals; records that it looked, so
* the background harvest does not ask again.
*/
async harvest(tenantId: string, runId: string): Promise<Skill[]> {
running++;
try {
const { run, project, events, reviews, existing } = await this.store.read(tenantId, async tx => {
const run = await must<Run>(tx, 'run', runId);
return {
run,
project: await must<Project>(tx, 'project', run.projectId),
events: await tx.events(runId),
reviews: await tx.list<CodeReview>('code_review', { runId }),
existing: await tx.list<Skill>('skill', { projectId: run.projectId }),
};
});
const work = {
project: project.name,
goal: run.goal,
acceptanceCriteria: run.acceptanceCriteria,
status: run.status,
implementationSummary: run.implementationSummary?.slice(0, 6000),
changedFiles: changedFiles(events),
failures: events
.filter(event => ['run.repair', 'run.scope', 'provider.failed'].includes(event.type))
.map(event => event.message.slice(0, 1500))
.slice(-5),
lastFailure: run.lastFailure
? { kind: run.lastFailure.kind, outputTail: run.lastFailure.outputTail.slice(-2000) }
: undefined,
reviewComments: reviews.flatMap(review => (review.comment ? [review.comment] : [])).slice(0, 5),
existingSkills: existing
.filter(skill => skill.status !== 'disabled')
.map(skill => ({ name: skill.name, description: skill.description, content: skill.content.slice(0, 1500) })),
};
const output = await this.ask({
binary: this.env.WF_CLAUDE_BIN!,
home: this.env.WF_CLAUDE_LOCAL_AUTH_HOME!,
system: HARVEST_RULES,
prompt: JSON.stringify(work, null, 2),
schema: harvestSchema,
timeoutMs: 180_000,
});
const proposals = z
.object({ skills: z.array(z.unknown()).default([]) })
.strip()
.parse(output)
.skills.flatMap(item => {
const parsed = proposal.safeParse(item);
return parsed.success ? [parsed.data] : [];
})
.slice(0, 2);
return await this.store.transaction(tenantId, async tx => {
const names = new Set((await tx.list<Skill>('skill', { projectId: run.projectId })).map(skill => skill.name));
const created: Skill[] = [];
for (const item of proposals) {
// A name the project uses already gets the next free number.
let name = item.name;
for (let n = 2; names.has(name); n++) name = `${item.name}-${n}`;
names.add(name);
const skill: Skill = {
...record(tenantId),
projectId: run.projectId,
name,
description: redact(item.description),
content: redact(item.content).slice(0, SKILL_CONTENT_LIMIT),
status: 'proposed',
sourceRunIds: [run.id],
createdBy: 'wishforge',
};
await tx.put('skill', skill);
created.push(skill);
}
await this.recordHarvest(tx, run, { status: 'done', skillIds: created.map(skill => skill.id) });
if (created.length)
await tx.event(
run.id,
'skill.proposed',
`Proposed ${created.length} project skill${created.length > 1 ? 's' : ''}: ${created.map(skill => skill.name).join(', ')}`,
{ skillIds: created.map(skill => skill.id) },
);
return created;
});
} catch (error) {
await this.store
.transaction(tenantId, async tx => {
const run = await tx.get<Run>('run', runId);
if (run)
await this.recordHarvest(tx, run, {
status: 'failed',
skillIds: [],
error: error instanceof Error ? error.message.slice(0, 500) : 'no answer',
});
})
.catch(() => undefined);
if (error instanceof DomainError) throw error;
throw new DomainError(
'SKILLS_FAILED',
`Learning skills failed: ${error instanceof Error ? error.message : 'no answer'}`,
502,
);
} finally {
running--;
}
}
private async recordHarvest(tx: Transaction, run: Run, result: Pick<SkillHarvest, 'status' | 'skillIds' | 'error'>) {
const previous = await tx.get<SkillHarvest>('skill_harvest', run.id);
const harvest: SkillHarvest = {
...(previous ? touch(previous) : { ...record(run.tenantId), id: run.id }),
runId: run.id,
projectId: run.projectId,
attempts: (previous?.attempts ?? 0) + 1,
...result,
};
if (!result.error) delete harvest.error;
await tx.put('skill_harvest', harvest);
}
/**
* Looks at the oldest succeeded run not looked at yet (or whose look failed fewer than three
* times) and returns its id; undefined when there is none.
*/
async harvestNext(tenantId: string): Promise<string | undefined> {
const next = await this.store.read(tenantId, async tx => {
const harvests = new Map((await tx.list<SkillHarvest>('skill_harvest')).map(item => [item.runId, item]));
return (await tx.list<Run>('run', { status: 'succeeded' })).reverse().find(run => {
const harvest = harvests.get(run.id);
return !harvest || (harvest.status === 'failed' && harvest.attempts < 3);
});
});
if (!next) return undefined;
await this.harvest(tenantId, next.id);
return next.id;
}
/**
* Every run that succeeded is looked at once, oldest first, one at a time; a failed look is tried
* again a few times. Runs only where the deployment's Claude account serves its tenant.
*/
startHarvesting(intervalMs = 60_000) {
const tenantId = this.env.WF_TENANT_ID;
if (!tenantId || !this.available(tenantId)) return () => undefined;
let busy = false;
const tick = async () => {
if (busy || running >= CONCURRENCY) return;
busy = true;
try {
await this.harvestNext(tenantId);
} catch (error) {
console.error(`[skills] ${error instanceof Error ? error.message : 'harvest failed'}`);
} finally {
busy = false;
}
};
const timer = setInterval(() => void tick(), intervalMs);
timer.unref();
return () => clearInterval(timer);
}
/** Whoever may wish for the project may shape the skills its later wishes follow. */
private authorize(actor: Actor, project: Project) {
requireHuman(actor);
if (wishScopeOf(actor, project) === 'none')
throw new DomainError('FORBIDDEN', 'Your account cannot change this project’s skills', 403);
}
private async uniqueName(tx: Transaction, projectId: string, name: string, except?: string) {
if ((await tx.list<Skill>('skill', { projectId })).some(skill => skill.name === name && skill.id !== except))
throw new DomainError('SKILL_NAME_TAKEN', `This project already has a skill named ${name}`, 409);
}
}

View File

@ -0,0 +1,354 @@
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';
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')
.map(event => workspacePath(event.message.replace(/^Changed /, ''))),
),
];
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` };
});
}
}

View File

@ -35,6 +35,8 @@ import { ControlPlane, must, projectAccess, record, touch } from './domain/contr
import { Releases } from './domain/releases.js';
import { AgentBundles } from './domain/agent-bundles.js';
import { Lessons } from './domain/lessons.js';
import { Skills } from './domain/skills.js';
import { WishReports } from './domain/wish-report.js';
import { Connections } from './domain/connections.js';
import { RunnerBroker } from './domain/runner-broker.js';
import { GitStorage } from './domain/git-storage.js';
@ -55,6 +57,8 @@ export class Services {
releases: Releases;
bundles: AgentBundles;
lessons: Lessons;
skills: Skills;
reports: WishReports;
connections: Connections;
runners: RunnerBroker;
github: GitHubIntegration;
@ -65,6 +69,8 @@ export class Services {
this.releases = new Releases(control.store, control.env);
this.bundles = new AgentBundles(control.store);
this.lessons = new Lessons(control.store);
this.skills = new Skills(control.store, control.env);
this.reports = new WishReports(control.store);
this.connections = new Connections(control.store, control.env);
this.runners = new RunnerBroker(control.store, this.releases, control.env);
this.github = new GitHubIntegration(control.store, control.env);
@ -347,6 +353,50 @@ export class ApiController {
@Delete('lessons/:id') async deleteLesson(@Req() r: AuthRequest, @Param('id') id: string) {
return ok(await this.s.lessons.remove(r.actor, id));
}
@Get('projects/:id/skills') async skills(@Req() r: AuthRequest, @Param('id') id: string) {
return ok(await this.s.skills.list(r.actor, id));
}
@Post('projects/:id/skills') async createSkill(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) {
return ok(await this.s.skills.create(r.actor, id, b));
}
/** Every active skill (and with ?proposed=1 the proposals) as a zip, one directory per skill. */
@Get('projects/:id/skills/export') async exportSkills(
@Req() r: AuthRequest,
@Res() res: Response,
@Param('id') id: string,
@Query('proposed') proposed?: string,
) {
const exported = await this.s.skills.exportAll(r.actor, id, proposed === '1');
res.type('application/zip').setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`);
res.send(exported.content);
}
@Patch('skills/:id') async updateSkill(@Req() r: AuthRequest, @Param('id') id: string, @Body() b: unknown) {
return ok(await this.s.skills.update(r.actor, id, b));
}
@Delete('skills/:id') async deleteSkill(@Req() r: AuthRequest, @Param('id') id: string) {
return ok(await this.s.skills.remove(r.actor, id));
}
@Get('skills/:id/export') async exportSkill(@Req() r: AuthRequest, @Res() res: Response, @Param('id') id: string) {
const exported = await this.s.skills.exportOne(r.actor, id);
res
.type('text/markdown; charset=utf-8')
.setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`);
res.send(exported.content);
}
@Post('runs/:id/skill-suggestions') @HttpCode(200) async suggestSkills(
@Req() r: AuthRequest,
@Param('id') id: string,
) {
return ok(await this.s.skills.suggest(r.actor, id));
}
/** Every run of a wish, its stages and the AI's work, as Markdown. */
@Get('wishes/:id/report') async wishReport(@Req() r: AuthRequest, @Res() res: Response, @Param('id') id: string) {
const report = await this.s.reports.markdown(r.actor, id);
res
.type('text/markdown; charset=utf-8')
.setHeader('Content-Disposition', `attachment; filename="${report.filename}"`);
res.send(report.content);
}
@Post('projects/:id/wish-refinements') @HttpCode(200) async refineWish(
@Req() r: AuthRequest,
@Param('id') id: string,

View File

@ -35,6 +35,8 @@ export async function bootstrap() {
const store = new PgStore(process.env.DATABASE_URL);
await store.assertSafeRole();
const service = new Services(new ControlPlane(store));
// Succeeded runs are looked at for skills worth keeping, one at a time, in the background.
service.skills.startHarvesting();
const telemetry = await observability();
@Module({
controllers: [ApiController, InternalController, WorkspaceLifecycleController, WorkspaceLaunchController],

View File

@ -66,6 +66,8 @@ async function proxy(request: NextRequest, context: Context) {
'Cache-Control': 'no-store',
'Content-Type': upstream.headers.get('content-type') ?? 'application/json',
});
const disposition = upstream.headers.get('content-disposition');
if (disposition) responseHeaders.set('Content-Disposition', disposition);
if (stream) {
responseHeaders.set('X-Accel-Buffering', 'no');
responseHeaders.set('Connection', 'keep-alive');

View File

@ -3033,3 +3033,170 @@ fieldset:disabled label {
.member-scopes {
font-size: 13px;
}
/* Project skills */
.skill-list {
list-style: none;
margin: 0;
padding: 0 23px 12px;
}
.skill-list li {
display: flex;
gap: 14px;
align-items: flex-start;
border-top: 1px solid var(--border);
padding: 14px 0;
}
.skill-list li > svg {
color: var(--teal);
margin-top: 3px;
flex: none;
}
.skill-list li.skill-proposed > svg {
color: var(--amber);
}
.skill-body {
flex: 1;
min-width: 0;
}
.skill-body p {
margin: 0 0 4px;
}
.skill-content {
margin-top: 8px;
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 4px 14px;
background: #fafbfd;
}
.text-button {
background: none;
border: 0;
padding: 0;
color: var(--teal);
cursor: pointer;
font: inherit;
font-size: 13px;
}
.text-button:hover {
text-decoration: underline;
}
/* Markdown written by WishForge: reports and skills */
.markdown {
line-height: 1.65;
overflow-wrap: anywhere;
}
.markdown h1 {
font-size: 24px;
margin: 0 0 16px;
}
.markdown h2 {
font-size: 19px;
margin: 28px 0 10px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.markdown h3 {
font-size: 16px;
margin: 20px 0 8px;
}
.markdown h4 {
font-size: 14px;
margin: 14px 0 6px;
}
.markdown p,
.markdown ul,
.markdown ol,
.markdown blockquote {
margin: 0 0 10px;
}
.markdown code {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.92em;
background: #f1f4f8;
border-radius: 4px;
padding: 0 4px;
}
.markdown pre.markdown-code {
background: #f6f8fa;
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 10px 12px;
overflow-x: auto;
white-space: pre-wrap;
font-size: 12.5px;
line-height: 1.5;
}
.markdown pre.markdown-code code {
background: none;
padding: 0;
}
.markdown-table {
overflow-x: auto;
margin: 0 0 12px;
}
.markdown table {
border-collapse: collapse;
width: 100%;
font-size: 13px;
}
.markdown th,
.markdown td {
border: 1px solid var(--border);
padding: 5px 8px;
text-align: left;
vertical-align: top;
}
.markdown th {
background: #f6f8fa;
}
.markdown blockquote {
border-left: 3px solid var(--border);
padding-left: 12px;
color: var(--muted);
}
/* A wish's report, for reading and printing to PDF */
.report-page {
max-width: 1000px;
margin: 0 auto;
padding: 20px 28px 60px;
}
.report-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
flex-wrap: wrap;
padding-bottom: 14px;
margin-bottom: 18px;
border-bottom: 1px solid var(--border);
}
@media print {
@page {
size: A4;
margin: 14mm 12mm;
}
.report-toolbar {
display: none;
}
.report-page {
max-width: none;
padding: 0;
}
.markdown pre.markdown-code,
.markdown tr,
.markdown h2,
.markdown h3 {
break-inside: avoid-page;
}
.markdown h2,
.markdown h3,
.markdown h4 {
break-after: avoid-page;
}
.markdown pre.markdown-code {
break-inside: auto;
}
}

View File

@ -0,0 +1,5 @@
import { WishReportView } from '@/features/wish-report';
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
return <WishReportView wishId={id} />;
}

View File

@ -23,6 +23,7 @@ import {
import { RunTable } from '@/components/run-table';
import { ProjectSettings } from './project-settings';
import { LessonsPanel } from './lessons';
import { SkillsPanel } from './skills';
import { browserId } from '@/lib/browser-id';
export function ProjectsView({ create = false }: { create?: boolean }) {
const { data, error, isLoading, mutate } = useResource<Project[]>('/projects');
@ -388,6 +389,7 @@ export function ProjectView({ id }: { id: string }) {
<RunTable runs={runs.data ?? []} projects={[project]} />
)}
</Panel>
<SkillsPanel projectId={id} />
<LessonsPanel projectId={id} />
{showSettings ? (
<ProjectSettings

View File

@ -8,11 +8,13 @@ import {
Check,
ChevronRight,
FileCheck2,
FileDown,
GitBranch,
LockOpen,
Pause,
Play,
Plus,
Printer,
RotateCcw,
Search,
Send,
@ -21,7 +23,7 @@ import {
Square,
X,
} from 'lucide-react';
import { formatTime, messageOf, mutateApi, safeUrl, shortId, useResource } from '@/lib/api';
import { downloadApi, formatTime, messageOf, mutateApi, safeUrl, shortId, useResource } from '@/lib/api';
import type {
CommandEvidence,
Evidence,
@ -797,6 +799,8 @@ export function RunDetailView({ id }: { id: string }) {
const [answer, setAnswer] = useState('');
const [confirmCancel, setConfirmCancel] = useState(false);
const [confirmScope, setConfirmScope] = useState(false);
const [skillNotice, setSkillNotice] = useState('');
const [exporting, setExporting] = useState('');
const run = runResource.data;
useEffect(() => {
if (!run || !['running', 'queued', 'waiting'].includes(run.status)) return;
@ -897,9 +901,65 @@ export function RunDetailView({ id }: { id: string }) {
撤销这次改动
</Button>
) : null}
<Button
variant="ghost"
busy={exporting === 'markdown'}
title="导出这个愿望所有运行的阶段和 AI 细节"
onClick={() => {
setExporting('markdown');
setError('');
downloadApi(`/wishes/${run.wishId}/report`, `wish-${run.wishId.slice(0, 8)}.md`)
.catch(failure => setError(messageOf(failure)))
.finally(() => setExporting(''));
}}
>
<FileDown size={14} />
导出 Markdown
</Button>
<Button
variant="ghost"
title="打开排版好的报告并打印,在打印窗口里选择「另存为 PDF」"
onClick={() => window.open(`/reports/wishes/${run.wishId}?print=1`, '_blank', 'noopener')}
>
<Printer size={14} />
导出 PDF
</Button>
{run.implementationSummary || terminal ? (
<Button
variant="ghost"
busy={exporting === 'skills'}
title="从这次运行提炼这个项目可复用的技能"
onClick={() => {
setExporting('skills');
setError('');
setSkillNotice('');
mutateApi<{ id: string }[]>(`/runs/${id}/skill-suggestions`, undefined)
.then(created =>
setSkillNotice(
created.length
? `提炼出 ${created.length} 条技能,已加入项目技能,等待确认。`
: '这次运行里没有值得沉淀的新技能。',
),
)
.catch(failure => setError(messageOf(failure)))
.finally(() => setExporting(''));
}}
>
<Sparkles size={14} />
提炼技能
</Button>
) : null}
</div>
}
/>
{skillNotice ? (
<Notice>
{skillNotice}{' '}
<Link className="text-link" href={`/projects/${run.projectId}`}>
去项目页查看
</Link>
</Notice>
) : null}
<div className="run-identification">
{/* While pausing the run still runs: the executor saves the work so far first. */}
<Status value={run.status === 'running' && run.pauseRequestedAt ? 'pausing' : run.status} />

View File

@ -0,0 +1,257 @@
'use client';
import Link from 'next/link';
import { useState } from 'react';
import { Check, Download, Pencil, Plus, Sparkles, Trash2 } from 'lucide-react';
import { downloadApi, formatTime, messageOf, mutateApi, useResource } from '@/lib/api';
import { Markdown } from '@/lib/markdown';
import type { Skill } from '@/lib/types';
import { Button, EmptyState, ErrorNotice, Field, FormError, Loading, Modal, Panel, Status } from '@/components/ui';
const STATUS: Record<Skill['status'], [string, string]> = {
proposed: ['waiting', '待确认'],
active: ['ready', '启用'],
disabled: ['disabled', '已停用'],
};
type Draft = Pick<Skill, 'name' | 'description' | 'content'>;
/**
* The project's skills: know-how the platform proposes from finished runs and people confirm,
* edit or write themselves. Active skills enter the prompts of the project's later wishes.
*/
export function SkillsPanel({ projectId }: { projectId: string }) {
const skills = useResource<Skill[]>(`/projects/${projectId}/skills`, 15000);
const [editing, setEditing] = useState<Skill | 'new'>();
const [open, setOpen] = useState<string>();
const [busy, setBusy] = useState('');
const [error, setError] = useState('');
async function run(key: string, action: () => Promise<unknown>) {
setBusy(key);
setError('');
try {
await action();
await skills.mutate();
return true;
} catch (failure) {
setError(messageOf(failure));
return false;
} finally {
setBusy('');
}
}
const proposed = skills.data?.filter(skill => skill.status === 'proposed').length ?? 0;
const exportable = skills.data?.some(skill => skill.status === 'active');
return (
<Panel
title="项目技能"
aside={
<div className="button-group">
<Button
variant="ghost"
disabled={!exportable}
busy={busy === 'export'}
onClick={() => void run('export', () => downloadApi(`/projects/${projectId}/skills/export`, 'skills.zip'))}
>
<Download size={15} />
导出全部
</Button>
<Button variant="ghost" onClick={() => setEditing('new')}>
<Plus size={15} />
新建技能
</Button>
</div>
}
>
<p className="panel-intro">
平台会从完成的运行里提炼这个项目可复用的做法,作为「待确认」的技能;确认后,之后的愿望都会参考启用中的技能(最近修改的
8 条)。可以编辑、停用、删除,或导出为 SKILL.md(全部导出为 zip,可直接放进 .claude/skills/)。
{proposed ? <strong> 有 {proposed} 条待确认。</strong> : null}
</p>
{skills.error ? (
<ErrorNotice error={skills.error} retry={() => void skills.mutate()} />
) : skills.isLoading ? (
<Loading />
) : skills.data?.length ? (
<ul className="skill-list">
{skills.data.map(skill => {
const [tone, label] = STATUS[skill.status];
return (
<li key={skill.id} className={skill.status === 'proposed' ? 'skill-proposed' : undefined}>
<Sparkles size={18} />
<div className="skill-body">
<p>
<strong>{skill.name}</strong> <Status value={tone} label={label} />
</p>
<p>{skill.description}</p>
<p className="muted text-small">
{skill.createdBy === 'wishforge' ? '平台提炼' : '手动添加'} · 更新于 {formatTime(skill.updatedAt)}
{skill.sourceRunIds.map(runId => (
<span key={runId}>
{' · '}
<Link className="text-link" href={`/runs/${runId}`}>
来源运行
</Link>
</span>
))}
</p>
<button
type="button"
className="text-button"
onClick={() => setOpen(open === skill.id ? undefined : skill.id)}
>
{open === skill.id ? '收起做法' : '查看做法'}
</button>
{open === skill.id ? (
<div className="markdown skill-content">
<Markdown source={skill.content} />
</div>
) : null}
</div>
<div className="button-group">
{skill.status === 'proposed' ? (
<Button
variant="secondary"
busy={busy === `confirm:${skill.id}`}
onClick={() =>
void run(`confirm:${skill.id}`, () =>
mutateApi(`/skills/${skill.id}`, { status: 'active' }, 'PATCH'),
)
}
>
<Check size={15} />
确认启用
</Button>
) : (
<Button
variant="ghost"
busy={busy === `status:${skill.id}`}
onClick={() =>
void run(`status:${skill.id}`, () =>
mutateApi(
`/skills/${skill.id}`,
{ status: skill.status === 'active' ? 'disabled' : 'active' },
'PATCH',
),
)
}
>
{skill.status === 'active' ? '停用' : '启用'}
</Button>
)}
<Button variant="ghost" aria-label="编辑这个技能" onClick={() => setEditing(skill)}>
<Pencil size={15} />
</Button>
<Button
variant="ghost"
aria-label="导出 SKILL.md"
busy={busy === `export:${skill.id}`}
onClick={() =>
void run(`export:${skill.id}`, () =>
downloadApi(`/skills/${skill.id}/export`, `${skill.name}.SKILL.md`),
)
}
>
<Download size={15} />
</Button>
<Button
variant="ghost"
aria-label="删除这个技能"
busy={busy === `delete:${skill.id}`}
onClick={() => {
if (window.confirm(`删除技能「${skill.name}」?`))
void run(`delete:${skill.id}`, () => mutateApi(`/skills/${skill.id}`, undefined, 'DELETE'));
}}
>
<Trash2 size={15} />
</Button>
</div>
</li>
);
})}
</ul>
) : (
<EmptyState
compact
title="还没有项目技能"
description="运行成功后,平台会自动提炼值得沉淀的做法;也可以在运行页点「提炼技能」,或在这里新建。"
/>
)}
{!editing ? <FormError message={error} /> : null}
{editing ? (
<SkillEditor
skill={editing === 'new' ? undefined : editing}
busy={busy === 'save'}
error={error}
onClose={() => {
setEditing(undefined);
setError('');
}}
onSave={draft =>
void run('save', () =>
editing === 'new'
? mutateApi(`/projects/${projectId}/skills`, draft)
: mutateApi(`/skills/${editing.id}`, draft, 'PATCH'),
).then(saved => {
if (saved) setEditing(undefined);
})
}
/>
) : null}
</Panel>
);
}
function SkillEditor({
skill,
busy,
error,
onClose,
onSave,
}: {
skill?: Skill;
busy: boolean;
error: string;
onClose: () => void;
onSave: (draft: Draft) => void;
}) {
const [draft, setDraft] = useState<Draft>({
name: skill?.name ?? '',
description: skill?.description ?? '',
content: skill?.content ?? '',
});
const set = (field: keyof Draft) => (event: { target: { value: string } }) =>
setDraft(previous => ({ ...previous, [field]: event.target.value }));
return (
<Modal
title={skill ? `编辑技能 ${skill.name}` : '新建技能'}
description="写清什么时候用、怎么做。启用中的技能会进入这个项目之后每个愿望的提示词。"
onClose={onClose}
>
<form
className="form-stack"
onSubmit={event => {
event.preventDefault();
onSave({ name: draft.name.trim(), description: draft.description.trim(), content: draft.content.trim() });
}}
>
<Field label="名称" hint="小写英文单词和连字符,例如 lazy-load-page-css;导出时作为目录名。">
<input required maxLength={64} pattern="[a-z0-9]+(-[a-z0-9]+)*" value={draft.name} onChange={set('name')} />
</Field>
<Field label="什么时候用" hint="一两句话,最多 500 字。">
<textarea required maxLength={500} rows={2} value={draft.description} onChange={set('description')} />
</Field>
<Field label="做法(Markdown)" hint="适用场景、步骤、注意事项、如何验证,最多 2 万字。">
<textarea required maxLength={20000} rows={14} value={draft.content} onChange={set('content')} />
</Field>
<FormError message={error} />
<div className="modal-actions">
<Button type="button" variant="secondary" onClick={onClose}>
取消
</Button>
<Button busy={busy} disabled={!draft.name.trim() || !draft.description.trim() || !draft.content.trim()}>
保存
</Button>
</div>
</form>
</Modal>
);
}

View File

@ -0,0 +1,70 @@
'use client';
import { useEffect, useState } from 'react';
import { Download, Printer } from 'lucide-react';
import { apiText, downloadApi, messageOf } from '@/lib/api';
import { Markdown } from '@/lib/markdown';
import { Button, FormError, Loading } from '@/components/ui';
/**
* A wish's report laid out for reading and printing: the browser's print dialog saves it as a
* PDF. Opened with ?print=1 it asks to print once the report is shown.
*/
export function WishReportView({ wishId }: { wishId: string }) {
const [report, setReport] = useState<string>();
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
let active = true;
apiText(`/wishes/${wishId}/report`).then(
text => active && setReport(text),
failure => active && setError(messageOf(failure)),
);
return () => {
active = false;
};
}, [wishId]);
useEffect(() => {
if (!report || new URLSearchParams(window.location.search).get('print') !== '1') return;
const title = report.match(/^# (.*)$/m)?.[1];
if (title) document.title = title;
// Printing waits for the layout, so the dialog shows the whole report.
const timer = setTimeout(() => window.print(), 300);
return () => clearTimeout(timer);
}, [report]);
async function download() {
setBusy(true);
setError('');
try {
await downloadApi(`/wishes/${wishId}/report`, `wish-${wishId.slice(0, 8)}.md`);
} catch (failure) {
setError(messageOf(failure));
} finally {
setBusy(false);
}
}
return (
<div className="report-page">
<div className="report-toolbar">
<span className="muted">愿望报告 · 在打印窗口里选择「另存为 PDF」即可保存为 PDF</span>
<div className="button-group">
<Button variant="secondary" busy={busy} onClick={() => void download()}>
<Download size={15} />
下载 Markdown
</Button>
<Button disabled={!report} onClick={() => window.print()}>
<Printer size={15} />
打印 / 另存为 PDF
</Button>
</div>
</div>
<FormError message={error} />
{report ? (
<article className="markdown report">
<Markdown source={report} />
</article>
) : error ? null : (
<Loading />
)}
</div>
);
}

View File

@ -80,3 +80,32 @@ export function safeUrl(value?: string) {
export function formatNumber(value?: number) {
return value === undefined ? '—' : new Intl.NumberFormat('zh-CN').format(value);
}
/** What a failed export said, or why it failed. */
async function failure(response: Response) {
const payload = await response.json().catch(() => null);
return new ApiError(
payload?.error?.code ?? 'REQUEST_FAILED',
payload?.error?.message ?? `请求失败 (${response.status})`,
response.status,
payload?.error?.details,
);
}
/** Text the control plane serves as a file, such as a Markdown report. */
export async function apiText(path: string): Promise<string> {
const response = await fetch(`/api${path}`, { cache: 'no-store', credentials: 'same-origin' });
if (!response.ok) throw await failure(response);
return response.text();
}
/** Saves a file the control plane serves (an export) under `filename`. */
export async function downloadApi(path: string, filename: string) {
const response = await fetch(`/api${path}`, { cache: 'no-store', credentials: 'same-origin' });
if (!response.ok) throw await failure(response);
const url = URL.createObjectURL(await response.blob());
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.append(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}

View File

@ -0,0 +1,34 @@
import { describe, expect, it } from 'vitest';
import { createElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { Markdown } from './markdown';
const html = (source: string) => renderToStaticMarkup(createElement(Markdown, { source }));
describe('the Markdown WishForge writes', () => {
it('renders headings, tables, lists, code and inline marks', () => {
const out = html(
[
'# 报告',
'| 项目 | 内容 |',
'| --- | --- |',
'| a \\| b | `x` |',
'',
'1. one',
'2. **two**',
'',
'````diff',
'+```',
'````',
].join('\n'),
);
expect(out).toContain('<h1>报告</h1>');
expect(out).toContain('<td>a | b</td><td><code>x</code></td>');
expect(out).toContain('<ol><li>one</li><li><strong>two</strong></li></ol>');
expect(out).toContain('<pre class="markdown-code language-diff"><code>+```</code></pre>');
});
it('never treats text as HTML, and does not stall on a stray pipe', () => {
expect(html('<img src=x onerror=alert(1)>')).toBe('<p>&lt;img src=x onerror=alert(1)&gt;</p>');
expect(html('| not a table\nnext')).toBe('<p>| not a table<br/>next</p>');
});
});

View File

@ -0,0 +1,144 @@
import { Fragment, type ReactNode } from 'react';
/**
* Renders the Markdown WishForge writes itself (wish reports, skills): headings, paragraphs,
* lists, tables, fenced code and quotes, with **bold** and `code` inline. Text is never treated
* as HTML.
*/
export function Markdown({ source }: { source: string }) {
return <>{blocks(source.replace(/\r\n/g, '\n').split('\n'))}</>;
}
function inline(text: string): ReactNode[] {
const parts: ReactNode[] = [];
const pattern = /(`+)([\s\S]*?)\1|\*\*([^*]+)\*\*/g;
let last = 0;
for (const match of text.matchAll(pattern)) {
if (match.index! > last) parts.push(text.slice(last, match.index));
parts.push(
match[2] !== undefined ? (
<code key={match.index}>{match[2]}</code>
) : (
<strong key={match.index}>{match[3]}</strong>
),
);
last = match.index! + match[0].length;
}
if (last < text.length) parts.push(text.slice(last));
return parts;
}
const cells = (line: string) =>
line
.trim()
.replace(/^\||\|$/g, '')
.split(/(?<!\\)\|/)
.map(cell => cell.trim().replace(/\\\|/g, '|'));
function blocks(lines: string[]): ReactNode[] {
const out: ReactNode[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i]!;
const key = out.length;
const fence = /^(`{3,})(\S*)\s*$/.exec(line);
if (fence) {
const body: string[] = [];
i++;
while (i < lines.length && lines[i] !== fence[1]) body.push(lines[i++]!);
i++;
out.push(
<pre key={key} className={fence[2] ? `markdown-code language-${fence[2]}` : 'markdown-code'}>
<code>{body.join('\n')}</code>
</pre>,
);
continue;
}
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
if (heading) {
const Tag = `h${heading[1]!.length}` as 'h1';
out.push(<Tag key={key}>{inline(heading[2]!)}</Tag>);
i++;
continue;
}
if (line.trim().startsWith('|') && /^\s*\|?\s*-{3,}/.test(lines[i + 1] ?? '')) {
const head = cells(line);
const rows: string[][] = [];
i += 2;
while (i < lines.length && lines[i]!.trim().startsWith('|')) rows.push(cells(lines[i++]!));
out.push(
<div key={key} className="markdown-table">
<table>
<thead>
<tr>
{head.map((cell, n) => (
<th key={n}>{inline(cell)}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, r) => (
<tr key={r}>
{row.map((cell, n) => (
<td key={n}>{inline(cell)}</td>
))}
</tr>
))}
</tbody>
</table>
</div>,
);
continue;
}
const item = /^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(line);
if (item) {
const ordered = /\d/.test(item[2]!);
const items: string[] = [];
while (i < lines.length) {
const next = /^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(lines[i]!);
if (!next || /\d/.test(next[2]!) !== ordered) break;
items.push(next[3]!);
i++;
}
const List = ordered ? 'ol' : 'ul';
out.push(
<List key={key}>
{items.map((text, n) => (
<li key={n}>{inline(text)}</li>
))}
</List>,
);
continue;
}
if (line.startsWith('>')) {
const quoted: string[] = [];
while (i < lines.length && lines[i]!.startsWith('>')) quoted.push(lines[i++]!.replace(/^>\s?/, ''));
out.push(<blockquote key={key}>{blocks(quoted)}</blockquote>);
continue;
}
if (!line.trim() || /^---+\s*$/.test(line)) {
i++;
continue;
}
// A paragraph takes at least its first line, so a stray "|" cannot stop the rendering.
const paragraph: string[] = [line];
i++;
while (
i < lines.length &&
lines[i]!.trim() &&
!/^(`{3,}|#{1,6}\s|>|\s*([-*]|\d+\.)\s)/.test(lines[i]!) &&
!lines[i]!.trim().startsWith('|')
)
paragraph.push(lines[i++]!);
out.push(
<p key={key}>
{paragraph.map((text, n) => (
<Fragment key={n}>
{n ? <br /> : null}
{inline(text)}
</Fragment>
))}
</p>,
);
}
return out;
}

View File

@ -292,3 +292,17 @@ export type CodeReview = {
/** The run started from this branch; its commits merge too. */
sourceBranch?: string;
};
export type Skill = {
id: string;
projectId: string;
name: string;
description: string;
content: string;
/** `proposed`: suggested by the platform from a run, waiting for a person. */
status: 'proposed' | 'active' | 'disabled';
sourceRunIds: string[];
createdBy: string;
updatedBy?: string;
createdAt: string;
updatedAt: string;
};

View File

@ -1,6 +1,6 @@
import path from 'node:path';
import type { Project, ProviderId, Run, VerificationProfile, WaitingReason } from '@wishforge/contracts';
import type { AgentBundleConfig } from '@wishforge/agent';
import type { AgentBundleConfig, PromptSkill } from '@wishforge/agent';
import {
GitWorkspace,
readLocalPocBindings,
@ -50,6 +50,8 @@ export interface RunContext {
verificationProfileRequired?: boolean;
bundleConfig?: AgentBundleConfig;
lessons?: string[];
/** The project's active skills, most recently changed first. */
skills?: PromptSkill[];
delivery?: {
release?: { id: string; status: string };
verificationEvidenceId?: string;

View File

@ -343,6 +343,7 @@ export async function executeRun(config: WorkerConfig, input: RunInput): Promise
repairCount: run.repairCount,
lastFailure,
lessons: context.lessons,
skills: context.skills,
sourceBranch: run.sourceBranch,
...(revert ? { revert } : {}),
...(run.frontendOnly && context.project.codeReview?.paths.length

View File

@ -10,6 +10,16 @@ const QUESTION_MAX_LENGTH = 300;
export const LESSON_LIMIT = 5;
export const LESSON_CHARS = 4096;
export const LESSON_MAX_LENGTH = 1000;
/** At most this many skills, and this many characters of them, enter a prompt. */
export const SKILL_LIMIT = 8;
export const SKILL_CHARS = 16000;
/** A project skill as a prompt carries it. */
export interface PromptSkill {
name: string;
description: string;
content: string;
}
export interface PromptInput {
goal: string;
@ -19,6 +29,8 @@ export interface PromptInput {
lastFailure?: FailureSummary;
/** Active project lessons, most recent first. */
lessons?: string[];
/** Active project skills, most recently changed first. */
skills?: PromptSkill[];
/** The branch the workspace started from instead of the target branch. */
sourceBranch?: string;
/**
@ -45,6 +57,26 @@ export function selectLessons(summaries: string[]): string[] {
return chosen;
}
/** Keeps the most recently changed skills that fit the count and size limits. */
export function selectSkills(skills: PromptSkill[]): PromptSkill[] {
const chosen: PromptSkill[] = [];
let used = 0;
for (const skill of skills.slice(0, SKILL_LIMIT)) {
const size = skill.name.length + skill.description.length + skill.content.length;
if (used + size > SKILL_CHARS) continue;
chosen.push(skill);
used += size;
}
return chosen;
}
function skillsSection(skills: PromptSkill[]) {
return [
'Skills confirmed for this project: reusable know-how from earlier work. Follow a skill when the requirement matches what it is for; ignore the others.',
...skills.map(skill => `### ${skill.name}\nFor: ${skill.description}\n\n${skill.content}`),
].join('\n\n');
}
/** Which files a frontend-only wish must leave alone, and what to do when that is not enough. */
function frontendOnlySection(scope: NonNullable<PromptInput['frontendOnly']>, mayAsk: boolean) {
return [
@ -104,6 +136,7 @@ export function bundlePrompt(config: AgentBundleConfig, input: PromptInput) {
.filter(Boolean)
.join('\n\n');
const lessons = selectLessons(input.lessons ?? []);
const skills = selectSkills(input.skills ?? []);
return [
instructions,
input.goal,
@ -111,6 +144,7 @@ export function bundlePrompt(config: AgentBundleConfig, input: PromptInput) {
lessons.length
? `Lessons from earlier work on this project (apply them when relevant):\n${lessons.map(lesson => `- ${lesson}`).join('\n')}`
: '',
skills.length ? skillsSection(skills) : '',
input.sourceBranch
? `The workspace starts from branch ${input.sourceBranch}, which holds changes people made themselves (for example in the IDE). Keep those changes and build on them; this run verifies and merges them into the target branch together with your work.`
: '',

View File

@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';
import { BASELINE_BUNDLE, SKILL_CHARS, SKILL_LIMIT, bundlePrompt, selectSkills } from '../src/index.js';
const skill = (name: string, size = 10) => ({ name, description: 'when', content: 'x'.repeat(size) });
describe('project skills in a prompt', () => {
it('carries the confirmed skills, most recently changed first, within the count and size limits', () => {
expect(selectSkills(Array.from({ length: SKILL_LIMIT + 3 }, (_, i) => skill(`s${i}`)))).toHaveLength(SKILL_LIMIT);
const big = skill('big', SKILL_CHARS);
// One too large to fit is left out; smaller ones after it still fit.
expect(selectSkills([skill('a'), big, skill('b')]).map(item => item.name)).toEqual(['a', 'b']);
});
it('tells the agent to follow a skill only where the requirement matches it', () => {
const prompt = bundlePrompt(BASELINE_BUNDLE, {
goal: 'Make the greeting say hello world',
acceptanceCriteria: ['check passes'],
repairCount: 0,
skills: [{ name: 'greeting-check', description: 'When changing greeting.txt', content: 'Run node check.mjs.' }],
});
expect(prompt).toContain('Follow a skill when the requirement matches what it is for');
expect(prompt).toContain('### greeting-check\nFor: When changing greeting.txt\n\nRun node check.mjs.');
expect(bundlePrompt(BASELINE_BUNDLE, { goal: 'g', acceptanceCriteria: ['c'], repairCount: 0 })).not.toContain(
'Skills confirmed',
);
});
});

View File

@ -66,7 +66,9 @@ export type EntityKind =
| 'entitlement_event'
| 'code_review'
| 'local_account'
| 'notification';
| 'notification'
| 'skill'
| 'skill_harvest';
export interface Entity {
id: string;
tenantId: string;
@ -262,6 +264,36 @@ export interface FailureSummary {
targetCommit?: string;
}
/** Knowledge reused by later runs of the same project (docs/requirements.md FR-I2). */
/**
* Know-how a project's later wishes can reuse: when it applies and how to do it. The platform
* proposes skills from finished runs; people confirm, edit and export them. Active skills enter
* the prompts of the project's later runs.
*/
export interface Skill extends Entity {
projectId: string;
/** Lowercase words joined by hyphens, unique within the project; the directory name on export. */
name: string;
/** When to use it, in one or two sentences. */
description: string;
/** How to do it, in Markdown. */
content: string;
/** `proposed`: suggested by the platform, waiting for a person; only `active` skills are used. */
status: 'proposed' | 'active' | 'disabled';
/** The runs it was learned from. */
sourceRunIds: string[];
/** `wishforge` for proposals, else the person who wrote it. */
createdBy: string;
updatedBy?: string;
}
/** Whether the platform has looked for skills in a finished run; its id is the run's. */
export interface SkillHarvest extends Entity {
runId: string;
projectId: string;
status: 'done' | 'failed';
attempts: number;
skillIds: string[];
error?: string;
}
export interface Lesson extends Entity {
projectId: string;
kind: 'repair' | 'convention';
@ -465,6 +497,24 @@ export const projectInput = z
})
.strict();
export const lessonInput = z.object({ summary: text.max(1000) }).strict();
export const skillName = z
.string()
.trim()
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, 'Use lowercase letters and digits joined by hyphens, such as lazy-load-page-css')
.max(64);
export const SKILL_CONTENT_LIMIT = 20000;
export const skillInput = z
.object({ name: skillName, description: text.max(500), content: text.max(SKILL_CONTENT_LIMIT) })
.strict();
export const skillUpdateInput = z
.object({
name: skillName.optional(),
description: text.max(500).optional(),
content: text.max(SKILL_CONTENT_LIMIT).optional(),
status: z.enum(['active', 'disabled']).optional(),
})
.strict()
.refine(value => Object.values(value).some(field => field !== undefined), 'Change at least one field');
/** A model name as an executor or gateway spells it, such as `deepseek-pro@latest[1m]` or `gpt-5.4`. */
export const modelName = z
.string()

View File

@ -38,6 +38,8 @@ export const PROJECT_KINDS = [
'code_review',
'lesson',
'bundle',
'skill',
'skill_harvest',
];
/** Where the containers keep POC state; a rehearsal of this script names another directory. */
const POC_STATE = process.env.WF_CLUSTER_POC_STATE ?? '/var/lib/wishforge/poc-state';

View File

@ -30,6 +30,8 @@ import {
import { executeCommand, type CommandExecutor, type HostCheckSandbox, type ProviderStart } from '@wishforge/runtime';
import { ManagedProvider } from '../packages/runtime/src/providers/base.js';
import { ControlPlane } from '../apps/api/src/domain/control-plane.js';
import { Skills } from '../apps/api/src/domain/skills.js';
import { WishReports } from '../apps/api/src/domain/wish-report.js';
import { Services } from '../apps/api/src/http.js';
import { ServiceTokens } from '../apps/api/src/service-tokens.js';
import { recordAllocation, reserveExecutionGrant } from '../apps/api/src/domain/entitlements.js';
@ -457,6 +459,107 @@ describe('local main loop', () => {
expect(existsSync(`${workspace}.recovery.json`)).toBe(true);
});
it('learns project skills from a succeeded run, uses the confirmed ones and reports the wish', async () => {
const project = await createProject();
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-skills-0001');
let round = 0;
const session = await provision(runId, async start => {
round++;
if (round === 1) return writeGreeting('hello wrld', 'Updated the greeting.')(start);
return writeGreeting('hello world', 'Fixed the typo in greeting.txt so it reads "hello world".')(start);
});
expect(await drive(session)).toEqual({ status: 'complete' });
await release(runId, session.generation);
// The background harvest looks at the run once; the model proposes two skills, one named
// like a skill the project has.
const asked: string[] = [];
const skills = new Skills(store, { ...env, WF_TENANT_ID: TENANT }, async input => {
asked.push(input.prompt);
return {
skills: [
{
name: 'greeting-check',
description: 'When changing greeting.txt',
content: '1. Edit greeting.txt.\n2. Run `node check.mjs`.',
},
{ name: 'Not A Name', description: 'x', content: 'y' },
],
};
});
await skills.create(owner, project.id, {
name: 'greeting-check',
description: 'An older skill',
content: 'Keep greetings lowercase.',
});
expect(await skills.harvestNext(TENANT)).toBe(runId);
expect(await skills.harvestNext(TENANT)).toBeUndefined();
expect(JSON.parse(asked[0]!)).toMatchObject({
goal: 'Make the greeting say hello world',
changedFiles: ['greeting.txt'],
existingSkills: [{ name: 'greeting-check' }],
});
const listed = await skills.list(owner, project.id);
const proposed = listed.find(skill => skill.status === 'proposed')!;
expect(listed).toHaveLength(2);
expect(proposed).toMatchObject({ name: 'greeting-check-2', createdBy: 'wishforge', sourceRunIds: [runId] });
expect((await services.control.events(owner, runId)).map(event => event.type)).toContain('skill.proposed');
// Someone who may not wish for the project may not shape its skills; anyone who may can.
const viewer = await person(project.id, 'li', { wish: 'none', manage: false, releases: false, reviewCode: false });
await expect(skills.update(viewer, proposed.id, { status: 'active' })).rejects.toMatchObject({ code: 'FORBIDDEN' });
const frontend = await person(project.id, 'wang', 'frontend');
await skills.update(frontend, proposed.id, {
status: 'active',
content: 'Edit greeting.txt, then run node check.mjs.',
});
await expect(skills.update(owner, proposed.id, { name: 'greeting-check' })).rejects.toMatchObject({
code: 'SKILL_NAME_TAKEN',
});
// The confirmed skills reach the next run's prompt.
const next = await submit(project.id, 'Make the greeting say hello world again', 'wish-skills-0002');
let prompt = '';
const second = await provision(next, async start => {
prompt = start.prompt;
return writeGreeting('hello world', 'Nothing to change.')(start);
});
await second.executor.executeRun(second.input);
expect(prompt).toContain('### greeting-check-2');
expect(prompt).toContain('Edit greeting.txt, then run node check.mjs.');
expect(prompt).toContain('### greeting-check');
// Exports: one SKILL.md, or a zip with a directory per active skill.
const one = await skills.exportOne(owner, proposed.id);
expect(one.content).toMatch(/^---\nname: greeting-check-2\ndescription: "When changing greeting.txt"\n---\n\nEdit/);
const zip = await skills.exportAll(owner, project.id);
expect(zip.content.subarray(0, 4).toString('hex')).toBe('504b0304');
const unzipped = path.join(root, 'skills.zip');
await writeFile(unzipped, zip.content);
const listing = await run('unzip', ['-Z1', unzipped]).then(result => result.stdout.trim().split('\n'));
expect(listing.sort()).toEqual(['greeting-check-2/SKILL.md', 'greeting-check/SKILL.md']);
expect((await run('unzip', ['-p', unzipped, 'greeting-check-2/SKILL.md'])).stdout).toBe(one.content);
// The wish's report carries every stage, the agent's work, the change and the checks.
const report = await new WishReports(store).markdown(owner, (await services.control.run(owner, runId)).wishId);
expect(report.filename).toMatch(/^wish-[0-9a-f]{8}-\d{8}\.md$/);
for (const part of [
'# 愿望报告:Make the greeting say hello world',
'### 验收标准',
'### 阶段时间线',
'#### Agent 的回复',
'Fixed the typo in greeting.txt',
'#### Agent 改动的文件',
'### 代码改动',
'+hello world',
'### 验证证据',
'验证 · 通过',
'### 失败与修复',
'### 完整事件日志',
])
expect(report.content, part).toContain(part);
});
it('repairs a failed check with the verifier output, integrates the change and learns from it', async () => {
const project = await createProject();
const runId = await submit(project.id, 'Make the greeting say hello world', 'wish-repair-0001');

20
tests/wish-report.test.ts Normal file
View File

@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest';
import { fenced, nested, reportTime } from '../apps/api/src/domain/wish-report.js';
describe('a wish report', () => {
it('places the agent’s own Markdown under the report’s heading, leaving its code alone', () => {
const summary = ['## 定位到的问题', '正文', '### 细节', '```md', '## 代码里的标题', '```'].join('\n');
expect(nested(summary)).toBe(
['#### 定位到的问题', '正文', '##### 细节', '```md', '## 代码里的标题', '```'].join('\n'),
);
expect(nested('没有标题')).toBe('没有标题');
expect(nested('###### 最深\n#### 较浅')).toBe('###### 最深\n#### 较浅');
});
it('fences text so its own backticks cannot close the block', () => {
expect(fenced('a ``` b', 'text')).toBe('````text\na ``` b\n````');
});
it('writes times in Beijing time', () => {
expect(reportTime('2026-11-01T19:20:00.000Z')).toBe('2026-11-02 03:20:00');
expect(reportTime(undefined)).toBe('—');
});
});