feat: ship bounded tool feedback and Python engineering checks in 1.7.0
This commit is contained in:
+54
-12
@@ -1,17 +1,21 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { spawn, execFile } from 'node:child_process';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
import { inspectProject, createCheckList } from './project-inspector.mjs';
|
||||
import { safePath } from '../server/files.mjs';
|
||||
import { assertChangeSetsResolved } from '../shared/contracts/change-sets.mjs';
|
||||
import { assertWorkspacesResolved } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
|
||||
import { bindPythonChecks, preparePythonInvocation, pythonEnvironment, readPythonEvidence, pythonResultBinding } from './python-runtime.mjs';
|
||||
|
||||
const at = () => new Date().toISOString();
|
||||
const conflict = message => Object.assign(new Error(message), { status: 409 });
|
||||
const removeAnsi = text => text.replace(/\u001b\[[0-9;]*[a-zA-Z]/g, '');
|
||||
const checkContract = plan => ({ schemaVersion: 1, kind: 'sealed-check-plan', id: plan.id, sessionId: plan.sessionId,
|
||||
projectId: plan.projectId, taskId: plan.taskId, runId: plan.runId, fingerprint: plan.fingerprint,
|
||||
sourceFingerprint: plan.sourceFingerprint, checks: plan.checks });
|
||||
|
||||
export function parseTestEvidence(output, framework) {
|
||||
const text = removeAnsi(output), values = {};
|
||||
@@ -46,10 +50,12 @@ function npmInvocation(name, runtimeDirectory) {
|
||||
}
|
||||
|
||||
export class CheckRunner {
|
||||
constructor(store, { redact = value => String(value), timeoutMs = 180000, projectBusy = () => false, runtimeDirectory = null } = {}) {
|
||||
constructor(store, { redact = value => String(value), timeoutMs = 180000, projectBusy = () => false, runtimeDirectory = null,
|
||||
pythonExecutable = null, pythonRunnerPath = path.join(process.cwd(), 'scripts', 'python-check-runner.py') } = {}) {
|
||||
this.store = store; this.redact = redact; this.timeoutMs = timeoutMs; this.projectBusy = projectBusy;
|
||||
this.active = new Map(); this.projects = new Map();
|
||||
this.runtimeDirectory = runtimeDirectory;
|
||||
this.pythonExecutable = pythonExecutable; this.pythonRunnerPath = pythonRunnerPath;
|
||||
}
|
||||
isActive(sessionId) { return [...this.active.values()].some(value => value.sessionId === sessionId); }
|
||||
projectActive(projectId) { return this.projects.has(projectId); }
|
||||
@@ -61,13 +67,18 @@ export class CheckRunner {
|
||||
if (!session.taskId || !session.runId) throw conflict('先发送一个项目任务,再识别本任务的检查计划。');
|
||||
const identity = { taskId: session.taskId, runId: session.runId };
|
||||
const inspection = await inspectProject(this.store.project(session.projectId));
|
||||
const checks = await bindPythonChecks(this.store.project(session.projectId), createCheckList(inspection, names), {
|
||||
executable: this.pythonExecutable ?? process.env.AGENT_WORKBENCH_PYTHON_PATH ?? inspection.python?.preferredExecutable,
|
||||
runnerPath: this.pythonRunnerPath });
|
||||
if (identity.taskId !== session.taskId || identity.runId !== session.runId) throw conflict('识别期间任务已切换,请重新准备当前任务的检查。');
|
||||
const run = this.store.owned('run', session.runId, session.id);
|
||||
const artifact = this.store.artifactStore.write(session, run, JSON.parse(this.redact(JSON.stringify(inspection))), { kind: 'project-inspection' });
|
||||
this.store.core.artifact.set(artifact.id, artifact);
|
||||
const plan = { id: randomUUID(), sessionId: session.id, projectId: session.projectId, taskId: session.taskId, runId: session.runId,
|
||||
status: 'planned', createdAt: at(), fingerprint: inspection.fingerprint, sourceFingerprint: inspection.sourceFingerprint, project: inspection, artifactId: artifact.id,
|
||||
checks: createCheckList(inspection, names).map(check => ({ id: randomUUID(), ...check })) };
|
||||
checks: checks.map(check => ({ id: randomUUID(), ...check })) };
|
||||
const contract = this.store.artifactStore.write(session, run, checkContract(plan), { kind: 'check-plan' });
|
||||
this.store.core.artifact.set(contract.id, contract); plan.contractArtifactId = contract.id; plan.contractSha256 = contract.sha256;
|
||||
const task = this.store.core.task.get(session.taskId);
|
||||
if (task.verification.status === 'passed') {
|
||||
const last = this.store.core.check_job.get(task.verification.checkJobId);
|
||||
@@ -79,7 +90,12 @@ export class CheckRunner {
|
||||
planFor(session, planId) {
|
||||
const plan = this.store.owned('check_plan', planId, session.id);
|
||||
if (plan.taskId !== session.taskId) throw conflict('检查计划属于此前任务,请重新识别当前任务。');
|
||||
if (!plan.checks.length) throw conflict('没有可执行的npm检查脚本。');
|
||||
if (!plan.checks.length) throw conflict('没有可执行的工程检查。');
|
||||
if (plan.contractArtifactId) {
|
||||
const artifact = this.store.owned('artifact', plan.contractArtifactId, session.id);
|
||||
if (artifact.kind !== 'check-plan' || artifact.taskId !== plan.taskId || artifact.sha256 !== plan.contractSha256
|
||||
|| this.store.artifactStore.read(artifact) !== JSON.stringify(checkContract(plan))) throw conflict('检查计划与封存的执行范围不一致,请重新识别检查。');
|
||||
} else if (plan.checks.some(check => check.engine === 'python')) throw conflict('Python检查缺少封存执行范围,请重新识别检查。');
|
||||
return plan;
|
||||
}
|
||||
|
||||
@@ -126,9 +142,18 @@ export class CheckRunner {
|
||||
const text = this.redact(result.stdout + (result.stderr ? '\n--- stderr ---\n' + result.stderr : ''));
|
||||
const artifact = this.store.artifactStore.write(session, run, text, { kind: 'check-log', mediaType: 'text/plain' });
|
||||
this.store.core.artifact.set(artifact.id, artifact);
|
||||
const { stdout, stderr, ...record } = result;
|
||||
const { stdout, stderr, collectedEvidence, checkInput, ...record } = result;
|
||||
if (collectedEvidence) {
|
||||
const metrics = this.store.artifactStore.write(session, run, collectedEvidence, { kind: 'check-metrics' });
|
||||
this.store.core.artifact.set(metrics.id, metrics); record.metricsArtifactId = metrics.id; record.metricsSha256 = metrics.sha256;
|
||||
}
|
||||
if (checkInput) {
|
||||
const input = this.store.artifactStore.write(session, run, checkInput, { kind: 'check-input' });
|
||||
this.store.core.artifact.set(input.id, input); record.inputArtifactId = input.id;
|
||||
}
|
||||
job.results.push({ id: randomUUID(), name: check.name, kind: check.kind, command: check.command, ...record, logArtifactId: artifact.id, logExcerpt: text.slice(-8000) });
|
||||
this.store.save(session, { type: 'check.result', detail: { jobId: job.id, checkId: check.id, status: record.status, artifactId: artifact.id } });
|
||||
if (record.status === 'stale') { job.stale = true; break; }
|
||||
if (['cancelled', 'unknown'].includes(record.status)) break;
|
||||
const after = await inspectProject(this.store.project(session.projectId));
|
||||
if (after.sourceFingerprint !== job.sourceFingerprint) { job.stale = true; break; }
|
||||
@@ -155,19 +180,21 @@ export class CheckRunner {
|
||||
return job;
|
||||
}
|
||||
|
||||
executeCheck(check, project, signal) {
|
||||
async executeCheck(check, project, signal) {
|
||||
const started = Date.now();
|
||||
let invocation;
|
||||
try { invocation = npmInvocation(check.name, this.runtimeDirectory); } catch (error) { return Promise.resolve({ status: 'failed', exitCode: null, durationMs: 0, tests: null, stdout: '', stderr: error.message, reason: error.message }); }
|
||||
const isPython = check.engine === 'python';
|
||||
try { invocation = isPython ? await preparePythonInvocation(check, project, { signal }) : npmInvocation(check.name, this.runtimeDirectory); }
|
||||
catch (error) { return { status: signal.aborted ? 'cancelled' : error.status === 409 ? 'stale' : 'failed', exitCode: null, durationMs: Date.now() - started, tests: null, stdout: '', stderr: error.message, reason: error.message }; }
|
||||
return new Promise(resolve => {
|
||||
const env = { ...process.env, NO_COLOR: '1', CI: '1' };
|
||||
const env = isPython ? pythonEnvironment() : { ...process.env, NO_COLOR: '1', CI: '1' };
|
||||
delete env.FORCE_COLOR;
|
||||
delete env.AGENT_WORKBENCH_API_KEY;
|
||||
delete env.NODE_TEST_CONTEXT;
|
||||
const priorPath = process.env.PATH || '';
|
||||
for (const key of Object.keys(env)) if (key.toLowerCase() === 'path') delete env[key];
|
||||
env.PATH = path.dirname(process.execPath) + path.delimiter + priorPath;
|
||||
const child = spawn(invocation.executable, invocation.args, { cwd: safePath(project), env, windowsHide: true, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
const child = spawn(invocation.executable, invocation.args, { cwd: safePath(project), env, windowsHide: true, detached: process.platform !== 'win32', stdio: [isPython ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
|
||||
const streams = { stdout: { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') }, stderr: { head: '', tail: '', characters: 0, decoder: new StringDecoder('utf8') } };
|
||||
let settled = false, timedOut = false, terminating = false, killTimer;
|
||||
const append = (name, text) => { const value = streams[name]; value.characters += text.length; value.head = (value.head + text).slice(0, 240000); value.tail = (value.tail + text).slice(-240000); };
|
||||
@@ -175,10 +202,24 @@ export class CheckRunner {
|
||||
const finish = (code, error, unknown = false) => {
|
||||
if (settled) return; settled = true; clearTimeout(timeout); clearTimeout(killTimer); signal.removeEventListener('abort', terminate);
|
||||
const stdout = captured('stdout'), stderr = captured('stderr') + (error ? '\n' + error.message : '');
|
||||
const tests = check.kind === 'test' ? parseTestEvidence(streams.stdout.tail, check.framework) : null;
|
||||
const status = unknown ? 'unknown' : signal.aborted ? 'cancelled' : timedOut || error || code !== 0 || tests?.failed > 0 ? 'failed' : check.kind === 'test' && (!tests || tests.total === 0 || tests.passed !== tests.total || tests.cancelled > 0) ? 'unverified' : 'passed';
|
||||
let collectedEvidence = null, collectedResult = null, evidenceError = null, cleanupError = null;
|
||||
if (isPython && !unknown && code !== null && !error) {
|
||||
try { const saved = readPythonEvidence(invocation, code); collectedEvidence = saved.text; collectedResult = saved.result; } catch (failure) { evidenceError = failure.message; }
|
||||
}
|
||||
const tests = check.kind === 'test' ? isPython ? collectedResult?.tests ?? null : parseTestEvidence(streams.stdout.tail, check.framework) : null;
|
||||
const status = unknown ? 'unknown' : signal.aborted ? 'cancelled'
|
||||
: timedOut || error || code !== 0 || evidenceError || tests?.failed > 0 || collectedResult?.collectionErrors > 0 ? 'failed'
|
||||
: (check.kind === 'test' && (!tests || tests.total === 0 || tests.passed !== tests.total || tests.cancelled > 0 || collectedResult?.collectionSkipped > 0)
|
||||
|| isPython && collectedResult?.compilation?.total === 0) ? 'unverified' : 'passed';
|
||||
if (isPython && !unknown) { try { invocation.dispose(); } catch (failure) { cleanupError = failure.message; } }
|
||||
resolve({ status, exitCode: code, durationMs: Date.now() - started, tests, stdout, stderr, timedOut, truncated: streams.stdout.characters > 480000 || streams.stderr.characters > 480000,
|
||||
reason: unknown ? '进程终止未得到确认,需要核对实际副作用。' : timedOut ? '检查超过时间上限,已请求终止进程树。' : status === 'unverified' ? '测试为空、有跳过项,或没有可验证的测试数量。' : undefined });
|
||||
...(isPython ? { engine: 'python', python: pythonResultBinding(invocation), collectedEvidence, checkInput: invocation.input.toString('utf8'),
|
||||
compilation: collectedResult?.compilation ?? null, collectionErrors: collectedResult?.collectionErrors ?? null,
|
||||
collectionSkipped: collectedResult?.collectionSkipped ?? null, evidenceValidated: !!collectedResult, evidenceError, cleanupError,
|
||||
...(unknown ? { hostEvidenceDirectory: invocation.directory } : {}) } : {}),
|
||||
reason: unknown ? '进程终止未得到确认,需要核对实际副作用。' : timedOut ? '检查超过时间上限,已请求终止进程树。'
|
||||
: evidenceError || collectedResult?.collectorError || (collectedResult?.collectionErrors > 0 ? 'Python测试收集或类初始化有错误。' : null)
|
||||
|| (status === 'unverified' ? '测试为空、有跳过项,或没有可验证的测试数量。' : undefined) });
|
||||
};
|
||||
const terminate = () => {
|
||||
if (settled || terminating) return; terminating = true;
|
||||
@@ -189,6 +230,7 @@ export class CheckRunner {
|
||||
signal.addEventListener('abort', terminate, { once: true });
|
||||
for (const name of ['stdout', 'stderr']) { child[name].on('data', bytes => append(name, streams[name].decoder.write(bytes))); child[name].on('end', () => append(name, streams[name].decoder.end())); }
|
||||
child.once('error', error => finish(null, error)); child.once('close', code => finish(code));
|
||||
if (isPython) { child.stdin.on('error', () => {}); child.stdin.end(invocation.input); }
|
||||
if (signal.aborted) terminate();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ export function filePage(file, args, { maximumMessageBytes = 16000, callId = ''
|
||||
|
||||
export function recordArtifactRead(task, artifact, result, invocationId) {
|
||||
const progress = task.readProgress ??= { schemaVersion: 1, reads: [], repeated: 0, changingIndexes: [], warning: null, pause: false };
|
||||
progress.sessionInspection = null;
|
||||
const identity = artifact.id + ':' + artifact.sha256, start = result.offset, end = result.next_offset;
|
||||
let read = progress.reads.find(value => value.identity === identity);
|
||||
if (!read) { read = { identity, ranges: [] }; progress.reads.push(read); if (progress.reads.length > 128) progress.reads.shift(); }
|
||||
@@ -87,4 +88,27 @@ export function recordArtifactRead(task, artifact, result, invocationId) {
|
||||
export function clearReadStreak(task) {
|
||||
if (!task.readProgress) return;
|
||||
task.readProgress.repeated = 0; task.readProgress.changingIndexes = []; task.readProgress.warning = null; task.readProgress.pause = false;
|
||||
task.readProgress.sessionInspection = null;
|
||||
}
|
||||
|
||||
export function recordSessionInspection(task, result) {
|
||||
const progress = task.readProgress ??= { schemaVersion: 1, reads: [], repeated: 0, changingIndexes: [], warning: null, pause: false };
|
||||
const execution = result.execution ?? {};
|
||||
// Revision, request usage and tool counters change merely by inspecting.
|
||||
// They must not make identical engineering state appear to be progress.
|
||||
const state = { sessionId: result.session?.id, status: result.session?.status,
|
||||
lastFailure: result.lastFailure, changes: result.changes, approvals: result.pendingApprovals,
|
||||
verification: execution.task?.verification,
|
||||
needsVerification: execution.progress?.requiresVerification,
|
||||
checks: execution.checks?.map(job => ({ id: job.id, status: job.status, stale: job.stale,
|
||||
results: job.results.map(check => ({ name: check.name, status: check.status, exitCode: check.exitCode, tests: check.tests })) })),
|
||||
changeSets: execution.changeSets?.map(set => ({ id: set.id, status: set.status, requiresVerification: set.requiresVerification })),
|
||||
deliveries: execution.deliveries?.map(job => ({ id: job.id, status: job.status, commit: job.commit })) };
|
||||
const signature = createHash('sha256').update(JSON.stringify(state)).digest('hex');
|
||||
const previous = progress.sessionInspection;
|
||||
const consecutive = previous?.signature === signature ? previous.consecutive + 1 : 1;
|
||||
progress.sessionInspection = { signature, consecutive };
|
||||
progress.warning = consecutive >= 2 ? '连续核对的工程状态没有变化,请使用已经返回的状态与源码推进当前任务。' : null;
|
||||
progress.pause = consecutive >= 3;
|
||||
return progress;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
||||
import { BudgetExceeded, accountedTokens } from '../../shared/contracts/execution.mjs';
|
||||
import { completionBody, requestMetrics } from '../../shared/contracts/model-request.mjs';
|
||||
import { workingCandidates, workingDocument, workingEntry, workingMessage, verifyWorkingDocument } from './working-set.mjs';
|
||||
import { latestToolDocument, latestToolMessage, verifyLatestToolDocument } from './tool-feedback.mjs';
|
||||
|
||||
const hash = value => createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value), 'utf8').digest('hex');
|
||||
const PLACEHOLDER_ID = '00000000-0000-0000-0000-000000000000';
|
||||
@@ -163,11 +164,13 @@ export class RequestPlanner {
|
||||
const evidence = workingEvidence(groups, descriptions, this.store.core.artifact);
|
||||
const original = completionBody(config, [fixed, ...session.providerMessages], tools), before = requestMetrics(original);
|
||||
const selected = new Set(groups.map(group => group.index));
|
||||
let omitted = [], reference = null, workingReference = null;
|
||||
let omitted = [], reference = null, workingReference = null, latestReference = null;
|
||||
const latestDocument = latestToolDocument(this.store, session, run, groups);
|
||||
const entries = [];
|
||||
const metricsFor = (indices, includeNotice = true, currentEntries = entries) => {
|
||||
const missing = groups.filter(group => !indices.has(group.index));
|
||||
const messages = [fixed, ...(missing.length && includeNotice ? [notice({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, missing, descriptions, evidence)] : []),
|
||||
...(latestDocument && !indices.has(latestDocument.group_index) ? [latestToolMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, latestDocument)] : []),
|
||||
...(currentEntries.length ? [workingMessage({ id: PLACEHOLDER_ID, sha256: PLACEHOLDER_SHA }, workingDocument(session, run, currentEntries))] : []),
|
||||
...groups.filter(group => indices.has(group.index)).flatMap(group => group.messages)];
|
||||
return requestMetrics(completionBody(config, messages, tools));
|
||||
@@ -238,7 +241,9 @@ export class RequestPlanner {
|
||||
}
|
||||
}
|
||||
if (entries.length) workingReference = this.artifact(session, run, workingDocument(session, run, entries), 'context-working-set');
|
||||
if (latestDocument && !selected.has(latestDocument.group_index)) latestReference = this.artifact(session, run, latestDocument, 'context-latest-tools');
|
||||
const messages = [fixed, ...(reference ? [notice(reference, omitted, descriptions, evidence)] : []),
|
||||
...(latestReference ? [latestToolMessage(latestReference, latestDocument)] : []),
|
||||
...(workingReference ? [workingMessage(workingReference, workingDocument(session, run, entries))] : []),
|
||||
...structuredClone(groups.filter(group => selected.has(group.index)).flatMap(group => group.messages))];
|
||||
const body = completionBody(config, messages, tools), metrics = requestMetrics(body);
|
||||
@@ -254,11 +259,12 @@ export class RequestPlanner {
|
||||
workingRetentionTokens: Math.min(2048, Math.max(0, metricsFor(new Set(lastUser ? [lastUser.index] : []), true,
|
||||
entries.filter(entry => entry.observation.kind === 'file' && !entry.truncated && entry.total_content_characters <= 2000)).estimatedInputTokens
|
||||
- metricsFor(new Set(lastUser ? [lastUser.index] : []), true, []).estimatedInputTokens)),
|
||||
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - (reference ? 1 : 0) - (workingReference ? 1 : 0),
|
||||
originalMessages: session.providerMessages.length, retainedMessages: messages.length - 1 - (reference ? 1 : 0) - (workingReference ? 1 : 0) - (latestReference ? 1 : 0),
|
||||
archivedGroups: omitted.length, retainedGroups: groups.filter(group => selected.has(group.index)).map(group => group.index),
|
||||
historyIndexArtifactId: reference?.id ?? null, historyIndexSha256: reference?.sha256 ?? null, actualUsage: null,
|
||||
workingSetArtifactId: workingReference?.id ?? null, workingSetSha256: workingReference?.sha256 ?? null, workingSetEntries: entries.length,
|
||||
workingSetViewVersion: 2,
|
||||
latestToolsArtifactId: latestReference?.id ?? null, latestToolsSha256: latestReference?.sha256 ?? null, latestToolsEntries: latestReference ? latestDocument.entries.length : 0,
|
||||
requestAttempts: 0, responseSha256: null, source: 'workbench' };
|
||||
const artifact = this.artifact(session, run, record, 'context-plan'); record.artifactId = artifact.id;
|
||||
run.currentContextPlanId = record.id; session.estimatedTokens = record.estimatedInputTokens;
|
||||
@@ -296,6 +302,17 @@ export function verifyPlanEvidence(store, session, plan, cache = new Map()) {
|
||||
|| (frozen.workingSetEntries ?? 0) !== (plan.workingSetEntries ?? 0)) throw new Error('工作依据与发送前的封存记录不匹配。');
|
||||
if ((frozen.workingSetViewVersion ?? 1) !== (plan.workingSetViewVersion ?? 1)
|
||||
|| (frozen.workingRetentionTokens ?? 0) !== (plan.workingRetentionTokens ?? 0)) throw new Error('工作依据视图或保留预算与封存记录不匹配。');
|
||||
if ((frozen.latestToolsArtifactId ?? null) !== (plan.latestToolsArtifactId ?? null)
|
||||
|| (frozen.latestToolsSha256 ?? null) !== (plan.latestToolsSha256 ?? null)
|
||||
|| (frozen.latestToolsEntries ?? 0) !== (plan.latestToolsEntries ?? 0)) throw new Error('最新工具反馈与发送前的封存记录不匹配。');
|
||||
if (plan.latestToolsArtifactId) {
|
||||
const artifact = get(plan.latestToolsArtifactId, 'context-latest-tools', plan.latestToolsSha256);
|
||||
const document = JSON.parse(store.artifactStore.read(artifact));
|
||||
if (artifact.taskId !== plan.taskId) throw new Error('最新工具反馈的工件任务归属不匹配。');
|
||||
verifyLatestToolDocument(store, session, plan, document, historyGroups(session.providerMessages.slice(0, plan.originalMessages)));
|
||||
const message = latestToolMessage(artifact, document);
|
||||
if (body.messages.filter(value => value.role === 'system' && value.content === message.content).length !== 1) throw new Error('最新工具反馈与实际发送内容不匹配。');
|
||||
}
|
||||
if (plan.workingSetArtifactId) {
|
||||
const artifact = get(plan.workingSetArtifactId, 'context-working-set', plan.workingSetSha256);
|
||||
const document = JSON.parse(store.artifactStore.read(artifact));
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const hash = value => createHash('sha256').update(value, 'utf8').digest('hex');
|
||||
const excerpt = (text, maximum = 400) => {
|
||||
const end = Math.min(text.length, maximum);
|
||||
return text.slice(0, end > 0 && /[\uD800-\uDBFF]/.test(text[end - 1]) ? end - 1 : end);
|
||||
};
|
||||
function fields(value, keys) {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
|
||||
const result = {};
|
||||
for (const key of keys) {
|
||||
const item = value[key];
|
||||
if (typeof item === 'string') result[key] = excerpt(item, 512);
|
||||
else if (item === null || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item)) result[key] = item;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
const stats = value => fields(value, ['total', 'passed', 'failed', 'errors', 'skipped', 'cancelled']);
|
||||
const checkResult = value => ({ ...fields(value, ['id', 'name', 'kind', 'status', 'exitCode', 'exit_code', 'command', 'logArtifactId', 'reason']),
|
||||
...(value.tests ? { tests: stats(value.tests) } : {}) });
|
||||
const checkJob = value => ({ ...fields(value, ['id', 'status', 'taskId', 'runId', 'planId', 'stale', 'requiresVerification', 'summary']),
|
||||
...(Array.isArray(value.results) ? { results: value.results.slice(0, 6).map(checkResult), totalResults: value.results.length } : {}) });
|
||||
|
||||
// These are deterministic selected fields from a saved result, never a new
|
||||
// execution or an inferred success. Full JSON/text remains in its own artifact.
|
||||
export function compactToolFeedback(content) {
|
||||
let value;
|
||||
try { value = JSON.parse(content); } catch { return { format: 'text-excerpt', excerpt: excerpt(content) }; }
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return { format: 'json-excerpt', excerpt: excerpt(content) };
|
||||
const result = fields(value, ['source', 'version', 'kind', 'id', 'status', 'requires_verification', 'requiresVerification',
|
||||
'task_id', 'taskId', 'runId', 'plan_id', 'job_id', 'change_id', 'change_set_id', 'artifact_id', 'report_status', 'check_status',
|
||||
'path', 'sha256', 'base_sha256', 'fingerprint', 'exit_code', 'exitCode', 'offset', 'next_offset', 'total_characters',
|
||||
'returned_characters', 'truncated', 'totalMatches', 'error', 'message', 'summary', 'reason', 'note']);
|
||||
for (const key of ['content', 'stdout', 'stderr']) if (typeof value[key] === 'string') result[key + '_excerpt'] = excerpt(value[key]);
|
||||
for (const key of ['session', 'project']) if (value[key]) result[key] = fields(value[key], ['id', 'name', 'root', 'status', 'revision']);
|
||||
if ('lastFailure' in value) result.lastFailure = value.lastFailure === null ? null : fields(value.lastFailure, ['source', 'stage', 'kind', 'title', 'message', 'runId']);
|
||||
if (Array.isArray(value.changes)) {
|
||||
result.changes = value.changes.slice(-8).map(change => fields(change, ['id', 'path', 'status'])); result.totalChanges = value.changes.length;
|
||||
}
|
||||
if (Array.isArray(value.pendingApprovals)) {
|
||||
result.pendingApprovals = value.pendingApprovals.slice(0, 6).map(approval => fields(approval, ['id', 'status']));
|
||||
result.totalPendingApprovals = value.pendingApprovals.length;
|
||||
}
|
||||
if (Array.isArray(value.checks)) result.checks = value.checks.slice(0, 6).map(check => ({ ...fields(check, ['id', 'name', 'kind', 'framework', 'command', 'status']),
|
||||
...(typeof check.script === 'string' ? { scriptSha256: hash(check.script), scriptExcerpt: excerpt(check.script, 200) } : {}) }));
|
||||
if (Array.isArray(value.results)) result.results = value.results.slice(0, 6).map(item => ({ ...checkResult(item),
|
||||
...fields(item, ['path', 'line', 'name', 'kind', 'sha256', 'target']) }));
|
||||
if (Array.isArray(value.files)) result.files = value.files.slice(0, 8).map(file => fields(file, ['path', 'change_id', 'base_sha256', 'sha256', 'kind', 'bytes']));
|
||||
if (Array.isArray(value.paths)) result.paths = value.paths.slice(0, 8).map(item => typeof item === 'string' ? excerpt(item, 512) : null);
|
||||
if (value.execution && typeof value.execution === 'object') {
|
||||
const execution = value.execution;
|
||||
result.execution = {};
|
||||
if (execution.task) result.execution.task = { ...fields(execution.task, ['id', 'status']),
|
||||
...(execution.task.verification ? { verification: fields(execution.task.verification, ['status', 'checkJobId']) } : {}) };
|
||||
if (execution.run) result.execution.run = fields(execution.run, ['id', 'status', 'stopReason', 'steps', 'toolCalls']);
|
||||
if (execution.progress) result.execution.progress = { ...fields(execution.progress, ['totalTools', 'completedTools']),
|
||||
requiresVerification: (execution.progress.requiresVerification ?? []).slice(0, 6).map(tool => fields(tool, ['id', 'tool', 'state', 'callId'])),
|
||||
totalRequiresVerification: execution.progress.requiresVerification?.length ?? 0 };
|
||||
if (Array.isArray(execution.checks)) result.execution.checks = execution.checks.slice(-2).map(checkJob);
|
||||
if (Array.isArray(execution.changeSets)) result.execution.changeSets = execution.changeSets.slice(-2).map(set => fields(set, ['id', 'status', 'fingerprint', 'requiresVerification']));
|
||||
if (Array.isArray(execution.deliveries)) result.execution.deliveries = execution.deliveries.slice(-2).map(job => fields(job, ['id', 'status', 'commit', 'requiresVerification']));
|
||||
if (Array.isArray(execution.deliveryPlans)) result.execution.deliveryPlans = execution.deliveryPlans.slice(-1).map(plan => fields(plan, ['id', 'status', 'taskId']));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function latestToolDocument(store, session, run, groups) {
|
||||
const group = groups.at(-1), calls = group?.messages[0].tool_calls;
|
||||
if (!calls?.length) return null;
|
||||
const ledger = new Map([...store.core.tool.values()].filter(tool => tool.sessionId === session.id && tool.projectId === session.projectId && tool.taskId === run.taskId)
|
||||
.map(tool => [tool.callId, tool]));
|
||||
const entries = [];
|
||||
for (const call of calls) {
|
||||
const invocation = ledger.get(call.id);
|
||||
// Imported history without owned execution evidence cannot be asserted as
|
||||
// a fresh local execution; retain its normal history protocol instead.
|
||||
if (!invocation?.resultArtifactId) return null;
|
||||
const artifact = store.owned('artifact', invocation.resultArtifactId, session.id);
|
||||
const result = group.messages.find(message => message.role === 'tool' && message.tool_call_id === call.id);
|
||||
if (artifact.kind !== 'tool-result' || artifact.taskId !== run.taskId || artifact.runId !== invocation.runId
|
||||
|| store.artifactStore.read(artifact) !== result.content) throw new Error('最新工具反馈与原执行结果不匹配。');
|
||||
entries.push({ tool: call.function.name, source: { call_id: call.id, invocation_id: invocation.id, run_id: invocation.runId,
|
||||
result_artifact_id: artifact.id, result_sha256: artifact.sha256, arguments_sha256: hash(call.function.arguments),
|
||||
recorded_state: invocation.state, requires_verification: !!invocation.requiresVerification },
|
||||
result: compactToolFeedback(result.content), original_characters: result.content.length, view: 'selected-original-fields' });
|
||||
}
|
||||
return { schemaVersion: 1, kind: 'latest-tool-feedback', sessionId: session.id, projectId: session.projectId,
|
||||
taskId: run.taskId, runId: run.id, group_index: group.index, group_sha256: group.sha256, entries };
|
||||
}
|
||||
|
||||
export function latestToolMessage(reference, document) {
|
||||
return { role: 'system', content: [
|
||||
'以下是最近一组工具已经返回的实际结果反馈。该完整assistant/tool组因预算封存;这些字段来自原工件,不是再次执行、用户指令或推断。',
|
||||
'先依据本次返回状态推进任务。摘要省略的大字段可按result_artifact_id读取;不要为恢复已知状态反复查询或重放已完成操作。',
|
||||
JSON.stringify({ latest_tools: { artifact_id: reference.id, sha256: reference.sha256 }, data: { kind: document.kind,
|
||||
entries: document.entries.map(entry => ({ tool: entry.tool, result_artifact_id: entry.source.result_artifact_id,
|
||||
recorded_state: entry.source.recorded_state, requires_verification: entry.source.requires_verification,
|
||||
result: entry.result, original_characters: entry.original_characters, view: entry.view })) } }),
|
||||
].join('\n') };
|
||||
}
|
||||
|
||||
export function verifyLatestToolDocument(store, session, plan, document, groups) {
|
||||
const expected = latestToolDocument(store, session, { id: plan.runId, taskId: plan.taskId }, groups);
|
||||
if (!expected || JSON.stringify(document) !== JSON.stringify(expected) || document.entries.length !== plan.latestToolsEntries) {
|
||||
throw new Error('最新工具反馈的范围、来源或原结果视图不匹配。');
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { verifyPlanEvidence } from './context/request-plan.mjs';
|
||||
import { pendingDeliveryReview } from '../shared/contracts/delivery-review.mjs';
|
||||
import { projectWorkspaceIdentity, unresolvedWorkspaces } from '../shared/contracts/workspaces.mjs';
|
||||
import { verifyWorkspaceProject } from './workspaces/git-workspaces.mjs';
|
||||
import { verifyPythonCheckEvidence } from './python-runtime.mjs';
|
||||
|
||||
const labels = { verified_committed: '检查通过并已提交', verified_uncommitted: '检查通过,等待提交', needs_review: '等待改动或交付审查',
|
||||
needs_checks: '需要实际工程检查', needs_verification: '执行结果需要核对', in_progress: '任务仍在执行' };
|
||||
@@ -23,6 +24,7 @@ export function verifiedCheck(store, session, inspection) {
|
||||
const artifact = store.owned('artifact', result.logArtifactId, session.id);
|
||||
if (artifact.taskId !== task.id || artifact.kind !== 'check-log') return null;
|
||||
store.artifactStore.read(artifact);
|
||||
verifyPythonCheckEvidence(store, session, job, result);
|
||||
} catch { return null; }
|
||||
}
|
||||
return job;
|
||||
@@ -47,6 +49,17 @@ export class DeliveryReporter {
|
||||
.map(value => ({ id: value.id, tool: value.tool, status: value.state }));
|
||||
requiresVerification.push(...unresolvedWorkspaces(this.store, project.id).map(value => ({ id: value.id, tool: 'workspace', status: value.status })));
|
||||
const unresolved = jobs.filter(value => value.requiresVerification || value.status === 'unknown');
|
||||
const checkJobs = [...this.store.core.check_job.values()].filter(value => value.taskId === taskId);
|
||||
const pythonEvidence = new Map();
|
||||
for (const checkJob of checkJobs) if (!checkJob.stale && checkJob.sourceFingerprint === inspection.sourceFingerprint) {
|
||||
for (const result of checkJob.results.filter(value => value.engine === 'python' && value.status === 'passed')) {
|
||||
try { verifyPythonCheckEvidence(this.store, session, checkJob, result); pythonEvidence.set(result.id, { verified: true }); }
|
||||
catch (error) {
|
||||
pythonEvidence.set(result.id, { verified: false, error: error.message });
|
||||
requiresVerification.push({ id: result.id, tool: 'python_check', status: 'evidence_unverified' });
|
||||
}
|
||||
}
|
||||
}
|
||||
const sets = [...this.store.core.change_set.values()].filter(value => value.sessionId === session.id && value.taskId === taskId);
|
||||
const changeSets = sets.map(set => {
|
||||
let snapshotVerified = true, snapshotError = null;
|
||||
@@ -71,7 +84,9 @@ export class DeliveryReporter {
|
||||
historyIndexArtifactId: plan.historyIndexArtifactId, historyIndexSha256: plan.historyIndexSha256,
|
||||
workingSetArtifactId: plan.workingSetArtifactId ?? null, workingSetSha256: plan.workingSetSha256 ?? null,
|
||||
workingSetEntries: plan.workingSetEntries ?? 0, workingSetViewVersion: plan.workingSetViewVersion ?? 1,
|
||||
workingRetentionTokens: plan.workingRetentionTokens ?? 0, evidenceVerified, evidenceError };
|
||||
workingRetentionTokens: plan.workingRetentionTokens ?? 0,
|
||||
latestToolsArtifactId: plan.latestToolsArtifactId ?? null, latestToolsSha256: plan.latestToolsSha256 ?? null,
|
||||
latestToolsEntries: plan.latestToolsEntries ?? 0, evidenceVerified, evidenceError };
|
||||
});
|
||||
requiresVerification.push(...contextPlans.filter(plan => !plan.evidenceVerified).map(plan => ({ id: plan.id, tool: 'model_context', status: 'evidence_unverified' })));
|
||||
const deliveryReview = pendingDeliveryReview(this.store, session);
|
||||
@@ -94,11 +109,13 @@ export class DeliveryReporter {
|
||||
changeSets,
|
||||
...(deliveryReview ? { deliveryReview: { planId: deliveryReview.id, status: 'pending', paths: deliveryReview.paths } } : {}),
|
||||
contextPlans,
|
||||
checks: [...this.store.core.check_job.values()].filter(value => value.taskId === taskId).map(value => ({ id: value.id, status: value.status,
|
||||
checks: checkJobs.map(value => ({ id: value.id, status: value.status, planId: value.planId,
|
||||
contractArtifactId: this.store.core.check_plan.get(value.planId)?.contractArtifactId ?? null,
|
||||
stale: !!value.stale || (value.sourceFingerprint ? value.sourceFingerprint !== inspection.sourceFingerprint : value.fingerprint !== inspection.fingerprint),
|
||||
sourceFingerprint: value.sourceFingerprint ?? null, startedAt: value.startedAt, finishedAt: value.finishedAt,
|
||||
results: value.results.map(result => ({ ...result, logExcerpt: undefined,
|
||||
logSha256: this.store.core.artifact.get(result.logArtifactId)?.sha256 ?? null })) })),
|
||||
logSha256: this.store.core.artifact.get(result.logArtifactId)?.sha256 ?? null,
|
||||
...(result.engine === 'python' ? { pythonEvidence: pythonEvidence.get(result.id) ?? { verified: false, state: 'historical_or_not_passed' } } : {}) })) })),
|
||||
verifiedCheckJobId: check?.id ?? null,
|
||||
deliveries: jobs.map(value => ({ id: value.id, status: value.status, commit: value.commit ?? null, expectedCommit: value.expectedCommit ?? null,
|
||||
parent: value.parent, sourceFingerprint: value.sourceFingerprint, paths: value.paths, summary: value.summary, requiresVerification: !!value.requiresVerification,
|
||||
@@ -137,6 +154,13 @@ export function renderDeliveryMarkdown(report) {
|
||||
lines.push('', '## 实际检查', '', '| Job / 命令 | 状态 | 退出码 | 实际测试 | 日志SHA256 |', '| --- | --- | --- | --- | --- |');
|
||||
for (const job of report.checks) for (const result of job.results) lines.push('| ' + [job.id.slice(0, 8) + ' / ' + result.command,
|
||||
job.stale ? '源码已变化 / ' + result.status : result.status, result.exitCode ?? '未知', result.tests ? result.tests.passed + '/' + result.tests.total : '不适用或未知', result.logSha256 ?? '未知'].map(escapeCell).join(' | ') + ' |');
|
||||
const pythonResults = report.checks.flatMap(job => job.results.filter(result => result.python));
|
||||
if (pythonResults.length) {
|
||||
lines.push('', '### Python实际执行', '', '| 检查 | 解释器 | 版本 | 结构化结果SHA256 |', '| --- | --- | --- | --- |');
|
||||
for (const result of pythonResults) lines.push('| ' + [result.command, result.python.runtime.executable, result.python.runtime.version, result.metricsSha256 ?? '未返回'].map(escapeCell).join(' | ') + ' |',
|
||||
'', '运行器SHA256:' + result.python.runner.sha256, '封存输入SHA256:' + result.python.inputSha256,
|
||||
...(result.compilation ? ['语法编译:' + result.compilation.compiled + '/' + result.compilation.total + ' 个源码文件。'] : []));
|
||||
}
|
||||
lines.push('', '## Git交付', '');
|
||||
if (report.deliveryReview) lines.push('Git提交预览已保存,等待确认。计划:' + report.deliveryReview.planId, '');
|
||||
if (!report.deliveries.length) lines.push('尚无内置Git提交记录。');
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { listFiles, safePath, readText, excludedFromInventory } from '../server/files.mjs';
|
||||
import { runGit } from './git-process.mjs';
|
||||
import { inspectPythonProject } from './python-project.mjs';
|
||||
|
||||
const hash = value => createHash('sha256').update(value).digest('hex');
|
||||
const languages = { '.js': 'JavaScript', '.mjs': 'JavaScript', '.cjs': 'JavaScript', '.ts': 'TypeScript', '.tsx': 'TypeScript', '.mts': 'TypeScript', '.cts': 'TypeScript', '.jsx': 'JavaScript', '.py': 'Python', '.go': 'Go', '.rs': 'Rust', '.cs': 'C#', '.vue': 'Vue', '.html': 'HTML', '.css': 'CSS' };
|
||||
@@ -99,13 +100,14 @@ export async function inspectProject(project, { includeFiles = false } = {}) {
|
||||
for (const relative of ['pyproject.toml', 'Cargo.toml', 'go.mod', 'tsconfig.json']) {
|
||||
const file = declaration(project, relative); if (file) declarations[relative] = { sha256: file.sha256, excerpt: file.content.slice(0, 1000) };
|
||||
}
|
||||
const python = inspectPythonProject(project, sourceFiles, relative => declaration(project, relative));
|
||||
const fingerprint = hash(JSON.stringify({ projectId: project.id, root, files: fingerprints, packageSha256: packageFile?.sha256 ?? null,
|
||||
head: git.head, gitStatus: git.statusSha256 ?? null, complete }));
|
||||
...(python ? { pythonDeclarationHashes: python.declarationHashes } : {}), head: git.head, gitStatus: git.statusSha256 ?? null, complete }));
|
||||
const sourceFingerprint = hash(JSON.stringify({ projectId: project.id, root, files: fingerprints,
|
||||
packageSha256: packageFile?.sha256 ?? null, complete }));
|
||||
packageSha256: packageFile?.sha256 ?? null, ...(python ? { pythonDeclarationHashes: python.declarationHashes } : {}), complete }));
|
||||
const { paths, ...visibleGit } = git;
|
||||
return { projectId: project.id, name: typeof manifest?.name === 'string' ? manifest.name.slice(0, 150) : project.name,
|
||||
languages: [...detected].sort(), packageManager, scripts, rules, declarations,
|
||||
languages: [...detected].sort(), packageManager, scripts, rules, declarations, ...(python ? { python } : {}),
|
||||
entryPoints: [manifest?.main, typeof manifest?.bin === 'string' ? manifest.bin : null, names.includes('src/index.ts') ? 'src/index.ts' : null, names.includes('src/index.mjs') ? 'src/index.mjs' : null].filter(value => typeof value === 'string').slice(0, 5),
|
||||
git: visibleGit, fingerprint, sourceFingerprint, inspectedAt: new Date().toISOString(),
|
||||
...(includeFiles ? { files: sourceFiles } : {}),
|
||||
@@ -115,11 +117,17 @@ export async function inspectProject(project, { includeFiles = false } = {}) {
|
||||
|
||||
export function createCheckList(inspection, names) {
|
||||
if (names !== undefined && (!Array.isArray(names) || !names.length || names.length > 6 || names.some(name => typeof name !== 'string'))) throw new Error('检查脚本选择需要1到6个已识别名称。');
|
||||
if (inspection.packageManager !== 'npm') return [];
|
||||
if (inspection.python?.status === 'invalid' && (inspection.packageManager !== 'npm' || names?.some(name => name.startsWith('python:')))) throw new Error(inspection.python.message);
|
||||
const npmScripts = inspection.packageManager === 'npm' ? inspection.scripts : [];
|
||||
const pythonChecks = inspection.python?.checks ?? [];
|
||||
if (!npmScripts.length && !pythonChecks.length) return [];
|
||||
const preferred = ['test', 'typecheck', 'check', 'lint', 'build'];
|
||||
const selected = names ?? [...(inspection.scripts.some(script => script.name === 'test') ? ['test'] : inspection.scripts.filter(script => script.kind === 'test').map(script => script.name).slice(0, 2)), ...preferred.slice(1).filter(name => inspection.scripts.some(script => script.name === name))].slice(0, 6);
|
||||
const selected = names ?? (inspection.packageManager === 'npm'
|
||||
? [...(npmScripts.some(script => script.name === 'test') ? ['test'] : npmScripts.filter(script => script.kind === 'test').map(script => script.name).slice(0, 2)), ...preferred.slice(1).filter(name => npmScripts.some(script => script.name === name))].slice(0, 6)
|
||||
: pythonChecks.map(check => check.name));
|
||||
return [...new Set(selected)].map(name => {
|
||||
const script = inspection.scripts.find(item => item.name === name);
|
||||
const python = pythonChecks.find(item => item.name === name); if (python) return structuredClone(python);
|
||||
const script = npmScripts.find(item => item.name === name);
|
||||
if (!script) throw new Error('这个脚本不在已识别的检查能力中:' + name);
|
||||
return { ...script, command: 'npm run ' + name };
|
||||
});
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import fs from 'node:fs';
|
||||
import { parse } from 'smol-toml';
|
||||
import { safePath } from '../server/files.mjs';
|
||||
|
||||
export function inspectPythonProject(project, files, readDeclaration) {
|
||||
const sources = files.filter(file => file.language === 'Python' && file.sha256).map(file => ({ path: file.path, sha256: file.sha256 }));
|
||||
const pyproject = readDeclaration('pyproject.toml'), pytestIni = readDeclaration('pytest.ini');
|
||||
if (!sources.length && !pyproject && !pytestIni) return null;
|
||||
const declarationHashes = Object.fromEntries([['pyproject.toml', pyproject], ['pytest.ini', pytestIni]].filter(([, file]) => file).map(([name, file]) => [name, file.sha256]));
|
||||
let document = {}, settings, framework, testPaths, pattern;
|
||||
try {
|
||||
if (pyproject) document = parse(pyproject.content);
|
||||
const own = document.tool?.['agent-workbench']?.python ?? {};
|
||||
if (!own || typeof own !== 'object' || Array.isArray(own)) throw new Error('tool.agent-workbench.python需要一个表。');
|
||||
const pytest = document.tool?.pytest?.ini_options;
|
||||
const dependencies = [...(document.project?.dependencies ?? []), ...Object.values(document.project?.['optional-dependencies'] ?? {}).flat(),
|
||||
...Object.values(document['dependency-groups'] ?? {}).flat()].filter(item => typeof item === 'string');
|
||||
framework = own.framework ?? (pytest || pytestIni || dependencies.some(item => /^pytest(?:[<>=!~\s;\[]|$)/i.test(item)) ? 'pytest' : 'unittest');
|
||||
if (!['pytest', 'unittest'].includes(framework)) throw new Error('Python检查框架只支持unittest或pytest。');
|
||||
const common = ['tests', 'test'].find(folder => sources.some(file => file.path.startsWith(folder + '/')));
|
||||
testPaths = own['test-paths'] ?? (framework === 'pytest' ? pytest?.testpaths : undefined) ?? [common || '.'];
|
||||
if (!Array.isArray(testPaths) || !testPaths.length || testPaths.length > 6 || testPaths.some(item => typeof item !== 'string' || !item || item.length > 500)) throw new Error('Python test-paths需要1到6个项目相对路径。');
|
||||
testPaths = [...new Set(testPaths)];
|
||||
for (const relative of testPaths) {
|
||||
const absolute = safePath(project, relative);
|
||||
if (fs.lstatSync(absolute).isSymbolicLink() || !fs.statSync(absolute).isDirectory() && !(framework === 'pytest' && fs.statSync(absolute).isFile() && relative.endsWith('.py'))) throw new Error('Python检查目标需要常规目录或pytest测试文件。');
|
||||
}
|
||||
if (framework === 'unittest' && testPaths.length !== 1) throw new Error('unittest当前支持一个显式发现目录。');
|
||||
pattern = own.pattern ?? 'test*.py';
|
||||
if (typeof pattern !== 'string' || pattern.length > 128 || !/^[a-z0-9_.*?\[\]-]+\.py$/i.test(pattern)) throw new Error('unittest pattern需要文件名模式,不能包含目录或命令。');
|
||||
settings = framework === 'unittest' ? { startDirectory: testPaths[0], pattern } : { testPaths,
|
||||
configPath: pytestIni ? 'pytest.ini' : pytest ? 'pyproject.toml' : null, neutralizeAddopts: true };
|
||||
} catch (error) {
|
||||
return { status: 'invalid', declarationHashes, sources, checks: [], message: 'Python检查声明无效:' + error.message };
|
||||
}
|
||||
const hasTests = sources.some(file => /(^|\/)(test[^/]*|[^/]*_test)\.py$/i.test(file.path)) || !!document.tool?.pytest || !!pytestIni || !!document.tool?.['agent-workbench']?.python;
|
||||
const checks = [];
|
||||
if (hasTests) checks.push({ name: 'python:test', kind: 'test', framework, engine: 'python', command: framework + ' · ' + testPaths.join(', '),
|
||||
script: framework === 'unittest' ? 'unittest发现目录:' + testPaths[0] + '\n文件模式:' + pattern : 'pytest测试目标:' + testPaths.join(', ') + '\n配置:' + (settings.configPath || '默认') + '\n使用所选目标;不追加环境或配置中的addopts。',
|
||||
lifecycle: [], python: { mode: framework, settings, files: sources } });
|
||||
if (sources.length) checks.push({ name: 'python:compile', kind: 'check', framework: null, engine: 'python', command: 'Python源码编译 · ' + sources.length + ' 个文件',
|
||||
script: '按已登记源码字节进行语法编译,不执行模块。', lifecycle: [], python: { mode: 'compile', settings: {}, files: sources } });
|
||||
const candidates = ['.venv/Scripts/python.exe', 'venv/Scripts/python.exe', '.venv/bin/python', 'venv/bin/python'];
|
||||
const preferredExecutable = candidates.find(relative => {
|
||||
try { const absolute = safePath(project, relative); return fs.statSync(absolute).isFile(); } catch { return false; }
|
||||
}) ?? null;
|
||||
return { status: 'detected', framework, declarationHashes, settings, sources, checks, preferredExecutable,
|
||||
note: '静态识别源码、测试目标和声明;未导入项目或执行项目解释器。' };
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
const executeFile = promisify(execFile);
|
||||
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
|
||||
const normalize = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
|
||||
const within = (root, file) => normalize(file) === normalize(root) || normalize(file).startsWith(normalize(root) + path.sep);
|
||||
const fileIdentity = file => {
|
||||
const resolved = fs.realpathSync.native(file), info = fs.statSync(resolved);
|
||||
if (!info.isFile() || info.size > 64 * 1024 * 1024) throw new Error('Python运行文件不是受支持的常规文件。');
|
||||
return { path: resolved, sha256: digest(fs.readFileSync(resolved)) };
|
||||
};
|
||||
export function pythonEnvironment() {
|
||||
const environment = { ...process.env, NO_COLOR: '1', CI: '1', PYTEST_DISABLE_PLUGIN_AUTOLOAD: '1', PYTHONDONTWRITEBYTECODE: '1' };
|
||||
for (const key of ['AGENT_WORKBENCH_API_KEY', 'NODE_TEST_CONTEXT', 'PYTEST_ADDOPTS', 'PYTEST_PLUGINS', 'PYTHONPATH', 'PYTHONHOME', 'PYTHONSTARTUP', 'FORCE_COLOR']) delete environment[key];
|
||||
return environment;
|
||||
}
|
||||
function configurationFor(executable) {
|
||||
for (const file of [path.join(path.dirname(executable), 'pyvenv.cfg'), path.join(path.dirname(executable), '..', 'pyvenv.cfg')]) {
|
||||
if (fs.existsSync(file)) return fileIdentity(file);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function candidates(project, executable) {
|
||||
if (executable) return [path.isAbsolute(executable) ? path.resolve(executable) : path.resolve(project.root, executable)];
|
||||
const values = [];
|
||||
for (const directory of (process.env.PATH ?? '').split(path.delimiter).filter(Boolean)) {
|
||||
if (process.platform === 'win32' && /[\\/]Microsoft[\\/]WindowsApps(?:[\\/]|$)/i.test(directory)) continue;
|
||||
for (const name of process.platform === 'win32' ? ['python.exe', 'python3.exe'] : ['python3', 'python']) values.push(path.join(directory, name));
|
||||
}
|
||||
if (process.platform === 'win32' && process.env.LOCALAPPDATA) {
|
||||
const installed = path.join(process.env.LOCALAPPDATA, 'Programs', 'Python');
|
||||
if (fs.existsSync(installed)) for (const item of fs.readdirSync(installed, { withFileTypes: true }).filter(item => item.isDirectory() && /^Python\d+/i.test(item.name)).sort((a, b) => b.name.localeCompare(a.name))) values.push(path.join(installed, item.name, 'python.exe'));
|
||||
}
|
||||
return [...new Set(values)].filter(file => fs.existsSync(file));
|
||||
}
|
||||
const probeCode = 'import json,os,sys; print(json.dumps({"executable":os.path.realpath(sys.executable),"version":sys.version.split()[0],"baseExecutable":os.path.realpath(getattr(sys,"_base_executable",sys.executable))}))';
|
||||
|
||||
export async function resolvePythonRuntime(project, { executable, allowProjectProbe = false, signal } = {}) {
|
||||
const errors = [];
|
||||
for (const logicalExecutable of candidates(project, executable)) {
|
||||
try {
|
||||
const identity = fileIdentity(logicalExecutable), configuration = configurationFor(logicalExecutable);
|
||||
const insideProject = within(project.root, logicalExecutable) || within(project.root, identity.path);
|
||||
if (insideProject && !allowProjectProbe) return { status: 'deferred', logicalExecutable, executable: identity.path,
|
||||
sha256: identity.sha256, configuration, version: null, probe: 'after-check-approval', insideProject: true };
|
||||
const output = await executeFile(logicalExecutable, ['-I', '-S', '-X', 'utf8', '-c', probeCode],
|
||||
{ cwd: os.tmpdir(), env: pythonEnvironment(), windowsHide: true, timeout: 5000, maxBuffer: 16000, signal });
|
||||
const info = JSON.parse(output.stdout.trim()), version = info.version?.split('.').map(Number);
|
||||
if (version?.[0] !== 3 || version[1] < 10) throw new Error('内置Python检查需要Python 3.10或更新版本。');
|
||||
if (normalize(info.executable) !== normalize(identity.path)) throw new Error('Python探测返回了不同的解释器。');
|
||||
const base = fileIdentity(info.baseExecutable);
|
||||
const libraries = process.platform === 'win32' ? fs.readdirSync(path.dirname(base.path)).filter(name => /^python\d+\.dll$/i.test(name)).sort().map(name => fileIdentity(path.join(path.dirname(base.path), name))) : [];
|
||||
return { status: 'available', logicalExecutable, executable: identity.path, sha256: identity.sha256, configuration,
|
||||
version: info.version, baseExecutable: base.path, baseSha256: base.sha256, libraries, insideProject,
|
||||
probe: insideProject ? 'after-check-approval' : 'isolated-host-probe' };
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw error;
|
||||
errors.push({ executable: logicalExecutable, message: String(error.message).slice(0, 300) });
|
||||
}
|
||||
}
|
||||
return { status: 'missing', logicalExecutable: executable ?? null, executable: null, version: null, errors: errors.slice(0, 3),
|
||||
message: '未找到可用的Python 3.10+解释器。可安装Python或设置AGENT_WORKBENCH_PYTHON_PATH,然后重新识别检查。' };
|
||||
}
|
||||
|
||||
export async function bindPythonChecks(project, checks, { executable, runnerPath } = {}) {
|
||||
if (!checks.some(check => check.engine === 'python')) return checks;
|
||||
const runtime = await resolvePythonRuntime(project, { executable }), runner = fileIdentity(runnerPath);
|
||||
return checks.map(check => check.engine === 'python' ? { ...check, python: { ...check.python, runtime, runner } } : check);
|
||||
}
|
||||
|
||||
export async function preparePythonInvocation(check, project, { signal } = {}) {
|
||||
const planned = check.python.runtime;
|
||||
if (planned.status === 'missing') throw new Error(planned.message);
|
||||
const runner = fileIdentity(check.python.runner.path);
|
||||
if (runner.sha256 !== check.python.runner.sha256) throw Object.assign(new Error('内置Python检查器在计划后变化,请重新识别检查。'), { status: 409 });
|
||||
if (fileIdentity(planned.logicalExecutable).sha256 !== planned.sha256 || JSON.stringify(configurationFor(planned.logicalExecutable)) !== JSON.stringify(planned.configuration)
|
||||
|| planned.status === 'available' && [
|
||||
{ path: planned.baseExecutable, sha256: planned.baseSha256 }, ...(planned.libraries ?? [])
|
||||
].some(file => fileIdentity(file.path).sha256 !== file.sha256)) {
|
||||
throw Object.assign(new Error('Python解释器或环境声明在计划后变化,未执行探测或检查。'), { status: 409 });
|
||||
}
|
||||
const actual = await resolvePythonRuntime(project, { executable: planned.logicalExecutable, allowProjectProbe: true, signal });
|
||||
if (actual.status !== 'available') throw new Error(actual.message);
|
||||
if (actual.sha256 !== planned.sha256 || JSON.stringify(actual.configuration) !== JSON.stringify(planned.configuration)
|
||||
|| planned.status === 'available' && (actual.version !== planned.version || actual.baseSha256 !== planned.baseSha256 || JSON.stringify(actual.libraries) !== JSON.stringify(planned.libraries))) {
|
||||
throw Object.assign(new Error('Python解释器或环境声明在计划后变化,请重新识别检查。'), { status: 409 });
|
||||
}
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'awb-python-'));
|
||||
if (within(project.root, directory)) throw new Error('Python结果目录必须位于项目之外。');
|
||||
const executableRunner = path.join(directory, 'runner.py'), resultPath = path.join(directory, 'result.json'), invocationId = randomUUID();
|
||||
fs.writeFileSync(executableRunner, fs.readFileSync(runner.path), { flag: 'wx' });
|
||||
const input = Buffer.from(JSON.stringify({ invocationId, root: fs.realpathSync.native(project.root), mode: check.python.mode,
|
||||
settings: check.python.settings, files: check.python.files }));
|
||||
const args = ['-I', '-B', '-u', '-X', 'utf8', executableRunner, resultPath];
|
||||
return { executable: planned.logicalExecutable, args, input, resultPath, directory, mode: check.python.mode,
|
||||
runtime: actual, runner, invocationId, inputSha256: digest(input), files: check.python.files,
|
||||
dispose() {
|
||||
const resolved = path.resolve(directory), temporary = path.resolve(os.tmpdir());
|
||||
if (!within(temporary, resolved) || !path.basename(resolved).startsWith('awb-python-')) throw new Error('Python临时目录归属需要核对。');
|
||||
fs.rmSync(resolved, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 });
|
||||
} };
|
||||
}
|
||||
|
||||
export function readPythonEvidence(invocation, exitCode) {
|
||||
if (!fs.existsSync(invocation.resultPath)) throw new Error('Python进程未返回结构化结果,日志文字不能代替测试统计。');
|
||||
if (fs.statSync(invocation.resultPath).size > 2 * 1024 * 1024) throw new Error('Python结构化结果超过读取上限。');
|
||||
const text = fs.readFileSync(invocation.resultPath, 'utf8'), result = JSON.parse(text);
|
||||
validatePythonEvidence(result, invocation, exitCode);
|
||||
return { result, text };
|
||||
}
|
||||
|
||||
export function validatePythonEvidence(result, invocation, exitCode) {
|
||||
if (result.schemaVersion !== 1 || result.kind !== 'python-check-result' || result.invocationId !== invocation.invocationId
|
||||
|| result.inputSha256 !== invocation.inputSha256 || result.runnerSha256 !== invocation.runner.sha256 || result.mode !== invocation.mode
|
||||
|| result.exitCode !== exitCode || result.runtime?.sha256 !== invocation.runtime.sha256
|
||||
|| result.runtime?.baseSha256 !== invocation.runtime.baseSha256 || result.runtime?.version !== invocation.runtime.version
|
||||
|| normalize(result.runtime?.executable ?? '') !== normalize(invocation.runtime.executable)) throw new Error('Python结果与实际调用、解释器或封存输入不匹配。');
|
||||
if (!result.collectorError) {
|
||||
if (invocation.mode === 'compile') {
|
||||
const value = result.compilation;
|
||||
if (!value || value.total !== invocation.files.length || !Number.isSafeInteger(value.compiled) || value.compiled < 0
|
||||
|| !Array.isArray(value.failures) || value.compiled + value.failures.length !== value.total) throw new Error('Python编译数量无法核对。');
|
||||
} else {
|
||||
const value = result.tests, keys = ['total', 'passed', 'failed', 'skipped', 'cancelled'];
|
||||
if (result.framework !== invocation.mode || !value || keys.some(key => !Number.isSafeInteger(value[key]) || value[key] < 0)
|
||||
|| value.total !== value.passed + value.failed + value.skipped + value.cancelled
|
||||
|| !Number.isSafeInteger(result.collectionErrors) || result.collectionErrors < 0
|
||||
|| !Number.isSafeInteger(result.collectionSkipped) || result.collectionSkipped < 0) throw new Error('Python实际测试数量无法核对。');
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function pythonResultBinding(invocation) {
|
||||
return { invocationId: invocation.invocationId, inputSha256: invocation.inputSha256, runner: invocation.runner,
|
||||
executable: invocation.executable, args: invocation.args, runtime: invocation.runtime, mode: invocation.mode };
|
||||
}
|
||||
|
||||
export function verifyPythonCheckEvidence(store, session, job, result) {
|
||||
if (result.engine !== 'python') return;
|
||||
if (!result.evidenceValidated || !result.metricsArtifactId || !result.inputArtifactId || !result.python) throw new Error('Python检查缺少实际结构化证据。');
|
||||
const metrics = store.owned('artifact', result.metricsArtifactId, session.id), input = store.owned('artifact', result.inputArtifactId, session.id);
|
||||
if (metrics.kind !== 'check-metrics' || input.kind !== 'check-input' || metrics.taskId !== job.taskId || metrics.runId !== job.runId
|
||||
|| input.taskId !== job.taskId || input.runId !== job.runId || metrics.sha256 !== result.metricsSha256 || input.sha256 !== result.python.inputSha256) throw new Error('Python检查证据归属或输入散列不匹配。');
|
||||
const payload = JSON.parse(store.artifactStore.read(input)), collected = JSON.parse(store.artifactStore.read(metrics));
|
||||
if (payload.invocationId !== result.python.invocationId || payload.mode !== result.python.mode) throw new Error('Python检查封存输入与执行身份不匹配。');
|
||||
validatePythonEvidence(collected, { ...result.python, files: payload.files }, result.exitCode);
|
||||
if (JSON.stringify(collected.tests ?? null) !== JSON.stringify(result.tests) || JSON.stringify(collected.compilation ?? null) !== JSON.stringify(result.compilation)) throw new Error('Python检查统计与原收集结果不一致。');
|
||||
for (const file of [{ path: result.python.runtime.executable, sha256: result.python.runtime.sha256 },
|
||||
{ path: result.python.runtime.baseExecutable, sha256: result.python.runtime.baseSha256 }, result.python.runner,
|
||||
result.python.runtime.configuration, ...(result.python.runtime.libraries ?? [])].filter(Boolean)) {
|
||||
if (fileIdentity(file.path).sha256 !== file.sha256) throw new Error('Python执行环境在检查后变化,需要重新验证。');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user