Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/web/client/draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export function editableTaskDraft(draft: TaskDraft, unresolved = false, fixedEnv
? draft : { ...draft, environment };
}

const archiveSchemas = ['theorem-os.web-export.v1', 'theorem-os.web-archive.v1'];
const archiveSchemas = ['theorem-os.web-export.v1', 'theorem-os.web-archive.v1', 'theorem-os.web-archive.v2'];
const maximumFileBytes = 16 * 1024 * 1024;
const encoder = new TextEncoder();
const editableNumber = /^[+-]?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d*)?|\.)?$/;
Expand Down
30 changes: 20 additions & 10 deletions apps/web/client/trajectory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,25 @@ export function buildTrajectory(input: TrajectoryInput): TrajectoryStep[] {
if (found) found.used = true;
return found;
};
/** An assembled check covers every target; the copies stored under each goal task are one check. */
/** Match the batch outcome and prefer a receipt that explains why it passed or failed. */
const claimAssembly = (at: number, passed: boolean) => {
const found = claim(at, slot => slot.check.passed === passed && (!targets.length || targets.every(name => slot.check.theorems.includes(name))));
if (found) for (let position = firstAt(found.check.at); position < slots.length && slots[position]!.check.at === found.check.at; position++)
if (slots[position]!.version.commit === found.version.commit) slots[position]!.used = true;
const found = claim(at, slot => slot.check.originalProblemPassed === passed && slot.check.passed === passed) ??
claim(at, slot => slot.check.originalProblemPassed === passed) ??
claim(at, slot => slot.check.originalProblemPassed === undefined && slot.check.passed === passed &&
(!targets.length || targets.every(name => slot.check.theorems.includes(name))));
// Older pages may still have a complete copy of the same batch under each goal.
if (found && found.check.originalProblemPassed === undefined) {
for (let position = firstAt(found.check.at); position < slots.length && slots[position]!.check.at === found.check.at; position++) {
const slot = slots[position]!;
if (slot.version.commit === found.version.commit && slot.check.originalProblemPassed === undefined) slot.used = true;
}
}
return found;
};
const forTask = (slot: Slot, taskId: string, passed?: boolean) => slot.version.taskId === taskId &&
slot.check.originalProblemPassed === undefined && (passed === undefined || slot.check.passed === passed);
const latestCheck = (taskId: string, at: number) => {
for (let position = firstAt(at + 1) - 1; position >= 0; position--) if (slots[position]!.version.taskId === taskId) return slots[position];
for (let position = firstAt(at + 1) - 1; position >= 0; position--) if (forTask(slots[position]!, taskId)) return slots[position];
};
const refOf = (slot: Slot | undefined): TrajectoryRef | undefined => slot && { version: slot.version, check: slot.check };
const deliveryFor = proofDeliveryLookup(data.deliveries.values());
Expand All @@ -160,7 +170,7 @@ export function buildTrajectory(input: TrajectoryInput): TrajectoryStep[] {
// A reused check is the latest recorded one of the task; it is not claimed again.
slot = latestCheck(taskId, at);
passed ??= event.type === 'task_failure_check_reused' ? false : slot?.check.passed;
} else slot = claim(at, item => item.version.taskId === taskId && (passed === undefined || item.check.passed === passed));
} else slot = claim(at, item => forTask(item, taskId, passed));
if (passed === undefined) return;
const ref = refOf(slot), outcome: TrajectoryOutcome = passed ? details.conditional ? 'conditional' : 'passed' : 'failed';
const previous = lastAttempt.get(taskId);
Expand All @@ -172,14 +182,14 @@ export function buildTrajectory(input: TrajectoryInput): TrajectoryStep[] {
const taskId = event.details?.taskId;
if (!taskId) return;
// Integrating checks the task on the main line; that check belongs to this step, not to a new attempt.
claim(at, item => item.version.taskId === taskId && item.check.passed);
claim(at, item => forTask(item, taskId, true));
const step = lastAttempt.get(taskId);
if (step) step.integrated = true;
};
const recheck = (event: WebEvent, at: number) => {
const taskId = event.details?.taskId, passed = event.details?.passed;
if (!taskId) return;
const slot = claim(at, item => item.version.taskId === taskId && (passed === undefined || item.check.passed === passed));
const slot = claim(at, item => forTask(item, taskId, passed));
const result: RecheckResult = { taskId, passed: passed ?? slot?.check.passed ?? false, ref: refOf(slot),
...(event.type === 'task_conditional_recheck_finished' ? { conditional: true } : {}) };
const last = steps.at(-1);
Expand Down Expand Up @@ -253,10 +263,10 @@ export function buildTrajectory(input: TrajectoryInput): TrajectoryStep[] {
inputs.sort((a, b) => a.at - b.at || a.order - b.order || a.sequence - b.sequence);
for (const item of inputs) item.run();

// Every unconsumed check is an attempt of its own, even when the same commit was checked more than once.
// Every unconsumed task check is an attempt of its own, even when the same commit was checked more than once.
// Assembly, integration and rechecks already consumed their slots; reusing a receipt does not consume a new check.
for (const { version, check, used } of slots) {
if (used) continue;
if (used || check.originalProblemPassed !== undefined) continue;
steps.push({ kind: 'attempt', at: check.at, taskId: version.taskId, workerId: owners.get(version.taskId), number: 0,
outcome: check.passed ? 'passed' : 'failed', ref: { version, check }, reused: false, integrated: false, note: noteOf(version.taskId, { version, check }) });
}
Expand Down
3 changes: 2 additions & 1 deletion apps/web/jobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { WebKnowledgeService } from './knowledgeService';
import { freezeModuleConfiguration } from './moduleRegistry';
import { WebStorageError } from './storage';
import { isAcceptedRun, isStatementReviewed } from './presentation';
import { projectStoredObservationChecks } from './observationChecks';

type Job = { owner: string; run: WebRun; input: WebRunInput; provider: WebWorkerProvider; controller: AbortController;
formalization?: WorkerInput['formalization'];
Expand Down Expand Up @@ -327,7 +328,7 @@ export class WebJobs {
}
if (actualHarness) job.run.agentHarness = { ...actualHarness };
job.run.solverAttempt = { solverRunId: observation.solverRunId, round: current?.round ?? 0, sequence: observation.sequence };
job.run.observation = observation;
job.run.observation = projectStoredObservationChecks(observation);
job.run.updatedAt = observation.observedAt;
this.persist(job.run);
}
Expand Down
38 changes: 38 additions & 0 deletions apps/web/observationChecks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { WebCheckReceipt, WebObservation } from './collaboration';

/** Earlier frames copied each original-goal receipt onto every goal in its batch. */
export function projectStoredObservationChecks(observation: WebObservation): WebObservation {
const targets = observation.inspection.problem?.targets ?? [];
if (targets.length < 2 || observation.checks.length < 2) return observation;

const targetByName = new Map(targets.map(target => [target.theoremName, target]));
const taskKey = (id: string, version: string) => `${id}\0${version}`;
const goalTargets = new Map(observation.inspection.tasks.filter(task => task.kind === 'goal' && task.theorem)
.map(task => [taskKey(task.id, task.version), targetByName.get(task.theorem!)]));
const assignedTarget = (check: WebCheckReceipt) => goalTargets.get(taskKey(check.taskId, check.taskVersion));
const receiptKey = (check: WebCheckReceipt) =>
`${check.id}\0${check.commit}\0${check.sourceDigest}\0${check.environmentDigest}`;

const copied = new Set<string>();
for (const check of observation.checks) {
const assigned = assignedTarget(check), { theoremName, proofPath } = check.record;
if (!assigned || typeof theoremName !== 'string' || theoremName === assigned.theoremName) continue;
const checked = targetByName.get(theoremName);
if (checked && checked.proofPath === proofPath) copied.add(receiptKey(check));
}
if (!copied.size) return observation;

const checks = observation.checks.flatMap(check => {
const target = assignedTarget(check);
if (!target || !copied.has(receiptKey(check))) return [check];
const { record } = check;
if (record.theoremName !== target.theoremName || record.proofPath !== target.proofPath) return [];
// The per-target verdict must bind to this frozen declaration and this exact commit.
const passed = record.status === 'kernel_verified' && record.claim === 'statement' &&
record.targetCommit === check.commit && Boolean(target.declarationHash) &&
record.sourceDeclarationHash === target.declarationHash;
if (typeof record.passed !== 'boolean') return [check];
return [{ ...check, record: { ...record, originalProblemPassed: record.passed, passed: passed || record.passed } }];
});
return { ...observation, checks };
}
17 changes: 11 additions & 6 deletions apps/web/observationSources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { mathDigest } from '../../src/math/mathRuntimeIo';
import type { WebObservation, WebTaskSource } from './collaboration';

type SourceReference = { sha256: string };
type ObservationWithSource<Text> = Omit<WebObservation, 'sources'> & {
sources: (Omit<WebTaskSource, 'source' | 'dependencySources'> & {
source: Text; dependencySources?: { file: string; source: Text }[];
})[];
type TaskSourceWithText<Text> = Omit<WebTaskSource, 'source' | 'dependencySources'> & {
source: Text; dependencySources?: { file: string; source: Text }[];
};
type ObservationWithSource<Text> = Omit<WebObservation, 'sources'> & { sources: TaskSourceWithText<Text>[] };

export type CompactWebTaskSource = TaskSourceWithText<SourceReference>;
export type CompactWebObservation = ObservationWithSource<SourceReference>;
export type WorkerObservationFrame = {
type: 'observation';
Expand All @@ -27,9 +27,10 @@ function mapSources<From, To>(observation: ObservationWithSource<From>, map: (so
};
}

export function compactObservation(observation: WebObservation, save: (digest: string, text: string) => void): CompactWebObservation {
/** Share text hashes across a batch of observations without reading or hashing unchanged text again. */
export function observationCompactor(save: (digest: string, text: string) => void): (observation: WebObservation) => CompactWebObservation {
const digests = new Map<string, string>();
return mapSources(observation, (source: string) => {
return observation => mapSources(observation, (source: string) => {
let sha256 = digests.get(source);
if (!sha256) {
sha256 = mathDigest(source);
Expand All @@ -40,6 +41,10 @@ export function compactObservation(observation: WebObservation, save: (digest: s
});
}

export function compactObservation(observation: WebObservation, save: (digest: string, text: string) => void): CompactWebObservation {
return observationCompactor(save)(observation);
}

/** Legacy records inline their sources. References must all resolve before handing the observation to a consumer. */
export function hydrateObservation(observation: WebObservation | CompactWebObservation,
read: (digest: string) => string | undefined): WebObservation {
Expand Down
6 changes: 5 additions & 1 deletion apps/web/sample.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import fs from 'node:fs';
import type { WebObservation } from './collaboration';
import { projectStoredObservationChecks } from './observationChecks';
import { webArchive } from './storage';
import { webAgentActionLimits, webSampleRunId, type WebAgentAction, type WebEvent, type WebRun } from './shared';
import { recordedTrajectory, trajectoryPage, trajectoryQuery, trajectoryVersion, trajectoryVersionDetail, trajectoryVersionQuery, type TrajectoryIndex } from './trajectory';
Expand All @@ -25,7 +26,10 @@ const readOnly: WebSampleResponse = { status: 403, body: { error: '示例运行
export function loadWebSample(file = new URL('./sample/run.json', import.meta.url)): WebSampleFile | undefined {
try {
const sample = JSON.parse(fs.readFileSync(file, 'utf8')) as WebSampleFile;
return sample.schema === webSampleSchema && sample.run?.id === webSampleRunId ? sample : undefined;
if (sample.schema !== webSampleSchema || sample.run?.id !== webSampleRunId) return undefined;
sample.observations = sample.observations.map(projectStoredObservationChecks);
if (sample.run.observation) sample.run.observation = projectStoredObservationChecks(sample.run.observation);
return sample;
} catch { return undefined; }
}

Expand Down
54 changes: 43 additions & 11 deletions apps/web/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import { canonicalMathJson, mathDigest, syncMathDirectory, writeMathFrozen } fro
import type { WebArchive, WebCheckReceipt, WebCommandResult, WebObservation, WebTaskSource } from './collaboration';
import type { WebAccountIdentity, WebAgentAction, WebEvent, WebExplanation, WebRun, WorkerExplanationCheckpoint } from './shared';
import type { WebShareSnapshot } from './share';
import { compactObservation, hydrateObservation, type CompactWebObservation } from './observationSources';
import { compactObservation, hydrateObservation, observationCompactor,
type CompactWebObservation, type CompactWebTaskSource } from './observationSources';
import { projectStoredObservationChecks } from './observationChecks';

export type WebCreation = { schema: 'theorem-os.web-creation.v1'; requestId: string; digest: string };
type StoredRun = { owner: string; run: WebRun; creation?: WebCreation };
Expand All @@ -14,18 +16,28 @@ type ObservationRecord = WebObservation | CompactWebObservation;
type StoredExplanationCheckpoint = { binding: string; checkpoint: WorkerExplanationCheckpoint };

export type StoredWebSession = { id: string; csrf: string; touchedAt: number; account?: WebAccountIdentity & { id: string }; passwordResetUntil?: number };
export type StoredWebArchive = {
schema: 'theorem-os.web-archive.v1';
summary: WebArchive;
type ArchiveEvidence = {
run: WebRun;
observations: WebObservation[];
sources: WebTaskSource[];
};
type ArchiveRecords = {
summary: WebArchive;
checks: WebCheckReceipt[];
events: WebEvent[];
/** Older saved archives did not contain the separately stored Agent actions. */
actions?: WebAgentAction[];
commands: WebCommandResult[];
};
type StoredWebArchiveV1 = ArchiveRecords & ArchiveEvidence & { schema: 'theorem-os.web-archive.v1'; commands: WebCommandResult[] };
export type StoredWebArchiveV2 = ArchiveRecords & {
schema: 'theorem-os.web-archive.v2';
run: Omit<WebRun, 'observation'> & { observation?: CompactWebObservation };
observations: CompactWebObservation[];
sources: CompactWebTaskSource[];
sourceBlobs: Record<string, string>;
commands: (Omit<WebCommandResult, 'observation'> & { observation?: CompactWebObservation })[];
};
export type StoredWebArchive = StoredWebArchiveV1 | StoredWebArchiveV2;

export type StoredWebShare = { token: string; createdAt: string; snapshot: WebShareSnapshot };
type ShareIndex = { ownerDigest: string; runId: string };
Expand All @@ -48,8 +60,16 @@ const publicRecord = <T>(value: T): T => JSON.parse(JSON.stringify(value,

/** All retained process evidence, with coverage of the recording rather than a claim of fresh proof acceptance. */
export function webArchive(run: WebRun, records: { observations: WebObservation[]; events: WebEvent[];
actions: WebAgentAction[]; commands: WebCommandResult[] }, catalogDigest?: string): StoredWebArchive {
const { observations, events, actions, commands } = records;
actions: WebAgentAction[]; commands: WebCommandResult[] }, catalogDigest?: string): StoredWebArchiveV2 {
const { events, actions, commands } = records;
const sourceBlobs: Record<string, string> = {};
const referenceSources = observationCompactor((digest, source) => { sourceBlobs[digest] = source; });
const compact = (frame: WebObservation) => referenceSources(projectStoredObservationChecks(frame));
const observations = records.observations.map(compact);
const { observation, ...runFields } = run;
const archivedRun = { ...runFields, ...(observation ? { observation: compact(observation) } : {}) };
const archivedCommands = commands.map(({ observation: recorded, ...command }) =>
({ ...command, ...(recorded ? { observation: compact(recorded) } : {}) }));
const unique = <T>(items: T[]) => [...new Map(items.map(item => [mathDigest(encoded(item)), item])).values()];
const sources = unique(observations.flatMap(item => item.sources)), checks = unique(observations.flatMap(item => item.checks));
const complete = (items: { sequence: number }[], expected: number) => items.length === expected
Expand All @@ -67,10 +87,22 @@ export function webArchive(run: WebRun, records: { observations: WebObservation[
events: events.length, observations: observations.length, actions: actions.length, commands: commands.length,
droppedActions: run.actions?.dropped ?? 0, sources: sources.length, checks: checks.length, coverage,
...(catalogDigest ? { catalogDigest } : {}) };
const payload = publicRecord({ schema: 'theorem-os.web-archive.v1' as const, run, observations, sources, checks, events, actions, commands });
const payload = publicRecord({
schema: 'theorem-os.web-archive.v2' as const, run: archivedRun, observations, sources, sourceBlobs, checks, events, actions,
commands: archivedCommands,
});
return { ...payload, summary: { ...identity, digest: mathDigest(encoded({ ...payload, identity })) } };
}

/** Consumers that need inline observations can read either archive format. */
export function readWebArchiveObservations(archive: StoredWebArchive): Pick<ArchiveEvidence, 'run' | 'observations'> {
if (archive.schema === 'theorem-os.web-archive.v1') return { run: archive.run, observations: archive.observations };
const { observation, ...run } = archive.run;
const hydrate = (frame: CompactWebObservation) => hydrateObservation(frame, digest => archive.sourceBlobs[digest]);
return { run: { ...run, ...(observation ? { observation: hydrate(observation) } : {}) },
observations: archive.observations.map(hydrate) };
}

/** Optional web-only persistence. An omitted root keeps the same API in memory for disposable fixtures. */
export class WebStorage {
readonly root?: string;
Expand Down Expand Up @@ -246,13 +278,13 @@ export class WebStorage {
}
private hydrateObservations(directory: string[], records: ObservationRecord[]): WebObservation[] {
const sources = new Map<string, string>();
return records.map(record => hydrateObservation(record, digest => {
return records.map(record => projectStoredObservationChecks(hydrateObservation(record, digest => {
const cached = sources.get(digest);
if (cached !== undefined) return cached;
const text = this.getRecord<string>([...directory, 'source-blobs', `${digest}.json`]);
if (text !== undefined) sources.set(digest, text);
return text;
}));
})));
}
private readObservation(directory: string[], sequence: number): WebObservation | undefined {
const observation = this.getRecord<ObservationRecord>([...directory, 'observations', `${sequence}.json`]);
Expand Down Expand Up @@ -370,7 +402,7 @@ export class WebStorage {
return records;
}

exportRun(owner: string, run: WebRun, catalogDigest?: string): StoredWebArchive {
exportRun(owner: string, run: WebRun, catalogDigest?: string): StoredWebArchiveV2 {
if (!this.getRun(owner, run.id)) throw new WebStorageError(404, '运行不存在或不属于当前会话。');
return webArchive(run, { observations: this.listObservations(owner, run.id), events: this.listEvents(owner, run.id),
actions: this.listActionsAfter(owner, run.id, 0, Number.MAX_SAFE_INTEGER), commands: this.listCommands(owner, run.id) }, catalogDigest);
Expand Down
Loading
Loading