From 3855b54730d8761bef3586436489eb731e1fda23 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 18 Nov 2026 08:55:20 +0000 Subject: [PATCH] feat(questions): a ruling inbox kind for the readiness pass (M3.3 slice 1) kind: ruling carries a required gate: (kebab slug) and an optional issue:. add_text skips a ruling while one on the same task and gate is Open or Deferred, whatever its shift; the (shift, task, issue) repeat rule now applies to questions only. answer() writes 'ruling , shift X' on the prompt; show() names the gate. lifecycle check validates gate and flags two open rulings on one task and gate. Header documents the kind. Part of PyAutoLabs/PyAutoBrain#671 Co-Authored-By: Claude Opus 5.5 --- questions.md | 6 +- scripts/lifecycle.py | 46 +++++++++++-- scripts/questions_edit.py | 85 ++++++++++++++++++----- tests/test_questions_edit.py | 130 +++++++++++++++++++++++++++++++++++ 4 files changed, 243 insertions(+), 24 deletions(-) diff --git a/questions.md b/questions.md index 04ed75d87..1528e651f 100644 --- a/questions.md +++ b/questions.md @@ -6,13 +6,17 @@ a `/questions` chat (PyAutoBrain `skills/questions`) answers, defers or drops them with `scripts/questions_edit.py`. Never edit by hand: the section an entry sits under is its state, and `lifecycle.py check` validates the file. An answer releases the parked task: the next shift resumes it with the answer -in its prompt. +in its prompt. Kind `ruling` is filed by the readiness pass (PyAutoBrain +`batch ready`, M3.3) for a gate on a queued task: it carries `gate:`, may have +no `issue:`, never holds or releases a parked task, and answering it records +the ruling on the prompt. ```markdown ### Q. — - task: draft///.md - issue: https://github.com///issues/ - kind: question +- gate: (kind ruling only; a ruling may have no issue:) - ask: - options: (a) · (b) - shift: diff --git a/scripts/lifecycle.py b/scripts/lifecycle.py index 51e298612..a75f4d975 100644 --- a/scripts/lifecycle.py +++ b/scripts/lifecycle.py @@ -3064,7 +3064,28 @@ def goals_findings(root: Path) -> "tuple[list[Finding], list[Finding]]": QUESTION_HEAD_RE = re.compile(r"^###\s+Q(\d+)\.\s+(.+?)\s*$") QUESTION_FIELD_RE = re.compile(r"^-\s+([a-z][a-z-]*):[ \t]*(.*?)\s*$") QUESTION_REQUIRED = ("task", "issue", "kind", "ask", "shift", "asked", "worker") -QUESTION_KINDS = ("question", "blocked") +QUESTION_KINDS = ("question", "blocked", "ruling") +#: A `ruling` (filed by PyAutoBrain's readiness pass, `batch ready`, M3.3) names +#: the gate it found on a queued task in `gate:` and may have no `issue:`. +QUESTION_RULING = "ruling" +QUESTION_GATE_RE = re.compile(r"^[a-z][a-z0-9-]*$") + + +def question_required(kind: "str | None") -> "tuple[str, ...]": + """The keys an entry of `kind` must carry: a ruling needs `gate:`, not `issue:`.""" + if kind == QUESTION_RULING: + return tuple(k for k in QUESTION_REQUIRED if k != "issue") + ("gate",) + return QUESTION_REQUIRED + + +def question_gate_errors(kind: "str | None", gate) -> "list[str]": + """What is wrong with an entry's `gate:` given its kind (missing is left + to the required-key check).""" + if kind == QUESTION_RULING: + if gate and not QUESTION_GATE_RE.match(str(gate)): + return [f"gate `{gate}` is not a kebab-case slug ([a-z][a-z0-9-]*)"] + return [] + return ["gate: is for kind ruling only"] if gate else [] #: The keys each later state adds (and `reopen` strips). QUESTION_STATE_KEYS = ("until", "deferred", "answered", "answer", "answer-comment", "dropped") @@ -3145,21 +3166,34 @@ def questions_findings(root: Path) -> "list[Finding]": out = [Finding(f"questions.md: {e}", at) for e in errors] seen: "dict[str, int]" = {} triples: "dict[tuple, str]" = {} + rulings: "dict[tuple, str]" = {} for e in entries: qid, f = e["id"], e["fields"] seen[qid] = seen.get(qid, 0) + 1 if seen[qid] == 2: out.append(Finding(f"questions.md: {qid} is used twice — ids are unique", at)) - missing = [k for k in QUESTION_REQUIRED + QUESTION_STATE_REQUIRED.get(e["state"], ()) - if not f.get(k)] + kind = f.get("kind") + missing = [k for k in question_required(kind) + + QUESTION_STATE_REQUIRED.get(e["state"], ()) if not f.get(k)] if missing: out.append(Finding(f"questions.md: {qid} has no {', '.join(k + ':' for k in missing)}", at)) - if f.get("kind") and f["kind"] not in QUESTION_KINDS: - out.append(Finding(f"questions.md: {qid} has kind `{f['kind']}` — one of " + if kind and kind not in QUESTION_KINDS: + out.append(Finding(f"questions.md: {qid} has kind `{kind}` — one of " f"{' | '.join(QUESTION_KINDS)}", at)) + for err in question_gate_errors(kind, f.get("gate")): + out.append(Finding(f"questions.md: {qid} {err}", at)) + if kind == QUESTION_RULING and f.get("gate") and f.get("task") \ + and e["state"] in ("open", "deferred"): + pair = (Path(f["task"]).name, f["gate"]) + if pair in rulings: + out.append(Finding(f"questions.md: {qid} repeats {rulings[pair]} (an open " + f"ruling on the same task and gate `{f['gate']}`) — " + "keep one", at)) + rulings.setdefault(pair, qid) + # Rulings are unique by (task, gate) below, not by this triple. triple = (f.get("shift"), f.get("task"), f.get("issue")) - if all(triple): + if kind != QUESTION_RULING and all(triple): if triple in triples: out.append(Finding(f"questions.md: {qid} repeats {triples[triple]} (same " "shift, task and issue) — keep one", at)) diff --git a/scripts/questions_edit.py b/scripts/questions_edit.py index 51597067b..52e929227 100644 --- a/scripts/questions_edit.py +++ b/scripts/questions_edit.py @@ -13,6 +13,9 @@ python3 scripts/questions_edit.py add --task PATH --issue URL --kind question|blocked --ask TEXT [--option TEXT]... --shift S --asked T --worker K + python3 scripts/questions_edit.py add --task PATH [--issue URL] --kind ruling + --gate SLUG --ask TEXT [--option TEXT]... + --shift S --asked T --worker K python3 scripts/questions_edit.py answer Q --text TEXT [--comment URL] [--by LOGIN] [--via chat|issue] python3 scripts/questions_edit.py defer Q [--until YYYY-MM-DD] [--by LOGIN] @@ -22,7 +25,10 @@ The section an entry sits under is its state: Open, Deferred, Answered, Dropped. Ids are global and increasing (the file's highest plus 1, worked out in the tree being written), and `(shift, task, issue)` is unique: an add -whose triple exists is a silent repeat. `answer` also appends the answer to +whose triple exists is a silent repeat. A `ruling` (PyAutoBrain's readiness +pass, `batch ready`, M3.3, filing a gate it found on a queued task) carries +`gate:` and may have no `issue:`; while one on the same task and gate is Open +or Deferred, another add of it is a silent repeat, whatever the shift. `answer` also appends the answer to the task's prompt under `## Answers from the human` (wherever the prompt is now, `draft/` or `active/`) — the next worker reads it there — and prints `prompt: ` so the caller commits that path too. A write that would add a @@ -57,13 +63,17 @@ them with `scripts/questions_edit.py`. Never edit by hand: the section an entry sits under is its state, and `lifecycle.py check` validates the file. An answer releases the parked task: the next shift resumes it with the answer -in its prompt. +in its prompt. Kind `ruling` is filed by the readiness pass (PyAutoBrain +`batch ready`, M3.3) for a gate on a queued task: it carries `gate:`, may have +no `issue:`, never holds or releases a parked task, and answering it records +the ruling on the prompt. ```markdown ### Q. — - task: draft///.md - issue: https://github.com///issues/ - kind: question +- gate: (kind ruling only; a ruling may have no issue:) - ask: - options: (a) · (b) - shift: @@ -124,6 +134,17 @@ def _find(text: str, who: str) -> dict: return e +def is_ruling(fields: dict) -> bool: + return (fields or {}).get("kind") == lifecycle.QUESTION_RULING + + +def subject(fields: dict) -> str: + """`ruling ` for a ruling; the issue's short form otherwise.""" + if is_ruling(fields): + return f"ruling {fields.get('gate') or '?'}" + return issue_short(fields.get("issue", "")) + + def issue_short(url: str) -> str: """`autolens_workspace#670` for an issue URL; the URL itself otherwise.""" m = ISSUE_RE.match(url or "") @@ -164,10 +185,17 @@ def entry_errors(entry: dict) -> "list[str]": """What is wrong with an add's entry; empty when it may be added.""" if not isinstance(entry, dict): return ["the entry is not an object"] - errs = [f"{k} is missing" for k in lifecycle.QUESTION_REQUIRED + kind = entry.get("kind") + errs = [f"{k} is missing" for k in lifecycle.question_required(kind) if not isinstance(entry.get(k), str) or not _one_line(entry.get(k))] - if entry.get("kind") and entry.get("kind") not in lifecycle.QUESTION_KINDS: + if kind and kind not in lifecycle.QUESTION_KINDS: errs.append(f"kind must be one of {' | '.join(lifecycle.QUESTION_KINDS)}") + for k in ("issue", "gate"): + if entry.get(k) is not None and not isinstance(entry.get(k), str): + errs.append(f"{k} must be a string") + gate = entry.get("gate") + errs += lifecycle.question_gate_errors( + kind, _one_line(gate) if isinstance(gate, str) else None) task = entry.get("task") if isinstance(task, str) and task and (not task.startswith(("draft/", "active/")) or ".." in Path(task).parts): @@ -181,9 +209,13 @@ def entry_errors(entry: dict) -> "list[str]": def add_text(text: str, entry: dict, root: "Path | None" = None) -> "tuple[str, str, bool]": """(`questions.md` with `entry` added at the end of `## Open`, its id, whether it was added). An entry whose `(shift, task, issue)` is already - in the file is a silent repeat: (text unchanged, that id, False). + in the file is a silent repeat: (text unchanged, that id, False). A + ruling repeats an Open or Deferred ruling on the same task and gate, + whatever its shift; once that one is Answered or Dropped it may be filed + again. - `entry`: {task, issue, kind, ask, options: [..], shift, asked, worker}. + `entry`: {task, issue, kind, ask, options: [..], shift, asked, worker}, + plus `gate` for kind ruling (whose `issue` is optional). With `root` (the tree being written), `task` is resolved to where the prompt is now and refused when it is in neither `draft/` nor `active/`.""" errs = entry_errors(entry) @@ -197,17 +229,27 @@ def add_text(text: str, entry: dict, root: "Path | None" = None) -> "tuple[str, task = now text = text if text.strip() else TEMPLATE entries = parse(text) - issue, shift = _one_line(entry["issue"]), _one_line(entry["shift"]) + issue, shift = _one_line(entry.get("issue")), _one_line(entry["shift"]) + kind, gate = entry["kind"], _one_line(entry.get("gate")) for e in entries: f = e["fields"] - if (f.get("shift"), Path(f.get("task", "")).name, f.get("issue")) == \ - (shift, Path(task).name, issue): + same_task = Path(f.get("task", "")).name == Path(task).name + if kind == lifecycle.QUESTION_RULING: + if is_ruling(f) and same_task and f.get("gate") == gate \ + and e["state"] in ("open", "deferred"): + return text, e["id"], False + elif issue and not is_ruling(f) and same_task \ + and (f.get("shift"), f.get("issue")) == (shift, issue): return text, e["id"], False n = max([e["n"] for e in entries] or [0]) + 1 ask = _clip(entry["ask"], ASK_MAX) - block = [f"### Q{n}. {Path(task).stem} — {_clip(ask, SHORT_MAX)}", - f"- task: {task}", f"- issue: {issue}", f"- kind: {entry['kind']}", - f"- ask: {ask}"] + block = [f"### Q{n}. {Path(task).stem} — {_clip(ask, SHORT_MAX)}", f"- task: {task}"] + if issue: + block.append(f"- issue: {issue}") + block.append(f"- kind: {kind}") + if kind == lifecycle.QUESTION_RULING: + block.append(f"- gate: {gate}") + block.append(f"- ask: {ask}") options = _labelled(entry.get("options")) if options: block.append(f"- options: {options}") @@ -247,6 +289,8 @@ def add(root: Path, entry: dict) -> str: old = _read(root) new, qid, added = add_text(old, entry, root) if not added: + if entry.get("kind") == lifecycle.QUESTION_RULING: + return f"{qid} already holds this ruling (same task and gate, still open) — no change" return f"{qid} already holds this question (same shift, task and issue) — no change" _write(root, [(FILE, old if (root / FILE).exists() else None, new)]) return f"added {qid}" @@ -293,8 +337,12 @@ def answer(root: Path, who: str, text: str, comment: str = "", by: str = "", writes = [(FILE, old, new)] prompt = task_now(root, f.get("task", "")) if prompt is not None: - line = (f"- {e['id']} ({day or _today()}, shift {f.get('shift', '?')} question on " - f"{issue_short(f.get('issue', ''))}): {said}" + (f" {comment}" if comment else "")) + if is_ruling(f): + what = f"{subject(f)}, shift {f.get('shift', '?')}" + else: + what = f"shift {f.get('shift', '?')} question on {subject(f)}" + line = (f"- {e['id']} ({day or _today()}, {what}): {said}" + + (f" {comment}" if comment else "")) ptext = (root / prompt).read_text(encoding="utf-8") writes.append((prompt, ptext, append_answer(ptext, line))) _write(root, writes) @@ -378,7 +426,7 @@ def show(root: Path, which: str = "", who: str = "", today: str = "") -> "list[s out = [] for e in picked: f = e["fields"] - out.append(f"{e['id']} [{e['state']}] {e['title']} — {issue_short(f.get('issue', ''))}" + out.append(f"{e['id']} [{e['state']}] {e['title']} — {subject(f)}" + (f" (until {f['until']})" if f.get("until") else "")) counts = {s.lower(): sum(e["state"] == s.lower() for e in entries) for s in lifecycle.QUESTION_SECTIONS} @@ -397,8 +445,10 @@ def main(argv=None) -> int: s.add_argument("qid", nargs="?", default="") s.add_argument("--today", default="", help=argparse.SUPPRESS) a = sub.add_parser("add") - for k in ("task", "issue", "kind", "ask", "shift", "asked", "worker"): + for k in ("task", "kind", "ask", "shift", "asked", "worker"): a.add_argument(f"--{k}", required=True) + a.add_argument("--issue", default=None, help="required unless --kind ruling") + a.add_argument("--gate", default=None, help="kind ruling only: the gate's slug") a.add_argument("--option", action="append", default=[]) r = sub.add_parser("answer") r.add_argument("qid") @@ -429,7 +479,8 @@ def main(argv=None) -> int: return 0 if args.verb == "add": entry = {k: getattr(args, k) for k in - ("task", "issue", "kind", "ask", "shift", "asked", "worker")} + ("task", "issue", "kind", "ask", "shift", "asked", "worker", "gate") + if getattr(args, k) is not None} entry["options"] = list(args.option) print(f"questions.md: {add(root, entry)}") elif args.verb == "answer": diff --git a/tests/test_questions_edit.py b/tests/test_questions_edit.py index c4db3db43..6a7ff58ff 100644 --- a/tests/test_questions_edit.py +++ b/tests/test_questions_edit.py @@ -385,3 +385,133 @@ def test_close_moves_the_tasks_open_questions_to_answered(tmp_path, monkeypatch) [e] = qe.parse((root / "questions.md").read_text()) assert e["state"] == "answered" and e["fields"]["answer"] == "(task completed)" assert lifecycle.questions_findings(root) == [] + + +# --- kind ruling (the readiness pass, PyAutoBrain#671, M3.3) ---------------------- + +def _ruling(task="draft/feature/flywheel/sprocket_calibration.md", gate="claimed", + shift="2026-11-18-am", **kw): + e = {"task": task, "kind": "ruling", "gate": gate, + "ask": "PyAutoMind is claimed by another task. Run this one anyway?", + "options": ["override", "wait"], "shift": shift, + "asked": "2026-11-18T08:00Z", "worker": "ready"} + e.update(kw) + return e + + +def test_add_a_ruling_without_an_issue(mind): + text, qid, added = qe.add_text(qe.TEMPLATE, _ruling(), mind) + assert (qid, added) == ("Q1", True) + assert ("### Q1. sprocket_calibration — PyAutoMind is claimed by another task. Run this " + "one anyway?\n- task: draft/feature/flywheel/sprocket_calibration.md\n" + "- kind: ruling\n- gate: claimed\n" + "- ask: PyAutoMind is claimed by another task. Run this one anyway?\n" + "- options: (a) override · (b) wait\n- shift: 2026-11-18-am\n" + "- asked: 2026-11-18T08:00Z\n- worker: ready\n") in text + assert "- issue:" not in text[text.index("## Open"):] + (mind / "questions.md").write_text(text) + assert lifecycle.questions_findings(mind) == [] + assert qe.show(mind)[0].endswith("— ruling claimed") + # The CLI takes --gate and no --issue. + (mind / "questions.md").write_text(qe.TEMPLATE) + e = _ruling(gate="no-next-phase") + res = _run(mind, "add", "--task", e["task"], "--kind", "ruling", "--gate", e["gate"], + "--ask", e["ask"], "--shift", e["shift"], "--asked", e["asked"], + "--worker", e["worker"]) + assert res.returncode == 0 and "added Q1" in res.stdout, res.stderr + res = _run(mind, "add", "--task", e["task"], "--kind", "ruling", "--gate", e["gate"], + "--ask", e["ask"], "--shift", "2026-11-18-pm", "--asked", e["asked"], + "--worker", e["worker"]) + assert res.returncode == 0 and "Q1 already holds this ruling" in res.stdout + _check(mind) + + +def test_a_ruling_needs_a_well_formed_gate_and_a_question_takes_none(): + with pytest.raises(qe.Refused, match="gate is missing"): + qe.add_text(qe.TEMPLATE, _ruling(gate="")) + with pytest.raises(qe.Refused, match="not a kebab-case slug"): + qe.add_text(qe.TEMPLATE, _ruling(gate="Claimed_By")) + with pytest.raises(qe.Refused, match="gate: is for kind ruling only"): + qe.add_text(qe.TEMPLATE, _entry(gate="claimed")) + with pytest.raises(qe.Refused, match="issue is missing"): + qe.add_text(qe.TEMPLATE, _entry(issue=None)) + # A ruling may still carry an issue. + text, _q, _a = qe.add_text(qe.TEMPLATE, _ruling(issue=ISSUE)) + assert f"- issue: {ISSUE}\n- kind: ruling\n- gate: claimed\n" in text + + +def test_a_ruling_dedupes_by_task_and_gate_across_shifts_while_open_or_deferred(): + text, qid, _ = qe.add_text(qe.TEMPLATE, _ruling()) + # Another shift, the same task (by prompt name: claimed since) and gate: repeat. + again, q, added = qe.add_text(text, _ruling(task="active/sprocket_calibration.md", + shift="2026-11-19-am")) + assert (again, q, added) == (text, "Q1", False) + # A different gate, or a different task, is a new ruling. + text, q, added = qe.add_text(text, _ruling(gate="no-next-phase")) + assert (q, added) == ("Q2", True) + text, q, added = qe.add_text(text, _ruling(task="draft/feature/flywheel/gearbox_rattle.md")) + assert (q, added) == ("Q3", True) + # Deferred still blocks a re-file. + text = lifecycle.question_move_text(text, "Q1", "deferred", {"deferred": "d by h"}) + assert qe.add_text(text, _ruling(shift="2026-11-20-am"))[1:] == ("Q1", False) + # Answered (or Dropped), it may be filed again. + text = lifecycle.question_move_text(text, "Q1", "answered", + {"answered": "t by h (chat)", "answer": "wait"}) + text, q, added = qe.add_text(text, _ruling(shift="2026-11-20-am")) + assert (q, added) == ("Q4", True) + text = lifecycle.question_move_text(text, "Q4", "dropped", {"dropped": "d by h — no"}) + assert qe.add_text(text, _ruling(shift="2026-11-21-am"))[1:] == ("Q5", True) + + +def test_answering_a_ruling_records_it_on_the_prompt(mind): + text, _q, _a = qe.add_text(qe.TEMPLATE, _ruling(), mind) + (mind / "questions.md").write_text(text) + msg, prompt = qe.answer(mind, "Q1", "override: run it in its own worktree", by="h", + day="2026-11-18", at="2026-11-18T09:00Z") + assert prompt == "draft/feature/flywheel/sprocket_calibration.md" + body = (mind / prompt).read_text() + assert body.endswith("## Answers from the human\n- Q1 (2026-11-18, ruling claimed, shift " + "2026-11-18-am): override: run it in its own worktree\n") + assert _states(mind) == {"Q1": "answered"} + assert qe.show(mind, "all")[0] == ("Q1 [answered] sprocket_calibration — PyAutoMind is " + "claimed by another task. Run this one anyway? — " + "ruling claimed") + _check(mind) + + +def test_check_reports_a_ruling_without_gate_a_stray_gate_and_duplicate_open_rulings(mind): + good, _q, _a = qe.add_text(qe.TEMPLATE, _ruling()) + assert _findings(mind, good) == [] + assert any("Q1 has no gate:" in m + for m in _findings(mind, good.replace("- gate: claimed\n", ""))) + assert any("not a kebab-case slug" in m + for m in _findings(mind, good.replace("gate: claimed", "gate: Claimed"))) + question, _q, _a = qe.add_text(qe.TEMPLATE, _entry()) + assert any("Q1 gate: is for kind ruling only" in m for m in _findings( + mind, question.replace("- kind: question\n", "- kind: question\n- gate: claimed\n"))) + assert any("Q1 has no issue:" in m + for m in _findings(mind, question.replace(f"- issue: {ISSUE}\n", ""))) + block = good[good.index("### Q1"):good.index("## Deferred")] + dup = good.replace("## Deferred", block.replace("### Q1.", "### Q2.") + .replace("draft/feature/flywheel/", "active/") + .replace("2026-11-18-am", "2026-11-19-am") + "## Deferred") + assert any("Q2 repeats Q1 (an open ruling on the same task and gate `claimed`)" in m + for m in _findings(mind, dup)) + settled = lifecycle.question_move_text(dup, "Q1", "answered", + {"answered": "t by h (chat)", "answer": "x"}) + assert not any("repeats" in m for m in _findings(mind, settled)) + + +def test_rulings_and_questions_sharing_an_issue_are_not_triple_repeats(mind): + """Two gates on one task, shift and issue, and a question plus a ruling on + one issue, all add and leave `lifecycle.py check` clean.""" + text, q1, a1 = qe.add_text(qe.TEMPLATE, _ruling(issue=ISSUE, shift="2026-11-14-pm2"), mind) + text, q2, a2 = qe.add_text(text, _ruling(issue=ISSUE, shift="2026-11-14-pm2", + gate="unattended"), mind) + text, q3, a3 = qe.add_text(text, _entry(), mind) # a question, same shift/task/issue + assert (q1, a1, q2, a2, q3, a3) == ("Q1", True, "Q2", True, "Q3", True) + assert _findings(mind, text) == [] + # Replays stay silent repeats of their own kind. + assert qe.add_text(text, _entry(), mind)[1:] == ("Q3", False) + assert qe.add_text(text, _ruling(issue=ISSUE, gate="unattended"), mind)[1:] == ("Q2", False) + _check(mind)