Skip to content
Open
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
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,35 @@ if result.get("isError"):

Calls under `client.fixes` never retry. Results retain untrusted-text wrappers, availability, assessment gaps, and `isError`. `PENDING` and `NOT_VERIFIED` do not establish a fix, and a tool request never records a human disposition.

## Reviewer guidance for coding agents

A repository's reviewer guidance is the set of rules Proofline checks its pull requests against. Coding agents such as Codex, Claude Code and Cursor read `AGENTS.md` or `CLAUDE.md` before they write code but never see that guidance, so they break rules the reviewer then flags. `proofline.guidance` copies the guidance into those files, so an agent writes code to the same rules before a pull request exists. It helps teams that let agents open pull requests, and reviewers who would otherwise flag the same rule on every agent's change.

The token needs `guidance:read`. The command fetches the guidance once and syncs each file:

```sh
export PROOFLINE_ORGANIZATION_ID=... PROOFLINE_REPOSITORY_ID=...
python -m proofline.guidance AGENTS.md CLAUDE.md
```

Each file gets one managed block between `<!-- proofline:review-guidance:start -->` and `<!-- proofline:review-guidance:end -->`, appended after a blank line the first time and replaced in place afterwards. Everything outside the block is left as it is, the file keeps its line endings, and a `CLAUDE.md` symlinked to `AGENTS.md` stays a symlink. When no guidance is set, the block is removed and a missing file is not created. A lone, repeated or out-of-order marker, or guidance that contains a marker, is refused before any file changes.

In CI, `--check` writes nothing, prints a unified diff and exits 1 when a file is stale:

```sh
python -m proofline.guidance --check AGENTS.md CLAUDE.md
```

From Python, `apply_review_guidance(text, guidance)` returns the updated text and `write_review_guidance(path, guidance, check=False)` syncs one file and returns whether it changed. Both accept the `RepositoryGuidance` that `get_review_guidance` returns, or a string.

```python
from proofline.guidance import write_review_guidance

with ProoflineClient() as client:
guidance = client.get_review_guidance(organization_id, repository_id)
write_review_guidance("AGENTS.md", guidance)
```

## Development

The repository bundles its public API contract in `openapi.public.json`. New public operations generate typed methods on both `ProoflineClient` and `AsyncProoflineClient` along with the code in `proofline/_generated/`.
Expand Down
167 changes: 167 additions & 0 deletions proofline/guidance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
"""Sync a repository's reviewer guidance into coding-agent instruction files.

Coding agents read files such as ``AGENTS.md`` and ``CLAUDE.md`` before they
write code. Keeping the repository's Proofline reviewer guidance in one
managed block there lets an agent follow the rules the reviewer checks before
a pull request exists. Run ``python -m proofline.guidance [--check] PATH...``.
"""

from __future__ import annotations

import argparse
import difflib
import os
import sys
from pathlib import Path
from uuid import UUID

from ._generated.models.repository_guidance import RepositoryGuidance
from ._transport import ProoflineError
from .client import ProoflineClient

START = "<!-- proofline:review-guidance:start -->"
END = "<!-- proofline:review-guidance:end -->"
HEADER = (
"## Proofline review guidance",
"",
"Proofline reviews pull requests in this repository against this guidance.",
"It is synced by `python -m proofline.guidance`; change it in Proofline, not here.",
"",
)


def _prompt(guidance: RepositoryGuidance | str | None) -> str:
if isinstance(guidance, RepositoryGuidance):
guidance = guidance.additional_prompt if isinstance(guidance.additional_prompt, str) else ""
return (guidance or "").strip()


def apply_review_guidance(text: str, guidance: RepositoryGuidance | str | None) -> str:
"""Return ``text`` with its managed guidance block added, replaced or removed.

Guidance that is unset or blank removes the block. Text outside the block
stays byte-identical, except that a new block is appended after one blank
line and a removed block takes one adjacent blank line with it. The block
uses the line ending of the text's first line.
"""
prompt = _prompt(guidance)
if START in prompt or END in prompt:
raise ValueError("The review guidance contains a Proofline guidance marker.")
starts, ends = text.count(START), text.count(END)
if starts > 1 or ends > 1:
raise ValueError("A Proofline guidance marker appears more than once.")
if starts != ends:
raise ValueError("A Proofline guidance marker has no matching start or end marker.")
first = text.find("\n")
eol = "\r\n" if first > 0 and text[first - 1] == "\r" else "\n"
lines = [START, *HEADER, *prompt.replace("\r\n", "\n").split("\n"), END]
block = eol.join(lines) if prompt else ""
if not starts:
if not block:
return text
if not text:
return block + eol
return text + ("" if text.endswith("\n") else eol) + eol + block + eol
begin, end = text.index(START), text.index(END) + len(END)
if end < begin:
raise ValueError("The Proofline guidance end marker comes before the start marker.")
before, after = text[:begin], text[end:]
if block:
return before + block + after
if before and not before.endswith("\n"):
return before + after
after = after.removeprefix(eol)
if before.endswith(eol + eol) or before == eol:
before = before[: -len(eol)]
elif not before:
after = after.removeprefix(eol)
return before + after


def _change(file: Path, guidance: RepositoryGuidance | str | None) -> tuple[str, str] | None:
current = file.read_bytes().decode() if file.exists() else None
if current is None and not _prompt(guidance):
return None
updated = apply_review_guidance(current or "", guidance)
return None if updated == current else (current or "", updated)


def write_review_guidance(
path: str | os.PathLike[str],
guidance: RepositoryGuidance | str | None,
*,
check: bool = False,
) -> bool:
"""Sync the guidance block in the file at ``path``; return whether it changed.

With ``check=True`` nothing is written. The file is rewritten in place, so a
symbolic link stays a link, and a missing file is created only when there
is guidance to write.
"""
change = _change(Path(path), guidance)
if change is not None and not check:
Path(path).write_bytes(change[1].encode())
return change is not None


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="python -m proofline.guidance",
description="Sync a repository's Proofline reviewer guidance into agent instruction files.",
)
parser.add_argument(
"paths", nargs="+", type=Path, metavar="PATH", help="file to sync, such as AGENTS.md"
)
parser.add_argument(
"--check", action="store_true", help="write nothing; print a diff and exit 1 when stale"
)
parser.add_argument(
"--organization-id",
type=UUID,
default=os.environ.get("PROOFLINE_ORGANIZATION_ID"),
help="default: $PROOFLINE_ORGANIZATION_ID",
)
parser.add_argument(
"--repository-id",
type=UUID,
default=os.environ.get("PROOFLINE_REPOSITORY_ID"),
help="default: $PROOFLINE_REPOSITORY_ID",
)
parser.add_argument("--base-url", default="https://proofline.sh")
args = parser.parse_args(argv)
if args.organization_id is None or args.repository_id is None:
parser.error(
"pass --organization-id and --repository-id, or set "
"PROOFLINE_ORGANIZATION_ID and PROOFLINE_REPOSITORY_ID"
)
try:
with ProoflineClient(base_url=args.base_url) as client:
guidance = client.get_review_guidance(args.organization_id, args.repository_id)
# Read and apply every file before writing any, so a bad file changes nothing.
changes = [(path, _change(path, guidance)) for path in args.paths]
pending = [(path, *change) for path, change in changes if change is not None]
except ProoflineError as error:
detail = ": ".join(part for part in (error.title, error.detail) if part)
print(f"{parser.prog}: HTTP {error.status} {detail}", file=sys.stderr)
return 2
except (OSError, ValueError) as error:
print(f"{parser.prog}: {error}", file=sys.stderr)
return 2
for path, current, updated in pending:
if args.check:
sys.stdout.writelines(
difflib.unified_diff(
current.splitlines(keepends=True),
updated.splitlines(keepends=True),
f"a/{path}",
f"b/{path}",
)
)
else:
path.write_bytes(updated.encode())
print(f"Updated {path}")
return 1 if args.check and pending else 0


if __name__ == "__main__":
sys.exit(main())
185 changes: 185 additions & 0 deletions tests/test_guidance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
from __future__ import annotations

import os
from pathlib import Path
from uuid import UUID

import pytest

from proofline import RepositoryGuidance
from proofline.guidance import END, START, apply_review_guidance, main, write_review_guidance

from .fixtures import ORG, REPOSITORY, TOKEN
from .http_server import Reply, Request, Server

RULES = "Never call blocking I/O from a request handler.\nEvery migration is reversible."
AGENTS = "# Agents\n\nRun the tests before committing.\n"


def test_adds_one_block_after_a_blank_line_and_is_idempotent() -> None:
added = apply_review_guidance(AGENTS, RULES)
assert added.startswith(AGENTS + "\n" + START + "\n")
assert added.endswith(RULES + "\n" + END + "\n")
assert apply_review_guidance(added, RULES) == added
assert apply_review_guidance(AGENTS.rstrip("\n"), RULES) == added
assert apply_review_guidance("", RULES) == added.removeprefix(AGENTS + "\n")


def test_replaces_the_block_in_place_and_keeps_the_rest_byte_identical() -> None:
old = apply_review_guidance("", "Old rule.")
text = "# Top\n" + old + "\n## Bottom\n\ttabs and trailing spaces \n"
replaced = apply_review_guidance(text, RULES)
assert replaced == "# Top\n" + apply_review_guidance("", RULES) + text.split(old)[1]
assert "Old rule." not in replaced


@pytest.mark.parametrize("guidance", [None, "", " \n\t", RepositoryGuidance(REPOSITORY)])
def test_no_guidance_removes_the_block_and_its_blank_line(
guidance: RepositoryGuidance | str | None,
) -> None:
assert apply_review_guidance(apply_review_guidance(AGENTS, RULES), guidance) == AGENTS
assert apply_review_guidance(AGENTS, guidance) == AGENTS
block = apply_review_guidance("", RULES)
assert apply_review_guidance(block, guidance) == ""
assert apply_review_guidance(block + "\nTail\n", guidance) == "Tail\n"
assert apply_review_guidance("Head\n\n" + block + "\nTail\n", guidance) == "Head\n\nTail\n"


def test_accepts_the_api_model_and_normalizes_guidance_line_endings() -> None:
model = RepositoryGuidance(REPOSITORY, additional_prompt="\n" + RULES.replace("\n", "\r\n"))
assert apply_review_guidance(AGENTS, model) == apply_review_guidance(AGENTS, RULES)


def test_crlf_files_keep_crlf() -> None:
text = AGENTS.replace("\n", "\r\n")
added = apply_review_guidance(text, RULES)
assert added.startswith(text)
assert "\n" not in added.replace("\r\n", "")
assert apply_review_guidance(added, None) == text


@pytest.mark.parametrize(
("text", "message"),
[
(f"{START}\n", "no matching"),
(f"{END}\n", "no matching"),
(f"{START}\n{START}\n{END}\n", "more than once"),
(f"{START}\n{END}\n{END}\n", "more than once"),
(f"{END}\n{START}\n", "before the start"),
],
)
def test_malformed_markers_are_refused(text: str, message: str) -> None:
for guidance in (RULES, None):
with pytest.raises(ValueError, match=message):
apply_review_guidance(text, guidance)


@pytest.mark.parametrize("marker", [START, END])
def test_guidance_containing_a_marker_is_refused(marker: str) -> None:
with pytest.raises(ValueError, match="contains a Proofline guidance marker"):
apply_review_guidance(AGENTS, f"Rule one.\n{marker}\nRule two.")


def test_write_check_mode_and_missing_files(tmp_path: Path) -> None:
agents = tmp_path / "AGENTS.md"
agents.write_bytes(AGENTS.encode())
assert write_review_guidance(agents, RULES, check=True)
assert agents.read_bytes() == AGENTS.encode()
assert write_review_guidance(agents, RULES)
assert not write_review_guidance(agents, RULES)
assert not write_review_guidance(agents, RULES, check=True)
missing = tmp_path / "CLAUDE.md"
assert not write_review_guidance(missing, None)
assert not missing.exists()
assert write_review_guidance(missing, RULES, check=True)
assert not missing.exists()
assert write_review_guidance(missing, RULES)
assert missing.read_text() == apply_review_guidance("", RULES)


def test_writes_through_a_symlink_and_keeps_it(tmp_path: Path) -> None:
agents = tmp_path / "AGENTS.md"
agents.write_bytes(AGENTS.replace("\n", "\r\n").encode())
claude = tmp_path / "CLAUDE.md"
claude.symlink_to("AGENTS.md")
assert write_review_guidance(claude, RULES)
assert claude.is_symlink() and os.readlink(claude) == "AGENTS.md"
assert (
agents.read_bytes() == apply_review_guidance(AGENTS, RULES).replace("\n", "\r\n").encode()
)
assert not write_review_guidance(agents, RULES)


def serve(prompt: str | None) -> Server:
path = f"/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/review-guidance"

def respond(request: Request, index: int) -> Reply:
assert (request.method, request.path) == ("GET", path)
assert request.headers["Authorization"] == f"Bearer {TOKEN}"
return Reply(body={"repository_id": str(REPOSITORY), "additional_prompt": prompt})

return Server(respond)


def run(server: Server, *args: str) -> int:
return main(
["--organization-id", str(ORG), "--repository-id", str(REPOSITORY)]
+ ["--base-url", server.url, *args]
)


def test_cli_fetches_once_and_syncs_every_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
monkeypatch.setenv("PROOFLINE_TOKEN", TOKEN)
agents, claude = tmp_path / "AGENTS.md", tmp_path / "CLAUDE.md"
agents.write_text(AGENTS)
with serve(RULES) as server:
assert run(server, "--check", str(agents), str(claude)) == 1
diff = capsys.readouterr().out
assert f"--- a/{agents}" in diff and f"+++ b/{claude}" in diff and f"+{START}" in diff
assert agents.read_text() == AGENTS and not claude.exists()
assert run(server, str(agents), str(claude)) == 0
assert agents.read_text() == apply_review_guidance(AGENTS, RULES)
assert claude.read_text() == apply_review_guidance("", RULES)
capsys.readouterr()
assert run(server, "--check", str(agents), str(claude)) == 0
assert capsys.readouterr().out == ""
assert len(server.requests) == 3
with serve(None) as server:
assert run(server, str(agents)) == 0
assert agents.read_text() == AGENTS


def test_cli_changes_nothing_when_any_file_is_malformed(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
monkeypatch.setenv("PROOFLINE_TOKEN", TOKEN)
agents, broken = tmp_path / "AGENTS.md", tmp_path / "CLAUDE.md"
agents.write_text(AGENTS)
broken.write_text(f"{START}\n")
with serve(RULES) as server:
assert run(server, str(agents), str(broken)) == 2
assert agents.read_text() == AGENTS
assert "no matching" in capsys.readouterr().err


def test_cli_reports_a_refused_request(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
monkeypatch.setenv("PROOFLINE_TOKEN", TOKEN)
problem = {"type": "about:blank", "title": "Forbidden", "status": 403, "detail": "No scope."}
with Server(
lambda request, index: Reply(403, problem, {"Content-Type": "application/problem+json"})
) as server:
assert run(server, str(tmp_path / "AGENTS.md")) == 2
error = capsys.readouterr().err
assert "HTTP 403" in error and TOKEN not in error


def test_cli_requires_both_ids(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("PROOFLINE_ORGANIZATION_ID", raising=False)
monkeypatch.setenv("PROOFLINE_REPOSITORY_ID", str(UUID(int=1)))
with pytest.raises(SystemExit) as caught:
main(["AGENTS.md"])
assert caught.value.code == 2