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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ slow-unit-*
timeout-*
oom-*
leak-*
bot/pf_sandbox_report.md
.coverage
.coverage.*
17 changes: 17 additions & 0 deletions bot/NIGHT_CLERK.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,23 @@ or the `pf-bot` label on an issue or pull request. Code: [pf_teammate.py](pf_tea
Turn it on with `"teammate": true` under `jobs`; a file named `TEAMMATE_OFF` next to
night_clerk.py stops it before the next item (one already running finishes). Try it without posting: `python pf_teammate.py pr 100` or `python pf_teammate.py issue 36 "how do I show 1/13?"`.

### The sandbox: test the PF bot without GitHub

`python pf_sandbox.py` runs the bot's real code, with the real model and engine, on made-up pull requests and
questions from [pf_sandbox_cases.json](pf_sandbox_cases.json). It never talks to GitHub (no key, no way to post),
and the live bot keeps running. It writes `pf_sandbox_report.md`: for each broken example, whether a fix was tried,
whether it runs, and whether it prints what the contributor meant (the output of the case's `ref` program); for
each question, whether it answered and whether the answer is right. Add a case to the JSON to test a new idea.

"Without GitHub" is not host isolation: the engine (`node cli.js`) runs with your own rights, so point `--clone` only
at a past-forever checkout you trust. For steady scores use a checkout of its own (`--clone path/to/copy`), since
Night Clerk may update its shelf copy mid-run. `--url` picks the model server; the case questions, programs and
engine errors go to it, so keep it on your own machine (the default, LM Studio on localhost).

First run (2026-12-04): 10 broken examples. A fix was tried for 9, ran for 8, and printed what was meant for all 7
with a known intent. One fix ran but changed the meaning (`is prime` became `is odd`), which is why the comment
says "check it says what you meant". Questions: 2 of 4 answered, both right, and it stayed quiet on the rest.

Stale claims are not Night Clerk's job: `.github/workflows/stale-claims.yml` in each repo nudges a claim after
7 days with no pull request and frees it after 10, with fixed text and no AI. Set the repository variable
`STARTER_SHELF_OFF` to `true` to stop it.
153 changes: 153 additions & 0 deletions bot/pf_sandbox.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"""PF bot sandbox: try the Past Forever bot (pf_teammate.py) on made-up pull requests and questions, safely.

It runs the bot's real code with the real local model (LM Studio) and the real engine (node cli.js), but it never
talks to GitHub: each case's files are handed to the bot directly, and it has no GitHub key and no way to post. The
live bot keeps running; this only reads the same model.

For each broken example it reports: did the bot see it was broken, did it offer a fix, does the fix run, and does
the fix print what the contributor meant (the engine output of the case's "ref" program). For each question:
did it answer, and is the answer right. What the bot would have posted goes in a report file.

python pf_sandbox.py every case in pf_sandbox_cases.json
python pf_sandbox.py --only typo_shw one case
python pf_sandbox.py --clone path/to/past-forever --report sandbox_report.md

Needs Node and a copy of connabyss/past-forever (default: shelf_repos/past-forever next to this file).
"""

import argparse
import json
import sys
import urllib.request
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import pf_teammate as t # noqa: E402

FAKE_SHA = "sandbox" + "0" * 33 # shows as `sandbox` in the comment


def want_of(clone, case):
"""The right output: what the engine prints for the case's ref program, or None if there's no ref."""
if not case.get("ref"):
return None
ok, out = t.run_pf(clone, case["ref"])
if not ok:
raise ValueError(f"case {case['name']}: its ref program doesn't run: {out}")
return out


def fake_pr(case):
"""A pull request that adds one example, served without GitHub."""
path = f"examples/{case['name']}.txt"

def gh_get(url, raw=False):
if raw:
return case["broken"]
return [{"filename": path, "status": "added"}] if "page=1" in url else []
return {"number": 0, "head": {"sha": FAKE_SHA}}, gh_get


def try_example(clone, url, case):
want = want_of(clone, case)
ran_ok, broken_out = t.run_pf(clone, case["broken"])
pr, gh_get = fake_pr(case)
seen, calls = {}, []
real_run = t.run_pf

def spy(cl, prog): # the bot runs the sent program first; any later run is a fix it tried, even an unchanged one
got = real_run(cl, prog)
calls.append(prog)
if len(calls) > 1:
seen["fix"], seen["fix_out"], seen["fix_ok"] = prog, got[1], got[0]
return got
t.run_pf = spy
try:
body, why = t.check_pr(clone, url, gh_get, pr)
finally:
t.run_pf = real_run
row = {"name": case["name"], "kind": "example", "broken_runs": ran_ok, "fix_tried": "fix" in seen,
"fix_runs": bool(seen.get("fix_ok")), "fix_shown": bool(body and "A fix that does run" in body),
"fix": seen.get("fix", ""), "fix_out": seen.get("fix_out", ""), "body": body or f"(quiet: {why})"}
# a fix must print what was meant; with no fix tried, the program as sent must already print it
row["right"] = None if want is None else (row["fix_runs"] and seen.get("fix_out") == want) or (
ran_ok and not seen and broken_out == want)
return row


def try_question(clone, url, case):
want = want_of(clone, case)
body, why = t.answer_question(clone, url, "", case["question"], "someone", invited=True)
out = ""
if body:
out = body.split("Past Forever printed:")[1].split("```")[1].strip()
row = {"name": case["name"], "kind": "question", "answered": body is not None, "out": out,
"body": body or f"(quiet: {why})"}
# no ref means the bot should stay quiet; with a ref, an answer must print exactly what the ref prints
row["right"] = (body is None) if want is None else (body is not None and out == want)
return row


def report(rows):
ex = [r for r in rows if r["kind"] == "example"]
qs = [r for r in rows if r["kind"] == "question"]
broken = [r for r in ex if not r["broken_runs"]]
lines = ["# PF bot sandbox report", "",
f"Broken examples: {len(broken)}. Fix tried {sum(r['fix_tried'] for r in broken)}, "
f"fix runs {sum(r['fix_runs'] for r in broken)}, "
f"fix prints what was meant {sum(1 for r in broken if r['right'])} "
f"(of {sum(1 for r in broken if r['right'] is not None)} with a known intent).",
f"Questions: {len(qs)}. Answered {sum(r['answered'] for r in qs)}, right {sum(r['right'] for r in qs)}.",
"", "| case | result |", "|---|---|"]
for r in rows:
if r["kind"] == "example":
res = ("runs as sent" if r["broken_runs"] else
"no fix tried" if not r["fix_tried"] else
"fix doesn't run (not shown)" if not r["fix_runs"] else
"fix runs, prints what was meant" if r["right"] else
"fix runs, intent unknown" if r["right"] is None else "fix runs but prints something else")
else:
res = ("answered, right" if r["answered"] and r["right"] else "answered, WRONG" if r["answered"]
else "quiet (right)" if r["right"] else "quiet")
lines.append(f"| {r['name']} | {res} |")
lines += ["", "## What it would have posted", ""]
for r in rows:
lines += [f"### {r['name']}", "", r["body"].replace(t.MARK, "").strip(), ""]
return "\n".join(lines)


def main(argv=None):
ap = argparse.ArgumentParser(description="Try the PF bot on made-up cases. Posts nothing.")
ap.add_argument("--clone", default=str(HERE / "shelf_repos" / "past-forever"))
ap.add_argument("--cases", default=str(HERE / "pf_sandbox_cases.json"))
ap.add_argument("--report", default=str(HERE / "pf_sandbox_report.md"))
ap.add_argument("--url", default="http://localhost:1234/v1")
ap.add_argument("--only")
args = ap.parse_args(argv)
clone = Path(args.clone)
if not (clone / "cli.js").exists():
raise SystemExit(f"~ no Past Forever copy at {clone} (pass --clone)")
try:
urllib.request.urlopen(args.url + "/models", timeout=5).close()
except OSError:
raise SystemExit("~ LM Studio isn't answering. Start its server first (lms server start).") from None
cases = json.loads(Path(args.cases).read_text(encoding="utf-8"))
rows = []
for c in cases["examples"]:
if not args.only or c["name"] == args.only:
rows.append(try_example(clone, args.url, c))
print(f"{c['name']}: done", flush=True)
for c in cases["questions"]:
if not args.only or c["name"] == args.only:
rows.append(try_question(clone, args.url, c))
print(f"{c['name']}: done", flush=True)
text = report(rows)
Path(args.report).write_text(text, encoding="utf-8")
print("\n".join(text.splitlines()[2:4]))
print(f"Report: {args.report}")
return 0


if __name__ == "__main__":
sys.exit(main())
23 changes: 23 additions & 0 deletions bot/pf_sandbox_cases.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"_about": "Cases for pf_sandbox.py. 'broken' is an example program a contributor might send; 'ref' is what they meant, and its engine output is the right answer (left out when the intent can't be known). A question case has 'question' and 'ref'.",
"examples": [
{"name": "print_for_show", "broken": "x = 1 / 7\nprint x", "ref": "x = 1 / 7\nshow x"},
{"name": "python_while", "broken": "x = 0\nwhile True: x = 3 + 10 * x\nshow x", "ref": "x = 0\nforever: x = 3 + 10 × x\nshow x"},
{"name": "star_star_power", "broken": "x = 5\nforever: x = x ** 2\nshow x", "ref": "x = 5\nforever: x = x ^ 2\nshow x"},
{"name": "percent_for_mod", "broken": "n = 0 total = 0\nrepeat 10:\n n = n + 1\n if n % 2 = 0: total = total + n\nshow total", "ref": "n = 0 total = 0\nrepeat 10:\n n = n + 1\n if n mod 2 = 0: total = total + n\nshow total"},
{"name": "typo_shw", "broken": "x = 2 / 3\nshw 8 digits of x", "ref": "x = 2 / 3\nshow 8 digits of x"},
{"name": "missing_colon", "broken": "x = 6\nforever x = x ^ 5\nshow x", "ref": "x = 6\nforever: x = x ^ 5\nshow x"},
{"name": "made_up_is_prime", "broken": "n = 0 odds = 0\nrepeat 20:\n n = n + 1\n if n is prime: odds = odds + 1\nshow odds"},
{"name": "js_semicolons", "broken": "let x = 0;\nforever: x = 1 + 10 * x;\nshow x;", "ref": "x = 0\nforever: x = 1 + 10 × x\nshow x"},
{"name": "divide_by_two", "broken": "show 1 / 2"},
{"name": "zero_digits", "broken": "show 0 digits of 1 / 7"},
{"name": "already_fine", "broken": "x = 1 / 13\nshow x", "ref": "x = 1 / 13\nshow x"}
],
"questions": [
{"name": "show_1_13", "question": "how do I show 1/13 so a calculator can check it?", "ref": "show 1 / 13"},
{"name": "never_settles", "question": "how do I write a loop that never settles?", "ref": "x = 0\nforever: x = x + 1 / 7\nshow x"},
{"name": "one_third_twice", "question": "what does show 1/3 + 1/3 print?", "ref": "show 1 / 3 + 1 / 3"},
{"name": "repunit", "question": "why is …1111 equal to -1/9? Can you show it?", "ref": "x = 0\nforever: x = 1 + 10 × x\nshow x"},
{"name": "not_a_question", "question": "Can u confirm its still open"}
]
}
100 changes: 100 additions & 0 deletions tests/test_pf_sandbox.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""Tests for the PF bot sandbox (bot/pf_sandbox.py). No network, no model, no Node: all faked."""

import json
import sys
from pathlib import Path

import pytest

BOT = Path(__file__).parent.parent / "bot"
sys.path.insert(0, str(BOT))
import pf_sandbox as sb # noqa: E402
import pf_teammate as t # noqa: E402

GOOD = {"x = 1 / 7\nshow x": "…857142857143 (this is 1/7)", "show 1 / 13": "…923076923077 (this is 1/13)"}


@pytest.fixture
def fake(monkeypatch):
"""A tiny engine: programs in GOOD run and print their line, everything else stops with an error."""
def run_pf(clone, prog):
prog = prog.strip()
return (True, GOOD[prog]) if prog in GOOD else (False, "error: line 1: nope")
monkeypatch.setattr(t, "run_pf", run_pf)
answers = {"model": "x = 1 / 7\nshow x"}
monkeypatch.setattr(t, "ask_model", lambda url, task: answers["model"])

def no_network(*a, **k):
raise AssertionError("the sandbox must never reach the network")
monkeypatch.setattr(t.urllib.request, "urlopen", no_network)
return answers


def test_a_broken_example_with_a_right_fix(fake):
row = sb.try_example(Path("."), "u", {"name": "p", "broken": "x = 1 / 7\nprint x", "ref": "x = 1 / 7\nshow x"})
assert not row["broken_runs"] and row["fix_runs"] and row["fix_shown"] and row["right"] is True
assert "sandbox" in row["body"]


def test_a_fix_that_runs_but_prints_something_else_is_not_right(fake):
fake["model"] = "show 1 / 13"
row = sb.try_example(Path("."), "u", {"name": "p", "broken": "print x", "ref": "x = 1 / 7\nshow x"})
assert row["fix_runs"] and row["right"] is False


def test_a_fix_that_does_not_run_is_never_shown(fake):
fake["model"] = "still broken"
row = sb.try_example(Path("."), "u", {"name": "p", "broken": "print x"})
assert row["fix_tried"] and not row["fix_runs"] and not row["fix_shown"] and row["right"] is None


def test_an_example_that_already_runs_gets_no_fix(fake):
row = sb.try_example(Path("."), "u", {"name": "p", "broken": "show 1 / 13", "ref": "show 1 / 13"})
assert row["broken_runs"] and not row["fix_tried"] and row["right"] is True


def test_an_example_that_runs_but_prints_something_else_is_not_right(fake):
row = sb.try_example(Path("."), "u", {"name": "p", "broken": "show 1 / 13", "ref": "x = 1 / 7\nshow x"})
assert row["broken_runs"] and not row["fix_tried"] and row["right"] is False


def test_a_fix_that_repeats_the_broken_program_still_counts_as_tried(fake):
fake["model"] = "print x"
row = sb.try_example(Path("."), "u", {"name": "p", "broken": "print x", "ref": "x = 1 / 7\nshow x"})
assert row["fix_tried"] and not row["fix_runs"] and row["right"] is False
assert "| p | fix doesn't run (not shown) |" in sb.report([row])


def test_questions_are_scored_against_the_ref(fake):
fake["model"] = "show 1 / 13"
right = sb.try_question(Path("."), "u", {"name": "q", "question": "how do I show 1/13?", "ref": "show 1 / 13"})
fake["model"] = "nope"
quiet = sb.try_question(Path("."), "u", {"name": "q2", "question": "can you confirm it's open"})
assert right["answered"] and right["right"] and right["out"] == GOOD["show 1 / 13"]
assert not quiet["answered"] and quiet["right"]


def test_a_ref_that_does_not_run_is_a_broken_case(fake):
with pytest.raises(ValueError):
sb.try_example(Path("."), "u", {"name": "p", "broken": "print x", "ref": "also broken"})


def test_the_report_counts_and_lists_every_case(fake):
rows = [sb.try_example(Path("."), "u", {"name": "p", "broken": "print x", "ref": "x = 1 / 7\nshow x"}),
sb.try_question(Path("."), "u", {"name": "q", "question": "how do I show 1/7?", "ref": "x = 1 / 7\nshow x"})]
text = sb.report(rows)
assert "Fix tried 1, fix runs 1, fix prints what was meant 1" in text
assert "| p | fix runs, prints what was meant |" in text and "| q | answered, right |" in text
assert t.MARK not in text


def test_the_shipped_cases_are_well_formed():
cases = json.loads((BOT / "pf_sandbox_cases.json").read_text(encoding="utf-8"))
names = [c["name"] for c in cases["examples"] + cases["questions"]]
assert len(names) == len(set(names))
assert all(c.get("broken") for c in cases["examples"]) and all(c.get("question") for c in cases["questions"])


def test_the_sandbox_has_no_way_to_post():
src = (BOT / "pf_sandbox.py").read_text(encoding="utf-8")
assert "night_clerk" not in src and "GitHub(" not in src and "post_or_edit" not in src and "token" not in src.lower()
Loading