sakura-infinity 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/AGENT-GUIDE.md +104 -0
  2. package/LICENSE +21 -0
  3. package/README.md +275 -2
  4. package/dist/bin/flags.js +110 -0
  5. package/dist/bin/infinity.js +98 -0
  6. package/dist/bin/load-task.js +39 -0
  7. package/dist/bin/model.js +37 -0
  8. package/dist/bin/scaffold.js +121 -0
  9. package/dist/src/agent-worker.js +157 -0
  10. package/dist/src/backoff.js +12 -0
  11. package/dist/src/budget.js +49 -0
  12. package/dist/src/capacity.js +103 -0
  13. package/dist/src/clock.js +16 -0
  14. package/dist/src/code-leaderboard.js +48 -0
  15. package/dist/src/code-report.js +157 -0
  16. package/dist/src/command-class.js +59 -0
  17. package/dist/src/command-limits.js +46 -0
  18. package/dist/src/commit-plugin.js +36 -0
  19. package/dist/src/component.js +1 -0
  20. package/dist/src/csv.js +8 -0
  21. package/dist/src/defaults.js +35 -0
  22. package/dist/src/error-cluster.js +20 -0
  23. package/dist/src/evaluation.js +84 -0
  24. package/dist/src/form.js +191 -0
  25. package/dist/src/gate.js +111 -0
  26. package/dist/src/gpu-shim.js +165 -0
  27. package/dist/src/handoff.js +12 -0
  28. package/dist/src/hidden-keeper.js +183 -0
  29. package/dist/src/host.js +180 -0
  30. package/dist/src/jsonl.js +30 -0
  31. package/dist/src/ladder.js +118 -0
  32. package/dist/src/launch.js +123 -0
  33. package/dist/src/lean-kit.js +42 -0
  34. package/dist/src/lean-runner.js +84 -0
  35. package/dist/src/lean-setup.js +23 -0
  36. package/dist/src/lean-tool.js +57 -0
  37. package/dist/src/leftover.js +59 -0
  38. package/dist/src/machine-config.js +43 -0
  39. package/dist/src/machine-sampler.js +103 -0
  40. package/dist/src/machine-summary.js +64 -0
  41. package/dist/src/mode-factory.js +25 -0
  42. package/dist/src/mode.js +1 -0
  43. package/dist/src/network.js +12 -0
  44. package/dist/src/orchestrator.js +375 -0
  45. package/dist/src/planner.js +98 -0
  46. package/dist/src/platform.js +21 -0
  47. package/dist/src/pool.js +73 -0
  48. package/dist/src/pressure-brake.js +26 -0
  49. package/dist/src/proc-readings.js +207 -0
  50. package/dist/src/prompts.js +46 -0
  51. package/dist/src/records.js +2 -0
  52. package/dist/src/report.js +81 -0
  53. package/dist/src/review-loop.js +141 -0
  54. package/dist/src/review-rules.js +104 -0
  55. package/dist/src/review-run.js +110 -0
  56. package/dist/src/review-schedule.js +53 -0
  57. package/dist/src/review-snapshot.js +150 -0
  58. package/dist/src/run-layout.js +29 -0
  59. package/dist/src/run-notes.js +61 -0
  60. package/dist/src/run-recorder.js +51 -0
  61. package/dist/src/run-state.js +17 -0
  62. package/dist/src/run-status.js +37 -0
  63. package/dist/src/rung-meter.js +39 -0
  64. package/dist/src/safety-review.js +43 -0
  65. package/dist/src/sakura-tools.js +130 -0
  66. package/dist/src/shell-kit.js +113 -0
  67. package/dist/src/slot-gate.js +136 -0
  68. package/dist/src/slot-leases.js +64 -0
  69. package/dist/src/stuck.js +47 -0
  70. package/dist/src/submit-tool.js +99 -0
  71. package/dist/src/task-mode.js +170 -0
  72. package/dist/src/task.js +85 -0
  73. package/dist/src/verifier.js +115 -0
  74. package/dist/src/work-repo.js +50 -0
  75. package/dist/src/worker-policy.js +16 -0
  76. package/dist/tasks/math-odd-sum/task.js +6 -0
  77. package/dist/tasks/math-parity/task.js +6 -0
  78. package/dist/viewer/index.html +397 -0
  79. package/dist/viewer/run-reader.js +600 -0
  80. package/dist/viewer/server.js +160 -0
  81. package/dist/viewer/view.js +50 -0
  82. package/package.json +53 -4
@@ -0,0 +1,170 @@
1
+ import { chmodSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { restoreOnExit } from "./hidden-keeper.js";
4
+ import { better, targetOf } from "./task.js";
5
+ const DEFAULT_EVAL_TIMEOUT_MINUTES = 10;
6
+ /**
7
+ * The one mode: agents improve a result, and every official submit is scored (by the task's evaluator, or by the Lean verifier of a proof task). The mode owns what
8
+ * is the same for every task: the shared files, the hidden data, the ledger line of a submit, the best score, the target, the end markers. The tools are the kit's.
9
+ */
10
+ export class TaskMode {
11
+ plannerKind;
12
+ plannerSubject;
13
+ branchReview;
14
+ bestScore = null;
15
+ options;
16
+ sharedLinks = Object.create(null);
17
+ hiddenPaths = [];
18
+ prepared = false;
19
+ guard;
20
+ constructor(options) {
21
+ this.options = options;
22
+ this.plannerKind = options.kit.plannerKind;
23
+ this.plannerSubject = options.kit.plannerSubject;
24
+ this.branchReview = options.task.branchReview;
25
+ }
26
+ restore(prior) {
27
+ this.bestScore = prior.bestScore;
28
+ }
29
+ /** Writes the result down; keeps the best verified score; ends the run when the target is reached. */
30
+ accept(agent, submission, info, env) {
31
+ const { result } = submission;
32
+ env.recorder.result(agent, {
33
+ command: submission.command,
34
+ entry: submission.entry,
35
+ files: submission.files,
36
+ status: result.status,
37
+ score: result.score,
38
+ metrics: result.metrics,
39
+ details: result.details,
40
+ selfReported: submission.selfReported,
41
+ ...info,
42
+ });
43
+ if (result.status !== "ok" || result.score === null || submission.selfReported)
44
+ return { changed: false };
45
+ const { task } = this.options;
46
+ const direction = task.metric?.direction ?? "max";
47
+ if (this.bestScore === null || better(result.score, this.bestScore, direction))
48
+ this.bestScore = result.score;
49
+ const target = targetOf(task);
50
+ if (target !== undefined && (direction === "max" ? result.score >= target : result.score <= target)) {
51
+ env.recorder.event({ type: "target", agent, score: result.score });
52
+ return { changed: true, finish: "target" };
53
+ }
54
+ return { changed: true };
55
+ }
56
+ progress() {
57
+ return { bestScore: this.bestScore };
58
+ }
59
+ endFields() {
60
+ return { bestScore: this.bestScore };
61
+ }
62
+ async prepare() {
63
+ const { task, layout, keeper } = this.options;
64
+ const originals = (task.hidden ?? []).map((path) => resolve(path));
65
+ const hiddenSources = originals.map((path) => (existsSync(path) ? realpathSync(path) : path));
66
+ const files = Object.entries(task.files ?? {}).map(([name, source]) => {
67
+ const from = resolve(source);
68
+ if (!existsSync(from))
69
+ throw new Error(`files['${name}']: ${from} does not exist`);
70
+ const visible = realpathSync(from);
71
+ if (hiddenSources.some((hidden) => containsPath(visible, hidden) || containsPath(hidden, visible))) {
72
+ throw new Error(`files['${name}'] overlaps hidden data. Use separate paths for visible and hidden files.`);
73
+ }
74
+ return { name, from };
75
+ });
76
+ for (const { name, from } of files) {
77
+ const to = join(layout.sharedDir, name);
78
+ if (!existsSync(to)) {
79
+ mkdirSync(layout.sharedDir, { recursive: true });
80
+ const staging = mkdtempSync(join(layout.root, ".shared-"));
81
+ try {
82
+ const copy = join(staging, name);
83
+ cpSync(from, copy, { recursive: true });
84
+ makeReadOnly(copy);
85
+ renameSync(copy, to);
86
+ }
87
+ finally {
88
+ rmSync(staging, { recursive: true, force: true });
89
+ }
90
+ }
91
+ this.sharedLinks[name] = to;
92
+ }
93
+ if (keeper && originals.length > 0) {
94
+ keeper.hide(originals);
95
+ this.hiddenPaths = originals.map((path) => keeper.privatePath(path));
96
+ this.guard = restoreOnExit(keeper, process, this.options.signal);
97
+ }
98
+ await this.options.kit.prepare();
99
+ this.prepared = true;
100
+ }
101
+ agentSetup(hint, agent) {
102
+ if (!this.prepared)
103
+ throw new Error("TaskMode.prepare() must finish before agents are set up");
104
+ const { goalObjective, ...setup } = this.options.kit.agentSetup({ hint, agent, links: this.sharedLinks, score: (input) => this.score(input) });
105
+ return { ...setup, goal: { objective: goalObjective, verify: "test -f ../finished" }, links: this.sharedLinks };
106
+ }
107
+ warnings() {
108
+ const warnings = this.options.kit.warnings();
109
+ if (this.options.keeper)
110
+ warnings.push("The hidden data is protected only by a private, unguessable path and by the review rules; the agents' shell is NOT blocked from reading it by the operating system (ShellGuard is not built).");
111
+ return warnings;
112
+ }
113
+ /** Everything is put back and every agent is told, by its marker, that it may stop. Safe to call again. */
114
+ finish(agents) {
115
+ for (const agent of agents) {
116
+ try {
117
+ writeFileSync(this.options.layout.finishedMarker(agent), "the run has ended\n");
118
+ }
119
+ catch {
120
+ // the agent's directory may be gone; the agent is cancelled anyway
121
+ }
122
+ }
123
+ this.options.keeper?.restore();
124
+ this.guard?.dispose();
125
+ this.guard = undefined;
126
+ }
127
+ async score(input) {
128
+ const { task, evalPool } = this.options;
129
+ if (!task.evaluate) {
130
+ const claimed = task.metric ? input.claim[task.metric.name] : Object.values(input.claim)[0];
131
+ return { result: { status: "ok", score: claimed ?? null, metrics: input.claim, details: "" }, selfReported: true };
132
+ }
133
+ const release = await evalPool.acquire(input.signal);
134
+ try {
135
+ const timeout = AbortSignal.timeout((task.evalTimeoutMinutes ?? DEFAULT_EVAL_TIMEOUT_MINUTES) * 60_000);
136
+ const signal = AbortSignal.any([input.signal, timeout]);
137
+ const result = await task.evaluate({
138
+ workDir: input.workDir,
139
+ commit: input.commit,
140
+ command: input.command,
141
+ files: input.files,
142
+ hidden: this.hiddenPaths,
143
+ signal,
144
+ });
145
+ return { result, selfReported: false };
146
+ }
147
+ catch (error) {
148
+ return {
149
+ result: { status: "error", score: null, metrics: {}, details: `the evaluator failed: ${error instanceof Error ? error.message : String(error)}` },
150
+ selfReported: false,
151
+ };
152
+ }
153
+ finally {
154
+ release();
155
+ }
156
+ }
157
+ }
158
+ function containsPath(parent, path) {
159
+ const child = relative(parent, path);
160
+ return !isAbsolute(child) && child !== ".." && !child.startsWith(`..${sep}`);
161
+ }
162
+ /** Files are made read-only; directories stay writable so that a run directory can still be deleted. An agent with a shell can undo this: it is a guard against accidents, not a lock. */
163
+ function makeReadOnly(path) {
164
+ const entry = lstatSync(path);
165
+ if (entry.isDirectory())
166
+ for (const name of readdirSync(path))
167
+ makeReadOnly(join(path, name));
168
+ else if (!entry.isSymbolicLink())
169
+ chmodSync(path, 0o444);
170
+ }
@@ -0,0 +1,85 @@
1
+ import { profileProblems } from "./capacity.js";
2
+ import { reviewOutputProblems } from "./review-snapshot.js";
3
+ /** Is score `a` better than `b` when the metric goes in this direction? */
4
+ export const better = (a, b, direction) => (direction === "max" ? a > b : a < b);
5
+ /** The metric of a proof task: 1 for an accepted proof, 0 for a rejected one. */
6
+ export const PROOF_METRIC = { name: "proved", direction: "max" };
7
+ export const MAX_AGENTS = 100;
8
+ /** The number a submit has to reach to end the run, when the task has one. */
9
+ export const targetOf = (task) => (typeof task.stop === "object" ? task.stop.targetScore : undefined);
10
+ /** The one place that checks a task. A task that gets past it can run; the result has the defaults of a proof task filled in (metric, target, no review). */
11
+ export function defineTask(task) {
12
+ const problems = [];
13
+ if (task.name.trim() === "")
14
+ problems.push("name must not be empty");
15
+ if (!Number.isInteger(task.agents) || task.agents < 1 || task.agents > MAX_AGENTS)
16
+ problems.push(`agents must be a whole number from 1 to ${MAX_AGENTS}`);
17
+ if (task.tokens !== undefined && !(task.tokens > 0))
18
+ problems.push("tokens must be positive");
19
+ if (task.stuckMinutes !== undefined && !(task.stuckMinutes > 0))
20
+ problems.push("stuckMinutes must be positive");
21
+ if (task.profile)
22
+ problems.push(...profileProblems(task.profile));
23
+ const tools = task.tools ?? { kind: "shell" };
24
+ if (tools.kind === "lean")
25
+ checkLean(task, tools, problems);
26
+ else
27
+ checkShell(task, problems);
28
+ checkCommon(task, problems);
29
+ if (problems.length > 0)
30
+ throw new Error(`Invalid task '${task.name}': ${problems.join("; ")}`);
31
+ return tools.kind === "lean" ? { ...task, tools, metric: PROOF_METRIC, stop: { targetScore: 1 }, review: false } : { ...task, tools };
32
+ }
33
+ function checkLean(task, tools, problems) {
34
+ if (tools.statement.trim() === "")
35
+ problems.push("statement must not be empty");
36
+ if (tools.leanPool !== undefined && !(tools.leanPool >= 1))
37
+ problems.push("leanPool must be at least 1");
38
+ for (const field of ["evaluate", "hidden", "files", "protect", "branchReview", "metric"])
39
+ if (task[field] !== undefined)
40
+ problems.push(`'${field}' does not apply to a proof task (the evaluator is the Lean verifier)`);
41
+ if (task.stop === "until-stopped")
42
+ problems.push("a proof task stops at the first accepted proof");
43
+ if (task.review !== undefined && task.review !== false)
44
+ problems.push("a proof task has no shell, so no safety review");
45
+ }
46
+ function checkShell(task, problems) {
47
+ if (task.prompt === undefined || task.prompt.trim() === "")
48
+ problems.push("prompt must not be empty");
49
+ if (task.evaluate && !task.metric)
50
+ problems.push("metric is required with evaluate");
51
+ if (task.metric && !task.evaluate)
52
+ problems.push("metric needs an evaluate function (without one, agents' claims rank)");
53
+ if (task.review === undefined)
54
+ problems.push("review must be given: settings, or false to run without it");
55
+ for (const name of Object.keys(task.files ?? {})) {
56
+ if (!/^[A-Za-z0-9._-]+$/.test(name) || [".", "..", ".git", ".gitignore"].includes(name.toLowerCase())) {
57
+ problems.push(`files: '${name}' is not a plain name available in the work directory`);
58
+ }
59
+ }
60
+ }
61
+ function checkCommon(task, problems) {
62
+ if (task.metric && task.metric.name.trim() === "")
63
+ problems.push("metric name must not be empty");
64
+ if (typeof task.stop === "object" && !Number.isFinite(task.stop.targetScore))
65
+ problems.push("stop.targetScore must be a number");
66
+ if (typeof task.stop === "object" && !task.metric && task.tools?.kind !== "lean")
67
+ problems.push("stop.targetScore needs a metric");
68
+ if (task.evalSlots !== undefined && !(task.evalSlots >= 1))
69
+ problems.push("evalSlots must be at least 1");
70
+ if (task.submitIntervalMinutes !== undefined && !(task.submitIntervalMinutes >= 0))
71
+ problems.push("submitIntervalMinutes must not be negative");
72
+ if (task.evalTimeoutMinutes !== undefined && !(task.evalTimeoutMinutes > 0))
73
+ problems.push("evalTimeoutMinutes must be positive");
74
+ if (task.commandTimeoutMinutes !== undefined && !(task.commandTimeoutMinutes > 0))
75
+ problems.push("commandTimeoutMinutes must be positive");
76
+ const branch = task.branchReview;
77
+ if (branch?.everyMinutes !== undefined && !(branch.everyMinutes > 0))
78
+ problems.push("branchReview.everyMinutes must be positive");
79
+ if (branch?.maxTurns !== undefined && !(branch.maxTurns >= 1))
80
+ problems.push("branchReview.maxTurns must be at least 1");
81
+ if (branch?.maxConcurrent !== undefined && !(branch.maxConcurrent >= 1))
82
+ problems.push("branchReview.maxConcurrent must be at least 1");
83
+ if (branch?.output)
84
+ problems.push(...reviewOutputProblems(branch.output).map((problem) => `branchReview.output: ${problem}`));
85
+ }
@@ -0,0 +1,115 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ const ALLOWED_AXIOMS = ["propext", "Classical.choice", "Quot.sound"];
5
+ /** `Statement.Goal` is the statement every proof must have as the type of its theorem `main`. */
6
+ export function statementSource(statement) {
7
+ return `namespace Statement\nabbrev Goal : Prop := ${statement}\nend Statement\n`;
8
+ }
9
+ /**
10
+ * Constructs that make Lean run code at compile time or import more than the statement. A proof does not need them,
11
+ * and they are the ways a file could fake the verifier's report. This is defence in depth, not a boundary: without the optional sandbox of the runner a proof file runs with the user's rights.
12
+ */
13
+ const FORBIDDEN = /\b(initialize|builtin_initialize|run_cmd|run_elab|run_meta|elab|elab_rules|macro|macro_rules|syntax|declare_syntax_cat|unsafe|implemented_by|extern|export|prelude)\b|#eval|#exit/;
14
+ const IMPORT_LINE = /^\s*import\s+(\S+)/gm;
15
+ export function forbiddenConstruct(source) {
16
+ const match = FORBIDDEN.exec(source);
17
+ if (match)
18
+ return `the construct '${match[0]}' is not allowed in a proof file`;
19
+ for (const [, module] of source.matchAll(IMPORT_LINE))
20
+ if (module !== "Statement")
21
+ return `only 'import Statement' is allowed, found 'import ${module}'`;
22
+ return undefined;
23
+ }
24
+ const NO_OUTPUT = "No errors or warnings.";
25
+ const trimOutput = (text, limit = 3000) => (text.length > limit ? `${text.slice(0, limit)}\n... (cut)` : text);
26
+ /** Compiles `Statement` once (it fails here, loudly, if the statement itself is not valid Lean) and returns the verifier. */
27
+ export async function createVerifier(options) {
28
+ const { runner, leanDir } = options;
29
+ const checkTimeoutMs = options.checkTimeoutMs ?? 120_000;
30
+ const verifyTimeoutMs = options.verifyTimeoutMs ?? 180_000;
31
+ const newNonce = options.newNonce ?? (() => randomBytes(12).toString("hex"));
32
+ mkdirSync(leanDir, { recursive: true });
33
+ await compileStatement(runner, leanDir, options.statement, verifyTimeoutMs);
34
+ const inScratch = async (work) => {
35
+ const scratch = mkdtempSync(join(leanDir, "scratch-"));
36
+ try {
37
+ return await work(scratch);
38
+ }
39
+ finally {
40
+ rmSync(scratch, { recursive: true, force: true });
41
+ }
42
+ };
43
+ return {
44
+ check: (source, signal) => inScratch(async (scratch) => {
45
+ writeFileSync(join(scratch, "Proof.lean"), source);
46
+ const result = await runLean(["Proof.lean"], scratch, checkTimeoutMs, signal);
47
+ return describeCheck(result, checkTimeoutMs);
48
+ }),
49
+ verify: (source, signal) => inScratch(async (scratch) => {
50
+ const forbidden = forbiddenConstruct(source);
51
+ if (forbidden)
52
+ return { proved: false, reason: forbidden };
53
+ writeFileSync(join(scratch, "Proof.lean"), source);
54
+ const compiled = await runLean(["-o", "Proof.olean", "Proof.lean"], scratch, verifyTimeoutMs, signal);
55
+ if (compiled.timedOut || compiled.exitCode !== 0)
56
+ return { proved: false, reason: `does not compile:\n${describeCheck(compiled, verifyTimeoutMs)}` };
57
+ const nonce = newNonce();
58
+ writeFileSync(join(scratch, "Check.lean"), checkSource(nonce));
59
+ const report = await runLean(["Check.lean"], scratch, verifyTimeoutMs, signal);
60
+ return judge(report, nonce);
61
+ }),
62
+ };
63
+ function runLean(args, scratch, timeoutMs, signal) {
64
+ return runner.run({ cwd: scratch, args, leanPath: [leanDir, scratch], writableDirs: [scratch], timeoutMs, ...(signal ? { signal } : {}) });
65
+ }
66
+ }
67
+ async function compileStatement(runner, leanDir, statement, timeoutMs) {
68
+ writeFileSync(join(leanDir, "Statement.lean"), statementSource(statement));
69
+ const result = await runner.run({ cwd: leanDir, args: ["-o", "Statement.olean", "Statement.lean"], leanPath: [leanDir], writableDirs: [leanDir], timeoutMs });
70
+ if (result.exitCode !== 0 || result.timedOut)
71
+ throw new Error(`The statement does not compile:\n${trimOutput(result.output)}`);
72
+ }
73
+ function describeCheck(result, timeoutMs) {
74
+ if (result.timedOut)
75
+ return `Lean was stopped after ${Math.round(timeoutMs / 1000)} seconds.`;
76
+ const text = result.output.trim();
77
+ return text === "" ? NO_OUTPUT : trimOutput(text);
78
+ }
79
+ /**
80
+ * The check runs in a second Lean process, in a file written by the verifier, that imports the compiled proof and asks the environment:
81
+ * the theorem `main` exists, its type is exactly the constant `Statement.Goal`, and it depends on no axioms outside the standard three
82
+ * (`sorry` is the axiom `sorryAx`, a custom axiom is an axiom, `native_decide` is `Lean.ofReduceBool`). The report carries a random nonce.
83
+ */
84
+ function checkSource(nonce) {
85
+ return `import Lean
86
+ import Statement
87
+ import Proof
88
+ open Lean in
89
+ #eval show CoreM Unit from do
90
+ let env ← getEnv
91
+ match env.find? \`main with
92
+ | none => IO.println "${nonce}|missing"
93
+ | some info =>
94
+ let sameType := info.type == mkConst \`\`Statement.Goal
95
+ let isTheorem := match info with | .thmInfo _ => true | _ => false
96
+ let axioms ← collectAxioms \`main
97
+ IO.println s!"${nonce}|ok|{sameType}|{isTheorem}|{String.intercalate ";" (axioms.toList.map toString)}"
98
+ `;
99
+ }
100
+ function judge(report, nonce) {
101
+ const line = report.output.split("\n").find((candidate) => candidate.startsWith(`${nonce}|`));
102
+ if (!line)
103
+ return { proved: false, reason: `the verification did not report:\n${describeCheck(report, 0)}` };
104
+ const [, status, sameType, isTheorem, axiomList] = line.split("|");
105
+ if (status === "missing")
106
+ return { proved: false, reason: "there is no theorem named 'main' at the top level (a theorem declared inside a namespace gets a longer name)" };
107
+ if (sameType !== "true")
108
+ return { proved: false, reason: "'main' does not have exactly the type Statement.Goal" };
109
+ if (isTheorem !== "true")
110
+ return { proved: false, reason: "'main' must be a theorem" };
111
+ const extra = (axiomList ?? "").split(";").filter((axiom) => axiom !== "" && !ALLOWED_AXIOMS.includes(axiom));
112
+ if (extra.length > 0)
113
+ return { proved: false, reason: `the proof depends on axioms that are not allowed: ${extra.join(", ")}` };
114
+ return { proved: true, reason: "proved" };
115
+ }
@@ -0,0 +1,50 @@
1
+ import { execFile } from "node:child_process";
2
+ import { chmodSync, existsSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { promisify } from "node:util";
5
+ const execFileAsync = promisify(execFile);
6
+ const GIT_IDENTITY = ["-c", "user.name=infinity-agent", "-c", "user.email=agent@infinity.invalid", "-c", "commit.gpgsign=false"];
7
+ async function git(dir, args) {
8
+ const { stdout } = await execFileAsync("git", [...GIT_IDENTITY, ...args], { cwd: dir, maxBuffer: 10 * 1024 * 1024 });
9
+ return stdout.trim();
10
+ }
11
+ /** Makes `dir` a Git repository on branch main (safe to call again). */
12
+ export async function initWorkRepo(dir) {
13
+ await git(dir, ["init", "--quiet", "--initial-branch=main"]);
14
+ }
15
+ /** Commits everything in `dir`. Returns the new commit id, or undefined when nothing changed. */
16
+ export async function commitAll(dir, message) {
17
+ await git(dir, ["add", "--all"]);
18
+ const changes = await git(dir, ["status", "--porcelain"]);
19
+ if (changes === "")
20
+ return undefined;
21
+ await git(dir, ["commit", "--quiet", "--message", message]);
22
+ return git(dir, ["rev-parse", "HEAD"]);
23
+ }
24
+ /** The id of the current commit, or undefined when the repository has none yet. */
25
+ export async function headCommit(dir) {
26
+ try {
27
+ return await git(dir, ["rev-parse", "HEAD"]);
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ /** Creates the work directory as a Git repository holding read-only copies of the given files, and commits them as "start". Safe to repeat on resume. */
34
+ export async function createWorkDir(workDir, contents) {
35
+ mkdirSync(workDir, { recursive: true });
36
+ if (existsSync(join(workDir, ".git")))
37
+ return;
38
+ for (const [name, content] of Object.entries(contents.files)) {
39
+ const path = join(workDir, name);
40
+ writeFileSync(path, content);
41
+ chmodSync(path, 0o444);
42
+ }
43
+ for (const [name, target] of Object.entries(contents.links ?? {}))
44
+ symlinkSync(target, join(workDir, name));
45
+ const ignored = [...Object.keys(contents.links ?? {}), ...(contents.gitignore ?? [])];
46
+ if (ignored.length > 0)
47
+ writeFileSync(join(workDir, ".gitignore"), `${ignored.join("\n")}\n`);
48
+ await initWorkRepo(workDir);
49
+ await commitAll(workDir, "start");
50
+ }
@@ -0,0 +1,16 @@
1
+ /** Pauses in a row, without a single reply in between, after which an agent is given up. */
2
+ export const MAX_PAUSES_WITHOUT_REPLY = 20;
3
+ /** What a worker does when one run of its agent is over (pure: the worker acts on the answer). */
4
+ export function afterRun(state) {
5
+ const { cancelled, run } = state;
6
+ if (cancelled === "rescue")
7
+ return { type: "rescue" };
8
+ if (cancelled)
9
+ return { type: "end", end: { reason: "cancelled", cancelled } };
10
+ // the review's circuit breaker: too many refusals in a row. The agent ends as a failure and the ladder starts a new one.
11
+ if (run.reason === "paused" && run.pause === "approval")
12
+ return { type: "end", end: { reason: "failed", detail: "stopped by the review's circuit breaker (too many refused actions)" } };
13
+ if (run.reason === "paused" && !state.gateStopped && state.pausesWithoutReply < MAX_PAUSES_WITHOUT_REPLY)
14
+ return { type: "wait" };
15
+ return { type: "end", end: { reason: run.reason, ...(run.error ? { detail: run.error } : {}) } };
16
+ }
@@ -0,0 +1,6 @@
1
+ export default {
2
+ preset: "math",
3
+ name: "math-odd-sum",
4
+ statement: "∀ n : Nat, (List.range n).foldl (fun acc i => acc + (2 * i + 1)) 0 = n * n",
5
+ tokens: 3_000_000,
6
+ };
@@ -0,0 +1,6 @@
1
+ export default {
2
+ preset: "math",
3
+ name: "math-parity",
4
+ statement: "∀ n : Nat, n % 2 = 0 ∨ n % 2 = 1",
5
+ tokens: 3_000_000,
6
+ };