✨ Add the grounded project Copilot API over the Wiki snapshot
This commit is contained in:
parent
e1194fbf8b
commit
ccd87cc23e
348
apps/api/src/domain/copilot.ts
Normal file
348
apps/api/src/domain/copilot.ts
Normal file
@ -0,0 +1,348 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import os from 'node:os';
|
||||
import { z } from 'zod';
|
||||
import { askClaude } from '@wishforge/runtime';
|
||||
import {
|
||||
DomainError,
|
||||
copilotMessageInput,
|
||||
copilotWishInput,
|
||||
isProduction,
|
||||
providerBaseUrl,
|
||||
withAnswers,
|
||||
type ProviderConnection,
|
||||
type Actor,
|
||||
type CopilotMessage,
|
||||
type CopilotQuestion,
|
||||
type CopilotSession,
|
||||
} from '@wishforge/contracts';
|
||||
import type { Transaction } from '../db/store.js';
|
||||
import { ControlPlane, must, projectAccess, record, touch } from './control-plane.js';
|
||||
import { nativeClaudeEnabled } from './local-execution.js';
|
||||
import { CredentialVault } from './connections.js';
|
||||
import { requireHuman } from './policy.js';
|
||||
import { ProjectWiki, wikiSources, type WikiFile, type WikiSnapshot } from './project-wiki.js';
|
||||
|
||||
const option = z.object({
|
||||
label: z.string().trim().min(1).max(40),
|
||||
wish: z.string().trim().min(1).max(500),
|
||||
acceptanceCriterion: z.string().trim().min(1).max(500).optional(),
|
||||
});
|
||||
const question = z.object({
|
||||
question: z.string().trim().min(1).max(300),
|
||||
sourcePath: z.string().trim().min(1).max(256),
|
||||
options: z.array(option).min(2).max(4),
|
||||
});
|
||||
const modelAnswer = z.object({
|
||||
kind: z.enum(['faq', 'bug', 'feature', 'unknown']),
|
||||
answer: z.string().trim().min(1).max(12000),
|
||||
goal: z.string().trim().max(20000).optional(),
|
||||
acceptanceCriteria: z.array(z.string().trim().min(1).max(2000)).max(30).default([]),
|
||||
reproductionSteps: z.array(z.string().trim().min(1).max(1000)).max(12).default([]),
|
||||
contextSummary: z.string().trim().max(4000).optional(),
|
||||
questions: z.array(question).max(3).default([]),
|
||||
});
|
||||
const responseSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
kind: { type: 'string', enum: ['faq', 'bug', 'feature', 'unknown'] },
|
||||
answer: { type: 'string' },
|
||||
goal: { type: 'string' },
|
||||
acceptanceCriteria: { type: 'array', items: { type: 'string' } },
|
||||
reproductionSteps: { type: 'array', items: { type: 'string' } },
|
||||
contextSummary: { type: 'string' },
|
||||
questions: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
question: { type: 'string' },
|
||||
sourcePath: { type: 'string' },
|
||||
options: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
label: { type: 'string' },
|
||||
wish: { type: 'string' },
|
||||
acceptanceCriterion: { type: 'string' },
|
||||
},
|
||||
required: ['label', 'wish'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['question', 'sourcePath', 'options'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['kind', 'answer'],
|
||||
additionalProperties: false,
|
||||
};
|
||||
const SYSTEM = `你是 WishForge 项目 Copilot。只能依据随请求提供的 Wiki 快照回答项目事实,不能使用模型记忆补充,也不能编造代码、配置或来源。
|
||||
将问题分为 faq(FAQ/配置问题)、bug(有实际异常或复现线索的疑似系统 Bug)、feature(需求或改进)、unknown(依据不足或不清楚)。
|
||||
FAQ 的答案必须能由给定页面直接支撑;否则选择 unknown 并明确说不知道。Bug 要给出 answer、reproductionSteps、contextSummary,以及可编辑的 goal 和 acceptanceCriteria,但不能声称已经确认是代码缺陷。
|
||||
Feature 要给出可编辑的 goal 和 acceptanceCriteria。只有 Wiki 能支撑且必须由用户拍板的问题才进入 questions;每个 question 的 sourcePath 必须逐字使用一个给定 Wiki 路径,选项包含加入 goal 的 wish,必要时包含 acceptanceCriterion。FAQ 和 unknown 的 questions 必须为空。
|
||||
所有文字使用中文,answer 简洁但直接。`;
|
||||
const terms = (value: string) => {
|
||||
const normalized = value.toLowerCase();
|
||||
const words = normalized.match(/[a-z0-9_.-]{2,}|[\u4e00-\u9fff]+/g) ?? [];
|
||||
const grams = words.flatMap(word =>
|
||||
/^[\u4e00-\u9fff]+$/.test(word)
|
||||
? [...word].map((_, i) => word.slice(i, i + 2)).filter(x => x.length === 2)
|
||||
: [word],
|
||||
);
|
||||
return new Set(grams);
|
||||
};
|
||||
function retrieve(snapshot: WikiSnapshot, query: string): WikiFile[] {
|
||||
const wanted = terms(query);
|
||||
const ranked = snapshot.files
|
||||
.map(file => {
|
||||
const haystack = `${file.path}\n${file.content}`.toLowerCase();
|
||||
const score = [...wanted].reduce((total, term) => total + (haystack.includes(term) ? 1 : 0), 0);
|
||||
return { file, score };
|
||||
})
|
||||
.sort((a, b) => b.score - a.score);
|
||||
const matches = ranked
|
||||
.filter(item => item.score > 0)
|
||||
.slice(0, 4)
|
||||
.map(item => item.file);
|
||||
const index = snapshot.files.find(file => file.path === 'wiki/index.md');
|
||||
return [
|
||||
...new Map(
|
||||
[...matches, ...(index && !matches.includes(index) ? [index] : [])].map(file => [file.path, file]),
|
||||
).values(),
|
||||
];
|
||||
}
|
||||
async function sessionAccess(tx: Transaction, actor: Actor, projectId: string, sessionId: string) {
|
||||
await projectAccess(tx, actor, projectId);
|
||||
const session = await must<CopilotSession>(tx, 'copilot_session', sessionId);
|
||||
if (session.projectId !== projectId || session.userId !== actor.userId)
|
||||
throw new DomainError('NOT_FOUND', 'Copilot session not found', 404);
|
||||
return session;
|
||||
}
|
||||
|
||||
export class Copilot {
|
||||
constructor(
|
||||
private control: ControlPlane,
|
||||
private env = process.env,
|
||||
private askModel = askClaude,
|
||||
private wiki: Pick<ProjectWiki, 'snapshot'> = new ProjectWiki(control.store, env),
|
||||
) {}
|
||||
private get store() {
|
||||
return this.control.store;
|
||||
}
|
||||
private async tenantConnection(actor: Actor) {
|
||||
if (isProduction(this.env) || !this.env.WF_CLAUDE_BIN) return undefined;
|
||||
return this.store.read(actor.tenantId, async tx =>
|
||||
(await tx.list<ProviderConnection>('provider_connection')).find(
|
||||
connection => connection.provider === 'claude-code' && connection.status === 'active' && connection.ciphertext,
|
||||
),
|
||||
);
|
||||
}
|
||||
async available(tenantId: string) {
|
||||
if (nativeClaudeEnabled(this.env, tenantId)) return true;
|
||||
if (isProduction(this.env) || !this.env.WF_CLAUDE_BIN) return false;
|
||||
return this.store.read(tenantId, async tx =>
|
||||
(await tx.list<ProviderConnection>('provider_connection')).some(
|
||||
connection => connection.provider === 'claude-code' && connection.status === 'active' && connection.ciphertext,
|
||||
),
|
||||
);
|
||||
}
|
||||
private async tenantCredentials(actor: Actor) {
|
||||
const connection = await this.tenantConnection(actor);
|
||||
if (!connection?.ciphertext) return undefined;
|
||||
const apiKey = await new CredentialVault(this.env).open(actor.tenantId, String(connection.ciphertext));
|
||||
const baseUrl = providerBaseUrl(this.env, 'claude-code');
|
||||
return { ANTHROPIC_API_KEY: apiKey, ...(baseUrl ? { ANTHROPIC_BASE_URL: baseUrl } : {}) };
|
||||
}
|
||||
async createSession(actor: Actor, projectId: string) {
|
||||
requireHuman(actor);
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
await projectAccess(tx, actor, projectId);
|
||||
const session = { ...record(actor.tenantId), projectId, userId: actor.userId, messages: [] } as CopilotSession;
|
||||
await tx.put('copilot_session', session);
|
||||
return session;
|
||||
});
|
||||
}
|
||||
async session(actor: Actor, projectId: string, sessionId: string) {
|
||||
requireHuman(actor);
|
||||
return this.store.transaction(actor.tenantId, async tx => {
|
||||
const session = await sessionAccess(tx, actor, projectId, sessionId);
|
||||
const interrupted = session.messages.some(
|
||||
message => message.status === 'pending' && Date.now() - Date.parse(message.createdAt) > 210_000,
|
||||
);
|
||||
if (!interrupted) return session;
|
||||
const next = {
|
||||
...touch(session),
|
||||
messages: session.messages.map(message =>
|
||||
message.status === 'pending' && Date.now() - Date.parse(message.createdAt) > 210_000
|
||||
? { ...message, status: 'error' as const, content: '上次回答因连接或服务中断而停止,请重新提问。' }
|
||||
: message,
|
||||
),
|
||||
};
|
||||
await tx.put('copilot_session', next);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
async ask(actor: Actor, projectId: string, sessionId: string, input: unknown) {
|
||||
requireHuman(actor);
|
||||
const data = copilotMessageInput.parse(input);
|
||||
if (!(await this.available(actor.tenantId)))
|
||||
throw new DomainError('COPILOT_UNAVAILABLE', 'The project Copilot model is not configured', 503);
|
||||
const pending = await this.store.transaction(actor.tenantId, async tx => {
|
||||
const session = await sessionAccess(tx, actor, projectId, sessionId);
|
||||
const existing = session.messages.find(message => message.role === 'user' && message.clientId === data.clientId);
|
||||
if (existing)
|
||||
return {
|
||||
session,
|
||||
assistantId: session.messages.find(message => message.id === existing.id.replace(':user', ':assistant'))?.id,
|
||||
};
|
||||
const userId = `${randomUUID()}:user`;
|
||||
const assistantId = `${randomUUID()}:assistant`;
|
||||
const time = new Date().toISOString();
|
||||
const user: CopilotMessage = {
|
||||
id: userId,
|
||||
role: 'user',
|
||||
content: data.content,
|
||||
clientId: data.clientId,
|
||||
status: 'complete',
|
||||
createdAt: time,
|
||||
};
|
||||
const assistant: CopilotMessage = {
|
||||
id: assistantId,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
status: 'pending',
|
||||
createdAt: time,
|
||||
};
|
||||
const next = { ...touch(session), messages: [...session.messages, user, assistant].slice(-100) };
|
||||
await tx.put('copilot_session', next);
|
||||
return { session: next, assistantId };
|
||||
});
|
||||
if (pending.session.messages.find(message => message.id === pending.assistantId)?.status !== 'pending')
|
||||
return pending.session;
|
||||
if (pending.session.messages.at(-1)?.id !== pending.assistantId) return pending.session;
|
||||
try {
|
||||
const snapshot = await this.wiki.snapshot(actor, projectId);
|
||||
const files = retrieve(snapshot, data.content);
|
||||
const sources = wikiSources(snapshot, files);
|
||||
const attempts = nativeClaudeEnabled(this.env, actor.tenantId) ? ['native', 'tenant'] : ['tenant'];
|
||||
let result: z.infer<typeof modelAnswer> | undefined;
|
||||
let failure: unknown;
|
||||
for (const attempt of attempts) {
|
||||
try {
|
||||
const credentialEnv = attempt === 'native' ? undefined : await this.tenantCredentials(actor);
|
||||
if (attempt === 'tenant' && !credentialEnv) continue;
|
||||
result = modelAnswer.parse(
|
||||
await this.askModel({
|
||||
binary: this.env.WF_CLAUDE_BIN!,
|
||||
home: this.env.WF_CLAUDE_LOCAL_AUTH_HOME || os.tmpdir(),
|
||||
system: SYSTEM,
|
||||
...(this.env.WF_CLAUDE_ASK_MODEL ? { model: this.env.WF_CLAUDE_ASK_MODEL } : {}),
|
||||
timeoutMs: attempt === 'tenant' ? 300_000 : 180_000,
|
||||
schema: responseSchema,
|
||||
credentialEnv,
|
||||
prompt: JSON.stringify({
|
||||
project: snapshot.project.name,
|
||||
question: data.content,
|
||||
currentContext: data.context,
|
||||
wikiVersion: snapshot.version,
|
||||
wiki: files.map(file => ({ path: file.path, content: file.content.slice(0, 16000) })),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
break;
|
||||
} catch (error) {
|
||||
failure = error;
|
||||
console.warn(`Copilot ${attempt} model failed: ${error instanceof Error ? error.message : 'unknown error'}`);
|
||||
}
|
||||
}
|
||||
if (!result) throw failure ?? new Error('No Copilot model credential is available');
|
||||
const kind = result.kind === 'faq' && files.length === 0 ? 'unknown' : result.kind;
|
||||
const allowedPaths = new Set(files.map(file => file.path));
|
||||
const questions: CopilotQuestion[] =
|
||||
kind === 'feature' ? result.questions.filter(item => allowedPaths.has(item.sourcePath)) : [];
|
||||
const content =
|
||||
kind === result.kind
|
||||
? result.answer
|
||||
: '当前 Wiki 没有足够依据回答这个问题。请补充上下文,或改成一个明确的需求。';
|
||||
return await this.store.transaction(actor.tenantId, async tx => {
|
||||
const session = await sessionAccess(tx, actor, projectId, sessionId);
|
||||
const messages = session.messages.map(message =>
|
||||
message.id === pending.assistantId
|
||||
? {
|
||||
...message,
|
||||
status: 'complete' as const,
|
||||
content,
|
||||
kind,
|
||||
sources: kind === 'unknown' ? [] : sources,
|
||||
knowledgeVersion: snapshot.version,
|
||||
...(result.goal
|
||||
? { goal: result.goal }
|
||||
: kind === 'bug' || kind === 'feature'
|
||||
? { goal: data.content }
|
||||
: {}),
|
||||
...(kind === 'bug' || kind === 'feature' ? { acceptanceCriteria: result.acceptanceCriteria } : {}),
|
||||
...(kind === 'bug'
|
||||
? { reproductionSteps: result.reproductionSteps, contextSummary: result.contextSummary }
|
||||
: {}),
|
||||
questions,
|
||||
}
|
||||
: message,
|
||||
);
|
||||
const next = { ...touch(session), messages };
|
||||
await tx.put('copilot_session', next);
|
||||
return next;
|
||||
});
|
||||
} catch (error) {
|
||||
await this.store.transaction(actor.tenantId, async tx => {
|
||||
const session = await sessionAccess(tx, actor, projectId, sessionId);
|
||||
const next = {
|
||||
...touch(session),
|
||||
messages: session.messages.map(message =>
|
||||
message.id === pending.assistantId
|
||||
? { ...message, status: 'error' as const, content: '本次回答未完成,请重试;你的问题已保留。' }
|
||||
: message,
|
||||
),
|
||||
};
|
||||
await tx.put('copilot_session', next);
|
||||
});
|
||||
if (error instanceof DomainError) throw error;
|
||||
throw new DomainError('COPILOT_FAILED', 'The Copilot could not produce a grounded answer', 502);
|
||||
}
|
||||
}
|
||||
async createWish(actor: Actor, projectId: string, sessionId: string, input: unknown) {
|
||||
requireHuman(actor);
|
||||
const data = copilotWishInput.parse(input);
|
||||
const session = await this.session(actor, projectId, sessionId);
|
||||
const message = session.messages.find(item => item.id === data.messageId && item.role === 'assistant');
|
||||
if (!message || message.status !== 'complete' || !['bug', 'feature'].includes(message.kind ?? ''))
|
||||
throw new DomainError('COPILOT_WISH_NOT_READY', 'Only a completed Bug or feature answer can become a Wish', 409);
|
||||
if (message.wish) return message.wish;
|
||||
const provider = (await this.control.providers(actor)).find(item => item.enabled);
|
||||
if (!provider)
|
||||
throw new DomainError('COPILOT_NO_PROVIDER', 'Configure an enabled executor before creating a Wish', 409);
|
||||
const created = await this.control.submit(
|
||||
actor,
|
||||
projectId,
|
||||
{
|
||||
goal: withAnswers(data.goal, data.answers),
|
||||
acceptanceCriteria: data.acceptanceCriteria,
|
||||
provider: provider.id,
|
||||
budget: { maxTokens: 300000, maxMinutes: 30, maxRepairRounds: 3 },
|
||||
},
|
||||
`copilot:${sessionId}:${message.id}`,
|
||||
);
|
||||
const wish = { wishId: created.wish_id, runId: created.run_id, url: `/runs/${created.run_id}` };
|
||||
await this.store.transaction(actor.tenantId, async tx => {
|
||||
const current = await sessionAccess(tx, actor, projectId, sessionId);
|
||||
const next = {
|
||||
...touch(current),
|
||||
messages: current.messages.map(item => (item.id === message.id ? { ...item, wish } : item)),
|
||||
};
|
||||
await tx.put('copilot_session', next);
|
||||
});
|
||||
return wish;
|
||||
}
|
||||
}
|
||||
101
apps/api/src/domain/project-wiki.ts
Normal file
101
apps/api/src/domain/project-wiki.ts
Normal file
@ -0,0 +1,101 @@
|
||||
import { DomainError, plainHttpAllowed, type Actor, type CopilotSource, type Project } from '@wishforge/contracts';
|
||||
import type { Store } from '../db/store.js';
|
||||
import { projectAccess } from './control-plane.js';
|
||||
import { requireHuman } from './policy.js';
|
||||
|
||||
export type WikiFile = { path: string; content: string };
|
||||
export type WikiSnapshot = { version: string; files: WikiFile[]; project: Project };
|
||||
|
||||
export function codeReferences(projectId: string, version: string, content: string) {
|
||||
const found = new Map<string, { path: string; line?: number; url: string }>();
|
||||
const pattern =
|
||||
/(?:^|[\s`(])((?:apps|packages|tests|infra|docs)\/[A-Za-z0-9._/-]+\.(?:tsx|ts|mjs|js|yaml|yml|json|md))(?::(\d+))?/g;
|
||||
for (const match of content.matchAll(pattern)) {
|
||||
const path = match[1]!;
|
||||
const line = match[2] ? Number(match[2]) : undefined;
|
||||
const query = new URLSearchParams({ path, version });
|
||||
found.set(`${path}:${line ?? ''}`, {
|
||||
path,
|
||||
...(line ? { line } : {}),
|
||||
url: `/projects/${projectId}/wiki?${query}`,
|
||||
});
|
||||
}
|
||||
return [...found.values()].slice(0, 12);
|
||||
}
|
||||
|
||||
export function wikiSources(snapshot: WikiSnapshot, files: WikiFile[]): CopilotSource[] {
|
||||
return files.map(file => ({
|
||||
path: file.path,
|
||||
title: file.content.match(/^#\s+(.+)$/m)?.[1]?.trim() ?? file.path,
|
||||
version: snapshot.version,
|
||||
url: `/projects/${snapshot.project.id}/wiki?${new URLSearchParams({ path: file.path, version: snapshot.version })}`,
|
||||
excerpt: file.content
|
||||
.replace(/[#*`|>\[\]]/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.slice(0, 240),
|
||||
references: codeReferences(snapshot.project.id, snapshot.version, file.content),
|
||||
}));
|
||||
}
|
||||
|
||||
export class ProjectWiki {
|
||||
constructor(
|
||||
private store: Store,
|
||||
private env = process.env,
|
||||
private fetcher: typeof fetch = fetch,
|
||||
) {}
|
||||
|
||||
private async project(actor: Actor, projectId: string) {
|
||||
requireHuman(actor);
|
||||
return this.store.read(actor.tenantId, tx => projectAccess(tx, actor, projectId));
|
||||
}
|
||||
|
||||
private async readRepository(project: Project, path?: string) {
|
||||
if (project.repositoryStorage !== 'platform' || project.repositoryStatus !== 'ready')
|
||||
throw new DomainError('WIKI_UNAVAILABLE', 'This project has no readable platform Wiki', 503);
|
||||
if (!this.env.WF_GIT_SERVICE_URL || !this.env.WF_GIT_ADMIN_TOKEN)
|
||||
throw new DomainError('WIKI_UNAVAILABLE', 'Wiki storage is not configured', 503);
|
||||
const base = new URL(this.env.WF_GIT_SERVICE_URL);
|
||||
if (base.protocol !== 'https:' && !plainHttpAllowed(this.env, base))
|
||||
throw new DomainError('INSECURE_GIT_STORAGE', 'Wiki storage requires HTTPS', 503);
|
||||
let response: Response;
|
||||
try {
|
||||
response = await this.fetcher(new URL('/wiki', base), {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${this.env.WF_GIT_ADMIN_TOKEN}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tenantId: project.tenantId, projectId: project.id, branch: project.targetBranch, path }),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
} catch {
|
||||
throw new DomainError('WIKI_UNAVAILABLE', 'The project Wiki cannot be read right now', 503);
|
||||
}
|
||||
if (!response.ok)
|
||||
throw new DomainError('WIKI_UNAVAILABLE', 'The project Wiki is missing or unreadable at this revision', 503);
|
||||
return response.json() as Promise<{ version: string; files?: WikiFile[]; file?: WikiFile }>;
|
||||
}
|
||||
|
||||
async snapshot(actor: Actor, projectId: string): Promise<WikiSnapshot> {
|
||||
const project = await this.project(actor, projectId);
|
||||
const result = await this.readRepository(project);
|
||||
return { project, version: result.version, files: result.files ?? [] };
|
||||
}
|
||||
|
||||
async source(actor: Actor, projectId: string, path: string, expectedVersion?: string) {
|
||||
const project = await this.project(actor, projectId);
|
||||
const result = await this.readRepository(project, path);
|
||||
if (expectedVersion && result.version !== expectedVersion)
|
||||
throw new DomainError(
|
||||
'WIKI_VERSION_CHANGED',
|
||||
'The Wiki changed; reload this source at the current revision',
|
||||
409,
|
||||
);
|
||||
if (!result.file) throw new DomainError('NOT_FOUND', 'Source not found', 404);
|
||||
return {
|
||||
project: { id: project.id, name: project.name },
|
||||
version: result.version,
|
||||
file: result.file,
|
||||
references: codeReferences(project.id, result.version, result.file.content),
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -53,6 +53,8 @@ import { permissionsOf } from './domain/permissions.js';
|
||||
import { WishRefiner } from './domain/wish-refiner.js';
|
||||
import { ModelCatalog } from './domain/model-catalog.js';
|
||||
import { notificationsConfigured } from './domain/notifications.js';
|
||||
import { Copilot } from './domain/copilot.js';
|
||||
import { ProjectWiki } from './domain/project-wiki.js';
|
||||
|
||||
export class Services {
|
||||
auth: Authenticator;
|
||||
@ -67,6 +69,8 @@ export class Services {
|
||||
accounts: LocalAccounts;
|
||||
refiner: WishRefiner;
|
||||
modelCatalog: ModelCatalog;
|
||||
copilot: Copilot;
|
||||
wiki: ProjectWiki;
|
||||
constructor(readonly control: ControlPlane) {
|
||||
this.auth = new Authenticator(control.store, control.env);
|
||||
this.releases = new Releases(control.store, control.env);
|
||||
@ -80,6 +84,8 @@ export class Services {
|
||||
this.accounts = new LocalAccounts(control.store, control.env);
|
||||
this.refiner = new WishRefiner(control.store, control.env);
|
||||
this.modelCatalog = new ModelCatalog(control.env);
|
||||
this.copilot = new Copilot(control, control.env);
|
||||
this.wiki = new ProjectWiki(control.store, control.env);
|
||||
}
|
||||
}
|
||||
type AuthRequest = Request & { actor: Actor };
|
||||
@ -206,9 +212,10 @@ export class ApiController {
|
||||
});
|
||||
}
|
||||
/** What this deployment offers, so the console shows only what works here. */
|
||||
@Get('capabilities') capabilities(@Req() req: AuthRequest) {
|
||||
@Get('capabilities') async capabilities(@Req() req: AuthRequest) {
|
||||
return ok({
|
||||
wishRefinement: this.s.refiner.available(req.actor.tenantId),
|
||||
copilot: await this.s.copilot.available(req.actor.tenantId),
|
||||
modelCatalog: this.s.modelCatalog.available(req.actor.tenantId),
|
||||
localAccounts: localAccountsEnabled(this.s.control.env),
|
||||
notifications: notificationsConfigured(this.s.control.env),
|
||||
@ -413,6 +420,40 @@ export class ApiController {
|
||||
) {
|
||||
return ok(await this.s.refiner.refine(r.actor, id, b));
|
||||
}
|
||||
@Post('projects/:id/copilot/sessions') async createCopilotSession(@Req() r: AuthRequest, @Param('id') id: string) {
|
||||
return ok(await this.s.copilot.createSession(r.actor, id));
|
||||
}
|
||||
@Get('projects/:id/copilot/sessions/:sessionId') async copilotSession(
|
||||
@Req() r: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Param('sessionId') sessionId: string,
|
||||
) {
|
||||
return ok(await this.s.copilot.session(r.actor, id, sessionId));
|
||||
}
|
||||
@Post('projects/:id/copilot/sessions/:sessionId/messages') @HttpCode(200) async copilotMessage(
|
||||
@Req() r: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Param('sessionId') sessionId: string,
|
||||
@Body() b: unknown,
|
||||
) {
|
||||
return ok(await this.s.copilot.ask(r.actor, id, sessionId, b));
|
||||
}
|
||||
@Post('projects/:id/copilot/sessions/:sessionId/wish') @HttpCode(202) async copilotWish(
|
||||
@Req() r: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Param('sessionId') sessionId: string,
|
||||
@Body() b: unknown,
|
||||
) {
|
||||
return ok(await this.s.copilot.createWish(r.actor, id, sessionId, b));
|
||||
}
|
||||
@Get('projects/:id/wiki') async wikiSource(
|
||||
@Req() r: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
@Query('path') path: string,
|
||||
@Query('version') version?: string,
|
||||
) {
|
||||
return ok(await this.s.wiki.source(r.actor, id, z.string().min(1).max(256).parse(path), version));
|
||||
}
|
||||
@Post('projects/:id/wishes') @HttpCode(202) async submit(
|
||||
@Req() r: AuthRequest,
|
||||
@Param('id') id: string,
|
||||
|
||||
57
packages/contracts/src/copilot.ts
Normal file
57
packages/contracts/src/copilot.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import { z } from 'zod';
|
||||
import type { Entity } from './index.js';
|
||||
|
||||
export type CopilotSource = {
|
||||
path: string;
|
||||
title: string;
|
||||
version: string;
|
||||
url: string;
|
||||
excerpt: string;
|
||||
references: { path: string; line?: number; url: string }[];
|
||||
};
|
||||
export type CopilotQuestion = {
|
||||
question: string;
|
||||
sourcePath: string;
|
||||
options: { label: string; wish: string; acceptanceCriterion?: string }[];
|
||||
};
|
||||
export type CopilotMessage = {
|
||||
id: string;
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
clientId?: string;
|
||||
status: 'complete' | 'pending' | 'error';
|
||||
createdAt: string;
|
||||
kind?: 'faq' | 'bug' | 'feature' | 'unknown';
|
||||
sources?: CopilotSource[];
|
||||
knowledgeVersion?: string;
|
||||
goal?: string;
|
||||
acceptanceCriteria?: string[];
|
||||
reproductionSteps?: string[];
|
||||
contextSummary?: string;
|
||||
questions?: CopilotQuestion[];
|
||||
wish?: { wishId: string; runId: string; url: string };
|
||||
};
|
||||
export interface CopilotSession extends Entity {
|
||||
projectId: string;
|
||||
userId: string;
|
||||
messages: CopilotMessage[];
|
||||
}
|
||||
|
||||
export const copilotMessageInput = z
|
||||
.object({
|
||||
content: z.string().trim().min(1).max(8000),
|
||||
clientId: z.string().trim().min(8).max(200),
|
||||
context: z
|
||||
.object({ pathname: z.string().max(1000).optional(), runId: z.string().max(200).optional() })
|
||||
.strict()
|
||||
.optional(),
|
||||
})
|
||||
.strict();
|
||||
export const copilotWishInput = z
|
||||
.object({
|
||||
messageId: z.string().min(1).max(200),
|
||||
goal: z.string().trim().min(8).max(20000),
|
||||
acceptanceCriteria: z.array(z.string().trim().min(1).max(2000)).min(1).max(30),
|
||||
answers: z.array(z.string().trim().min(1).max(1000)).max(12).default([]),
|
||||
})
|
||||
.strict();
|
||||
@ -1,4 +1,5 @@
|
||||
import { pocReleaseInput, type PocReleaseSet } from './poc-delivery.js';
|
||||
export * from './copilot.js';
|
||||
export {
|
||||
pocReleaseInput,
|
||||
pocTargetImage,
|
||||
@ -69,7 +70,8 @@ export type EntityKind =
|
||||
| 'local_account'
|
||||
| 'notification'
|
||||
| 'skill'
|
||||
| 'skill_harvest';
|
||||
| 'skill_harvest'
|
||||
| 'copilot_session';
|
||||
export interface Entity {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
|
||||
234
tests/copilot.test.ts
Normal file
234
tests/copilot.test.ts
Normal file
@ -0,0 +1,234 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import type { Actor, CopilotSession, Wish } from '@wishforge/contracts';
|
||||
import { ControlPlane } from '../apps/api/src/domain/control-plane.js';
|
||||
import { Copilot } from '../apps/api/src/domain/copilot.js';
|
||||
import { Connections } from '../apps/api/src/domain/connections.js';
|
||||
import { ProjectWiki } from '../apps/api/src/domain/project-wiki.js';
|
||||
import { ApiController, Services } from '../apps/api/src/http.js';
|
||||
import { MemoryStore } from './helpers/memory-store.js';
|
||||
|
||||
const owner: Actor = { tenantId: 'demo', userId: 'owner', role: 'owner', kind: 'human' };
|
||||
const env = {
|
||||
NODE_ENV: 'test',
|
||||
WF_DEPLOYMENT_MODE: 'development',
|
||||
WF_PROVISIONER_BACKEND: 'local',
|
||||
WF_TENANT_ID: 'demo',
|
||||
WF_CLAUDE_BIN: '/usr/local/bin/claude',
|
||||
WF_CLAUDE_LOCAL_AUTH_HOME: '/Users/operator',
|
||||
};
|
||||
let store: MemoryStore,
|
||||
control: ControlPlane,
|
||||
projectId: string,
|
||||
snapshot: Awaited<ReturnType<ControlPlane['createProject']>>;
|
||||
const files = [
|
||||
{ path: 'wiki/index.md', content: '# WishForge Wiki\n从模块地图找到代码入口。' },
|
||||
{
|
||||
path: 'wiki/features/wishes.md',
|
||||
content: '# 提交 Wish\n填写目标和验收标准。\n依据 `apps/web/src/features/runs.tsx:416`。',
|
||||
},
|
||||
];
|
||||
beforeEach(async () => {
|
||||
store = new MemoryStore();
|
||||
store.seed('demo');
|
||||
control = new ControlPlane(store, env);
|
||||
snapshot = await control.createProject(owner, { name: 'Pilot', repositoryUrl: 'https://example.org/pilot.git' });
|
||||
projectId = snapshot.id;
|
||||
});
|
||||
const wiki = {
|
||||
snapshot: async () => ({ project: snapshot, version: 'a'.repeat(40), files }),
|
||||
};
|
||||
const input = (content: string) => ({
|
||||
content,
|
||||
clientId: `client-${content.length}-abcdef`,
|
||||
context: { pathname: '/projects/demo' },
|
||||
});
|
||||
function copilot(answer: (question: string) => unknown) {
|
||||
return new Copilot(control, env, async request => answer(JSON.parse(request.prompt).question), wiki);
|
||||
}
|
||||
|
||||
describe('project Copilot API', () => {
|
||||
it('answers FAQ from a versioned Wiki without creating a Wish and recovers its session', async () => {
|
||||
const service = copilot(() => ({ kind: 'faq', answer: '填写目标和验收标准后提交。' }));
|
||||
const session = await service.createSession(owner, projectId);
|
||||
const answered = await service.ask(owner, projectId, session.id, input('如何提交 Wish?'));
|
||||
const assistant = answered.messages[1]!;
|
||||
expect(assistant).toMatchObject({ kind: 'faq', status: 'complete', knowledgeVersion: 'a'.repeat(40) });
|
||||
expect(assistant.sources?.[0]).toMatchObject({ path: 'wiki/features/wishes.md' });
|
||||
expect(assistant.sources?.[0].references[0]).toMatchObject({ path: 'apps/web/src/features/runs.tsx', line: 416 });
|
||||
expect((await service.session(owner, projectId, session.id)).messages).toHaveLength(2);
|
||||
expect(await store.read('demo', tx => tx.list<Wish>('wish'))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('turns only a confirmed Bug draft into a real Wish, idempotently', async () => {
|
||||
const service = copilot(() => ({
|
||||
kind: 'bug',
|
||||
answer: '这是一个疑似提交异常,需要进一步复现。',
|
||||
goal: '修复提交 Wish 时的异常。',
|
||||
acceptanceCriteria: ['重复提交不会丢失已填写内容'],
|
||||
reproductionSteps: ['打开提交页', '点击提交'],
|
||||
contextSummary: '当前位于项目页面。',
|
||||
}));
|
||||
const session = await service.createSession(owner, projectId);
|
||||
const answered = await service.ask(owner, projectId, session.id, input('提交时总是报错'));
|
||||
const message = answered.messages[1]!;
|
||||
expect(message).toMatchObject({ kind: 'bug', reproductionSteps: ['打开提交页', '点击提交'] });
|
||||
const draft = {
|
||||
messageId: message.id,
|
||||
goal: message.goal!,
|
||||
acceptanceCriteria: message.acceptanceCriteria!,
|
||||
answers: [],
|
||||
};
|
||||
const first = await service.createWish(owner, projectId, session.id, draft);
|
||||
const second = await service.createWish(owner, projectId, session.id, draft);
|
||||
expect(second).toEqual(first);
|
||||
expect(first.url).toBe(`/runs/${first.runId}`);
|
||||
expect(await store.read('demo', tx => tx.list<Wish>('wish'))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('puts Wiki-grounded Grill-me answers into the goal and acceptance criteria', async () => {
|
||||
const service = copilot(() => ({
|
||||
kind: 'feature',
|
||||
answer: '需求可以先明确导出范围。',
|
||||
goal: '为项目增加报告导出。\n不改:现有权限。',
|
||||
acceptanceCriteria: ['可以导出报告'],
|
||||
questions: [
|
||||
{
|
||||
question: '导出什么格式?',
|
||||
sourcePath: 'wiki/features/wishes.md',
|
||||
options: [
|
||||
{ label: 'Markdown', wish: '导出 Markdown。', acceptanceCriterion: '下载内容是 Markdown' },
|
||||
{ label: 'PDF', wish: '导出 PDF。', acceptanceCriterion: '下载内容是 PDF' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}));
|
||||
const session = await service.createSession(owner, projectId);
|
||||
const answered = await service.ask(owner, projectId, session.id, input('我要导出 Wish 报告'));
|
||||
const message = answered.messages[1]!;
|
||||
expect(message.questions?.[0].sourcePath).toBe('wiki/features/wishes.md');
|
||||
const created = await service.createWish(owner, projectId, session.id, {
|
||||
messageId: message.id,
|
||||
goal: message.goal!,
|
||||
acceptanceCriteria: [...message.acceptanceCriteria!, '下载内容是 Markdown'],
|
||||
answers: ['导出 Markdown。'],
|
||||
});
|
||||
const wish = await store.read('demo', tx => tx.get<Wish>('wish', created.wishId));
|
||||
expect(wish?.goal).toContain('导出 Markdown。');
|
||||
expect(wish?.goal.indexOf('导出 Markdown。')).toBeLessThan(wish?.goal.indexOf('不改:') ?? -1);
|
||||
expect(wish?.acceptanceCriteria).toContain('下载内容是 Markdown');
|
||||
});
|
||||
|
||||
it('falls back to the server-held tenant Claude credential in development', async () => {
|
||||
const secureEnv = { ...env, WF_VAULT_KEY: 'a'.repeat(64) };
|
||||
await new Connections(store, secureEnv).create(owner, {
|
||||
provider: 'claude-code',
|
||||
label: 'test',
|
||||
apiKey: 'tenant-fixture-key',
|
||||
});
|
||||
const credentials: (Record<string, string> | undefined)[] = [];
|
||||
const service = new Copilot(
|
||||
control,
|
||||
secureEnv,
|
||||
async request => {
|
||||
credentials.push(request.credentialEnv);
|
||||
if (!request.credentialEnv) throw new Error('native login disabled');
|
||||
return { kind: 'faq', answer: '由租户凭据完成的有源回答。' };
|
||||
},
|
||||
wiki,
|
||||
);
|
||||
const session = await service.createSession(owner, projectId);
|
||||
const answered = await service.ask(owner, projectId, session.id, input('如何提交 Wish'));
|
||||
expect(answered.messages[1]).toMatchObject({ status: 'complete', kind: 'faq' });
|
||||
expect(credentials).toHaveLength(2);
|
||||
expect(credentials[0]).toBeUndefined();
|
||||
expect(credentials[1]).toMatchObject({ ANTHROPIC_API_KEY: 'tenant-fixture-key' });
|
||||
const production = new Copilot(control, { ...secureEnv, WF_DEPLOYMENT_MODE: 'production' }, async () => ({}), wiki);
|
||||
expect(await production.available('demo')).toBe(false);
|
||||
});
|
||||
|
||||
it('admits unknown answers, rejects cross-user sessions and persists model failures', async () => {
|
||||
const unknown = copilot(() => ({
|
||||
kind: 'unknown',
|
||||
answer: '当前 Wiki 没有足够依据。',
|
||||
sources: [{ path: 'fake' }],
|
||||
}));
|
||||
const session = await unknown.createSession(owner, projectId);
|
||||
const answered = await unknown.ask(owner, projectId, session.id, input('火星环境怎么配置'));
|
||||
expect(answered.messages[1]).toMatchObject({ kind: 'unknown', sources: [] });
|
||||
const other: Actor = { ...owner, userId: 'other' };
|
||||
await expect(unknown.session(other, projectId, session.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
|
||||
const failing = new Copilot(
|
||||
control,
|
||||
env,
|
||||
async () => {
|
||||
throw new Error('model offline');
|
||||
},
|
||||
wiki,
|
||||
);
|
||||
const failedSession = await failing.createSession(owner, projectId);
|
||||
await expect(failing.ask(owner, projectId, failedSession.id, input('模型现在可用吗'))).rejects.toMatchObject({
|
||||
code: 'COPILOT_FAILED',
|
||||
});
|
||||
expect((await failing.session(owner, projectId, failedSession.id)).messages[1]).toMatchObject({ status: 'error' });
|
||||
const unavailable = new Copilot(control, { ...env, WF_DEPLOYMENT_MODE: 'production' }, async () => ({}), wiki);
|
||||
await expect(unavailable.createSession(owner, projectId)).resolves.toBeDefined();
|
||||
await expect(unavailable.ask(owner, projectId, session.id, input('还能回答吗'))).rejects.toMatchObject({
|
||||
code: 'COPILOT_UNAVAILABLE',
|
||||
});
|
||||
});
|
||||
|
||||
it('marks an orphaned pending answer as interrupted so a new question can be sent', async () => {
|
||||
const service = copilot(() => ({ kind: 'unknown', answer: '不知道' }));
|
||||
const created = await service.createSession(owner, projectId);
|
||||
await service.ask(owner, projectId, created.id, input('中断恢复'));
|
||||
await store.transaction('demo', async tx => {
|
||||
const current = (await tx.get<CopilotSession>('copilot_session', created.id))!;
|
||||
await tx.put('copilot_session', {
|
||||
...current,
|
||||
messages: current.messages.map(message =>
|
||||
message.role === 'assistant'
|
||||
? { ...message, status: 'pending', createdAt: new Date(Date.now() - 211_000).toISOString() }
|
||||
: message,
|
||||
),
|
||||
});
|
||||
});
|
||||
expect((await service.session(owner, projectId, created.id)).messages[1]).toMatchObject({
|
||||
status: 'error',
|
||||
content: expect.stringContaining('中断'),
|
||||
});
|
||||
});
|
||||
|
||||
it('exposes the recoverable session and Wiki version through the HTTP controller', async () => {
|
||||
const services = new Services(control);
|
||||
services.copilot = copilot(() => ({ kind: 'faq', answer: '从 Wiki 提交入口操作。' }));
|
||||
const api = new ApiController(services);
|
||||
const created = await api.createCopilotSession({ actor: owner } as never, projectId);
|
||||
const session = (created as { data: CopilotSession }).data;
|
||||
const answered = await api.copilotMessage({ actor: owner } as never, projectId, session.id, input('Wish 入口在哪'));
|
||||
expect((answered as { data: CopilotSession }).data.messages[1]).toMatchObject({
|
||||
kind: 'faq',
|
||||
knowledgeVersion: 'a'.repeat(40),
|
||||
});
|
||||
});
|
||||
|
||||
it('enforces project access and rejects a stale Wiki version at the source API', async () => {
|
||||
await store.transaction('demo', async tx => {
|
||||
await tx.put('project', { ...snapshot, repositoryStorage: 'platform', repositoryStatus: 'ready' });
|
||||
});
|
||||
const service = new ProjectWiki(
|
||||
store,
|
||||
{ ...env, WF_GIT_SERVICE_URL: 'https://git.example', WF_GIT_ADMIN_TOKEN: 'server-side-fixture' },
|
||||
async () =>
|
||||
new Response(JSON.stringify({ version: 'b'.repeat(40), file: { path: 'wiki/index.md', content: '# Wiki' } }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
await expect(service.source(owner, projectId, 'wiki/index.md', 'a'.repeat(40))).rejects.toMatchObject({
|
||||
code: 'WIKI_VERSION_CHANGED',
|
||||
status: 409,
|
||||
});
|
||||
const other: Actor = { ...owner, userId: 'other', role: 'viewer' };
|
||||
await expect(service.source(other, projectId, 'wiki/index.md')).rejects.toMatchObject({ code: 'NOT_FOUND' });
|
||||
});
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user