diff --git a/.gitea/workflows/review.yml b/.gitea/workflows/review.yml index 2e63f31..687d115 100644 --- a/.gitea/workflows/review.yml +++ b/.gitea/workflows/review.yml @@ -30,6 +30,11 @@ on: type: string required: false default: README.md + review_only: + description: "Newline-separated paths or globs within docs that the drafter may read but not edit" + type: string + required: false + default: "" source_dirs: description: "Newline-separated directories whose new files count toward uncovered" type: string @@ -95,6 +100,7 @@ jobs: INPUT_DOCS: ${{ inputs.docs }} INPUT_GENERATED: ${{ inputs.generated }} INPUT_TOP_LEVEL: ${{ inputs.top_level }} + INPUT_REVIEW_ONLY: ${{ inputs.review_only }} INPUT_SOURCE_DIRS: ${{ inputs.source_dirs }} INPUT_WORKSTREAM: ${{ inputs.workstream }} INPUT_TRACKING_ISSUE: ${{ inputs.tracking_issue }} diff --git a/README.md b/README.md index 5cb2fe2..8a5a56e 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,8 @@ receives the diff (or a list of changed files), the listed documents, the reposi Claude runs with file tools only (read, search, edit), with no shell, and its permission rules confine those tools to its working directory. That directory is a copy of the tree -with no `.git` and no symlinks, and only listed documents are copied back out of it. +with no `.git` and no symlinks, and only listed documents not marked `review_only` are +copied back out of it. Its environment is an allowlist: system basics and its own Claude credential. The Gitea token never reaches it, drafted files are checked for credential values before they are committed, and everything posted to Gitea has credential values replaced with `***`. @@ -108,6 +109,7 @@ The package can also be run by hand: `python3 -m docs_review pr|closed|monthly - | `docs` | required | Newline-separated patterns for the living documents. | | `generated` | none | Patterns for generated files. | | `top_level` | `README.md` | The subset of `docs` the monthly pass re-reads in full. | +| `review_only` | none | Newline-separated patterns for documents in `docs` that the drafter may read but not edit, such as a vision statement in the owner's own words. Stage 1 flags them like any listed document; the drafter reports what is stale in them instead of editing them, and a run that changes one fails like one that changes a file outside `docs`. Each entry must match a `docs` pattern. | | `source_dirs` | `R` and `scripts` | Newline-separated directories whose files count as source. | | `workstream` | `docs` | Scope in draft commit messages, as `docs(): ...`. | | `tracking_issue` | none | Issue number the monthly pass's commit messages cite. | diff --git a/docs_review/draft.py b/docs_review/draft.py index be76d57..06dc8e6 100644 --- a/docs_review/draft.py +++ b/docs_review/draft.py @@ -6,12 +6,15 @@ import json import re from collections.abc import Iterable from dataclasses import dataclass +from pathlib import Path from docs_review.flags import Flag from docs_review.git import Commit from docs_review.inputs import matches_any from docs_review.report import render_sections +PROMPTS = Path(__file__).resolve().parent.parent / "prompts" +MODES = ("pr", "monthly") DIFF_CAP_BYTES = 200_000 LAST_HEAD = "" _LAST_HEAD_RE = re.compile(r"") @@ -31,6 +34,21 @@ GUIDE_NOTE = ( "purpose; write each edit for that reader." ) NO_GUIDE_NOTE = "No guide is set; make the smallest edit and match the surrounding document's voice." +REVIEW_ONLY_NOTE = ( + "\nDocuments you may read but not edit:\n\n{paths}\n\n" + "If one of them is stale, do not edit it; add an entry to the summary's `declined` " + "list, with its path as `flag`, saying what is stale.\n" +) + + +def load_template(mode: str) -> str: + """prompts/task.md with this mode's instructions, prompts/mode-.md, in place + of its {mode_text} field.""" + if mode not in MODES: + raise ValueError(f"unknown mode {mode!r}; expected one of {', '.join(MODES)}") + task = (PROMPTS / "task.md").read_text(encoding="utf-8") + mode_text = (PROMPTS / f"mode-{mode}.md").read_text(encoding="utf-8") + return task.replace("{mode_text}", mode_text, 1) def diff_payload(diff_text: str, numstat: str) -> str: @@ -47,9 +65,13 @@ def diff_payload(diff_text: str, numstat: str) -> str: def build_prompt( template: str, *, mode: str, pr: int | None, flags_json: str, payload: str, docs: tuple[str, ...], top_level: tuple[str, ...], guide_path: str | None, + review_only: tuple[str, ...] = (), ) -> str: - """Fill the template's named fields. Only the template is parsed for braces.""" + """Fill the template's named fields. Only the template is parsed for braces. + `docs` are the documents the drafter may edit; `review_only` the listed documents it + may only read, rendered as their own section or, when there are none, as nothing.""" note = GUIDE_NOTE.format(path=guide_path) if guide_path else NO_GUIDE_NOTE + read_only = REVIEW_ONLY_NOTE.format(paths="\n".join(review_only)) if review_only else "" return template.format_map({ "mode": mode, "pr": "none" if pr is None else pr, @@ -58,6 +80,7 @@ def build_prompt( "docs": "\n".join(docs), "top_level": "\n".join(top_level), "guide_note": note, + "review_only": read_only, }) diff --git a/docs_review/drafter.py b/docs_review/drafter.py index 9127dd6..8ac5050 100644 --- a/docs_review/drafter.py +++ b/docs_review/drafter.py @@ -124,12 +124,16 @@ def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str], def disallowed(change: sandbox.TreeChange, listed: frozenset[str], - patterns: tuple[str, ...], root: Path) -> list[str]: + patterns: tuple[str, ...], root: Path, + review_only: tuple[str, ...] = ()) -> list[str]: """Changed paths the drafter may not touch. A listed document may change or go; a - new file must match a docs pattern; anything written must be a regular file.""" + new file must match a docs pattern; anything written must be a regular file. Nothing + matching a review_only pattern may change, appear or go.""" bad = [] for p in change.paths: ok = p in listed or (p in change.new and matches_any(p, patterns)) + if ok and matches_any(p, review_only): + ok = False if ok and p not in change.deleted and not sandbox.is_regular(root, p): ok = False if not ok: @@ -176,10 +180,11 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path, if not result.ok: return Drafted(result, (), f"drafter failed: {result.error}") change = sandbox.compare(before, sandbox.snapshot(box)) - bad = disallowed(change, listed, inputs.docs, box) + bad = disallowed(change, listed, inputs.docs, box, inputs.review_only) if bad: names = ", ".join(f"`{p}`" for p in bad) - return Drafted(result, (), f"drafter failed: it changed files outside `docs`: {names}") + where = "outside `docs`" + (" or in `review_only`" if inputs.review_only else "") + return Drafted(result, (), f"drafter failed: it changed files {where}: {names}") if leaks_credential(change.new + change.changed, box, env): return Drafted(result, (), CREDENTIAL_NOTE) try: diff --git a/docs_review/inputs.py b/docs_review/inputs.py index 20e19d0..14daa44 100644 --- a/docs_review/inputs.py +++ b/docs_review/inputs.py @@ -25,6 +25,8 @@ class Inputs: tracking_issue: int | None doc_guide: str | None model: str + # Listed documents the drafter may read but not edit; each entry is within docs. + review_only: tuple[str, ...] = () def normalize_drafter(raw: str | None) -> str: @@ -48,6 +50,14 @@ def parse_inputs(env: Mapping[str, str]) -> Inputs: if not docs: raise ValueError("input 'docs' is required: list at least one document pattern") + review_only = _lines(env.get("INPUT_REVIEW_ONLY")) + for entry in review_only: + if not matches_any(entry, docs): + raise ValueError( + f"input 'review_only' entry {entry!r} matches no 'docs' pattern; " + "every review_only entry must also be a listed document" + ) + issue_raw = _text(env, "INPUT_TRACKING_ISSUE") try: tracking_issue = int(issue_raw) if issue_raw else None @@ -64,9 +74,18 @@ def parse_inputs(env: Mapping[str, str]) -> Inputs: tracking_issue=tracking_issue, doc_guide=_text(env, "INPUT_DOC_GUIDE") or None, model=_text(env, "INPUT_MODEL") or DEFAULT_MODEL, + review_only=review_only, ) +def split_review_only( + paths: tuple[str, ...], review_only: tuple[str, ...] +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """The listed documents split into (editable, review-only), each in the given order.""" + read_only = tuple(p for p in paths if matches_any(p, review_only)) + return tuple(p for p in paths if p not in read_only), read_only + + def _glob_files(pattern: str, repo_root: Path) -> list[str]: """Repository-relative POSIX paths of files matching one pattern.""" return [ diff --git a/docs_review/run_monthly.py b/docs_review/run_monthly.py index 05e52bb..687b4af 100644 --- a/docs_review/run_monthly.py +++ b/docs_review/run_monthly.py @@ -8,12 +8,12 @@ from collections.abc import Mapping from pathlib import Path from docs_review import git -from docs_review.draft import build_prompt, parse_summary, render_pr_body +from docs_review.draft import build_prompt, load_template, parse_summary, render_pr_body from docs_review.drafter import draft_in_sandbox from docs_review.flags import Flag, compute_flags, group_uncovered, whole_repo_changes -from docs_review.inputs import Inputs, expand_patterns +from docs_review.inputs import Inputs, expand_patterns, split_review_only from docs_review.report import MONTHLY_MARKER, render_issue, stage1_json -from docs_review.run_pr import TASK_PROMPT, read_guide, read_texts +from docs_review.run_pr import read_guide, read_texts MONTHLY_PREFIX = "docs-review/monthly-" MONTH_PATTERN = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$") @@ -123,9 +123,11 @@ def run_monthly(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path, MERGE_CONFLICT_NOTE.format(branch=reuse["head"]["ref"], base=base)) return 0 flags_json = json.dumps(stage1_json(flags, mode="monthly", head_sha=month)) + editable, read_only = split_review_only(docs, inputs.review_only) prompt = build_prompt( - TASK_PROMPT.read_text(encoding="utf-8"), mode="monthly", pr=None, - flags_json=flags_json, payload=NO_DIFF_PAYLOAD, docs=docs, + load_template("monthly"), mode="monthly", pr=None, + flags_json=flags_json, payload=NO_DIFF_PAYLOAD, docs=editable, + review_only=read_only, top_level=inputs.top_level, guide_path=inputs.doc_guide, ) drafted = draft_in_sandbox(inputs, prompt, cwd, env) diff --git a/docs_review/run_pr.py b/docs_review/run_pr.py index 5a3ce96..19ebb18 100644 --- a/docs_review/run_pr.py +++ b/docs_review/run_pr.py @@ -12,16 +12,15 @@ from pathlib import Path from docs_review import git from docs_review.changes import changed_names, parse_name_status from docs_review.draft import ( - DraftResult, build_prompt, diff_payload, parse_last_head, parse_summary, - render_pr_body, should_skip, + DraftResult, build_prompt, diff_payload, load_template, parse_last_head, + parse_summary, render_pr_body, should_skip, ) from docs_review.drafter import draft_in_sandbox from docs_review.flags import Flag, compute_flags -from docs_review.inputs import Inputs, expand_patterns +from docs_review.inputs import Inputs, expand_patterns, split_review_only from docs_review.report import STAGE1_MARKER, render_clean, render_comment, stage1_json from docs_review.tree import read_in_tree -TASK_PROMPT = Path(__file__).resolve().parent.parent / "prompts" / "task.md" CLOSED_BRANCH_NOTE = ( "docs-review/pr-{n} was closed without merging; delete that branch to get new drafts." ) @@ -210,9 +209,11 @@ def run_pr(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path, args: PrArg MERGE_CONFLICT_NOTE.format(n=args.number), docs_pr=pr_no) return 0 + editable, read_only = split_review_only(docs, inputs.review_only) prompt = build_prompt( - TASK_PROMPT.read_text(encoding="utf-8"), mode="pr", pr=args.number, - flags_json=flags_json, payload=payload, docs=docs, top_level=inputs.top_level, + load_template("pr"), mode="pr", pr=args.number, + flags_json=flags_json, payload=payload, docs=editable, review_only=read_only, + top_level=inputs.top_level, guide_path=inputs.doc_guide, ) drafted = draft_in_sandbox(inputs, prompt, cwd, env) diff --git a/prompts/mode-monthly.md b/prompts/mode-monthly.md new file mode 100644 index 0000000..848789c --- /dev/null +++ b/prompts/mode-monthly.md @@ -0,0 +1,13 @@ +In "monthly" mode there is no pull request. Your main job is to check every enumeration +in these top-level documents against what is actually in the repository: + +{top_level} + +An enumeration is any list of files, scripts, modules, filename prefixes, outputs or +steps, and any stated count. Use Glob to list the files each one describes. Where a list +or count no longer matches, correct it: add what is missing, remove what no longer +exists, fix the number. A list presented as complete must be complete. If a list is +deliberately partial, it should say so; when adding every missing item would make it +unwieldy (more than about 15 new entries), add that phrase instead. + +Then correct anything else in these documents that no longer matches the repository. diff --git a/prompts/mode-pr.md b/prompts/mode-pr.md new file mode 100644 index 0000000..c228c3e --- /dev/null +++ b/prompts/mode-pr.md @@ -0,0 +1 @@ +In "pr" mode, find what this pull request makes stale in the documents listed below. diff --git a/prompts/task.md b/prompts/task.md index 726bc50..cae08ab 100644 --- a/prompts/task.md +++ b/prompts/task.md @@ -1,17 +1,12 @@ You keep a repository's living documents current. Mode: {mode}. Pull request: {pr}. -In "pr" mode, find what this pull request makes stale in the documents listed below. -In "monthly" mode there is no pull request; re-read each of these top-level documents -against the repository as it stands and correct what no longer matches: - -{top_level} - +{mode_text} Documents you may edit: {docs} Edit only the documents listed above. Do not change any other file. - +{review_only} {guide_note} Make the smallest edit that corrects the stale fact, or adds the missing piece where the diff --git a/tests/fake_claude.py b/tests/fake_claude.py index e1d3a21..e280a0a 100755 --- a/tests/fake_claude.py +++ b/tests/fake_claude.py @@ -7,7 +7,8 @@ sentinel (file touched when invoked), env_file (file receiving the env var names cwd_file (file receiving the working directory), argv_file (file receiving argv as JSON), prompt_copy (file receiving the --append-system-prompt-file contents), edit (path to append a line to), write (text to append to `edit` instead), -delete (path to remove), fail (print an error result and exit 1). +delete (path to remove), fail (print an error result and exit 1), stdin_copy (file +receiving the prompt read on stdin). """ import json @@ -15,9 +16,11 @@ import os import sys from pathlib import Path -sys.stdin.read() +prompt = sys.stdin.read() config_path = Path(__file__).resolve().with_name("fake_claude.json") config = json.loads(config_path.read_text()) if config_path.exists() else {} +if config.get("stdin_copy"): + Path(config["stdin_copy"]).write_text(prompt, encoding="utf-8") if config.get("sentinel"): Path(config["sentinel"]).write_text("invoked\n", encoding="utf-8") diff --git a/tests/test_cli.py b/tests/test_cli.py index a1bff1a..42ecca6 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -473,6 +473,58 @@ class SandboxTests(CliCase): self.assertEqual(self.fake.prs, []) +class ReviewOnlyTests(CliCase): + """docs/vision.md is a listed document the drafter may read but not edit.""" + + def setUp(self): + super().setUp() + git(self.seed, "checkout", "-q", "main") + self.write(self.seed, "docs/vision.md", "Where `R/a.R` is going.\n") + git(self.seed, "add", ".") + git(self.seed, "commit", "-q", "-m", "vision") + git(self.seed, "push", "-q", "origin", "main") + git(self.seed, "checkout", "-q", "feat") + git(self.seed, "merge", "-q", "--ff-only", "main") + git(self.seed, "push", "-q", "origin", "feat") + self.env["INPUT_REVIEW_ONLY"] = "docs/vision.md" + self.prompt_file = Path(self._tmp.name) / "drafter-prompt" + + def test_prompt_lists_it_as_read_only(self): + self.claude(stdin_copy=str(self.prompt_file)) + self.assertEqual(self.run_pr(self.feature_commit()), 0) + prompt = self.prompt_file.read_text() + editable = prompt.split("Documents you may edit:")[1].split("Edit only")[0] + self.assertIn("docs/README.md", editable) + self.assertNotIn("docs/vision.md", editable) + self.assertIn("Documents you may read but not edit:\n\ndocs/vision.md", prompt) + + def test_it_is_still_flagged_in_stage1(self): + self.claude() + self.assertEqual(self.run_pr(self.feature_commit()), 0) + self.assertIn("docs/vision.md", self.comment_bodies()[0]) + + def test_editing_it_fails_and_commits_nothing(self): + self.claude(edit="docs/vision.md") + self.assertEqual(self.run_pr(self.feature_commit()), 1) + self.assertTrue(any("docs/vision.md" in b for b in self.comment_bodies())) + self.assertNotIn(BRANCH, " ".join(self.remote_branches())) + self.assertEqual(git(self.work, "status", "--porcelain"), "") + self.assertEqual(self.fake.prs, []) + + def test_deleting_it_fails(self): + self.claude(delete="docs/vision.md") + self.assertEqual(self.run_pr(self.feature_commit()), 1) + self.assertTrue((self.work / "docs" / "vision.md").exists()) + self.assertEqual(self.fake.prs, []) + + def test_new_file_matching_a_review_only_glob_is_refused(self): + self.env["INPUT_REVIEW_ONLY"] = "docs/v*.md" + self.claude(edit="docs/vnew.md") + self.assertEqual(self.run_pr(self.feature_commit()), 1) + self.assertFalse((self.work / "docs" / "vnew.md").exists()) + self.assertEqual(self.fake.prs, []) + + class SystemPromptTests(CliCase): def setUp(self): super().setUp() diff --git a/tests/test_cli_monthly.py b/tests/test_cli_monthly.py index 322c653..0e49038 100644 --- a/tests/test_cli_monthly.py +++ b/tests/test_cli_monthly.py @@ -153,6 +153,14 @@ class ClaudeMonthlyTests(MonthlyCase): self.assertIn("R/a.R", self.fake.issues[0]["body"]) self.assertEqual(git(self.work, "status", "--porcelain"), "") + def test_review_only_doc_edit_fails_and_commits_nothing(self): + self.claude(edit="docs/README.md") + self.assertEqual(self.run_monthly("2026-12", INPUT_REVIEW_ONLY="docs/README.md"), 1) + self.assertEqual(self.fake.prs, []) + self.assertNotIn("monthly", " ".join(self.remote_branches())) + self.assertIn("docs/README.md", self.fake.issues[0]["body"]) + self.assertEqual(git(self.work, "status", "--porcelain"), "") + def test_delivered_pr_closes_the_open_monthly_issue(self): self.claude(fail=True) self.assertEqual(self.run_monthly("2026-11"), 1) diff --git a/tests/test_draft.py b/tests/test_draft.py index 571b790..3fdf7bd 100644 --- a/tests/test_draft.py +++ b/tests/test_draft.py @@ -9,6 +9,7 @@ from docs_review.draft import ( build_prompt, claude_argv, diff_payload, + load_template, outside_docs, parse_claude_output, parse_last_head, @@ -59,14 +60,55 @@ class PromptTest(unittest.TestCase): self.assertIn("monthly|none|", out) def test_shipped_template_renders(self): - from pathlib import Path - t = Path(__file__).resolve().parent.parent / "prompts" / "task.md" - out = build_prompt(t.read_text(), mode="pr", pr=7, flags_json="{}", payload="{x}", + out = build_prompt(load_template("pr"), mode="pr", pr=7, flags_json="{}", payload="{x}", docs=("a.md",), top_level=("README.md",), guide_path=None) self.assertIn("```json", out) self.assertIn("{x}", out) self.assertNotIn("{mode}", out) + def test_review_only_section(self): + t = "{docs}|{review_only}" + none = build_prompt(t, mode="pr", pr=1, flags_json="{}", payload="", + docs=("a.md",), top_level=(), guide_path=None) + self.assertEqual(none, "a.md|") + out = build_prompt(t, mode="pr", pr=1, flags_json="{}", payload="", + docs=("a.md",), top_level=(), guide_path=None, + review_only=("v.md", "w.md")) + self.assertIn("Documents you may read but not edit:\n\nv.md\nw.md", out) + self.assertIn("declined", out) + + +class TemplateModeTest(unittest.TestCase): + def _render(self, mode, review_only=()): + return build_prompt(load_template(mode), mode=mode, pr=None if mode == "monthly" else 7, + flags_json="{}", payload="p", docs=("README.md", "docs/a.md"), + top_level=("README.md",), guide_path=None, + review_only=review_only) + + def test_monthly_asks_for_enumeration_check_and_lists_review_only(self): + out = self._render("monthly", ("docs/vision.md",)) + self.assertIn("check every enumeration", out) + self.assertIn("Glob", out) + self.assertIn("A list presented as complete must be complete", out) + self.assertIn("Documents you may read but not edit:\n\ndocs/vision.md", out) + self.assertIn("README.md", out) + for field in ("{top_level}", "{mode_text}", "{review_only}", "{docs}"): + self.assertNotIn(field, out) + + def test_pr_has_no_enumeration_check(self): + out = self._render("pr", ("docs/vision.md",)) + self.assertNotIn("enumeration", out) + self.assertIn("find what this pull request makes stale", out) + self.assertIn("Documents you may read but not edit:\n\ndocs/vision.md", out) + + def test_review_only_section_absent_when_empty(self): + for mode in ("pr", "monthly"): + self.assertNotIn("read but not edit", self._render(mode)) + + def test_unknown_mode_raises(self): + with self.assertRaises(ValueError): + load_template("weekly") + class ArgvTest(unittest.TestCase): def test_argv_matches_spec(self): diff --git a/tests/test_inputs.py b/tests/test_inputs.py index 4ef9052..7adffc4 100644 --- a/tests/test_inputs.py +++ b/tests/test_inputs.py @@ -6,6 +6,7 @@ from docs_review.inputs import ( matches_any, normalize_drafter, parse_inputs, + split_review_only, unmatched_patterns, ) from tests.helpers import tmp_tree @@ -64,6 +65,27 @@ class ParseInputsTest(unittest.TestCase): self.assertIsNone(i.tracking_issue) self.assertIsNone(i.doc_guide) + def test_review_only_defaults_to_empty(self): + self.assertEqual(parse_inputs({"INPUT_DOCS": "a.md"}).review_only, ()) + + def test_review_only_entries_within_docs(self): + i = parse_inputs({"INPUT_DOCS": "README.md\ndocs/*.md\npm/**/*.md", + "INPUT_REVIEW_ONLY": " docs/vision.md \n\nREADME.md\npm/v*.md\n"}) + self.assertEqual(i.review_only, ("docs/vision.md", "README.md", "pm/v*.md")) + + def test_review_only_entry_outside_docs_raises(self): + for entry in ("other/vision.md", "docs/sub/vision.md", "*.md"): + with self.assertRaisesRegex(ValueError, f"review_only.*{entry.replace('*', '[*]')}"): + parse_inputs({"INPUT_DOCS": "README.md\ndocs/*.md", + "INPUT_REVIEW_ONLY": f"docs/a.md\n{entry}"}) + + def test_split_review_only(self): + editable, read_only = split_review_only( + ("README.md", "docs/a.md", "docs/vision.md"), ("docs/v*.md",)) + self.assertEqual(editable, ("README.md", "docs/a.md")) + self.assertEqual(read_only, ("docs/vision.md",)) + self.assertEqual(split_review_only(("a.md",), ()), (("a.md",), ())) + def test_non_integer_tracking_issue_raises(self): with self.assertRaisesRegex(ValueError, "tracking_issue"): parse_inputs({"INPUT_DOCS": "a.md", "INPUT_TRACKING_ISSUE": "abc"})