190 lines
13 KiB
JavaScript
190 lines
13 KiB
JavaScript
import fs from 'node:fs';
|
||
import { createHash } from 'node:crypto';
|
||
import { safePath } from '../server/files.mjs';
|
||
import { inspectProject } from './project-inspector.mjs';
|
||
import { runGit } from './git-process.mjs';
|
||
|
||
const sha = value => createHash('sha256').update(value).digest('hex');
|
||
const sameRepository = (a, b) => ['reference', 'gitDir', 'indexPath'].every(key => a[key] === b[key]);
|
||
const sameState = (a, b) => sameRepository(a, b) && ['head', 'stage', 'flags'].every(key => a[key] === b[key])
|
||
&& JSON.stringify(a.config) === JSON.stringify(b.config);
|
||
const owns = (session, run) => session.taskId === run.taskId && session.runId === run.id && run.record.purpose !== 'diagnostic' && !run.worker;
|
||
const scopeFiles = files => files.map(({ path, changeIds, mode, beforeBlob, afterBlob, baseSha256, sha256 }) =>
|
||
({ path, changeIds, mode, beforeBlob, afterBlob, baseSha256, sha256 }));
|
||
|
||
function protectedIndex(snapshot, files) {
|
||
const paths = new Set(files.map(file => file.path));
|
||
return sha(JSON.stringify({
|
||
stage: snapshot.stage.split('\0').filter(line => line && !paths.has(line.slice(line.indexOf('\t') + 1))).sort(),
|
||
flags: snapshot.flags.split('\0').filter(line => line && !paths.has(line.slice(2))).sort(),
|
||
}));
|
||
}
|
||
|
||
function assertCurrentFiles(store, session, files) {
|
||
const project = store.project(session.projectId);
|
||
for (const file of files) {
|
||
const change = session.changes.findLast(row => row.taskId === session.taskId && row.path.replaceAll('\\', '/') === file.path && row.status === 'applied');
|
||
const target = safePath(project, file.path), stat = fs.lstatSync(target);
|
||
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error('任务交付路径不再是普通文件:' + file.path);
|
||
if (!change || change.id !== file.changeIds.at(-1) || change.sha256 !== file.sha256
|
||
|| sha(fs.readFileSync(target)) !== file.sha256) throw new Error('任务文件或已应用提案在观察后变化:' + file.path);
|
||
}
|
||
}
|
||
|
||
async function git(project, args) {
|
||
const result = await runGit(safePath(project), args);
|
||
if (!result.ok) throw new Error(result.error.trim() || '终端提交的Git只读核对失败。');
|
||
return result.text;
|
||
}
|
||
|
||
async function commitFacts(project, before, after) {
|
||
const ids = (await git(project, ['rev-list', '--reverse', before + '..' + after])).trim().split('\n').filter(Boolean);
|
||
const commits = [];
|
||
for (const id of ids) {
|
||
const parents = (await git(project, ['rev-list', '--parents', '-n', '1', id])).trim().split(' ').slice(1);
|
||
commits.push({ id, parents });
|
||
}
|
||
const paths = (await git(project, ['diff-tree', '--no-commit-id', '--no-renames', '--name-only', '-r', '-z', before, after])).split('\0').filter(Boolean).sort();
|
||
return { commits, paths };
|
||
}
|
||
|
||
async function assertCommitScope(project, baseline, before, after, facts) {
|
||
if (!sameRepository(baseline.snapshot, before) || !sameRepository(before, after) || baseline.snapshot.head !== before.head) throw new Error('Git仓库、分支或提交父基线已变化。');
|
||
let parent = before.head;
|
||
for (const commit of facts.commits) {
|
||
if (commit.parents.length !== 1 || commit.parents[0] !== parent) throw new Error('观察到的提交不是原基线上的连续单父提交。');
|
||
parent = commit.id;
|
||
}
|
||
if (!facts.commits.length || parent !== after.head) throw new Error('未能核对从原HEAD到当前HEAD的提交链。');
|
||
if (JSON.stringify(facts.paths) !== JSON.stringify(baseline.files.map(file => file.path).sort())) throw new Error('实际提交路径与本任务已应用文件范围不一致。');
|
||
if (protectedIndex(baseline.snapshot, baseline.files) !== protectedIndex(after, baseline.files)) throw new Error('非目标Git索引条目或标记发生变化。');
|
||
// Check each commit, too: an unrelated file added and reverted in the same
|
||
// command must not disappear from the ownership review of the net diff.
|
||
const allowed = new Set(baseline.files.map(file => file.path));
|
||
for (const commit of facts.commits) {
|
||
const paths = (await git(project, ['diff-tree', '--no-commit-id', '--no-renames', '--name-only', '-r', '-z', commit.parents[0], commit.id])).split('\0').filter(Boolean);
|
||
if (paths.some(name => !allowed.has(name))) throw new Error('中间提交包含本任务范围之外的文件。');
|
||
}
|
||
for (const file of baseline.files) {
|
||
const tree = (await git(project, ['ls-tree', '-z', after.head, '--', file.path])).split('\0').filter(Boolean);
|
||
if (tree.length !== 1 || tree[0] !== file.mode + ' blob ' + file.afterBlob + '\t' + file.path) throw new Error('提交中的文件blob或模式与任务文件不一致:' + file.path);
|
||
const index = after.stage.split('\0').filter(line => line.endsWith('\t' + file.path));
|
||
if (index.length !== 1 || index[0] !== file.mode + ' ' + file.afterBlob + ' 0\t' + file.path) throw new Error('提交后的目标索引与当前提交不一致:' + file.path);
|
||
}
|
||
}
|
||
|
||
// Observe actual repository state; this class never stages, commits, resets,
|
||
// retries a command, or turns terminal output into an internal delivery job.
|
||
export class TerminalGitObserver {
|
||
constructor(store, delivery) { this.store = store; this.delivery = delivery; }
|
||
|
||
async before(session, event, run) {
|
||
if (!owns(session, run)) return null;
|
||
const state = run.terminalGitState ??= {}, context = { errors: [], snapshot: null, baseline: null, externalDrift: false };
|
||
try {
|
||
context.snapshot = await this.delivery.snapshot(run.project);
|
||
if (!owns(session, run)) return null;
|
||
if (state.lastSnapshot && !sameState(state.lastSnapshot, context.snapshot)) {
|
||
context.externalDrift = true; context.previousHead = state.lastSnapshot.head; state.baseline = null;
|
||
context.errors.push('两次终端命令之间Git状态发生外部漂移,不能将该变化认证为本次命令产生。');
|
||
}
|
||
if (!state.baseline) {
|
||
try {
|
||
const files = scopeFiles(await this.delivery.selectedFiles(session, run.project, context.snapshot));
|
||
const inspection = await inspectProject(run.project);
|
||
state.baseline = { snapshot: context.snapshot, files, sourceFingerprint: inspection.sourceFingerprint,
|
||
invocationId: event.invocationId, taskId: run.taskId, runId: run.id };
|
||
} catch (error) { context.errors.push(error.message); }
|
||
}
|
||
if (state.baseline) {
|
||
assertCurrentFiles(this.store, session, state.baseline.files);
|
||
context.baseline = structuredClone(state.baseline);
|
||
}
|
||
} catch (error) { state.baseline = null; context.errors.push(error.message); }
|
||
return context;
|
||
}
|
||
|
||
async after(session, event, run, context, result) {
|
||
if (!context || !owns(session, run)) return null;
|
||
try {
|
||
const after = await this.delivery.snapshot(run.project);
|
||
if (!owns(session, run)) return null;
|
||
run.terminalGitState.lastSnapshot = after;
|
||
const changed = context.snapshot && context.snapshot.head !== after.head;
|
||
if (!changed && !context.externalDrift) return null;
|
||
const errors = [...context.errors], baseline = context.baseline, project = run.project;
|
||
const facts = changed ? await commitFacts(project, context.snapshot.head, after.head) : { commits: [], paths: [] };
|
||
const inspection = await inspectProject(project);
|
||
if (!baseline) errors.push('没有可核对的本任务已应用文件基线,仅保留实际Git观察。');
|
||
else {
|
||
try {
|
||
assertCurrentFiles(this.store, session, baseline.files);
|
||
await assertCommitScope(project, baseline, context.snapshot, after, facts);
|
||
if (inspection.sourceFingerprint !== baseline.sourceFingerprint) throw new Error('终端命令同时改变了源码,提交范围需要另行核对。');
|
||
} catch (error) { errors.push(error.message); }
|
||
}
|
||
if (!owns(session, run)) return null;
|
||
const evidence = { schemaVersion: 1, kind: 'terminal-git-evidence', sessionId: session.id, projectId: session.projectId,
|
||
taskId: run.taskId, runId: run.id, invocationId: event.invocationId, eventId: event.id, observedAt: new Date().toISOString(),
|
||
status: errors.length ? 'unverified' : 'verified', errors, processAttribution: 'unproven',
|
||
command: { status: result.status, exitCode: result.exit_code, argsSha256: this.store.core.tool.get(event.invocationId)?.argsSha256 },
|
||
observedInCommand: !!changed, externalDrift: context.externalDrift, previousHead: context.previousHead ?? null,
|
||
before: context.snapshot, after, baseline, ...facts, sourceFingerprint: inspection.sourceFingerprint };
|
||
const artifact = this.store.artifactStore.write(session, run.record, evidence, { kind: 'terminal-git-evidence' });
|
||
this.store.core.artifact.set(artifact.id, artifact);
|
||
(run.record.terminalGitEvidence ??= []).push({ artifactId: artifact.id, sha256: artifact.sha256 });
|
||
run.terminalGitState.baseline = null;
|
||
this.store.save(session, { type: 'git.terminal_observed', detail: { runId: run.id, artifactId: artifact.id, status: evidence.status, commit: after.head } });
|
||
return { status: evidence.status, artifact_id: artifact.id, commit: after.head, process_attribution: 'unproven' };
|
||
} catch (error) {
|
||
// Observation failure cannot suppress a completed terminal command.
|
||
run.record.terminalGitObservationError = this.delivery.redact(error.message);
|
||
return { status: 'unverified', message: run.record.terminalGitObservationError };
|
||
}
|
||
}
|
||
}
|
||
|
||
export async function inspectTerminalGit(store, session, inspection) {
|
||
const results = [], project = store.project(session.projectId);
|
||
for (const run of store.core.run.values()) {
|
||
if (run.sessionId !== session.id || run.taskId !== session.taskId || run.purpose === 'diagnostic') continue;
|
||
for (const reference of run.terminalGitEvidence ?? []) {
|
||
const row = { runId: run.id, artifactId: reference.artifactId, source: 'terminal', processAttribution: 'unproven',
|
||
evidenceVerified: false, currentVerified: false, status: 'unverified', commit: null, paths: [] };
|
||
try {
|
||
const artifact = store.owned('artifact', reference.artifactId, session.id);
|
||
if (artifact.taskId !== run.taskId || artifact.runId !== run.id || artifact.kind !== 'terminal-git-evidence' || artifact.sha256 !== reference.sha256) throw new Error('终端Git工件归属或SHA256不一致。');
|
||
const evidence = JSON.parse(store.artifactStore.read(artifact));
|
||
if (evidence.schemaVersion !== 1 || evidence.kind !== 'terminal-git-evidence' || evidence.sessionId !== session.id
|
||
|| evidence.projectId !== project.id || evidence.taskId !== run.taskId || evidence.runId !== run.id) throw new Error('终端Git证据身份不一致。');
|
||
const invocation = store.owned('tool', evidence.invocationId, session.id);
|
||
if (invocation.taskId !== run.taskId || invocation.runId !== run.id || invocation.tool !== 'run_command'
|
||
|| invocation.eventId !== evidence.eventId || invocation.argsSha256 !== evidence.command.argsSha256) throw new Error('终端Git证据不属于原命令调用。');
|
||
const original = store.owned('artifact', invocation.resultArtifactId, session.id);
|
||
if (original.taskId !== run.taskId || original.runId !== run.id) throw new Error('终端命令结果归属不一致。');
|
||
const result = JSON.parse(store.artifactStore.read(original));
|
||
if (result.terminal_git?.artifact_id !== artifact.id || result.status !== evidence.command.status || result.exit_code !== evidence.command.exitCode) throw new Error('终端Git证据与原命令结果不一致。');
|
||
row.evidenceVerified = true; row.commit = evidence.after.head; row.commits = evidence.commits;
|
||
row.paths = evidence.paths; row.observedInCommand = evidence.observedInCommand; row.command = evidence.command;
|
||
row.status = evidence.status; row.error = evidence.errors.join(';') || null;
|
||
if (evidence.status === 'verified') {
|
||
if (invocation.requiresVerification || !['completed', 'failed'].includes(invocation.state)) throw new Error('原终端命令结果仍未知,未认证当前提交。');
|
||
if (evidence.sourceFingerprint !== inspection.sourceFingerprint || evidence.after.head !== inspection.git.head) {
|
||
row.status = 'stale'; row.error = '当前源码或HEAD已变化,原终端提交观察保留。';
|
||
} else {
|
||
assertCurrentFiles(store, session, evidence.baseline.files);
|
||
const facts = await commitFacts(project, evidence.before.head, evidence.after.head);
|
||
if (JSON.stringify(facts.commits) !== JSON.stringify(evidence.commits) || JSON.stringify(facts.paths) !== JSON.stringify(evidence.paths)) throw new Error('Git实际提交链或文件范围与原观察不一致。');
|
||
// The original command window and immutable evidence bind the index;
|
||
// live tree checks additionally bind the commit to current task files.
|
||
await assertCommitScope(project, evidence.baseline, evidence.before, evidence.after, facts);
|
||
row.currentVerified = true;
|
||
}
|
||
}
|
||
} catch (error) { row.status = 'unverified'; row.error = error.message; }
|
||
results.push(row);
|
||
}
|
||
}
|
||
return results;
|
||
}
|