From 8f38636930ef9595b7bce8d3c6b614275dc62cf6 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:01:47 +0800 Subject: [PATCH 1/3] Show checked native-team evidence in the workbench proof map --- apps/web/agentActions.ts | 132 ++++++++++-- apps/web/client/proofMap.css | 6 + apps/web/client/proofMapModel.ts | 126 ++++++++++-- apps/web/client/solveProcess.ts | 58 ++++-- apps/web/client/ui/AgentRoute.tsx | 12 +- apps/web/client/ui/LiveWorkspace.tsx | 27 ++- apps/web/client/ui/ProofMap.tsx | 80 +++++++- apps/web/client/ui/ThinkingProcess.tsx | 3 +- apps/web/collaboration.ts | 23 +++ apps/web/nativeTeamObservation.ts | 190 ++++++++++++++++++ apps/web/runner.ts | 3 + apps/web/shared.ts | 12 +- apps/web/worker.ts | 11 +- apps/web/workerBridge.ts | 17 +- scripts/mathematics/checkLean.ts | 7 + scripts/test-web-proof-map.ts | 170 +++++++++++++--- .../references/parallel-work.md | 8 + .../references/team-roles.md | 10 + src/solver/agentTeam.ts | 2 +- src/solver/agentTeamEvidenceRef.ts | 14 ++ src/solver/agentTeamNative.ts | 12 +- src/solver/agentTeamProof.ts | 19 +- src/solver/agentTeamState.ts | 3 +- src/solver/agentTeamViews.ts | 5 +- tests/agentTeamNativeLifecycle.test.ts | 66 ++++++ tests/agentTeamSolver.test.ts | 2 +- tests/webAgentActions.test.ts | 48 ++++- 27 files changed, 946 insertions(+), 120 deletions(-) create mode 100644 apps/web/nativeTeamObservation.ts create mode 100644 src/solver/agentTeamEvidenceRef.ts diff --git a/apps/web/agentActions.ts b/apps/web/agentActions.ts index 72a07b99..e2473418 100644 --- a/apps/web/agentActions.ts +++ b/apps/web/agentActions.ts @@ -1,6 +1,11 @@ import path from 'node:path'; -import { webAgentActionKinds, webAgentActionLimits as limits, type WebAgentActionBody, type WebAgentActionIntent, type WebAgentFileChange, - type WebAgentLeanCheck, type WebAgentLeanSearch, type WebAgentLibraryAction, type WebAgentLibraryDeclaration } from './shared'; +import { assertMathCanonicalPath, repositoryRelativePath } from '../../src/math/paths'; +import { mathDigest, readMathFile, readMathText } from '../../src/math/mathRuntimeIo'; +import { currentWorkerProject } from '../../src/solver/workerProject'; +import { teamEvidenceRefSchema } from '../../src/solver/agentTeamEvidenceRef'; +import { webAgentActionKinds, webAgentActionLimits as limits, webLeanClassifications, type WebAgentActionBody, + type WebAgentActionIntent, type WebAgentFileChange, type WebAgentLeanCheck, type WebLeanMessage, + type WebAgentLeanSearch, type WebAgentLibraryAction, type WebAgentLibraryDeclaration } from './shared'; type Item = Record; export type AgentActionContext = { @@ -10,6 +15,7 @@ export type AgentActionContext = { hidden: readonly string[]; /** The Agent commands' file; `bun '' check-lean` reads `math check-lean`. */ tool?: string; apiKey?: string; + solverRunId?: string; }; const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&'); @@ -63,21 +69,85 @@ function lastJson(output: string): Item | undefined { const line = output.trimEnd().split('\n').reverse().find(value => value.startsWith('{')); try { return line ? object(JSON.parse(line)) : undefined; } catch { return; } } +const digest = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{64}$/u.test(value); +const classification = (value: unknown) => webLeanClassifications.find(item => item === value); + export function sanitizeAgentLeanCheck(result: Item, mask: (value: string) => string): WebAgentLeanCheck | undefined { - if (typeof result.timedOut !== 'boolean' || !Array.isArray(result.messages)) return; - const all = result.messages.flatMap((value): WebAgentLeanCheck['messages'] => { - const message = object(value), severity = string(message?.severity), text = string(message?.message); - if (!message || !text || (severity !== 'error' && severity !== 'warning' && severity !== 'info')) return []; - const file = string(message.file), line = count(message.line), column = count(message.column); - return [{ severity, ...(file ? { file: clip(mask(file), 1_000).text } : {}), ...(line !== undefined ? { line } : {}), - ...(column !== undefined ? { column } : {}), text: clip(mask(text).trim(), limits.leanMessage).text }]; + const classified = classification(result.classification); + if (typeof result.timedOut !== 'boolean' || !Array.isArray(result.messages) && !classified) return; + const messageView = (value: unknown): WebLeanMessage | undefined => { + const message = object(value), severity = message?.severity, text = string(message?.message); + if (!message || !text || (severity !== 'error' && severity !== 'warning' && severity !== 'info')) return; + const file = string(message.file), line = count(message.line), column = count(message.column), goalText = string(message.goalText); + return { severity, ...(file ? { file: clip(mask(file), 1_000).text } : {}), ...(line !== undefined ? { line } : {}), + ...(column !== undefined ? { column } : {}), text: clip(mask(text).trim(), limits.leanMessage).text, + ...(goalText && { goalText: clip(mask(goalText), limits.leanMessage).text }) }; + }; + const all = (Array.isArray(result.messages) ? result.messages : []).flatMap(value => { + const message = messageView(value); + return message ? [message] : []; }); + const error = object(result.error); + if (!all.length && error) { + const message = messageView({ ...error, severity: 'error' }); + if (message) all.push(message); + } + const firstBlocking = messageView(result.firstBlocking); // Errors first: a reader wants what blocks the proof before its warnings. const ordered = [...all.filter(message => message.severity === 'error'), ...all.filter(message => message.severity !== 'error')]; const messages = ordered.slice(0, limits.leanMessages); + const artifacts = (Array.isArray(result.diagnosticArtifacts) ? result.diagnosticArtifacts : []).flatMap(value => { + const ref = object(value), file = string(ref?.path); + if (!ref || !file || !repositoryRelativePath(file) || !file.startsWith('.lake/') || file.length > 1_000 || + !digest(ref.digest) || !digest(ref.sourceDigest) || !digest(ref.environmentDigest)) return []; + return [{ path: file, digest: ref.digest, sourceDigest: ref.sourceDigest, environmentDigest: ref.environmentDigest }]; + }).slice(-limits.leanArtifacts); const omitted = all.length - messages.length + (count(result.omittedMessages) ?? 0); return { passed: result.exitCode === 0 && !result.timedOut, ...(result.timedOut ? { timedOut: true } : {}), messages, - ...(omitted ? { omittedMessages: omitted } : {}) }; + ...(omitted ? { omittedMessages: omitted } : {}), ...(firstBlocking && { firstBlocking }), + ...(classified && { classification: classified }), ...(digest(result.sourceDigest) && { sourceDigest: result.sourceDigest }), + ...(digest(result.environmentDigest) && { environmentDigest: result.environmentDigest }), + ...(artifacts.length && { artifacts }) }; +} + +/** Copy a bounded source only while its exact bytes still match the saved diagnostic artifact. */ +function checkedLeanSource(lean: WebAgentLeanCheck, result: Item, context: AgentActionContext, + mask: (value: string) => string): WebAgentLeanCheck['checkedSource'] { + if (!lean.artifacts?.length || !lean.sourceDigest || !lean.environmentDigest || + lean.classification !== 'lean' && lean.classification !== 'success') return; + try { + const project = currentWorkerProject(context.worktree); + const projectPrefix = mask(project).replace(/\/$/u, '') + '/'; + const localPath = (file?: string) => file?.startsWith(projectPrefix) + ? file.slice(projectPrefix.length) : file?.replace(/^\.\//u, ''); + const blocking = localPath(lean.firstBlocking?.file); + for (const ref of lean.artifacts.toReversed()) { + if (ref.sourceDigest !== lean.sourceDigest || ref.environmentDigest !== lean.environmentDigest) continue; + const artifact = path.join(project, ref.path); + assertMathCanonicalPath(artifact); + const text = readMathText(artifact, 10 * 1024 * 1024); + if (mathDigest(text) !== ref.digest) continue; + const record = object(JSON.parse(text)), file = string(record?.file); + if (!record || record.schema !== 'theoremos.lean-diagnostics.v1' || record.sourceCurrent !== true || + record.sourceDigest !== lean.sourceDigest || record.environmentDigest !== lean.environmentDigest || + record.exitCode !== result.exitCode || !file || !file.endsWith('.lean') || !repositoryRelativePath(file) || + blocking && blocking !== file) continue; + const suffix = '.lake/diagnostic-artifacts/' + ref.digest + '.json'; + if (!ref.path.endsWith(suffix)) continue; + const root = path.join(project, ref.path.slice(0, -suffix.length)); + const identity = Array.isArray(record.sourceFiles) && record.sourceFiles.map(object).find(source => source?.file === file); + if (!identity || !digest(identity.digest)) continue; + const absolute = path.join(root, file); + assertMathCanonicalPath(absolute); + const bytes = readMathFile(absolute, limits.leanSource).bytes; + if (mathDigest(bytes) !== identity.digest) continue; + const source = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); + if (mask(source) !== source) continue; + for (const message of [...lean.messages, ...(lean.firstBlocking ? [lean.firstBlocking] : [])]) + if (localPath(message.file) === file) message.file = file; + return { file, digest: identity.digest, text: source, artifact: ref.digest }; + } + } catch { /* The diagnostic remains readable when the source is gone, moved or changed. */ } } function leanSearch(result: Item, mask: (value: string) => string): WebAgentLeanSearch | undefined { const queries = Array.isArray(result.queries) ? result.queries : string(result.query) !== undefined ? [result] : undefined; @@ -159,6 +229,14 @@ export function sanitizeAgentItem(phase: 'started' | 'completed', item: Item, co const masked = (value: string) => mask(value).text; const library = result ? libraryAction(result, command.text, masked) : undefined; const lean = result && !library && /\bcheck-lean\b/u.test(command.text) ? sanitizeAgentLeanCheck(result, masked) : undefined; + if (lean && result) { + const source = checkedLeanSource(lean, result, context, masked); + if (source) lean.checkedSource = source; + const work = object(result.candidate), candidate = teamEvidenceRefSchema.safeParse(work?.ref); + // Only a saved source and its check can substantiate a trial, including a Lean failure. + if (lean.checkedSource && work?.file === lean.checkedSource.file && context.solverRunId && candidate.success && raw.includes(candidate.data)) + lean.candidate = { ref: candidate.data, solverRunId: context.solverRunId }; + } const found = result && !library && !lean && /\bsearch-lean\b/u.test(command.text) ? leanSearch(result, masked) : undefined; const withheld = !library && !lean && !found && (command.hidden || output.hidden || outsideCwd); const shownCommand = clip(command.text.replace(/\b([a-f0-9]{12})[a-f0-9]{52}\b/gu, '$1…'), limits.command); @@ -232,12 +310,36 @@ const only = (item: Item, allowed: readonly string[]) => Object.keys(item).every export function isWebAgentLeanCheck(value: unknown): value is WebAgentLeanCheck { const lean = object(value); - return !!lean && only(lean, ['passed', 'timedOut', 'messages', 'omittedMessages']) && typeof lean.passed === 'boolean' && flag(lean.timedOut) && - integer(lean.omittedMessages) && Array.isArray(lean.messages) && lean.messages.length <= limits.leanMessages && lean.messages.every(entry => { + const diagnostic = (entry: unknown) => { const message = object(entry); - return !!message && only(message, ['severity', 'file', 'line', 'column', 'text']) && ['error', 'warning', 'info'].includes(message.severity as string) && - short(message.file, 1_000) && integer(message.line) && integer(message.column) && typeof message.text === 'string' && short(message.text, limits.leanMessage); - }); + return !!message && only(message, ['severity', 'file', 'line', 'column', 'text', 'goalText']) && + ['error', 'warning', 'info'].includes(message.severity as string) && short(message.file, 1_000) && + integer(message.line) && integer(message.column) && typeof message.text === 'string' && + short(message.text, limits.leanMessage) && short(message.goalText, limits.leanMessage); + }; + if (!lean || !only(lean, ['passed', 'timedOut', 'messages', 'omittedMessages', 'firstBlocking', 'classification', + 'sourceDigest', 'environmentDigest', 'artifacts', 'checkedSource', 'candidate']) || typeof lean.passed !== 'boolean' || + !flag(lean.timedOut) || !integer(lean.omittedMessages) || + lean.classification !== undefined && !classification(lean.classification) || + lean.firstBlocking !== undefined && !diagnostic(lean.firstBlocking) || + lean.sourceDigest !== undefined && !digest(lean.sourceDigest) || lean.environmentDigest !== undefined && !digest(lean.environmentDigest) || + !Array.isArray(lean.messages) || lean.messages.length > limits.leanMessages || !lean.messages.every(diagnostic)) return false; + if (lean.artifacts !== undefined && (!Array.isArray(lean.artifacts) || lean.artifacts.length > limits.leanArtifacts || + !lean.artifacts.every(value => { + const ref = object(value); + return ref && only(ref, ['path', 'digest', 'sourceDigest', 'environmentDigest']) && typeof ref.path === 'string' && + short(ref.path, 1_000) && repositoryRelativePath(ref.path) && digest(ref.digest) && digest(ref.sourceDigest) && digest(ref.environmentDigest); + }))) return false; + const checked = object(lean.checkedSource); + if (lean.checkedSource !== undefined && (!checked || !only(checked, ['file', 'digest', 'text', 'artifact']) || + typeof checked.file !== 'string' || !short(checked.file, 1_000) || !repositoryRelativePath(checked.file) || + typeof checked.text !== 'string' || Buffer.byteLength(checked.text) > limits.leanSource || mathDigest(checked.text) !== checked.digest || + !Array.isArray(lean.artifacts) || !lean.artifacts.some(ref => ref.digest === checked.artifact && + ref.sourceDigest === lean.sourceDigest && ref.environmentDigest === lean.environmentDigest))) return false; + const candidate = object(lean.candidate); + return lean.candidate === undefined || Boolean(checked && candidate && only(candidate, ['ref', 'solverRunId']) && + teamEvidenceRefSchema.safeParse(candidate.ref).success && typeof candidate.solverRunId === 'string' && + candidate.solverRunId.length > 0 && candidate.solverRunId.length <= 128); } function isLeanSearch(value: unknown) { return Array.isArray(value) && value.length >= 1 && value.length <= limits.queries && value.every(entry => { diff --git a/apps/web/client/proofMap.css b/apps/web/client/proofMap.css index 86af4f73..4c7e5221 100644 --- a/apps/web/client/proofMap.css +++ b/apps/web/client/proofMap.css @@ -160,6 +160,12 @@ .pm-detail-conditions li + li { margin-top: 5px; } .pm-root .pm-detail-reason { margin: 14px 0 0; padding: 9px 10px; border-left: 2px solid var(--pm-danger); border-radius: 0 4px 4px 0; background: var(--pm-danger-soft); color: var(--pm-danger); font-size: 13px; line-height: 1.7; white-space: pre-wrap; max-height: none; overflow-wrap: anywhere; } .pm-detail-finding > div { white-space: pre-wrap; } +.pm-team-evidence { display: grid; gap: 8px; overflow-wrap: anywhere; } +.pm-team-evidence:empty { display: none; } +.pm-team-proof, .pm-team-source { padding: 8px; border: 1px solid var(--pm-line); border-radius: 4px; } +.pm-team-proof > summary, .pm-team-source > summary { cursor: pointer; } +.pm-team-proof pre { overflow: auto; max-height: 18rem; white-space: pre; } +.pm-team-declaration { margin-block: 8px; } .pm-root .pm-detail-note { margin-top: 12px; color: var(--pm-muted); font-size: 12px; white-space: pre-wrap; } .pm-detail-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; } diff --git a/apps/web/client/proofMapModel.ts b/apps/web/client/proofMapModel.ts index 1f6bf728..005859f5 100644 --- a/apps/web/client/proofMapModel.ts +++ b/apps/web/client/proofMapModel.ts @@ -1,4 +1,4 @@ -import type { WebInspectedTask } from '../collaboration'; +import type { WebInspectedTask, WebNativeTeamTask, WebTeamAdoption, WebTeamDelivery, WebTeamFinding } from '../collaboration'; import type { WebFormalization } from '../formalizationTypes'; import type { WebRun } from '../shared'; import { locale as currentLocale, t, translator } from '../i18n'; @@ -58,6 +58,10 @@ export type ProofMapNode = { who?: string; attempts?: number; canGuide: boolean; + native?: { + task?: WebNativeTeamTask; delivery?: WebTeamDelivery; adoptions: WebTeamAdoption[]; + findings: WebTeamFinding[]; trials: { id: string; ref: string; consumer: string; passed: boolean }[]; + }; }; export type ProofMapStage = { @@ -102,7 +106,7 @@ export type ProofMapExternalCitation = { export type ProofMapModel = { key: string; - mode: 'planned' | 'pipeline'; + mode: 'planned' | 'pipeline' | 'native'; active: boolean; goalBridge?: ProofMapGoalBridge; reduction: ProofMapReductionStep[]; @@ -204,6 +208,93 @@ function taskLayers(tasks: readonly LiveTask[], dependencies: ReadonlyMap [id, stage(value)])); } +function nativeTeamMap(process: SolveProcess, theoremNames: string[], tx: (zh: string, en: string) => string) { + const team = process.nativeTeam, nodes: ProofMapNode[] = [], stages: ProofMapStage[] = [], edges: ProofMapEdge[] = []; + const accepted = process.state === 'accepted'; + const findings = team?.findings ?? []; + const trials = process.checks.flatMap(check => { + const candidate = check.lean?.candidate; + if (!team || !candidate || candidate.solverRunId !== team.runId || !check.lean?.checkedSource || !check.workerId) return []; + const source = findings.find(finding => finding.ref === candidate.ref); + if (!source || source.from === check.workerId || source.to && source.to !== check.workerId || + source.at !== undefined && source.at > Date.parse(check.at)) return []; + return [{ id: check.id, ref: candidate.ref, consumer: check.workerId, passed: check.state === 'passed' }]; + }); + const stage = (title: string, nodesForStage: ProofMapNode[]) => { + if (!nodesForStage.length) return; + const index = stages.length; + nodesForStage.forEach(node => { node.stageIndex = index; }); + stages.push({ title, index, number: String(index + 1).padStart(2, '0'), tone: aggregateTone(nodesForStage), nodeIds: nodesForStage.map(node => node.id) }); + nodes.push(...nodesForStage); + }; + const node = (id: string, title: string, kindLabel: string, statusLabel: string, tone: ProcessTone): ProofMapNode => ({ + id, title, stageIndex: 0, kind: 'pipeline', kindLabel, statusLabel, tone, + origin: tone === 'failed' ? 'blocked' : tone === 'active' ? 'active' : 'pending', + checkpointsIn: [], handoffsOut: [], useSummary: '', proveSummary: title, conditions: [], canGuide: false, + }); + const taskTitle = tx('成员任务', 'Member assignments'); + const noTask = team?.taskCount === 0 ? tx('尚未派工', 'No assignments yet') : tx('任务记录未提供', 'Assignment evidence unavailable'); + const tasks = process.tasks.filter(task => task.native).map(live => { + const task = live.native!; + const item = node(task.id, live.label, tx('成员任务', 'Assignment'), live.status, live.tone); + const related = findings.filter(entry => !entry.ref.startsWith('delivery:') && + (entry.taskId === task.id || entry.ref === task.reassignment?.ref)); + return { ...item, statement: live.statement, reason: live.reason, finding: live.finding, who: live.who, + useSummary: [task.memberId, ...task.profiles].join(' · '), + note: task.researchRef && !findings.some(entry => entry.ref === task.researchRef) ? tx('研究产物未记录', 'Research artifact unavailable') : undefined, + native: { task, adoptions: [], findings: related, trials: trials.filter(trial => + related.some(entry => entry.ref === trial.ref && entry.taskId === task.id)).slice(-8) } }; + }); + stage(taskTitle, tasks.length ? tasks : [node('native-unassigned', noTask, taskTitle, tx('等待记录', 'Awaiting evidence'), 'pending')]); + const deliveries = (team?.deliveries ?? []).map(record => { + const delivery = accepted ? record : { ...record, references: [] }; + const adoptions = team!.adoptions.filter(adoption => adoption.deliveryId === delivery.id); + const recordedAdoption = adoptions.some(adoption => adoption.status === 'completed' && adoption.receiptId); + const status = recordedAdoption ? tx('已采纳', 'Adopted') : delivery.proof ? tx('交付已核验', 'Delivery checked') : tx('交付证据未记录', 'Delivery evidence unavailable'); + const names = delivery.proof?.declarations.map(item => item.name); + const title = names?.length ? names.slice(0, 3).join(', ') : tx('成员交付', 'Member delivery'); + const item = node('delivery:' + delivery.id, title, tx('成员交付', 'Member delivery'), status, delivery.proof ? 'done' : 'pending'); + return { ...item, origin: delivery.proof ? 'checked' as const : item.origin, useSummary: delivery.memberId, proveSummary: status, + native: { delivery, adoptions, findings: [], trials: trials.filter(trial => trial.ref === 'delivery:' + delivery.id).slice(-8) } }; + }); + stage(tx('已记录交付', 'Recorded deliveries'), deliveries); + const finalStage = process.stages.find(item => item.id === 'verify'); + const finalTitle = tx('独立 Lean 验收', 'Independent Lean acceptance'); + const finalStatus = accepted ? tx('原题已通过验收', 'Original problem accepted') : tx('原题尚未通过验收', 'Original problem not yet accepted'); + const final = node('native-final', theoremNames.join(', ') || finalTitle, finalTitle, finalStatus, + accepted ? 'done' : finalStage?.tone === 'done' ? 'pending' : finalStage?.tone ?? 'pending'); + final.origin = accepted ? 'checked' : final.origin; + stage(finalTitle, [final]); + const byId = new Map(nodes.map(node => [node.id, node])); + const connect = (source: string, target: string, kind: ProofMapEdgeKind) => { + const a = byId.get(source), b = byId.get(target); + if (!a || !b || a === b) return; + edges.push({ id: source + '->' + target, from: source, to: target, kind }); + a.handoffsOut.push({ id: target, label: b.title, settled: kind === 'settled' }); + b.checkpointsIn.push({ id: source, label: a.title, settled: kind === 'settled' }); + }; + for (const item of deliveries) { + const delivery = item.native.delivery; + if (delivery.proof) connect(delivery.taskId, item.id, 'settled'); + if (accepted && delivery.proof && delivery.references.length) connect(item.id, final.id, 'settled'); + } + for (const item of tasks) { + const basis = item.native.task.reassignment; + const source = basis && findings.find(entry => entry.ref === basis.ref); + if (source?.taskId) connect(source.taskId, item.id, 'dependency'); + } + const reduction: ProofMapReductionStep[] = [ + { step: '01', title: taskTitle, value: team ? `${team.memberCount} / ${Math.max(0, team.maxAgents - 1)} · ${team.taskCount} ${tx('项任务', 'assignments')}` : noTask, + detail: team?.taskOmissions ? tx(`另有 ${team.taskOmissions} 项历史任务`, `${team.taskOmissions} earlier assignments`) : + tx('成员由 Lead 按缺口派工。', 'Lead assigns members to proof gaps.'), tone: stages[0]!.tone }, + { step: '02', title: tx('成员交付与采纳', 'Deliveries and adoptions'), + value: `${deliveries.filter(item => item.native.delivery.proof).length} ${tx('项交付已核验', 'deliveries checked')} · ${team?.adoptions.filter(item => item.receiptId).length ?? 0} ${tx('项已采纳', 'adoptions')}`, + detail: tx('采纳以宿主保存的整合回执为准。', 'Adoption is shown when its integration receipt is recorded.'), tone: deliveries.some(item => item.tone === 'done') ? 'done' : 'pending' }, + { step: '03', title: finalTitle, value: finalStatus, detail: theoremNames.join(', '), tone: final.tone }, + ]; + return { nodes, stages, edges, reduction }; +} + export function buildProofMap(input: BuildProofMapInput): ProofMapModel { const activeLocale = input.locale ?? currentLocale; const tx = (zh: string, en: string) => (activeLocale === 'en' ? en : zh); @@ -249,9 +340,11 @@ export function buildProofMap(input: BuildProofMapInput): ProofMapModel { } let nodes: ProofMapNode[], stages: ProofMapStage[], edges: ProofMapEdge[]; - const mode = process.tasks.length ? 'planned' : 'pipeline'; + const mode = process.nativeTeam || run?.nativeTeamCapacity ? 'native' : process.tasks.length ? 'planned' : 'pipeline'; + const native = mode === 'native' ? nativeTeamMap(process, theoremNames, tx) : undefined; const baseContext = tx('原始命题假设与基础 Mathlib 环境', 'Problem hypotheses and base Mathlib context'); - if (mode === 'planned') { + if (native) ({ nodes, stages, edges } = native); + else if (mode === 'planned') { const dependencies = new Map(process.tasks.map(live => { const agent = agents.get(live.id); const upstream = agent?.dependsOn ?? agent?.plannedDependencies ?? planned.get(live.id)?.dependsOn @@ -277,24 +370,29 @@ export function buildProofMap(input: BuildProofMapInput): ProofMapModel { research: tx('研究', 'Research'), sketch: tx('草图', 'Sketch'), lemma: tx('引理', 'Lemma'), goal: tx('原始目标', 'Original goal'), })[key]) ?? 'lemma'; const recordedProof = agentTask?.proof; + const conditionalCheck = recordedProof?.status === 'conditional'; const verified = agentTask?.verifiedArtifact !== undefined ? Boolean(agentTask.verifiedArtifact) : Boolean(recordedProof && ['checked', 'verified', 'integrated'].includes(recordedProof.status) && !recordedProof.conditions?.length); - const origin: ProofMapOrigin = liveTask.tone === 'done' - ? !agentTask || agentTask.kind === 'research' || verified ? 'checked' : 'conditional' - : liveTask.tone === 'failed' || agentTask?.status === 'blocked' ? 'blocked' - : liveTask.tone === 'active' ? 'active' : kind === 'sketch' && recordedProof?.status === 'conditional' ? 'conditional' : 'pending'; - const checkpointsIn = (dependencies.get(liveTask.id) ?? []).map(id => ({ id, label: liveById.get(id)?.label ?? id, settled: liveById.get(id)?.tone === 'done' })); - const handoffsOut: ProofMapHandoff[] = (dependents.get(liveTask.id) ?? []).map(id => ({ id, label: liveById.get(id)!.label, settled: liveTask.tone === 'done' })); - if (!handoffsOut.length && kind === 'goal') handoffsOut.push({ id: '__closure__', label: tx('目标定理闭合', 'Target theorem closure'), settled: liveTask.tone === 'done' }); + const origin: ProofMapOrigin = liveTask.tone === 'failed' || agentTask?.status === 'blocked' ? 'blocked' + : conditionalCheck ? 'conditional' + : liveTask.tone === 'done' ? !agentTask || agentTask.kind === 'research' || verified ? 'checked' : 'conditional' + : liveTask.tone === 'active' ? 'active' : 'pending'; + const checkpointsIn = (dependencies.get(liveTask.id) ?? []).map(id => ({ id, label: liveById.get(id)?.label ?? id, + settled: liveById.get(id)?.tone === 'done' && agents.get(id)?.proof?.status !== 'conditional' })); + const settled = liveTask.tone === 'done' && !conditionalCheck; + const handoffsOut: ProofMapHandoff[] = (dependents.get(liveTask.id) ?? []).map(id => ({ id, label: liveById.get(id)!.label, settled })); + if (!handoffsOut.length && kind === 'goal') handoffsOut.push({ id: '__closure__', label: tx('目标定理闭合', 'Target theorem closure'), settled }); const files = agentTask?.files ?? recordedProof?.actualReferences?.inputs.map(item => item.file) ?? (planTask?.proofPath ? [planTask.proofPath] : []); const declaration = agentTask?.declaration ?? agentTask?.type ?? planTask?.type; const conditions = unique([...(liveTask.waits ?? []), ...(recordedProof?.conditions ?? []).map(item => liveById.get(item.taskId)?.label ?? item.taskId), ...(kind === 'sketch' && origin !== 'checked' ? [tx('路线草稿仍需下游引理验证', 'Proof sketch still needs downstream lemma verification')] : []), - ...(origin === 'conditional' && kind !== 'sketch' ? [tx('尚未记录该任务的 Lean 核验', 'No Lean verification is recorded for this task')] : []), + ...(origin === 'conditional' && !conditionalCheck && kind !== 'sketch' ? [tx('尚未记录该任务的 Lean 核验', 'No Lean verification is recorded for this task')] : []), ...(liveTask.reason ? [liveTask.reason] : [])]); return { id: liveTask.id, taskId: liveTask.id, version: agentTask?.version, stageIndex: layers.get(liveTask.id)!, kind, - kindLabel: liveTask.kind, origin, tone: liveTask.tone, statusLabel: liveTask.status, title: liveTask.label, + kindLabel: liveTask.kind, origin, tone: liveTask.tone, + statusLabel: origin === 'conditional' && conditionalCheck ? tx('条件核验通过', 'Checked with open premises') : liveTask.status, + title: liveTask.label, codeName: agentTask?.theorem ?? planTask?.theoremName ?? (declaration ? declarationNames(declaration)[0] : undefined), statement: liveTask.statement, formulaOrType: declaration ?? liveTask.statement, checkpointsIn, handoffsOut, useSummary: checkpointsIn.length ? checkpointsIn.map(item => item.label).join(', ') : files.length ? files.join(', ') : baseContext, @@ -359,7 +457,7 @@ export function buildProofMap(input: BuildProofMapInput): ProofMapModel { const bottleneck = deepest.find(node => node.origin === 'blocked') ?? deepest.find(node => node.tone === 'active' && node.kind === 'lemma') ?? deepest.find(node => node.tone === 'active') ?? deepest.find(node => node.origin === 'conditional') ?? deepest.find(node => node.tone !== 'done'); - const reduction: ProofMapReductionStep[] = [ + const reduction: ProofMapReductionStep[] = native?.reduction ?? [ { step: '01', title: tx('全局证明义务', 'Planned obligations'), value: `${nodes.length} ${mode === 'planned' ? (nodes.length === 1 ? tx('项任务', 'task') : tx('项任务', 'tasks')) : (nodes.length === 1 ? tx('个证明阶段', 'proof stage') : tx('个证明阶段', 'proof stages'))} · ${edges.length} ${edges.length === 1 ? tx('条依赖', 'dependency') : tx('条依赖', 'dependencies')}`, detail: tx('按依赖组织输入、引理与目标定理。', 'Inputs, lemmas, and the target theorem organized by dependency.'), tone: closed ? 'done' : 'pending' }, { step: '02', title: tx('已核验供给', 'Verified supply'), value: `${checked} ${tx('项已核验', 'verified')} · ${passed} ${passed === 1 ? tx('次 Lean 检查通过', 'passed Lean check') : tx('次 Lean 检查通过', 'passed Lean checks')}`, diff --git a/apps/web/client/solveProcess.ts b/apps/web/client/solveProcess.ts index b29333f1..eb3ff5f5 100644 --- a/apps/web/client/solveProcess.ts +++ b/apps/web/client/solveProcess.ts @@ -1,5 +1,6 @@ import type { WebFormalization, WebFormalizationActivity, WebFormalizationRole, WebFormalizationRoleSummary } from '../formalizationTypes'; import type { WebAgentAction, WebAgentLeanCheck, WebEvent, WebRun } from '../shared'; +import type { WebNativeTeam, WebNativeTeamTask } from '../collaboration'; import { acceptedTitle, checkReason, isAcceptedRun, isFaultedRun, isRejectedRun, planGated, queueDescription, readableDuration, runProgress, runStages, runTokens, stoppedLabel } from '../presentation'; import { summarizeReport } from '../report'; import { localizeText, t } from '../i18n'; @@ -35,7 +36,7 @@ export type ProcessStage = { id: ProcessStageId; label: string; tone: ProcessTon export type LiveCheck = { id: string; stage: ProcessStageId; label: string; who?: string; at: string; state: 'running' | 'passed' | 'failed'; lean?: WebAgentLeanCheck; text?: string; file?: string; source?: string; sourceClipped?: boolean; - /** `changed`: the file shown was saved after this check, so its lines may have moved. */ sourceNote?: 'changed'; + workerId?: string; }; /** What an Agent or the platform is doing at this moment, one line each, for the workspace beside the conversation. */ export type LiveNow = { id: string; who?: string; text: string; code?: string; task?: { id: string; label: string } }; @@ -45,6 +46,7 @@ export type LiveTask = { /** Tried more than once. */ attempts?: number; /** Why it is blocked or failed, as recorded. */ reason?: string; /** What a task that did not fail reported. */ finding?: string; /** The unfinished tasks it waits for. */ waits?: string[]; + native?: WebNativeTeamTask; }; export type SolveState = 'queued' | 'formalizing' | 'review' | 'proving' | 'verifying' | 'accepted' | 'failed' | 'stopped' | 'cancelled'; export type SolveProcess = { @@ -57,6 +59,7 @@ export type SolveProcess = { thinking?: ThinkingEntry[]; /** What runs at this moment; empty once the task ended or between two steps. */ now: LiveNow[]; /** The research plan's tasks, in plan order; empty before a plan exists. */ tasks: LiveTask[]; + nativeTeam?: WebNativeTeam; }; export type SolveProcessInput = { formalization?: WebFormalization; activity?: readonly WebFormalizationActivity[]; activityDropped?: number; @@ -64,11 +67,14 @@ export type SolveProcessInput = { }; const base = (file: string) => file.split('/').filter(Boolean).at(-1) ?? file; -const firstError = (lean?: WebAgentLeanCheck) => lean?.messages.find(message => message.severity === 'error'); +const firstError = (lean?: WebAgentLeanCheck) => lean?.firstBlocking ?? lean?.messages.find(message => message.severity === 'error'); /** How a failed Lean check reads in a row: where Lean stopped, if it said. */ function leanOutcome(lean: WebAgentLeanCheck | undefined, passed: boolean): ProcessOutcome { if (passed) return { text: t('通过'), tone: 'passed' }; if (lean?.timedOut) return { text: t('超时'), tone: 'failed' }; + if (lean?.classification === 'source') return { text: t('源码预检失败'), tone: 'failed' }; + if (lean?.classification === 'infrastructure' || lean?.classification === 'tooling') + return { text: t('Lean 环境或工具出错'), tone: 'failed' }; const line = firstError(lean)?.line; return { text: line !== undefined ? t('第 {0} 行出错', line) : t('未通过'), tone: 'failed' }; } @@ -238,6 +244,30 @@ function taskFindingText(raw?: string): string { function liveTasks(run: WebRun): LiveTask[] { const inspection = run.observation?.inspection, tasks = inspection?.tasks ?? []; const live = run.status === 'queued' || run.status === 'running', names = taskNames(tasks), workers = workerNames(inspection?.workers ?? []); + if (inspection?.nativeTeam) { + const team = inspection.nativeTeam; + return team.tasks.map(task => { + const delivery = team.deliveries.find(delivery => delivery.id === task.deliveryId && delivery.taskId === task.id); + const adoption = team.adoptions.find(adoption => adoption.deliveryId === delivery?.id && adoption.status === 'completed' && adoption.receiptId); + const hasFinding = Boolean(task.finding || team.findings.some(finding => + finding.ref === task.researchRef && finding.status === 'recorded')); + const status: Record = { + queued: t('等待派工启动'), preparing: t('准备工作区'), running: hasFinding ? t('推进中,已有发现') : t('推进中,尚无发现记录'), + paused: t('已暂停并保留任务'), stopping: t('等待写入停止'), checking: t('宿主正在检查交付'), + rejected: t('交付检查未通过'), delivered: adoption ? t('已采纳') : delivery?.proof ? t('交付已核验') : t('交付证据未记录'), + completed: hasFinding ? t('研究已返回') : t('已返回,成果未记录'), failed: t('任务失败'), + interrupted: t('会话已中断'), cancelled: t('任务已取消'), + }; + const tone: ProcessTone = ['rejected', 'failed'].includes(task.status) ? 'failed' + : task.status === 'delivered' && delivery?.proof || task.status === 'completed' && hasFinding ? 'done' + : ['running', 'checking', 'preparing', 'stopping'].includes(task.status) ? live ? 'active' : 'stopped' + : ['interrupted', 'cancelled'].includes(task.status) ? 'stopped' : 'pending'; + const objective = task.objective.split('\n').filter(line => !/^(?:Profiles:|Based on:)/u.test(line)).join('\n').trim(); + return { id: task.id, native: task, label: objective.split('\n')[0]?.slice(0, 140) || task.id, + statement: objective, who: task.memberId, kind: t('成员任务'), tone, status: status[task.status], + finding: task.finding, reason: task.reason }; + }); + } const byId = new Map(tasks.map(task => [task.id, task])); return tasks.map((task): LiveTask => { const state = taskState(task), tone = taskTone(state, live), label = taskLabel(task, names); @@ -292,20 +322,14 @@ function planRow(run: WebRun, live: boolean): ProcessRow | undefined { tone: settled === tasks.length ? 'done' : live ? 'active' : 'stopped', meta: t('已完成 {0}/{1}', settled, tasks.length), details: [], rows }; } -/** An Agent's own `check-lean`; the file is shown when it is the candidate the run saved from that Agent. */ -function selfCheck(action: WebAgentAction, file: string, run: WebRun, who: string, live: boolean): LiveCheck { - const lean = action.lean, name = base(file || 'Submission.lean'); +/** An Agent's own `check-lean`; only the captured source can carry this check's line annotations. */ +function selfCheck(action: WebAgentAction, file: string, who: string, live: boolean): LiveCheck { + const lean = action.lean, name = lean?.checkedSource?.file || base(file || 'Submission.lean'); const passed = lean?.passed ?? action.status === 'done'; const state = action.status === 'running' ? live ? 'running' : 'failed' : passed ? 'passed' : 'failed'; - const check: LiveCheck = { id: `p:${action.workerId}:${action.itemId}`, stage: 'prove', label: t('{0} 自查 {1}', who, name), who, at: action.at, state, file: name, + return { id: `p:${action.workerId}:${action.itemId}`, stage: 'prove', label: t('{0} 自查 {1}', who, name), who, + workerId: action.workerId, at: action.at, state, file: name, ...(lean?.checkedSource && { source: lean.checkedSource.text }), ...(lean ? { lean } : !passed && action.output ? { text: action.output } : {}) }; - const artifact = run.artifact; - if (artifact && artifact.workerId === action.workerId && name === 'Submission.lean') { - check.source = artifact.source; - // Saved well after this check ended: the lines Lean names may have moved since. - if (Date.parse(artifact.capturedAt) > Date.parse(action.at) + (action.durationMs ?? 0) + 3_000) check.sourceNote = 'changed'; - } - return check; } const selfOutcome = (check: LiveCheck): ProcessOutcome => check.state === 'running' ? { text: t('检查中…'), tone: 'muted' } : check.state === 'failed' ? leanOutcome(check.lean, false) @@ -313,7 +337,7 @@ const selfOutcome = (check: LiveCheck): ProcessOutcome => check.state === 'runni // A lane shows its newest steps; the roadmap has all of them. const shownSteps = 6; -type LaneContext = { run: WebRun; live: boolean; name: string; tasks: ReadonlyMap; checks: LiveCheck[] }; +type LaneContext = { live: boolean; name: string; tasks: ReadonlyMap; checks: LiveCheck[] }; /** * One Agent's lane: the row says what it is on now, its latest steps sit inside, each opening to what the Agent did. * Acceptance steps are left to the acceptance stage. `attempts` counts the steps in which it wrote proof code. @@ -337,7 +361,7 @@ function laneRow(route: AgentRoute, ctx: LaneContext): { row: ProcessRow; attemp for (const action of actions) { const file = checkLeanFile(action); if (file === undefined) continue; - const self = selfCheck(action, file, ctx.run, ctx.name, ctx.live); + const self = selfCheck(action, file, ctx.name, ctx.live); ctx.checks.push(self); check = self.id; outcome = selfOutcome(self); } for (const item of step.items) { @@ -392,7 +416,7 @@ function proveStage(run: WebRun, events: readonly WebEvent[], routes: readonly A const ordered = [...routes].sort((a, b) => Number(b.workerId === lead) - Number(a.workerId === lead)); let attempts = 0, agents = 0; for (const route of ordered) { - const lane = laneRow(route, { run, live, name: names.get(route.workerId) ?? route.workerId, tasks, checks }); + const lane = laneRow(route, { live, name: names.get(route.workerId) ?? route.workerId, tasks, checks }); if (!lane) continue; rows.push(lane.row); attempts += lane.attempts; agents++; } @@ -506,6 +530,6 @@ export function buildSolveProcess(input: SolveProcessInput): SolveProcess { ...(item?.createdAt ?? run?.createdAt ? { startedAt: item?.createdAt ?? run?.createdAt } : {}), ...(endedAt ? { endedAt } : {}), ...(tokens ? { tokens } : {}), stages, checks, counts: { checks: checks.length, attempts, agents }, ...(current ? { current } : {}), dropped: (input.activityDropped ?? 0) + (input.actionsDropped ?? 0), thinking: buildThinkingEntries(input, checks), - now: active ? liveNow(stages, run, tasks) : [], tasks }; + now: active ? liveNow(stages, run, tasks) : [], tasks, nativeTeam: run?.observation?.inspection.nativeTeam }; } diff --git a/apps/web/client/ui/AgentRoute.tsx b/apps/web/client/ui/AgentRoute.tsx index e7ac4f52..cb088404 100644 --- a/apps/web/client/ui/AgentRoute.tsx +++ b/apps/web/client/ui/AgentRoute.tsx @@ -187,13 +187,21 @@ function Diff({ change }: { change: NonNullable[numbe } /** What Lean said in one check: each message with where it points, or why there is none. */ export function LeanReport({ lean }: { lean: WebAgentLeanCheck }) { + const first = lean.firstBlocking; + const messages = first && !lean.messages.some(message => message.file === first.file && message.line === first.line && message.text === first.text) + ? [first, ...lean.messages] : lean.messages; return
- {lean.messages.length ?
    {lean.messages.map((message, index) =>
  • + {messages.length ?
      {messages.map((message, index) =>
    • {message.severity === 'error' ? t('错误') : message.severity === 'warning' ? t('警告') : t('信息')} {message.line !== undefined && ` · ${message.file ? base(message.file) : ''}:${message.line}${message.column !== undefined ? `:${message.column}` : ''}`} -
      {message.text}
    • )}
    +
    {message.text}
    + {message.goalText && !message.text.includes(message.goalText) && <>{t('待证目标')}
    {message.goalText}
    } +
  • )}
: {lean.passed ? t('Lean 没有报告任何消息。') : lean.timedOut ? t('Lean 在时限内没有检查完。') : t('Lean 没有给出具体消息。')}} {lean.omittedMessages ? {t('另有 {0} 条消息没有显示。', lean.omittedMessages)} : null} + {lean.sourceDigest &&

{t('源码摘要')} {lean.sourceDigest}

} + {lean.environmentDigest &&

{t('检查环境')} {lean.environmentDigest}

} + {lean.artifacts?.map(ref =>

{t('诊断产物')} {ref.path}

)}
; } const installationLabel = (entry: WebAgentLibraryDeclaration) => entry.installation === 'installed-frozen' ? t('已冻结装入') : t('未装入'); diff --git a/apps/web/client/ui/LiveWorkspace.tsx b/apps/web/client/ui/LiveWorkspace.tsx index 0a4b4484..c4e1efbc 100644 --- a/apps/web/client/ui/LiveWorkspace.tsx +++ b/apps/web/client/ui/LiveWorkspace.tsx @@ -31,10 +31,13 @@ function leanMarks(lean: WebAgentLeanCheck | undefined, file: string, count: num const lines = new Map(); let elsewhere = 0; const errors = lean?.messages.filter(message => message.severity === 'error') ?? []; + if (lean?.firstBlocking && !errors.some(message => message.file === lean.firstBlocking?.file && + message.line === lean.firstBlocking?.line && message.text === lean.firstBlocking?.text)) errors.unshift(lean.firstBlocking); const shown = errors.length ? errors : lean?.messages.filter(message => message.severity === 'warning') ?? []; for (const message of shown) { const line = message.line; - if (line === undefined || line < 1 || line > count || (message.file && base(message.file) !== file)) { elsewhere++; continue; } + const where = lean?.checkedSource ? message.file?.replace(/^\.\//u, '') : message.file && base(message.file); + if (line === undefined || line < 1 || line > count || (lean?.checkedSource ? where !== file : where && where !== file)) { elsewhere++; continue; } const items = lines.get(line) ?? []; items.push({ severity: message.severity as Mark['severity'], text: message.text }); lines.set(line, items); @@ -55,9 +58,8 @@ function fileView(process: SolveProcess, check: LiveCheck | undefined, time: (at const kinds = { statement: t('当前 Lean 陈述'), candidate: t('当前候选'), proof: t('验收证明') }; const own = current && current.kind === 'candidate' && current.who ? `${kinds.candidate} · ${current.who}` : current ? kinds[current.kind] : ''; if (check?.source !== undefined) { - const changed = check.sourceNote === 'changed'; - return { file: check.file ?? 'Submission.lean', source: check.source, ...(check.sourceClipped ? { clipped: true } : {}), inline: !changed, - caption: `${check.label} · ${time(check.at)}`, ...(changed ? { note: t('这份文件在这次检查之后又改过,Lean 指出的行可能已经移动。') } : {}) }; + return { file: check.file ?? 'Submission.lean', source: check.source, ...(check.sourceClipped ? { clipped: true } : {}), inline: true, + caption: `${check.label} · ${time(check.at)}` }; } if (!current) return; return { file: current.file, source: current.source, ...(current.clipped ? { clipped: true } : {}), inline: false, @@ -154,10 +156,12 @@ function Now({ process, onTask }: { process: SolveProcess; onTask?: (id: string) } /** The research plan's tasks, in plan order, with where each one stands. */ -function Plan({ process, proofMap, props, hidden }: { process: SolveProcess; proofMap: ProofMapModel; props: LiveWorkspaceProps; hidden: boolean }) { +function Plan({ process, proofMap, props, hidden, onCheck }: { + process: SolveProcess; proofMap: ProofMapModel; props: LiveWorkspaceProps; hidden: boolean; onCheck(id: string): void; +}) { const planned = process.tasks.length > 0; return ; @@ -196,13 +200,15 @@ function LiveWorkspace(props: LiveWorkspaceProps) { const following = !picked, check = picked ?? checks.at(-1), view = fileView(process, check, props.time); const failedChecks = checks.filter(item => item.state === 'failed').length; // Messages the file cannot show under its lines are listed above it. - const listed = check && (check.lean ? !view?.inline && + const listed = check && (check.lean ? view?.inline + ?
{t('Lean 诊断与版本')}
+ : : check.text &&
{check.text}
); // The route and the Lean file take turns in the space below, so neither is squeezed. With a plan the route opens // first; picking a Lean check brings its file forward, and the reader's own choice of tab stays for this task. const planned = process.tasks.length > 0; const [chosen, setChosen] = useState<{ key: string; tab: Tab }>(); - const tab: Tab = chosen?.key === process.key ? chosen.tab : (planned ? 'plan' : 'file'); + const tab: Tab = chosen?.key === process.key ? chosen.tab : (planned || proofMap?.mode === 'native' ? 'plan' : 'file'); const show = (next: Tab) => setChosen({ key: process.key, tab: next }); const pickedBefore = useRef(props.selected); useLayoutEffect(() => { @@ -224,14 +230,15 @@ function LiveWorkspace(props: LiveWorkspaceProps) {
    {process.stages.map(stage =>
  1. {stage.label}
  2. )}
- +
- {proofMap &&