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 docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ bun run math run \

普通 research/sketch 的交付记录保存本次实际上下文的输入身份,包括任务、传递依赖的 finding 与证明状态、环境、检索/知识库和可见源码。续跑只比较并沿用这份原记录;输入变化会重开调查并保留旧 finding 的历史,重新调查即使结论文字相同也保留新的交付身份。新 Lean 收据编号不构成输入变化,独立重检失败的依赖则会使研究重开。无法从存档确认原分工的源码可见范围时,也会保守地重新调查。该状态只结束研究,不授予任何证明验收。旧快照缺少真实交付输入身份时按待办恢复,原始 finding 仍保存在历史附件中。

该入口只支持至少两个工人的协作运行,不能与 `--continuation-manifest` 同用。新团队无法承担的任务负责人(`ownerId`)会被释放,任务版本不变,由当前成员重新领取。加 `--startup-only` 可以停在已初始化的零轮 checkpoint;开始求解前,初始化、快照读取、工人附件分发或启动结果发布失败都保留可恢复的 `prepared` 状态,在原参数上加 `--resume` 重试,继续使用首次冻结的材料。开始过求解后,恢复时省略 `--continuation-source-run`,按普通 `--resume` 流程重新验证存档证明。
该入口只支持至少两个工人的协作运行,不能与 `--continuation-manifest` 同用。新团队无法承担的任务负责人(`ownerId`)会被释放,任务版本不变,由当前成员重新领取。加 `--startup-only` 会冻结续跑材料并保存零轮 checkpoint。待核验的辅助证明在移除 `--startup-only` 并加 `--resume` 后检查一次,随后直接在同一进程中开始求解。开始求解前,初始化、快照读取、工人附件分发或启动结果发布失败都保留可恢复的 `prepared` 状态,在原参数上加 `--resume` 可继续使用首次冻结的材料。开始过求解后,恢复时省略 `--continuation-source-run`,按普通 `--resume` 流程重新验证存档证明。

也可以保留分步流程:先用新构建执行 `run --startup-only`,再运行独立初始化命令:

Expand Down
4 changes: 4 additions & 0 deletions docs/web-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

本文针对独立 Linux 宿主机上的 Compose 部署。所有路径、域名和镜像名在执行前换成实际值;下面命令不调用付费模型、不发送邮件。`scripts/web-operations.ts` 输出 JSON 摘要,不输出邮箱、题目、密码、Cookie 或 API Key。

条件熵一类的独立长跑可以走 Web 服务的标准求证入口。宿主在 Docker 输出流断开后会等待 worker 停止,再读回磁盘上的最新候选和终验回执。

直接调用 worker 镜像做离线实验时,将输入 JSON 的 `observationSourceRefs` 设为 `true`,由采集器按内容哈希复用重复的 Lean 源码。为每次运行使用独立的命名卷挂载到 `/var/theoremos-proof`,并设置 `THEOREMOS_WORKER_JOURNAL=/var/theoremos-proof`。如需保留求证检查点和工作树,再将另一个命名卷挂载到 `/work`,取代该路径的 tmpfs。保留容器直到读回日志卷中的 `terminal.json` 和 `artifact.json`,可对停止的容器使用 `docker cp`。结果以匹配运行 ID 的终验回执为准。

## 发布镜像

`Verify TheoremOS` 在面向 `main` 的 pull request 和 `main` 推送上运行,也可手动运行。它以只读仓库权限执行 TypeScript 检查、运行时与网页构建、离线浏览器回归,以及 Lean 4.33.0 和 4.34.1 上的求解器回归。验证和镜像发布均使用 Ubuntu 24.04。
Expand Down
7 changes: 4 additions & 3 deletions src/math/leanSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ const isLeanNameCharacter = (value: string | undefined): boolean =>

// A structure initializer may place fields in the declaration's column.
// Command tokens, rather than indentation alone, delimit an empty field list.
const leanWhereCommand = /^(?:@\[|#|(?:theorem|lemma|def|abbrev|opaque|instance|example|class|structure|inductive|coinductive|axiom|constant|constants|variable|variables|universe|universes|namespace|section|end|mutual|open|export|include|omit|set_option|attribute|local|scoped|noncomputable|private|protected|public|unsafe|partial|nonrec|meta|syntax|macro|elab|notation|infix|infixl|infixr|prefix|postfix|initialize|builtin_initialize|import)(?![\p{L}\p{M}\p{N}_'.?!]))/u;
export const startsLeanSourceCommand = (text: string): boolean =>
/^(?:@\[|#|(?:theorem|lemma|def|abbrev|opaque|instance|example|class|structure|inductive|coinductive|axiom|constant|constants|variable|variables|universe|universes|namespace|section|end|mutual|open|export|include|omit|set_option|attribute|local|scoped|noncomputable|private|protected|public|unsafe|partial|nonrec|meta|syntax|macro|elab|notation|infix|infixl|infixr|prefix|postfix|initialize|builtin_initialize|import)(?![\p{L}\p{M}\p{N}_'.?!]))/u.test(text);

/** `instance` inside `@[…]` or `attribute […]`, or after `deriving`, names an attribute or a derive handler.
* Read as a declaration, `attribute [instance 1001] a` swallowed the next command up to its `:=`. */
Expand Down Expand Up @@ -189,7 +190,7 @@ function* leanSourceDeclarations(source: string, mode: LeanDeclarationIndex = 'n
if (nextToken === source.length) return true;
const nextLine = source.lastIndexOf('\n', nextToken - 1) + 1;
if (nextLine <= whereStart) return false;
return leanWhereCommand.test(source.slice(nextToken));
return startsLeanSourceCommand(source.slice(nextToken));
};

const hasEquationArrow = (start: number): boolean => {
Expand Down Expand Up @@ -600,7 +601,7 @@ function leanSourceDeclarationRegion(source: string, declaration: LeanSourceDecl
const boundaryLine = declaration.whereBody ? cleanedSource!.slice(start, end < 0 ? undefined : end) : line;
if (boundaryLine.trim() && !boundaryLine.trimStart().startsWith('--') &&
(line.match(/^\s*/u)?.[0].length ?? 0) <= indentation &&
(!declaration.whereBody || leanWhereCommand.test(boundaryLine.trimStart()))) {
(!declaration.whereBody || startsLeanSourceCommand(boundaryLine.trimStart()))) {
endOffset = start;
break;
}
Expand Down
73 changes: 66 additions & 7 deletions src/math/mathRuntimeIo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,49 @@ const normalizeJson = (item: unknown, compare: (a: string, b: string) => number)
throw new Error('math_runtime_invalid_json');
};

export function canonicalMathJson(value: unknown, compare: (a: string, b: string) => number = (a, b) => a < b ? -1 : a > b ? 1 : 0): string {
const compareJsonKeys = (a: string, b: string): number => a < b ? -1 : a > b ? 1 : 0;

export function canonicalMathJson(value: unknown, compare: (a: string, b: string) => number = compareJsonKeys): string {
return JSON.stringify(normalizeJson(value, compare));
}

/** Normalize current data, sharing only detached previous subtrees whose values still match. */
function checkpointJson(item: unknown, previous: unknown): unknown {
if (previous !== undefined && item === previous) return previous;
if (Array.isArray(item)) {
const prior = Array.isArray(previous) ? previous : undefined;
let unchanged = prior?.length === item.length;
const values = item.map((entry, index) => {
const current = checkpointJson(entry, prior?.[index]);
if (current !== prior?.[index]) unchanged = false;
return current;
});
// For a sparse array, a removed value is not visited by map.
return unchanged && prior!.every((_, index) => index in values) ? prior : values;
}
if (item && typeof item === 'object') {
const prototype = Object.getPrototypeOf(item);
if (prototype !== Object.prototype && prototype !== null) throw new Error('math_runtime_invalid_json');
const prior = previous && typeof previous === 'object' && !Array.isArray(previous)
? previous as Record<string, unknown> : undefined;
const entries = Object.entries(item);
let length = 0;
let unchanged = prior !== undefined;
for (const pair of entries) {
if (pair[1] === undefined) continue;
const saved = prior && Object.hasOwn(prior, pair[0]) ? prior[pair[0]] : undefined;
const current = checkpointJson(pair[1], saved);
if (current !== saved) unchanged = false;
pair[1] = current;
entries[length++] = pair;
}
if (unchanged && Object.keys(prior!).length === length) return prior;
entries.length = length;
return Object.fromEntries(entries.sort(([a], [b]) => compareJsonKeys(a, b)));
}
return normalizeJson(item, compareJsonKeys);
}

export const mathDigest = (value: string | Uint8Array): string =>
crypto.createHash('sha256').update(value).digest('hex');

Expand All @@ -53,15 +92,33 @@ export function writeMathJsonDurable(file: string, value: unknown, mode: 0o600 |
writeMathTextDurable(file, canonicalMathJson(value), mode);
}

/** Keep one detached checkpoint for frequently saved mutable state. The cached bytes still need the same file identity. */
export function createMathJsonCheckpointWriter(): (file: string, value: unknown) => void {
let last: { file: string; snapshot: unknown; identity: string } | undefined;
return (file, value) => {
const previous = last?.file === file ? last : undefined;
const snapshot = checkpointJson(value, previous?.snapshot);
if (previous && snapshot === previous.snapshot && durableFileMatches(file, previous.identity)) return;
const identity = replaceMathTextDurable(file, JSON.stringify(snapshot), 0o600);
last = { file, snapshot, identity };
};
}

function durableFileMatches(file: string, identity: string): boolean {
try { return mathFileIdentity(fs.lstatSync(file, { bigint: true })) === identity; }
catch { return false; } // Missing or replaced output must be written again.
}

/** Atomically replace `file` with `contents`; an unchanged, unreplaced output is not rewritten. */
export function writeMathTextDurable(file: string, contents: string, mode: 0o600 | 0o400 = 0o600): void {
replaceMathTextDurable(file, contents, mode);
}

function replaceMathTextDurable(file: string, contents: string, mode: 0o600 | 0o400): string {
const digest = mathDigest(contents);
const previous = durableWrites.get(file);
if (previous?.digest === digest && previous.mode === mode) {
try {
if (mathFileIdentity(fs.lstatSync(file, { bigint: true })) === previous.identity) return;
} catch { /* Missing or replaced output must be written again. */ }
}
if (previous?.digest === digest && previous.mode === mode && durableFileMatches(file, previous.identity))
return previous.identity;
const temporary = `${file}.${crypto.randomUUID()}.tmp`;
const descriptor = fs.openSync(
temporary,
Expand All @@ -79,7 +136,9 @@ export function writeMathTextDurable(file: string, contents: string, mode: 0o600
fs.renameSync(temporary, file);
syncMathDirectory(path.dirname(file));
if (durableWrites.size >= 128) durableWrites.delete(durableWrites.keys().next().value!);
durableWrites.set(file, { digest, mode, identity: mathFileIdentity(fs.lstatSync(file, { bigint: true })) });
const identity = mathFileIdentity(fs.lstatSync(file, { bigint: true }));
durableWrites.set(file, { digest, mode, identity });
return identity;
}

export function readMathFile(file: string, maxBytes = Infinity, options: { headOnly?: boolean } = {}) {
Expand Down
7 changes: 5 additions & 2 deletions src/solver/archive.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readMathJson, writeMathJsonDurable } from '../math/mathRuntimeIo';
import { createMathJsonCheckpointWriter, readMathJson } from '../math/mathRuntimeIo';
import { personalExpertSetSchema, type PersonalExpertSet } from './personalExperts';
import { agentTeamStateSchema, writerProcessSchema, type AgentTeamState } from './agentTeamState';
import type { SolverProblem } from './problem';
Expand Down Expand Up @@ -107,6 +107,7 @@ export type SolverRunState = {
knowledgeDigest?: string;
libraryCatalogDigest?: string;
continuationDigest?: string;
pendingContinuationSource?: string;
knowledgeRetrievals?: { dropped: number; observations: KnowledgeRetrievalObservation[] };
knowledgeUses?: (KnowledgeUse & { workerId: string; commit: string })[];
model: string;
Expand Down Expand Up @@ -328,6 +329,7 @@ const runState = research.extend({ schema: z.literal('deepscientist.math.solver.
problem: z.object({ workspace: z.string(), receiptDigest: z.string() }).passthrough(),
taskDigest: z.string(), buildDigest: z.string(), environmentDigest: z.string(), evaluatorDigest: z.string(),
continuationDigest: z.string().regex(/^[a-f0-9]{64}$/u).optional(),
pendingContinuationSource: z.string().min(1).optional(),
providerProfile: z.string().optional(), providerProfileDigest: z.string().regex(/^[a-f0-9]{64}$/u).optional(),
agentHarness: z.object({ id: z.enum(['codex', 'claude-code', 'opencode', 'cli']), executable: z.string().min(1),
executableDigest: z.string().regex(/^[a-f0-9]{64}$/u), profile: z.string().min(1),
Expand Down Expand Up @@ -450,9 +452,10 @@ export const readSolverRunState = (file: string): SolverRunState => {
if (!parsed.success) throw new Error(`math_resume_state_invalid:${parsed.error.issues[0]?.path.join('.')}`);
return parsed.data as unknown as SolverRunState;
};
const writeRunCheckpoint = createMathJsonCheckpointWriter();
export const writeSolverRunState = (file: string, state: SolverRunState): void => {
const safeResearch = <T extends Pick<SolverRunState, 'lastFailure'>>(research: T): T => research.lastFailure
? { ...research, lastFailure: { ...research.lastFailure, diagnostic: safeFailureDiagnostic(research.lastFailure.diagnostic) } }
: research;
writeMathJsonDurable(file, { ...safeResearch(state), workers: state.workers?.map(safeResearch) });
writeRunCheckpoint(file, { ...safeResearch(state), workers: state.workers?.map(safeResearch) });
};
Loading
Loading