Repository navigation
Expand file tree
/
Copy pathcheckLean.ts
More file actions
276 lines (274 loc) · 11.8 KB
/
Copy pathcheckLean.ts
File metadata and controls
276 lines (274 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#!/usr/bin/env bun
import { parseArgs } from 'node:util';
import fs from 'node:fs';
import path from 'node:path';
import { runLeanDiagnostics } from '../../src/math/leanDiagnostics';
import { parseLeanDiagnosticOutput, renderLeanDiagnosticMessage } from '../../src/math/leanDiagnosticMessages';
import { checkLeanType } from '../../src/math/leanTypeDiagnostics';
import { readMathJson } from '../../src/math/mathRuntimeIo';
import { assertSolverProjectSources, SolverSourceError, type SolverSourceConstraints } from '../../src/solver/problem';
import { currentWorkerProject, WorkerProjectArgumentError } from '../../src/solver/workerProject';
import { checkLeanEnvironmentHealth, leanEnvironmentFailure } from '../../src/math/leanEnvironmentHealth';
import { assertMathConstructionSources } from '../../src/math/mathConstructionSources';
import { teamEvidenceRefSchema } from '../../src/solver/agentTeamEvidenceRef';
let stage: 'usage' | 'project' | 'source' | 'diagnostics' = 'usage';
let project: string | undefined;
let compilationAttempted = false;
let brief = false;
const briefDetails: string[] = [];
const publish = <
T extends { classification: string; error?: { code: string; message: string; file?: string; recovery?: string } },
>(
result: T,
exitCode: number,
) => {
if (brief) {
const { error } = result;
console.log(
[
`check-lean: ${result.classification} (exit ${exitCode})`,
...(error ? [`${error.file ? `${error.file}: ` : ''}${error.code}: ${error.message}`, error.recovery] : []),
...briefDetails,
]
.filter(Boolean)
.join('\n'),
);
} else console.log(JSON.stringify(result));
process.exitCode = exitCode;
};
const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
async function main() {
const args = process.argv.slice(2);
if (args[0] === 'check-lean') args.shift();
const { values } = parseArgs({
args,
options: {
workspace: { type: 'string' },
worktree: { type: 'string' },
file: { type: 'string', multiple: true },
brief: { type: 'boolean' },
type: { type: 'string' },
context: { type: 'string' },
expression: { type: 'string' },
candidate: { type: 'string' },
'timeout-seconds': { type: 'string', default: '0' },
health: { type: 'boolean' },
help: { type: 'boolean' },
},
});
brief = Boolean(values.brief);
if (values.help)
console.log(
'Usage: theorem-os check-lean (--workspace DIR | --worktree ROOT) --file FILE [--brief] [--file FILE --timeout-seconds N]\n' +
'--worktree is the worker root containing .scratch/worker-project.json; --workspace is the Lean project directory.\n' +
'--file is relative to the Lean project, e.g. Submission.lean, without a generated/problem/ prefix.\n' +
"Save temporary Lean probes under the Lean project's .scratch/tmp/ and pass --file .scratch/tmp/Probe.lean.\n" +
'Use --brief for plain file diagnostics with positions, goals and the full diagnostic index.\n' +
'Optional: --type TYPE --context DECLARATION elaborates one closed type in a proof-erased snapshot of the single --file context.\n' +
'Add --expression TERM to check one selected closed application against that type. Local theorem bodies are erased; this is advisory sufficiency, not proof acceptance.\n' +
'Use --health instead of --file to verify the current namespace, sealed lease and pinned compiler without compiling sources.\n' +
'Use --candidate REF to record which peer result a saved single-file probe tests. REF is message:ID, research:ID or delivery:ID.\n' +
'Checks saved sources against pinned packages. Timeout 0 waits until completion. Diagnostics and type elaboration are advisory, not proof acceptance.',
);
else {
if (
brief &&
(values.health || values.type !== undefined || values.context !== undefined || values.expression !== undefined)
)
throw new Error('--brief applies only to ordinary --file checks');
const timeout = Number(values['timeout-seconds']);
if (
Boolean(values.workspace) === Boolean(values.worktree) ||
(!values.health && !values.file?.length) ||
!Number.isSafeInteger(timeout) ||
timeout < 0
)
throw new Error(
'Exactly one of --workspace/--worktree, --file (or --health) and a nonnegative --timeout-seconds are required',
);
if (
values.health &&
(values.file?.length ||
values.type !== undefined ||
values.context !== undefined ||
values.expression !== undefined)
)
throw new Error('--health checks the environment only; omit --file, --type, --context and --expression');
if (
(values.type !== undefined || values.context !== undefined) &&
(!values.type || !values.context || values.file?.length !== 1)
)
throw new Error('--type requires --context and exactly one --file');
if (values.expression !== undefined && !values.type) throw new Error('--expression requires --type and --context');
if (
values.candidate !== undefined &&
(values.file?.length !== 1 ||
values.type !== undefined ||
!teamEvidenceRefSchema.safeParse(values.candidate).success)
)
throw new Error('--candidate requires a team evidence reference and one saved --file probe');
stage = 'project';
project = values.workspace ? fs.realpathSync(values.workspace) : currentWorkerProject(values.worktree!);
stage = 'source';
const constraints = path.join(project, '.lake/source-constraints.json');
if (!values.health && fs.existsSync(constraints))
assertSolverProjectSources(readMathJson(constraints) as SolverSourceConstraints, project);
if (!values.health) assertMathConstructionSources(project, values.file!);
const controller = new AbortController();
const abort = () => controller.abort();
process.once('SIGINT', abort);
process.once('SIGTERM', abort);
let result;
const shared = {
projectRoot: project,
timeoutMs: timeout === 0 ? Infinity : timeout * 1000,
signal: controller.signal,
onProgress: (file: string) => {
compilationAttempted = true;
if (!brief) console.error(JSON.stringify({ event: 'lean_check_started', file }));
},
};
try {
const health = await checkLeanEnvironmentHealth(shared);
if (values.health || health.status !== 'ready') return publish(health, health.exitCode);
stage = 'diagnostics';
result = values.type
? await checkLeanType({
...shared,
file: values.file![0],
type: values.type,
context: values.context!,
expression: values.expression,
})
: await runLeanDiagnostics({
...shared,
files: values.file!,
...(brief && {
onLockProgress: () => {},
onCompilerOutput: (stdout: string, stderr: string) => {
for (const stream of [stdout, stderr]) {
const { messages, unlocated } = parseLeanDiagnosticOutput(stream);
for (const message of messages) {
const line = renderLeanDiagnosticMessage(message);
briefDetails.push(
message.severity === 'warning' && line.length > 480
? line.slice(0, 480) + '… [see diagnostics]'
: line,
);
}
briefDetails.push(...unlocated);
}
},
}),
});
} finally {
process.removeListener('SIGINT', abort);
process.removeListener('SIGTERM', abort);
}
const startupFailed = !result.timedOut && !result.aborted && 'started' in result && result.started === false;
if (brief && 'diagnosticArtifacts' in result) {
// A startup failure already reports stderr through its structured infrastructure error.
const startupDetail = startupFailed ? briefDetails.lastIndexOf(result.stderr.trimEnd()) : -1;
if (startupDetail !== -1) briefDetails.splice(startupDetail, 1);
if (result.stderr.startsWith('math_diagnostics_source_changed:')) briefDetails.push(result.stderr);
if (values.candidate) briefDetails.push(`candidate: ${values.candidate} (${values.file![0]})`);
if (result.diagnosticArtifacts.some(artifact => artifact.captureComplete === false))
briefDetails.push('Compiler output capture was truncated.');
briefDetails.push(`diagnostics: ${path.join(project, '.lake/lean-diagnostics-latest.json')}`);
}
publish(
{
...result,
classification: result.timedOut
? 'timeout'
: result.aborted
? 'cancelled'
: result.exitCode === 0
? 'success'
: startupFailed
? 'infrastructure'
: 'lean',
...(values.candidate && { candidate: { ref: values.candidate, file: values.file![0] } }),
...(startupFailed
? {
status: 'infrastructure-error',
leanStarted: false,
error: leanEnvironmentFailure(
'toolchain',
new Error(result.stderr || 'Lean compiler process did not start'),
),
}
: {}),
},
result.timedOut ? 124 : (result.exitCode ?? 1),
);
}
}
void main().catch(async error => {
if (error instanceof WorkerProjectArgumentError)
return publish(
{
status: 'usage-error',
classification: 'usage',
exitCode: 1,
timedOut: false,
leanStarted: false,
error: {
code: error.code,
message: error.message,
recovery:
`Use check-lean --worktree ${quote(error.worktreeRoot)} --file 'OWNED_FILE.lean', or ` +
`check-lean --workspace ${quote(error.projectRoot)} --file 'OWNED_FILE.lean'. ` +
'File paths are relative to the Lean project, without its prefix.',
},
},
1,
);
if (stage === 'diagnostics' && project) {
const health = await checkLeanEnvironmentHealth({ projectRoot: project });
if (health.status !== 'ready') return publish({ ...health, leanStarted: compilationAttempted ? null : false }, 1);
}
const message = error instanceof Error ? error.message : 'math_diagnostics_failed';
if (stage === 'project')
return publish(
{
status: 'infrastructure-error',
classification: 'infrastructure',
exitCode: 1,
timedOut: false,
leanStarted: false,
error: leanEnvironmentFailure('project', error),
},
1,
);
publish(
{
status:
stage === 'usage'
? 'usage-error'
: error instanceof SolverSourceError || stage === 'source'
? 'source-error'
: 'diagnostics-error',
classification:
stage === 'usage' ? 'usage' : error instanceof SolverSourceError || stage === 'source' ? 'source' : 'tooling',
exitCode: 1,
timedOut: false,
leanStarted: compilationAttempted ? null : false,
error: {
code: error instanceof SolverSourceError ? error.message : 'math_diagnostics_failed',
message,
...(stage === 'source' && project
? {
recovery:
`Inspect the requested saved sources and their imports in ${quote(project)}. ` +
'--file paths are relative to this Lean project; do not repeat the project directory prefix. ' +
`Save temporary probes under ${quote(path.join(project, '.scratch/tmp'))} and use --file '.scratch/tmp/Probe.lean'. ` +
`For example: check-lean --workspace ${quote(project)} --file 'Submission.lean'.`,
}
: {}),
...(error instanceof SolverSourceError ? { file: error.proofPath, recovery: error.recovery } : {}),
},
},
1,
);
});