diff options
| -rw-r--r-- | plugins/math-proof/README.md | 68 | ||||
| -rw-r--r-- | plugins/math-proof/agents/math-proof-judge-deep.md | 17 | ||||
| -rw-r--r-- | plugins/math-proof/agents/math-proof-judge.md | 4 | ||||
| -rw-r--r-- | plugins/math-proof/agents/math-proof-worker-deep.md | 2 | ||||
| -rw-r--r-- | plugins/math-proof/skills/siege/SKILL.md | 142 | ||||
| -rwxr-xr-x[-rw-r--r--] | plugins/math-proof/skills/siege/scripts/ledger.py | 128 | ||||
| -rw-r--r-- | plugins/math-proof/skills/solo/SKILL.md | 39 |
7 files changed, 229 insertions, 171 deletions
diff --git a/plugins/math-proof/README.md b/plugins/math-proof/README.md index 85107c4e..500926a3 100644 --- a/plugins/math-proof/README.md +++ b/plugins/math-proof/README.md @@ -2,7 +2,8 @@ Two Claude Code skills for hard, research-level mathematics problems. Each takes one problem stated in full, keeps everything it writes in a run folder, -switches web search off for its run, and ends with a self-contained `proof.md`. +switches Claude Code's web tools off for its run, and ends with a +self-contained `proof.md`. **`/math-proof:solo`**: Claude works the problem itself, in your session, as one long turn. It is instructed to write its plan and each intermediate result @@ -19,14 +20,17 @@ judge set, two more workers check that exact text line by line before the judge concludes; if the opening rounds do not get there, later rounds send more workers per round, most of them at the one step the proof still lacks. `proof.md` has a Status section saying plainly what is and is not proved. -Expect dozens of sub-agent runs; check `/usage` before starting. +Expect dozens of sub-agent runs, and well over a hundred if all fourteen rounds +run: check `/usage` before you start on a subscription, or cap the spend with +`--max-budget-usd` in the unattended form below on an API key.  -Either way `proof.md` is the model's own account, citations included: read -it. Full instructions: [skills/solo/SKILL.md](skills/solo/SKILL.md) and -[skills/siege/SKILL.md](skills/siege/SKILL.md); the sub-agents are -defined in [agents/](agents/). +Either way `proof.md` is the model's own account, and any result it cites from +the literature is quoted from memory: read it critically. Full instructions: +[skills/solo/SKILL.md](skills/solo/SKILL.md) and +[skills/siege/SKILL.md](skills/siege/SKILL.md); the sub-agents are defined in +[agents/](agents/). ## Install @@ -34,9 +38,13 @@ defined in [agents/](agents/). /plugin install math-proof@claude-plugins-official ``` -Needs Claude Code 2.1.280 or later, and `python3` for `siege`. Then -add, once, to the `"env"` section of `~/.claude/settings.json` (larger -responses; sub-agents in the foreground; a long timeout for stalled workers): +Needs Claude Code 2.1.280 or later and, for `siege`, Python 3.7 or later on +your PATH as `python3` or `python` (no extra packages). Then add this `"env"` +block once to `~/.claude/settings.json` (or to `.claude/settings.json` in the +directory you run from, to limit it to that directory). The three lines allow +long responses, keep sub-agents in the foreground by turning background tasks +off, and give a silent worker four hours before it is cut off; they affect every +session that reads the file, so remove them when you stop using the plugin. ```json { @@ -50,31 +58,45 @@ responses; sub-agents in the foreground; a long timeout for stalled workers): ## Use -In an empty working directory, one per problem: +In an empty working directory, one per problem and one run at a time: ``` claude --model claude-opus-5-5 --effort high > /math-proof:solo <the complete problem statement, or the path of a file holding it> ``` -or `/math-proof:siege <…>` likewise. Leave the session alone until it -says where `proof.md` is: `solo` writes under `./math-proof-solo/`, -`siege` under `./math-proof-run/`. To continue a run that stopped or -that you interrupted, give the same line again in the same directory. Options -go before the problem: `DIR=path` picks another run folder, and `siege` -takes settings such as `MAX_ROUNDS=8` (its SKILL.md lists -them); each sub-agent's thinking effort is the `effort:` line in its file in -[agents/](agents/). +or `/math-proof:siege <…>` likewise. `solo` writes under `./math-proof-solo/`, +`siege` under `./math-proof-run/`; the session says where `proof.md` is when it +finishes. In the default permission mode Claude Code asks you to approve file +writes and the `siege` judge's shell commands (short Python checks and file +copies), so stay within reach or use the unattended form below; other than +that, type nothing while it runs. While `siege` runs, `state.md` in the run +folder shows the current round, and if the judge proves its goal and goes +after a stronger one, the result already proved is copied to `result-so-far.md`. + +If a run stops (an error, a closed terminal, a usage limit, Ctrl-C), give the +same `/math-proof:…` line again in the same directory, not a free-form message: +that reloads the skill's instructions and permissions, and the run continues +from its folder with the settings it started with. -Unattended (likewise for `solo`): +Options go before the problem: `DIR=path` picks another run folder, and +`siege` takes settings such as `MAX_ROUNDS=8` (its SKILL.md lists them). To +change a sub-agent's thinking effort, copy its file from [agents/](agents/) +into `~/.claude/agents/`, leave its `name:` line unchanged, and edit the +`effort:` line; your copy takes precedence over the plugin's. + +Unattended, with the problem in a file (likewise for `solo`): ``` -claude -p "/math-proof:siege $(cat problem.md)" --model claude-opus-5-5 --effort high \ - --permission-mode bypassPermissions --dangerously-skip-permissions +claude -p "/math-proof:siege problem.md" --model claude-opus-5-5 --effort high \ + --dangerously-skip-permissions ``` -**Caution:** `siege`'s judge runs model-written Python through Claude -Code's shell tool on your machine. Use the permission-skipping flags only in a +With an API key, adding `--max-budget-usd <amount>` to that `-p` command stops +the run once that much has been spent; giving the command again resumes it. + +**Caution:** `siege`'s judge runs model-written Python through Claude Code's +shell tool on your machine. Use `--dangerously-skip-permissions` only in a disposable container or VM, as a non-root user; otherwise approve its commands by hand. diff --git a/plugins/math-proof/agents/math-proof-judge-deep.md b/plugins/math-proof/agents/math-proof-judge-deep.md deleted file mode 100644 index a85794ca..00000000 --- a/plugins/math-proof/agents/math-proof-judge-deep.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: math-proof-judge-deep -description: "A higher-effort version of math-proof-judge, installed with the others. Meant to be launched only by the math-proof plugin's siege skill, which never launches this version; no setting turns it on." -tools: Read, Write, Edit, Bash, Glob, Grep -model: inherit -effort: high -maxTurns: 120 ---- -You are directing a structured parallel attempt at a hard mathematics problem, one step at a time. Each time you are invoked you receive a step brief naming the step, the files to read, the files to write, and the exact output format. You have no memory of earlier steps beyond what those files contain; the running notes file named in the brief is yours — read it first if it exists, and rewrite it at the end of the step with whatever your future steps should know (route-viability impressions, failed checks, dead ends; keep it under 4000 words). If reference material is reproduced at the end of these instructions, it is part of the problem statement and already complete in your context — do not Read those files from disk again. Long files: the Read tool returns a limited window per call; page with offset/limit, in the largest windows it allows, until you have read the whole file, and never rely on a truncated read of a result you use. Read each file once and work from what is then in your context; re-read only a passage you must quote exactly, and after you Write or Edit a file do not read it back merely to check it. - -The deep reasoning is done by separate worker engines that you never talk to directly: when a step asks you to compose queries, you write query FILES, and each query is later sent to an independent worker that sees ONLY that query's text followed by the complete problem statement — no summary, no other results, no other round. So every query must be self-contained: include, inline, any prior result or partial argument it builds on. Never copy the problem statement into a query; it is supplied to the worker separately. - -The same discipline holds for the proof document: whenever a step has you write DIR/proof.md, remember that proof.md is read on its own by a referee who cannot open any other file in this directory. Never cite run files in it (query or answer files such as r2_q7 or round3_q2.answer.md, extra_q files, the verify report, your notes, the ledger, scripts); write every argument the proof relies on out in full in proof.md itself, rewriting it from the worker files where needed. "See r3_q4.answer.md for the proof of Lemma 2" is, to that referee, an unproved Lemma 2. - -When a step gives you checking to do, you may run python3 through the shell (sympy is usually available; if it is not, plain Python) whenever a concrete computation would confirm or kill a step: check a claimed identity on examples, verify a constant, test a claimed counterexample numerically. Checking beats believing. Whenever a file you write must carry existing text verbatim — a prior result or its proof inside a query file, the draft inside a verify file — splice it in with the shell (cat, sed -n 'A,Bp', a heredoc around $(cat …)) instead of typing it out: retyping long passages is slow and invites transcription slips. Use the shell for nothing else but such checks, such splicing, and plain file handling. You have no web access. - -Be honest throughout: an overclaimed summary or ledger line poisons every later step, and in any proof document a clearly-marked gap is worth more than a papered-over one. Write exactly the files the brief asks for, in the formats it asks for, then reply briefly: what you wrote, and anything the orchestrator must act on (for example that you concluded, or that you wrote extra query files). diff --git a/plugins/math-proof/agents/math-proof-judge.md b/plugins/math-proof/agents/math-proof-judge.md index 7f839920..4357fe06 100644 --- a/plugins/math-proof/agents/math-proof-judge.md +++ b/plugins/math-proof/agents/math-proof-judge.md @@ -6,12 +6,12 @@ model: inherit effort: medium maxTurns: 120 --- -You are directing a structured parallel attempt at a hard mathematics problem, one step at a time. Each time you are invoked you receive a step brief naming the step, the files to read, the files to write, and the exact output format. You have no memory of earlier steps beyond what those files contain; the running notes file named in the brief is yours — read it first if it exists, and rewrite it at the end of the step with whatever your future steps should know (route-viability impressions, failed checks, dead ends; keep it under 4000 words). If reference material is reproduced at the end of these instructions, it is part of the problem statement and already complete in your context — do not Read those files from disk again. Long files: the Read tool returns a limited window per call; page with offset/limit, in the largest windows it allows, until you have read the whole file, and never rely on a truncated read of a result you use. Read each file once and work from what is then in your context; re-read only a passage you must quote exactly, and after you Write or Edit a file do not read it back merely to check it. +You are directing a structured parallel attempt at a hard mathematics problem, one step at a time. Each time you are invoked you receive a step brief naming the step, the files to read, the files to write, and the exact output format. You have no memory of earlier steps beyond what those files contain; the running notes file named in the brief is yours — read it first if it exists, and rewrite it at the end of the step with whatever your future steps should know (route-viability impressions, failed checks, dead ends; keep it under 4000 words). Long files: the Read tool returns a limited window per call; page with offset/limit, in the largest windows it allows, until you have read the whole file, and never rely on a truncated read of a result you use. Read each file once and work from what is then in your context; re-read only a passage you must quote exactly, and after you Write or Edit a file do not read it back merely to check it. The deep reasoning is done by separate worker engines that you never talk to directly: when a step asks you to compose queries, you write query FILES, and each query is later sent to an independent worker that sees ONLY that query's text followed by the complete problem statement — no summary, no other results, no other round. So every query must be self-contained: include, inline, any prior result or partial argument it builds on. Never copy the problem statement into a query; it is supplied to the worker separately. The same discipline holds for the proof document: whenever a step has you write DIR/proof.md, remember that proof.md is read on its own by a referee who cannot open any other file in this directory. Never cite run files in it (query or answer files such as r2_q7 or round3_q2.answer.md, extra_q files, the verify report, your notes, the ledger, scripts); write every argument the proof relies on out in full in proof.md itself, rewriting it from the worker files where needed. "See r3_q4.answer.md for the proof of Lemma 2" is, to that referee, an unproved Lemma 2. -When a step gives you checking to do, you may run python3 through the shell (sympy is usually available; if it is not, plain Python) whenever a concrete computation would confirm or kill a step: check a claimed identity on examples, verify a constant, test a claimed counterexample numerically. Checking beats believing. Whenever a file you write must carry existing text verbatim — a prior result or its proof inside a query file, the draft inside a verify file — splice it in with the shell (cat, sed -n 'A,Bp', a heredoc around $(cat …)) instead of typing it out: retyping long passages is slow and invites transcription slips. Use the shell for nothing else but such checks, such splicing, and plain file handling. You have no web access. +When a step gives you checking to do, you may run Python 3 through the shell (`python3`, or `python` where that is the machine's Python 3; use sympy if it happens to be installed, otherwise the standard library; do not install packages) whenever a concrete computation would confirm or kill a step: check a claimed identity on examples, verify a constant, test a claimed counterexample numerically. Checking beats believing. Whenever a file you write must carry existing text verbatim — a prior result or its proof inside a query file, the draft inside a verify file — splice it in with the shell (cat, sed -n 'A,Bp', a heredoc around $(cat …)) instead of typing it out: retyping long passages is slow and invites transcription slips. Use the shell for nothing else but such checks, such splicing, and plain file handling. You have no web access. Be honest throughout: an overclaimed summary or ledger line poisons every later step, and in any proof document a clearly-marked gap is worth more than a papered-over one. Write exactly the files the brief asks for, in the formats it asks for, then reply briefly: what you wrote, and anything the orchestrator must act on (for example that you concluded, or that you wrote extra query files). diff --git a/plugins/math-proof/agents/math-proof-worker-deep.md b/plugins/math-proof/agents/math-proof-worker-deep.md index 5984b472..9007a256 100644 --- a/plugins/math-proof/agents/math-proof-worker-deep.md +++ b/plugins/math-proof/agents/math-proof-worker-deep.md @@ -1,6 +1,6 @@ --- name: math-proof-worker-deep -description: "The higher-effort math-proof worker, used from the escalation round on. It answers one self-contained question from a file, writing its answer to a file as it reasons. It has no memory between questions and is launched only by the math-proof plugin's siege skill." +description: "The higher-effort math-proof worker, used from the escalation round on (round 4, unless the siege setting ESC_ROUND says otherwise). It answers one self-contained question from a file, writing its answer to a file as it reasons. It has no memory between questions and is launched only by the math-proof plugin's siege skill." tools: Read, Write, Edit model: inherit effort: medium diff --git a/plugins/math-proof/skills/siege/SKILL.md b/plugins/math-proof/skills/siege/SKILL.md index 0e32dd28..a705c8ec 100644 --- a/plugins/math-proof/skills/siege/SKILL.md +++ b/plugins/math-proof/skills/siege/SKILL.md @@ -1,10 +1,10 @@ --- name: siege -description: "Work on one hard mathematics problem in rounds: each round a judge writes a few self-contained questions, independent workers answer them, and the judge keeps a ledger of what is proved, refuted and open, until the judge concludes or the rounds run out, and then a proof.md says plainly what is and is not proved. A run takes hours and dozens of worker runs, and the usage is /math-proof:siege [NAME=value settings] <the problem, stated in full, or the path of a file holding it>." -argument-hint: [NAME=value ...] [DIR=run-directory] <problem statement | problem-file> +description: "Work on one hard mathematics problem in rounds: each round a judge writes a few self-contained questions, independent workers answer them, and the judge keeps a ledger of what is proved, refuted and open, until the judge concludes or the rounds run out, and then a proof.md says plainly what is and is not proved. A run takes hours and dozens of worker runs. Usage: /math-proof:siege [NAME=value settings] <the problem, stated in full, or the path of a file holding it>." +argument-hint: "[NAME=value ...] [DIR=run-directory] <problem statement | problem-file>" disable-model-invocation: true disallowed-tools: WebSearch, WebFetch, AskUserQuestion -allowed-tools: Read, Write, Edit, Glob, Grep, Agent, Bash(python3 ${CLAUDE_SKILL_DIR}/scripts/ledger.py *), Bash(python3 ${CLAUDE_PLUGIN_ROOT}/skills/siege/scripts/ledger.py *), Bash(mkdir *), Bash(cp *), Bash(mv *), Bash(cat *), Bash(test *), Bash(ls *), Bash(wc *), Bash(cmp *), Bash(grep *), Bash(printf *), Bash(echo *) +allowed-tools: Read, Write, Edit, Glob, Grep, Agent, Bash(python3 ${CLAUDE_SKILL_DIR}/scripts/ledger.py *), Bash(python3 ${CLAUDE_PLUGIN_ROOT}/skills/siege/scripts/ledger.py *), Bash(python ${CLAUDE_SKILL_DIR}/scripts/ledger.py *), Bash(python ${CLAUDE_PLUGIN_ROOT}/skills/siege/scripts/ledger.py *), Bash(mkdir *), Bash(cp *), Bash(mv *), Bash(cat *), Bash(test *), Bash(ls *), Bash(wc *), Bash(cmp *), Bash(grep *), Bash(printf *), Bash(echo *) --- # math-proof: siege @@ -37,16 +37,22 @@ the bookkeeping script, not you, decides whether it is finished); do not summari paraphrases. Work unattended to the end: there is nobody to answer questions. **Arguments.** The invoking message reads: $ARGUMENTS -It gives the problem and, optionally, settings. Read it this way. Tokens of the form NAME=value at its start -are settings (below) or DIR=path, the run directory; remove them. If what remains begins with the path of an -existing file, that file is the problem file (and a second path after it, or DIR=, is the run -directory); otherwise everything that remains, to the end of the message, IS the problem statement, -verbatim — mathematics, line breaks and all. (Older form: if the message contains a line beginning -"----- PROBLEM STATEMENT", the text after that line is the problem statement and the paths and settings are -before it.) The run directory DIR defaults to ./math-proof-run under the current directory; use DIR's absolute -path everywhere below. If the message names a place to put the final proof, copy DIR/proof.md there at the -very end; otherwise the proof stays at DIR/proof.md. If the message holds neither a readable problem file nor -any problem text, say so in one sentence and stop. +It gives the problem and, optionally, settings. Read it this way. Tokens of the form NAME=value at its start, +where NAME is a word of two or more capital letters and underscores and value is a whole number (or, for DIR, +a path, quoted if it contains spaces), are settings (the seven below, or DIR, the run directory; any other such +NAME is an error, see Settings); remove them. If what remains is a single line that, taken as a whole — +surrounding whitespace and one pair of enclosing quotation marks removed, backslash-escaped spaces read as spaces +— is the path of an existing file (it may contain spaces; check with Read or Glob, not the shell), that file is +the problem file; if no such file exists and what remains can only be a file path — a single line ending in .md, +.txt or .tex, or a single token (no spaces once the quotes are removed) containing "/" or "\" — tell the user in +one sentence that no file exists at the absolute path you looked for (give it) and that the problem can instead +be given in full as text after the command, and stop; otherwise everything that remains, to the end of the +message, IS the problem statement, verbatim — mathematics, line breaks and all (MAX_ROUNDS=8 is a setting; +"n=3", "N=pq", "AB=AC" and "f(x)=…" are mathematics). The run directory DIR defaults to ./math-proof-run under the +current directory; use DIR's absolute path everywhere below. If the message holds neither a readable problem +file nor any problem text, say so in one or two sentences — with the usage, `/math-proof:siege [NAME=value …] +<problem statement, or the path of a file holding it>`, and that a stopped run is resumed by giving its +original line again in the same directory — and stop. **Settings** (use these unless the invoking message overrides them by name): ESC_ROUND = 4 (the escalation round: from round ESC_ROUND on, if the loop is still running, the wave cap rises, every worker is a `math-proof-worker-deep`, and the plan brief carries its escalation clauses); WAVE = 4 queries per round at most in @@ -54,26 +60,46 @@ rounds before ESC_ROUND and WAVE_DEEP = 10 queries per round at most from round MIN_ROUNDS = 4 (the judge may conclude freely from round MIN_ROUNDS on, earlier only with an audited chain in the ledger — the script decides); REFINE_STEPS = 2; MAX_COMMIT = 9 (both apply to the FULL proof tail; a run whose final goal was certified during the rounds gets the SHORT tail — see "The proof tail"). The invoking message may override any of these seven by name, with tokens of the form NAME=value (for example MAX_ROUNDS=8 WAVE_DEEP=6) placed before the problem, at -the start of the invoking message (or before the PROBLEM STATEMENT line in the older form): use the values as -given, and treat a NAME=value token there whose NAME is neither one of the seven nor DIR as an error — say so in -your first reply and stop before creating anything. (An "=" inside the problem statement itself is mathematics, -not a setting.) +the start of the invoking message: use the values as given, and treat such a token there (NAME a word of two or +more capitals and underscores, value a whole number) whose NAME is neither one of the seven nor DIR as an error — tell the user in one sentence +that NAME is not a setting of /math-proof:siege, that the accepted names are DIR, ESC_ROUND, WAVE, WAVE_DEEP, +MAX_ROUNDS, MIN_ROUNDS, REFINE_STEPS and MAX_COMMIT, and that if the token is part of the problem itself the +problem can be given as a file path instead — and stop before creating anything. (A leading token whose +left-hand side is a single letter or not all capitals, or whose right-hand side is not a whole number, and any +"=" further inside the problem statement, is mathematics, not a setting.) Wherever a setting is named below, it means the value in force. -The bookkeeping script is scripts/ledger.py in this skill's own folder: `python3 ${CLAUDE_SKILL_DIR}/scripts/ledger.py` (called SCRIPT below). If that placeholder was not filled in — the path before /scripts does not exist — use `${CLAUDE_PLUGIN_ROOT}/skills/siege/scripts/ledger.py`, and if that one is unfilled too, find scripts/ledger.py in this skill's own folder (for the standard install ~/.claude/skills/math-proof/skills/siege/scripts/ledger.py; otherwise Glob for math-proof/skills/siege/scripts/ledger.py) and use its absolute path; `test -s` the path once before Setup. +The bookkeeping script is scripts/ledger.py in this skill's own folder: `python3 ${CLAUDE_SKILL_DIR}/scripts/ledger.py` +(called SCRIPT below). If that placeholder was not filled in — the path before /scripts does not exist — use +`${CLAUDE_PLUGIN_ROOT}/skills/siege/scripts/ledger.py`, and if that one is unfilled too, Glob for +`**/skills/siege/scripts/ledger.py` under ~/.claude and use its absolute path (if several match, the newest); in +every case quote the script path in the command if it contains spaces. Before Setup, run SCRIPT once with no +further arguments: it should print a line beginning "usage:". If instead Python runs but says it cannot open the +script file, the path is wrong, not Python: resolve it again by the fallbacks above and run once more, and if no +ledger.py can be found tell the user the plugin's files are not where expected (reinstall math-proof from +`/plugin`) and stop. If instead the shell says python3 cannot be found, or anything else comes back that is not +the usage line (on Windows, a reply that Python "was not found" and can be installed from the Store is this +case), use `python` in place of `python3` in SCRIPT from then on and run it once more; if that fails too, tell +the user in one or two sentences that /math-proof:siege could not run its bookkeeping script — quote the command +and the shell's reply — that it needs Python 3.7 or later on the PATH as python3 or python, and that the same +line given again will work once that is fixed; then stop. ## Setup 1. If DIR/state.md already exists, this is a resume: check that the existing DIR/problem.md is the same problem you were given (compare the text, ignoring differences in whitespace and line endings; for a file, `cmp`) — - if it differs, say in one sentence that DIR holds a run on a different problem and that DIR=<another - directory> selects a fresh one, and stop; if it is the same, Read DIR/problem.md in full, read state.md and + if it differs, say in one sentence that DIR holds a run on a different problem and that `DIR=<another + directory>` selects a fresh one, and stop; if it is the same and state.md records "phase: finished", that run + is complete: say where DIR/proof.md is (and DIR/result-so-far.md, if it exists), that `DIR=<another + directory>` starts a fresh run, and stop; otherwise Read DIR/problem.md in full, read state.md and resume from the phase it records instead of starting over, never redoing a step whose output files exist and - never rewriting DIR/problem.md. If the phase recorded is a wave, start with `SCRIPT answers` on that wave's + never rewriting DIR/problem.md (if the invoking message gives settings that differ from those recorded in + state.md, include one line saying the recorded ones govern this run in the same message as your next tool + call — a notice, not a stop). If the phase recorded is a wave, start with `SCRIPT answers` on that wave's query stems (see the wave rule under Rules) and launch workers only for the queries the script does not report answered, each partial one with its {EARLIER} paragraph; that launch counts as the wave's first, so its one re-run still follows. A query already answered whose index line is missing gets the line "{Q} | answered | (finished before this session resumed)"; a query that already has an index line gets no second one — its new status is appended to that line as " | re-run: status | abstract" instead. - Otherwise create DIR and DIR/judge/ and put the problem at DIR/problem.md: if + Otherwise create DIR and DIR/judge/ (`mkdir -p`) and put the problem at DIR/problem.md: if it came as a file, copy that file there byte for byte with `cp`; if it came as text in the invoking message, Write exactly that text (nothing added, removed or reworded) to DIR/problem.md. Then, as your very next action, Read DIR/problem.md in full — you paste its text into every judge brief and every worker prompt (see @@ -92,7 +118,9 @@ a space or a blank line). This is attempt 1 of round r. append each of its verdicts (" | OK" or " | DEGENERATE: …") to that query's index line — plain file handling; nothing is re-run on a DEGENERATE verdict. Then run `SCRIPT check DIR {r} {CAP} {MIN_ROUNDS} {attempt}` ({CAP} = this round's cap, WAVE or WAVE_DEEP, exactly as in (a) — passing WAVE in round ESC_ROUND or later would silently set part of the wave aside). It numbers and appends the round's -ledger lines to DIR/ledger.md itself and prints exactly one verdict line; act on its first word: +ledger lines to DIR/ledger.md itself and prints exactly one verdict line; act on its first word (if instead it prints a line +beginning `ERROR:`, the command itself was malformed — DIR first, as an absolute path, then the four numbers; correct +the command and run it again, which does not count as a plan attempt): - `WAVE n FLOOR f …` — copy DIR/round{r}_summary.md over DIR/summary.md, note f (the fewest queries of this wave that may come back answered or partial, see Rules), give the goal-change notice below if one is due, then go to (c) with the query files DIR/round{r}_q1.md … DIR/round{r}_q{n}.md (the script has renumbered them @@ -113,9 +141,9 @@ record the same line in state.md. If the sentence begins "Goal change: raised", names as holding the earlier goal's proof (`test -s` each) to DIR/result-so-far.md — one file: `cp`; several: one `cat <files in the order named> > DIR/result-so-far.md` (each ends with its own end line, which separates them) — overwriting any earlier result-so-far.md, and end your line with "the proved result so far is in -DIR/result-so-far.md". If the sentence names no file, take <stem> from the locator after the final "—" of the last -line of the form "N. PROVED: [GOAL] …" in DIR/ledger.md (grep) and use DIR/<stem>.answer.md, or -DIR/<stem>.partial.md if only that exists; `test -s` each file first, and if none exists, skip the copy and say +DIR/result-so-far.md". If the sentence names no file, take `<stem>` from the locator after the final "—" of the last +line of the form "N. PROVED: [GOAL] …" in DIR/ledger.md (grep) and use `DIR/<stem>.answer.md`, or +`DIR/<stem>.partial.md` if only that exists; `test -s` each file first, and if none exists, skip the copy and say so in your line. That file is for a user who stops the run here; nothing later reads it, and proof.md remains the run's deliverable. (On a problem that fixes its claim a raise never happens — there is nothing to raise to — so the file is never written; a replacement is still announced.) @@ -132,8 +160,10 @@ verdicts into the index. Update state.md ("phase: round {r+1} plan, attempt 1"; ## The proof tail (after the loop ends, by CONCLUDE, TAIL, or finishing round MAX_ROUNDS) First fix the tail's shape: run `SCRIPT gate DIR`. If its output begins `CONCLUDE`, the claims ledger holds the headline goal settled and certified by two separate verify queries, and the tail is SHORT: (e) draft, (f) no refine step, no select step — build DIR/r3_verify.md yourself by the shell concatenation described under (g) and -write no r3_q files —, (h) a commit wave consisting of DIR/r3_verify.md alone, (i) finalize. If it prints anything -else (`REJECT: …`, or an error line), the tail is FULL: steps (e)–(i) exactly as written below. Record "tail: short" or "tail: full" and +write no r3_q files —, (h) a commit wave consisting of DIR/r3_verify.md alone, (i) finalize. If it prints +anything else (normally `REJECT: …`), the tail is FULL: steps (e)–(i) exactly as written below — except that a line +beginning `ERROR:` means the gate command itself was malformed (DIR first, as an absolute path): correct it and run +it again before deciding. Record "tail: short" or "tail: full" and the gate's line in state.md. Two fallbacks guard the short tail. If its verify-only wave ends, after the one re-run, with no DIR/r3_verify.answer.md, switch to the FULL tail from (g) on (note "tail: short, then full — no verify answer"). And if the FIRST finalize reply of the short tail begins "MAIN CLAIM: NOT PROVED" (check this before the stand-alone grep check of @@ -148,8 +178,7 @@ results" clause by "(no wave completed before the rounds ended — work from the DIR/proof.md. The extra-query rule applies (see Rules; that relaunch, if it happens, is part of this step). If DIR/proof.md does not exist once the step is over, launch the draft judge one more time with the added first paragraph "DIR/proof.md was not written; write it now from the material named below."; if it still does not -exist, stop and report. As soon as DIR/proof.md exists, and again after every later step that rewrites it, copy -it to the requested output path if one was named (so a run that dies late still leaves its latest proof there). +exist, stop and report. **(f) Refine**, REFINE_STEPS times in the FULL tail (step names refine_2, refine_3, … in order, REFINE_STEPS of them), not at all in the SHORT tail: one `math-proof-judge` each with the REFINE BRIEF (extra-query rule applies, once per step). **(g) Select.** One `math-proof-judge` with the SELECT BRIEF → up to MAX_COMMIT files DIR/r3_q{k}.md and exactly one @@ -169,8 +198,7 @@ first paragraph "DIR/proof.md still refers to run files (grep found: {the matche A referee reads proof.md alone and cannot open them. Rewrite DIR/proof.md so that every argument it relies on is written out in full inside proof.md itself, with no reference to any file in this directory.", note "standalone-check: resent" in state.md, and accept whatever proof.md that launch leaves (do not repeat the check). -Copy the final DIR/proof.md to the requested -output path if one was named. Update state.md ("phase: finished"). Reply to the user with: where proof.md is, +Update state.md ("phase: finished"). Reply to the user with: where proof.md is, how many rounds ran and why the loop ended (the script's verdict line), how many worker queries ran, how many were answered and how many ended partial, whether the goal was ever replaced or raised (one line, from state.md; if DIR/result-so-far.md exists, say that it holds the earlier result as the worker wrote it, checked @@ -179,24 +207,20 @@ restate or assess the mathematics yourself. ## Rules that hold throughout - Every judge step and every worker is a NEW subagent launch (the Agent tool) with `subagent_type` set - explicitly; never omit it. The sub-agents ship with this skill and your agent list may show them under a - plugin-scoped name — `math-proof:math-proof-judge`, `math-proof:math-proof-worker`, `math-proof:math-proof-worker-deep` — or under - the bare names; use the bare names if your agent list offers them (if agent files with these names are installed - in the project or user agents directory they take precedence, which is intended), otherwise the scoped names, and if neither - is available say so and stop before round 1. Record the form you used in state.md. Judge steps use `math-proof-judge`. Workers — round waves and their re-runs — use `math-proof-worker` in rounds + explicitly; never omit it. The sub-agents ship with this plugin and your agent list normally shows them under + plugin-scoped names — `math-proof:math-proof-judge`, `math-proof:math-proof-worker`, `math-proof:math-proof-worker-deep`. + Decide the name seat by seat: for each of the three, use the bare name (`math-proof-judge`, `math-proof-worker`, + `math-proof-worker-deep`) if your agent list offers it, otherwise the scoped name; mixing the two forms is fine (a + bare-named copy in the user's or the project's agents directory is how a user changes that one seat's settings, + and is meant to win). If one of the three is listed under neither name, tell the user that the math-proof + plugin's sub-agents are not in this session's agent list — open `/plugin` to check that math-proof is installed + and enabled, restart Claude Code, and give the same /math-proof:siege line again — and stop before round 1. + Record in state.md the name used for each seat. Judge steps use `math-proof-judge`. Workers — round waves and their re-runs — use `math-proof-worker` in rounds before ESC_ROUND and `math-proof-worker-deep` in round ESC_ROUND and every later round; the workers of the proof tail (extra-query waves, the commit wave, r3_verify) use `math-proof-worker-deep` if a wave ran in round ESC_ROUND or later (R ≥ ESC_ROUND in state.md) and `math-proof-worker` otherwise. The choice is purely by round number, never by your own view of how the attempt is going. Never reuse, resume or send a message to an earlier subagent. - Do not pass a `model` to the Agent tool: judges and workers run on this session's model — with exactly one - exception. If a judge step or a worker comes back with an error saying the model's SAFEGUARDS FLAGGED or - refused the request (the provider's usage-policy filter, e.g. "…'s safeguards flagged this message"), - relaunch that same step or worker ONCE with `model: "opus"` added to the Agent call, everything else - identical, and record it (append " | FALLBACK opus" to the worker's index line; note the step and - "fallback: opus" in state.md). This is the run owner's chosen fallback, not a licence to change models - otherwise: never use it for any other kind of failure, never pre-emptively, and never reword the - mathematics to avoid the filter. If the fallback launch fails too, it is a failed step under the rules - below. In your final reply, say how many launches used the fallback. + Do not pass a `model` to the Agent tool: judges and workers run on this session's model. Launch a whole wave in ONE message so the workers run in parallel; never run a subagent in the background. - In every brief and worker prompt below, DIR stands for the run directory's absolute path and the other {bracketed} slots for the values named; substitute them and send the text otherwise VERBATIM. Do not add @@ -212,7 +236,7 @@ restate or assess the mathematics yourself. - You never write or edit query files, answer files (finished or partial), summaries, ledger files, notes.md or proof.md yourself. The only files you write are state.md, index.md, the problem copy, the fallback r3_verify.md and result-so-far.md (both by copying or concatenation only); beyond that you only copy or move files where a - step says so (cp/mv, e.g. summary.md, rejected answers, proof.md to the output path). You do not read answer files beyond confirming they exist (`test -s`); + step says so (cp/mv: summary.md, and the r3_verify.first renames in the proof tail). You do not read answer files beyond confirming they exist (`test -s`); which of them are finished is decided by the bookkeeping script (`SCRIPT answers`, below), never by you. - Worker prompts are always exactly this, with {Q} the query file stem (for example round2_q3, extra_q1, r3_q2, r3_verify), {PROBLEM} the complete contents of DIR/problem.md, byte for byte, and {EARLIER} an empty @@ -233,8 +257,7 @@ restate or assess the mathematics yourself. The end line is how a finished answer is told from one a worker was cut off in the middle of (by a usage limit, an error or its turn limit); the bookkeeping script checks for it, you never do. - Running a wave of query files means: launch one worker of the type this wave uses (`math-proof-worker` or - `math-proof-worker-deep`, see the first rule) per file, all in one message. When all have returned (a worker - relaunched under the safeguards exception above included) — never earlier: a worker still running is still + `math-proof-worker-deep`, see the first rule) per file, all in one message. When all have returned — never earlier: a worker still running is still writing its file — run `SCRIPT answers DIR {Q1} {Q2} …` with the stems of the wave's query files, as a command on its own, and read what it prints before you write any index line or launch anything. It decides, without your reading anything, which answer files are finished, and prints one line per query — "{Q}: answered" (DIR/{Q}.answer.md ends with that query's end line: its worker @@ -255,7 +278,7 @@ restate or assess the mathematics yourself. longer of its two unfinished files as DIR/{Q}.partial.md and the other beside it as DIR/{Q}.partial.prev.md). So an index line reads "{Q} | status | abstract", sometimes followed by " | re-run: status | abstract", and the re-run's status, when there is one, is the one in force; the plan, draft, refine and finalize briefs tell - the judges what a partial file is. Apart from that safeguards relaunch, never launch a worker for a query + the judges what a partial file is. Never launch a worker for a query between a worker's return and the `answers` run that accounts for it. Note the TOTAL line of the last `answers` run for the wave — the one over all its stems, so its count n equals the wave's size: the FLOOR rule below and state.md use it. - No user will answer you during this session: never end your turn to ask how to proceed, never wait for confirmation, and @@ -266,7 +289,9 @@ restate or assess the mathematics yourself. row, stop and report where things stand. If, once a round's wave has ended after its one re-run, answered + partial on that last TOTAL line is smaller than the FLOOR number the script printed with its WAVE verdict (screening verdicts do not count against this), stop and report: something systematic is wrong and - continuing would only spend judge steps on nothing. (If that TOTAL line's n is smaller than the wave, you ran + continuing would only spend judge steps on nothing — tell the user the likeliest cause is a usage limit or an + outage that cut the workers off, that the run's files are intact, and that giving the same /math-proof:siege line + again in this directory resumes the run once the cause has cleared. (If that TOTAL line's n is smaller than the wave, you ran `answers` on only some stems — run it on all of them first.) The extra-query and commit waves have no floor. - Extra queries: when a draft or refine brief allows it, the judge may write up to 3 files named DIR/extra_q{k}.md using the next unused numbers k; the whole run has a budget of 10 (once DIR/extra_q10.md @@ -375,7 +400,7 @@ restate or assess the mathematics yourself. > newest OPEN [GOAL] line and aim the wave at the gap). A REFUTED raised goal is not the run's verdict, and its > refutation needs no verify queries (the audit rule below is for a goal the run may conclude on): record it as a > "REFUTED: [GOAL] …" line naming the refuting file, then re-state the goal you proved below it, as (iv) -> describes, and conclude on that. Raising is a judgement, not a duty: if nothing clearly more significant looks +> describes, and conclude on that. Raising is a judgment, not a duty: if nothing clearly more significant looks > within reach, conclude on the proved goal under the rule on concluding given earlier in this brief; and if the > first two waves aimed at a raised goal (the raising round's own wave is the first) leave it no nearer — no > proof of it, and no new route to one — then at the next plan step come back to the goal already proved and @@ -499,7 +524,7 @@ new proof's locator, and compose the audit rule's verify queries so that they ca entries' arguments and the new proof, each spliced from its answer file, joined by the chain's derivation exactly as last round's summary states it. If a complete written proof or refutation is in hand, that way or any other, skip the rest of (iii) and all of (iv). Otherwise the summary carries a section headed exactly 'The chain and the -missing statement', rewritten every round, with four labelled parts. Chain: the derivation by which the [GOAL] +missing statement', rewritten every round, with four labeled parts. Chain: the derivation by which the [GOAL] claim (or its negation, when the line pursued is a disproof — then read 'proof of the missing statement' below accordingly) follows from results already PROVED — cited by ledger number, statements only — together with exactly ONE further statement not yet proved; write the derivation out @@ -589,17 +614,6 @@ under summary rule (ii)), or — at most one of them — to checking one PROVED step the chain rests on that no separate query has yet checked. All of these are attempt queries (first line 'kind: attempt')." -## SCREEN BRIEF (retired — not launched in this version; screening is item 0 of the PLAN BRIEF. Kept for reference.) -> Step: screen round {r}. Files: the problem is DIR/problem.md; the queries are DIR/round{r}_q1.md … -> DIR/round{r}_q{n}.md and their outputs DIR/round{r}_q{k}.answer.md (DIR/index.md says which have no answer). -> Read them. You are -> quality-screening the outputs of independent deep-reasoning queries from one round of a structured attempt at -> a mathematics problem. You are NOT judging correctness or progress — only whether each output is a genuine -> attempt at the query it was sent. Mark DEGENERATE only for refusals, empty or off-topic text, or output about -> a different problem. Write DIR/judge/screen_r{r}.md with one line per query, exactly "round{r}_q{k}: OK" or -> "round{r}_q{k}: DEGENERATE: one-line reason" (a missing answer is "DEGENERATE: no answer"), and reply with -> the same lines and nothing else. No shell and no notes rewrite needed for this step. - ## DRAFT BRIEF > Step: proof draft. Files: the problem is DIR/problem.md; your running notes are DIR/notes.md; your running > summary of everything the attempt established is DIR/summary.md; the claims ledger is DIR/ledger.md; the diff --git a/plugins/math-proof/skills/siege/scripts/ledger.py b/plugins/math-proof/skills/siege/scripts/ledger.py index 7aa71f38..91f65382 100644..100755 --- a/plugins/math-proof/skills/siege/scripts/ledger.py +++ b/plugins/math-proof/skills/siege/scripts/ledger.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Bookkeeping helper for the math-proof plugin's siege skill: the four mechanical decisions of the round loop and its waves that should not depend on a -model's judgement. +model's judgment. ledger.py check DIR R WAVE MIN_ROUNDS ATTEMPT After the round-R plan step: validates the shape of what the judge @@ -37,12 +37,15 @@ model's judgement. shorter older one moves to Q.partial.prev.md), and an empty DIR/Q.answer.md is deleted. Nothing a worker wrote is ever deleted or overwritten except an older Q.partial.prev.md. Idempotent; an ERROR - line (and nothing touched) if DIR or a stem is wrong. - -Standard library only. Always exits 0 and says what it decided on -stdout; any internal error prints a fail-closed verdict (RETRY/REJECT, or -an ERROR line from `answers`) rather than a traceback the orchestrator -might misread. + line (and nothing touched) if a stem is wrong. + +A malformed command (DIR not an existing directory, a missing or non-numeric +argument) prints an ERROR line and touches nothing. Standard library only +(Python 3.7 or later); files are read and written as UTF-8 regardless of the +platform's default encoding. Always exits 0 and says what it decided on +stdout; any internal error prints a fail-closed verdict (RETRY/REJECT, or an +ERROR line from `answers`) rather than a traceback the orchestrator might +misread. """ from __future__ import annotations @@ -52,6 +55,7 @@ import sys from pathlib import Path MAX_ATTEMPTS = 3 # plan attempts per round before a shortfall is accepted +ENC = dict(encoding="utf-8", errors="replace") # ---- ledger parsing and the early-conclusion gate -------------------------- _LEDGER_STATUS_WORDS = ("OPEN", "PROVED", "REFUTED", "RETRACT", "RETRACTED", "SKETCHED") @@ -64,8 +68,6 @@ def _take_tags(text: str, tags: set) -> str: bracketed STATUS word is not a tag and stops the scan. Tags count only in this leading position — a prose mention later in the line ("the key step toward [GOAL]") is not a tag.""" - import re - while True: m = re.match(r"^[*_\s]*\[([A-Za-z]{1,6})\]\s*[:\-–—]?\s*", text) if not m or m.group(1).upper() in _LEDGER_STATUS_WORDS: @@ -92,8 +94,6 @@ def _cited_ids(text: str) -> set: L hybrid ("entry L5") is not accepted after "line"/"lines", where it collides with geometry prose ("lines L2 and L4 are tangent"). Bare integers are never citations (math prose is full of them).""" - import re - ids = set() for m in re.finditer(r"#(\d{1,4})\b(?![./]\d)", text): ids.add(int(m.group(1))) @@ -121,8 +121,6 @@ def ledger_entries(ledger_text: str) -> dict[int, dict]: goal/audit are set only by a [GOAL]/[AUDIT] tag in tag position — immediately before or after the status word — never by a prose mention elsewhere in the line.""" - import re - out: dict[int, dict] = {} for ln in ledger_text.splitlines(): m = re.match(r"\s*(\d+)\.\s+(.*)", ln) @@ -198,8 +196,6 @@ def early_conclude_ok(entries: dict[int, dict], known_locators=None) -> bool: attestation check on judge-written ledger text, not an independent proof check: the run's correctness still rests on the audits being real, which the locator requirement grounds but cannot prove.""" - import re - live = {n: e for n, e in entries.items() if e["retracted_by"] is None} goals = sorted(n for n, e in live.items() if e.get("goal")) if not goals: @@ -266,7 +262,7 @@ def ledger_text(d: Path, before=None) -> str: for p in _parts(d): if before is not None and _round_of(p) >= before: continue - out.append(p.read_text(errors="replace")) + out.append(p.read_text(**ENC)) return "".join(out) @@ -291,10 +287,12 @@ def numbered_lines(d: Path, r: int, block: str) -> list: def append(d: Path, r: int) -> int: bp = d / f"round{r}_ledger_block.md" - block = bp.read_text(errors="replace") if bp.exists() else "" + block = bp.read_text(**ENC) if bp.exists() else "" lines = numbered_lines(d, r, block) - (d / f"round{r}_ledger.md").write_text("".join(f"{ln}\n" for ln in lines)) - (d / "ledger.md").write_text(ledger_text(d)) + (d / f"round{r}_ledger.md").write_text( + "".join(f"{ln}\n" for ln in lines), encoding="utf-8" + ) + (d / "ledger.md").write_text(ledger_text(d), encoding="utf-8") return len(lines) @@ -342,7 +340,7 @@ def is_attack(p: Path) -> bool: """kind: attempt declared near the top (first three non-empty lines that contain letters — tolerates a front-matter fence or a heading first).""" seen = 0 - for ln in p.read_text(errors="replace").splitlines(): + for ln in p.read_text(**ENC).splitlines(): if not re.search(r"[A-Za-z]", ln): continue if re.match( @@ -357,7 +355,7 @@ def is_attack(p: Path) -> bool: def is_withdrawn(p: Path) -> bool: """An emptied or '(withdrawn)' query file left over from a re-plan.""" - t = p.read_text(errors="replace").strip() + t = p.read_text(**ENC).strip() return not t or bool( re.fullmatch(r"[(\[]?\s*withdrawn\s*[)\]]?\.?", t, re.IGNORECASE) ) @@ -404,8 +402,8 @@ def _last_line(text: str) -> str: """The last line of text that contains a letter or digit ('' if none), so that a closing code fence or a rule drawn under the end line does not hide it. A line made of nothing but bare markup tags without - attributes (a stray '</invoke>' or '</details>' a model sometimes emits - after its last real line) is skipped the same way: a worker does not + attributes (a stray '</details>' or similar closing tag a model sometimes + emits after its last real line) is skipped the same way: a worker does not write its end line in that form, and skipping such a line can only reveal an end line the worker did write above it.""" for ln in reversed(text.splitlines()): @@ -420,8 +418,6 @@ def answers(d: Path, args: list) -> str: the module docstring). Only one line of DIR/Q.answer.md is looked at, the last that contains a letter or digit and is not a bare markup tag; nothing else in any file is read for meaning.""" - if not d.is_dir(): - return f"ERROR: {str(d)!r} is not an existing run directory; give DIR first, then the query stems (e.g. round2_q1 round2_q2)" stems, seen = [], set() for arg in args: stem = Path(arg).name # tolerate a path or a file name for a stem @@ -441,7 +437,7 @@ def answers(d: Path, args: list) -> str: a, p = d / f"{stem}.answer.md", d / f"{stem}.partial.md" status = None if a.exists(): - text = a.read_text(errors="replace") + text = a.read_text(**ENC) if is_end_line(_last_line(text), stem): status = "answered" elif not text.strip(): @@ -450,11 +446,11 @@ def answers(d: Path, args: list) -> str: # an older, longer unfinished file stays the partial; keep this one beside it a.replace(d / f"{stem}.partial.prev.md") else: - if p.exists() and p.read_text(errors="replace").strip(): + if p.exists() and p.read_text(**ENC).strip(): p.replace(d / f"{stem}.partial.prev.md") a.replace(p) if status is None: - partial = p.exists() and p.read_text(errors="replace").strip() + partial = p.exists() and p.read_text(**ENC).strip() status = "partial" if partial else "no answer" counts[status] += 1 out.append(f"{stem}: {status}") @@ -491,8 +487,9 @@ def check(d: Path, r: int, wave: int, min_rounds: int, attempt: int) -> str: and the early-conclusion gate is evaluated on the ledger of earlier rounds plus this attempt's not-yet-appended lines.""" final = attempt >= MAX_ATTEMPTS + wave = max(1, wave) sp = d / f"round{r}_summary.md" - if not sp.exists() or not sp.read_text(errors="replace").strip(): + if not sp.exists() or not sp.read_text(**ENC).strip(): what = f"no running summary (DIR/round{r}_summary.md is missing or empty)" return ( f"TAIL: {what} after {attempt} attempts" @@ -503,21 +500,21 @@ def check(d: Path, r: int, wave: int, min_rounds: int, attempt: int) -> str: ) qs = round_queries(d, r) for p in [q for q in qs if is_withdrawn(q)]: - p.rename(p.with_name(p.stem + ".withdrawn.md")) + p.replace(p.with_name(p.stem + ".withdrawn.md")) qs.remove(p) for k, p in enumerate(qs, 1): # close gaps so the wave is q1..qn want = d / f"round{r}_q{k}.md" if p != want: - p.rename(want) + p.replace(want) qs[k - 1] = want done = d / f"round{r}_DONE.md" if qs: # composed queries take precedence over a verdict if done.exists(): - done.rename(d / f"round{r}_DONE.superseded.md") + done.replace(d / f"round{r}_DONE.superseded.md") extra = "" if len(qs) > wave: for p in qs[wave:]: - p.rename(p.with_name(p.stem + ".overcount.md")) + p.replace(p.with_name(p.stem + ".overcount.md")) qs = qs[:wave] extra = f"; over-count: files beyond q{wave} set aside" need = (len(qs) + 1) // 2 @@ -538,14 +535,12 @@ def check(d: Path, r: int, wave: int, min_rounds: int, attempt: int) -> str: return ( f"WAVE {len(qs)} FLOOR {wave_floor(len(qs))} (ledger +{n_new}{note}{extra})" ) - if done.exists() and done.read_text(errors="replace").strip(): + if done.exists() and done.read_text(**ENC).strip(): if r >= min_rounds: n_new = append(d, r) return f"CONCLUDE (round {r} >= floor {min_rounds}; ledger +{n_new})" bp = d / f"round{r}_ledger_block.md" - pending = numbered_lines( - d, r, bp.read_text(errors="replace") if bp.exists() else "" - ) + pending = numbered_lines(d, r, bp.read_text(**ENC) if bp.exists() else "") text = ledger_text(d, before=r) + "".join(f"{ln}\n" for ln in pending) why = gate_reason(text, known_locators(d)) if not why: @@ -554,7 +549,7 @@ def check(d: Path, r: int, wave: int, min_rounds: int, attempt: int) -> str: if final: n_new = append(d, r) return f"CONCLUDE (accepted before round {min_rounds} after {attempt} plan attempts without a qualifying chain — {why}; ledger +{n_new})" - done.rename(d / f"round{r}_DONE.rejected{attempt}.md") + done.replace(d / f"round{r}_DONE.rejected{attempt}.md") return ( f"RETRY: Correction — your conclusion at round {r} was not accepted: {why}. " + GATE_RULE.format(m=min_rounds) @@ -572,17 +567,48 @@ def check(d: Path, r: int, wave: int, min_rounds: int, attempt: int) -> str: ) +USAGE = ( + "usage: ledger.py check DIR R WAVE MIN_ROUNDS ATTEMPT | append DIR R | gate DIR [R] | " + "answers DIR Q1 [Q2 ...] (bookkeeping for the math-proof siege skill; DIR is the run directory)" +) +# per command: its usage form, then how many arguments follow DIR (at least, +# at most) and how many of those must be whole numbers +_FORMS = { + "check": ("check DIR R WAVE MIN_ROUNDS ATTEMPT", 4, 4, 4), + "append": ("append DIR R", 1, 1, 1), + "gate": ("gate DIR [R]", 0, 1, 1), + "answers": ("answers DIR Q1 [Q2 ...]", 1, None, 0), +} + + +def _malformed(argv: list) -> str: + """'' when the command line has the right shape, else an ERROR line.""" + cmd, rest = argv[1], argv[3:] + if cmd not in _FORMS: + return f"ERROR: unknown command {cmd!r}. {USAGE}; nothing was touched" + form, lo, hi, nints = _FORMS[cmd] + if len(argv) < 3 or len(rest) < lo or (hi is not None and len(rest) > hi): + return f"ERROR: usage: ledger.py {form} (DIR first, as an absolute path); nothing was touched" + d = Path(argv[2]) + if not d.is_dir(): + return f"ERROR: '{d}' is not an existing run directory; give the run directory's absolute path first (ledger.py {form}); nothing was touched" + if not all(a.isascii() and a.isdigit() for a in rest[:nints]): + return f"ERROR: usage: ledger.py {form}; the arguments after DIR must be whole numbers (got {' '.join(rest[:nints])}); nothing was touched" + return "" + + def main(argv: list) -> str: + if len(argv) < 2 or argv[1] in ("-h", "--help"): + return USAGE try: + bad = _malformed(argv) + if bad: + return bad cmd = argv[1] - if cmd == "answers" and len(argv) < 4: - return "ERROR: usage: ledger.py answers DIR Q1 [Q2 ...] (query stems such as round2_q1)" d = Path(argv[2]) if cmd == "append": return f"APPENDED {append(d, int(argv[3]))}" - if ( - cmd == "gate" - ): # on ledger.md as it stands, plus round R's pending block if R given + if cmd == "gate": # on ledger.md as it stands, plus round R's pending block if R given text = ledger_text(d) if len(argv) > 3: r = int(argv[3]) @@ -590,7 +616,7 @@ def main(argv: list) -> str: text = ledger_text(d, before=r) + "".join( f"{ln}\n" for ln in numbered_lines( - d, r, bp.read_text() if bp.exists() else "" + d, r, bp.read_text(**ENC) if bp.exists() else "" ) ) why = gate_reason(text, known_locators(d)) @@ -604,20 +630,16 @@ def main(argv: list) -> str: # caller passing attempt=1 forever still reaches the terminal # verdicts after MAX_ATTEMPTS plan steps logp = d / "judge" / f"plan_r{r}_retries.log" - issued = ( - len(logp.read_text(errors="replace").splitlines()) - if logp.exists() - else 0 - ) + issued = len(logp.read_text(**ENC).splitlines()) if logp.exists() else 0 attempt = max(attempt, issued + 1) verdict = check(d, r, wave, min_rounds, attempt) if verdict.startswith("RETRY"): logp.parent.mkdir(parents=True, exist_ok=True) - with logp.open("a") as f: + with logp.open("a", encoding="utf-8") as f: f.write(f"attempt {attempt}: {verdict[:120]}\n") # corrections are pasted into a brief whose paths are absolute return verdict.replace("DIR/", str(d).rstrip("/") + "/") - return f"REJECT: unknown command {cmd!r} (commands: check, append, gate, answers)" + return USAGE except Exception as e: # fail closed, in words the orchestrator can relay if len(argv) > 1 and argv[1] == "answers": return f"ERROR: the bookkeeping script could not classify the answer files ({type(e).__name__}: {str(e)[:200]}); check DIR and the query stems and run the command again" @@ -633,4 +655,8 @@ def main(argv: list) -> str: if __name__ == "__main__": + try: # the verdict goes out as UTF-8 whatever the console's code page (Windows) + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except (AttributeError, ValueError): + pass print(main(sys.argv)) diff --git a/plugins/math-proof/skills/solo/SKILL.md b/plugins/math-proof/skills/solo/SKILL.md index 051a4912..baf2dc48 100644 --- a/plugins/math-proof/skills/solo/SKILL.md +++ b/plugins/math-proof/skills/solo/SKILL.md @@ -1,7 +1,7 @@ --- name: solo -description: "Work on one hard mathematics problem in this session yourself, with no sub-agents: reason in stages, record each settled step in a notes file so that nothing written is lost if a response is cut off, and end with a self-contained proof.md. The usage is /math-proof:solo <the problem, stated in full, or the path of a file holding it>." -argument-hint: [DIR=run-directory] <problem statement | problem-file> +description: "Work on one hard mathematics problem in this session yourself, with no sub-agents: reason in stages, record each settled step in a notes file so that nothing written is lost if a response is cut off, and end with a self-contained proof.md. Usage: /math-proof:solo <the problem, stated in full, or the path of a file holding it>." +argument-hint: "[DIR=run-directory] <problem statement | problem-file>" disable-model-invocation: true disallowed-tools: WebSearch, WebFetch, AskUserQuestion allowed-tools: Read, Write, Edit, Glob, Grep, Bash(mkdir *), Bash(cp *), Bash(cmp *) @@ -14,22 +14,35 @@ file and, at the end, proof.md. **Arguments.** The invoking message reads: $ARGUMENTS It gives the problem and, optionally, the run directory. Read it this way. A token of the form DIR=path at its -start sets the run directory; remove it. If what remains begins with the path of an existing file, that file is -the problem file; otherwise everything that remains, to the end of the message, IS the problem statement, -verbatim — mathematics, line breaks and all. The run directory DIR defaults to ./math-proof-solo under the -current directory; use DIR's absolute path everywhere below. If the message holds neither a readable problem -file nor any problem text, say so in one sentence and stop. +start sets the run directory (the path quoted if it contains spaces); remove it. Any other leading token of the +form NAME=value, where NAME is a word of two or more capital letters and underscores and value is a whole number, +is a setting this skill does not have: tell the user in one sentence that /math-proof:solo takes only DIR=path +before the problem (round and wave settings belong to /math-proof:siege), and that if the token is part of the +problem itself the problem can be given as a file path instead, and stop. If what remains is a single line +that, taken as a whole — surrounding whitespace and one pair of enclosing quotation marks removed, +backslash-escaped spaces read as spaces — is the path of an existing file (it may contain spaces; check with +Read or Glob, not the shell), that file is the problem file; if no such file exists and what remains can only +be a file path — a single line ending in .md, .txt or .tex, or a single token (no spaces once the quotes are +removed) containing "/" or "\" — tell the user in one sentence that no file exists at the absolute path you +looked for (give it) and that the problem can instead be given in full as text after the command, and stop; +otherwise everything that remains, to the end of the message, IS the problem statement, verbatim — mathematics, +line breaks and all ("n=3", "N=pq" and "AB=AC" are mathematics, not settings). The run directory DIR defaults to +./math-proof-solo under the current directory; use DIR's absolute path everywhere below. If the message holds +neither a readable problem file nor any problem text, say so in one sentence — with the usage, +`/math-proof:solo <problem statement, or the path of a file holding it>` — and stop. **Setup.** The run's files are DIR/problem.md (the problem), DIR/notes.md (your notes) and DIR/proof.md (the deliverable). Create DIR with `mkdir -p`. If DIR/notes.md already exists, this problem was already being worked on in DIR: check that DIR/problem.md is the same problem you were given (compare the text, ignoring differences in whitespace and line endings; for a file, `cmp`) — if it differs, say in one sentence that DIR -holds work on a different problem and that DIR=<another directory> selects a fresh one, and stop; if it is the -same, the earlier session ended before it finished, and whatever reasoning it had not written down is lost: -read DIR/notes.md, and DIR/proof.md if it exists, and continue from the last point recorded there rather than -starting over. Otherwise put the problem at DIR/problem.md: if it came as a file, copy that file there byte for -byte with `cp`; if it came as text in the invoking message, Write exactly that text (nothing added, removed or -reworded). Then Read DIR/problem.md in full; it is the authoritative text of the problem. Use the shell for +holds work on a different problem and that `DIR=<another directory>` selects a fresh one, and stop; if it is +the same, read DIR/notes.md, and DIR/proof.md if it exists. If they record the solution as complete (proof.md +written and nothing in the notes still to do), the earlier session finished: say where proof.md is and that +`DIR=<another directory>` starts a fresh attempt, and stop. Otherwise the earlier session ended before it +finished, and whatever reasoning it had not written down is lost: continue from the last point recorded there +rather than starting over. If DIR/notes.md does not exist yet, put the problem at DIR/problem.md: if it came as +a file, copy that file there byte for byte with `cp`; if it came as text in the invoking message, Write +exactly that text (nothing added, removed or reworded). Then Read DIR/problem.md in full; it is the authoritative text of the problem. Use the shell for nothing but that `mkdir`, `cp` and `cmp`. **The task.** Solve the problem stated in DIR/problem.md; the deliverable is DIR/proof.md. After reasoning, |
