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
4 changes: 3 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,15 @@ parent: auth # optional; parent node ID (hierarchy)
depends_on: # optional; cross-branch dependencies
- contracts/api/users
language: typescript # optional; overrides config default
acceptance: # optional; hand-written tests the code must pass
- tests/acceptance/test_login.py
---

## Description
Prose description of what this spec requires...
```

Fields that affect the SHA-256 hash (trigger rebuild): `id`, `version`, `depends_on`, `parent`, `language`, body content.
Fields that affect the SHA-256 hash (trigger rebuild): `id`, `version`, `depends_on`, `parent`, `language`, body content. Acceptance test file contents are part of the node fingerprint (`plan.py`), run after generated tests (`agents/pipeline.py`), and are unwritable by agents.
Fields that do **not** affect the hash: `status`, `hash` (editorial-only).

### Code Conventions
Expand Down
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,24 @@ depends_on:

Everything below the frontmatter is your spec -- prose, code snippets, whatever communicates the intent.

### Acceptance tests

Generated tests are written by the same model that writes the code, so passing them only shows the model agrees with itself. To pin down behavior yourself, write the tests and list them on the spec:

```yaml
---
id: behaviors/auth/login
version: "1.0.0"
status: approved
acceptance:
- tests/acceptance/test_login.py
---
```

Acceptance tests are the contract. Agents see them, can never write them, and a spec is only saved once they pass; a failure goes to the repair stage with the instruction to fix the code. Editing an acceptance test marks its spec stale.

They run as `acceptance_command` (default: `test_command`) with the files appended, so keep them somewhere your `test_command` doesn't already collect -- otherwise the baseline run fails before their spec is built. Write them before the code exists and `specdiff build` becomes test-driven.

## Examples

Four generated example snapshots in [`examples/`](examples/), each with specs and generated output:
Expand Down Expand Up @@ -259,6 +277,7 @@ Extraction complete! Initialized 2 specs in .specdiff.
| `test_framework` | (none) | Test framework named to agents (e.g. `pytest`, `vitest`) |
| `test_command` | (none) | Run after each spec is generated, and once before the build as a baseline. Without it, no tests are generated and output is unverified. |
| `check_command` | (none) | Extra command that must pass, e.g. `npx tsc --noEmit` |
| `acceptance_command` | `test_command` | Runs a spec's acceptance tests, with their paths appended |
| `review_before_build` | `false` | Require spec review to pass before build |
| `max_retries` | `2` | Repair attempts per spec after a failed check |

Expand Down
8 changes: 8 additions & 0 deletions src/specdiff/agents/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ class NodeContext:
dep_files: dict[str, str] = field(default_factory=dict)
own_files: dict[str, str] = field(default_factory=dict)
others: dict[str, str] = field(default_factory=dict)
# Hand-written acceptance tests, keyed by path from the project root.
acceptance: dict[str, str] = field(default_factory=dict)
test_framework: str | None = None
test_command: str | None = None
check_command: str | None = None
Expand Down Expand Up @@ -71,6 +73,12 @@ def render(ctx: NodeContext) -> str:
f"# Spec `{node.id}` (version {node.version}) -- the one you are building\n\n"
f"{node.content.strip()}"
)
if ctx.acceptance:
sections.append(
"# Acceptance tests for this spec\n\nHand-written by the spec's author. They are "
"the contract: the code must pass them, and they can never be changed. Paths "
"here are from the project root.\n\n" + fileblocks.render(ctx.acceptance)
)
return "\n\n".join(sections) + "\n"


Expand Down
16 changes: 13 additions & 3 deletions src/specdiff/agents/pipeline.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import shlex
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
Expand All @@ -18,6 +19,7 @@ class PipelineConfig:
review: bool = True
test_command: str | None = None
check_command: str | None = None
acceptance_command: str | None = None


@dataclass
Expand Down Expand Up @@ -101,13 +103,21 @@ def _check(

sync(files)
ours.update(files)
for label, command in (("Check", cfg.check_command), ("Tests", cfg.test_command)):
acceptance = None
if ctx.acceptance and cfg.acceptance_command:
acceptance = f"{cfg.acceptance_command} {' '.join(map(shlex.quote, ctx.acceptance))}"
commands = (
("check", "Check failed", cfg.check_command),
("tests", "Tests failed", cfg.test_command),
("acceptance tests", "Hand-written acceptance tests failed (fix the code)", acceptance),
)
for name, heading, command in commands:
if not command:
continue
log(f"running {label.lower()}")
log(f"running {name}")
passed, output = run_command(command)
if not passed:
return f"{label} failed: `{command}`\n\n```\n{output}\n```"
return f"{heading}: `{command}`\n\n```\n{output}\n```"

if cfg.review:
log("reviewing")
Expand Down
1 change: 1 addition & 0 deletions src/specdiff/build/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ def node_context(
dep_files=_read([p for p in dep_paths if not is_test_path(p)], out),
own_files=_read(own, out),
others=others,
acceptance={p: Path(p).read_text("utf-8") for p in node.acceptance if Path(p).is_file()},
test_framework=config.test_framework,
test_command=config.test_command,
check_command=config.check_command,
Expand Down
10 changes: 10 additions & 0 deletions src/specdiff/build/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ def ok(self) -> bool:
def preflight(ordered_nodes: list[SpecNode], config: SpecdiffConfig, hm: HashMap,
specs_dir: Path, force: bool) -> None: # fmt: skip
"""Refuse to build when doing so could lose work or blame the wrong spec."""
missing = [
f" {n.id}: {p}" for n in ordered_nodes for p in n.acceptance if not Path(p).is_file()
]
if missing:
raise BuildRefused("Acceptance test files not found:\n" + "\n".join(missing))
if any(n.acceptance for n in ordered_nodes) and not (
config.acceptance_command or config.test_command
):
raise BuildRefused("Specs list acceptance tests, but no test_command is configured.")
if (specs_dir / BACKUP_DIR).exists():
raise BuildRefused(
f"{specs_dir / BACKUP_DIR} exists from an interrupted build. Copy back any files "
Expand Down Expand Up @@ -81,6 +90,7 @@ def execute_build(
review=review,
test_command=config.test_command,
check_command=config.check_command,
acceptance_command=config.acceptance_command or config.test_command,
)
report = BuildReport()
for node in ordered_nodes:
Expand Down
5 changes: 5 additions & 0 deletions src/specdiff/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,11 @@ def validate() -> None:
if node.parent and node.parent not in node_map:
errors.append(f" {node.id}: parent '{node.parent}' not found")

for node in nodes:
for path in node.acceptance:
if not Path(path).is_file():
errors.append(f" {node.id}: acceptance test '{path}' not found")

if not errors:
try:
build_graph(nodes)
Expand Down
1 change: 1 addition & 0 deletions src/specdiff/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ def load_config(specs_dir: Path) -> SpecdiffConfig:
language=raw.get("language", SpecdiffConfig.language),
test_framework=raw.get("test_framework"),
check_command=raw.get("check_command"),
acceptance_command=raw.get("acceptance_command"),
max_retries=raw.get("max_retries", SpecdiffConfig.max_retries),
)
2 changes: 2 additions & 0 deletions src/specdiff/default_skills/repair.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ you fix the root cause.
syntax error is usually the whole story.
- Change as little as the fix needs, and keep the planned interfaces unless they
are the problem.
- Acceptance tests are hand-written by the spec's author and can never be changed.
When one fails, the code is wrong.
- You may only change this spec's own files.
2 changes: 2 additions & 0 deletions src/specdiff/default_skills/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ the implementation; the spec and the plan are your contract.
- Import project code the way the project notes describe, from the planned paths.
- Keep tests deterministic and self-contained: temporary directories for files, no
network, no reliance on test order.
- If the spec has hand-written acceptance tests, do not duplicate them; cover what
they leave out.
- Do not write production code.
14 changes: 9 additions & 5 deletions src/specdiff/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,7 @@ def parse_spec_file(file_path: Path) -> SpecNode:
)
content_hash = hashlib.sha256(payload.encode("utf-8")).hexdigest()

raw_depends = meta.get("depends_on") or []
if not isinstance(raw_depends, list) or not all(isinstance(x, str) for x in raw_depends):
raise ValueError(
f"{file_path}: 'depends_on' must be a list of strings, got {raw_depends!r}"
)
raw_depends = _string_list(meta, "depends_on", file_path)

return SpecNode(
id=meta["id"],
Expand All @@ -47,9 +43,17 @@ def parse_spec_file(file_path: Path) -> SpecNode:
parent=meta.get("parent"),
depends_on=raw_depends,
language=meta.get("language"),
acceptance=_string_list(meta, "acceptance", file_path),
)


def _string_list(meta: dict, key: str, file_path: Path) -> list[str]:
value = meta.get(key) or []
if not isinstance(value, list) or not all(isinstance(x, str) for x in value):
raise ValueError(f"{file_path}: '{key}' must be a list of strings, got {value!r}")
return value


def discover_specs(root_dir: Path) -> list[SpecNode]:
"""Find and parse all *.spec.md files under root_dir, excluding proposed/."""
nodes: list[SpecNode] = []
Expand Down
8 changes: 7 additions & 1 deletion src/specdiff/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ def compute_states(
inputs[f"dep:{dep_id}"] = states[dep_id].fingerprint
if node.parent:
inputs[f"parent:{node.parent}"] = states[node.parent].fingerprint
for path in node.acceptance:
inputs[f"acceptance:{path}"] = file_digest(Path(path))

state = NodeState(inputs=inputs, fingerprint=_digest(inputs))
entry = hm.nodes.get(nid)
Expand All @@ -72,7 +74,7 @@ def compute_states(
return states


_EDGE_NAMES = {"dep": "dependency", "parent": "parent"}
_EDGE_NAMES = {"dep": "dependency", "parent": "parent", "acceptance": "acceptance test"}


def _diff_reasons(old: dict[str, str], new: dict[str, str]) -> list[str]:
Expand Down Expand Up @@ -125,6 +127,10 @@ def plan_build(
return BuildPlan(order=order, blocked=blocked)


def file_digest(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else "missing"


def _digest(data: dict) -> str:
payload = json.dumps(data, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
4 changes: 4 additions & 0 deletions src/specdiff/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ class SpecNode:
parent: str | None = None
depends_on: list[str] = field(default_factory=list)
language: str | None = None
# Hand-written test files (paths from the project root) the generated code must pass.
acceptance: list[str] = field(default_factory=list)


@dataclass
Expand Down Expand Up @@ -69,6 +71,8 @@ class SpecdiffConfig:
test_framework: str | None = None
# Command that must pass besides the tests, e.g. a typechecker.
check_command: str | None = None
# Runs a spec's acceptance tests, with their paths appended. Defaults to test_command.
acceptance_command: str | None = None
# Repair attempts per node after a failed check.
max_retries: int = 2

Expand Down
12 changes: 12 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -995,3 +995,15 @@ def test_build_notes_unused_legacy_skill_files(self, tmp_path, monkeypatch, fake
monkeypatch.chdir(proj)
result = CliRunner().invoke(cli, ["build"], catch_exceptions=False)
assert "architect.skill.md is no longer used" in result.output


class TestValidateAcceptance:
def test_missing_acceptance_file_is_reported(self, tmp_path, monkeypatch):
proj = _setup_project(tmp_path, [])
(proj / ".specdiff" / "a.spec.md").write_text(
"---\nid: a\nversion: '1'\nstatus: approved\nacceptance:\n - tests/acc.py\n---\nx\n"
)
monkeypatch.chdir(proj)
result = CliRunner().invoke(cli, ["validate"])
assert result.exit_code == 1
assert "acceptance test 'tests/acc.py' not found" in result.output
18 changes: 18 additions & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,21 @@ def test_depends_on_valid_list(self, tmp_path):
f = self._write(tmp_path, "ok.spec.md", "depends_on:\n - a/b\n - c/d\n")
node = parse_spec_file(f)
assert node.depends_on == ["a/b", "c/d"]


class TestAcceptanceField:
def _write(self, tmp_path, extra: str):
path = tmp_path / "a.spec.md"
path.write_text(f"---\nid: a\nversion: '1'\nstatus: approved\n{extra}---\nBody\n")
return path

def test_parsed_as_list(self, tmp_path):
node = parse_spec_file(self._write(tmp_path, "acceptance:\n - tests/acc/test_a.py\n"))
assert node.acceptance == ["tests/acc/test_a.py"]

def test_defaults_to_empty(self, tmp_path):
assert parse_spec_file(self._write(tmp_path, "")).acceptance == []

def test_string_rejected(self, tmp_path):
with pytest.raises(ValueError, match="'acceptance' must be a list of strings"):
parse_spec_file(self._write(tmp_path, "acceptance: tests/x.py\n"))
23 changes: 23 additions & 0 deletions tests/test_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,26 @@ def test_current_draft_does_not_block(self):
graph, states = _states(nodes, hm)
plan = plan_build(graph, states)
assert plan.order == ["b"] and plan.blocked == {}


class TestAcceptanceFingerprint:
def test_editing_an_acceptance_test_marks_the_spec_stale(self, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
acc = tmp_path / "test_acc.py"
acc.write_text("def test_a(): pass\n")
node = _node("a")
node.acceptance = ["test_acc.py"]
hm = _built([node])

acc.write_text("def test_a(): assert False\n")
_, states = _states([node], hm)
assert states["a"].reasons == ["test_acc.py changed"]

def test_new_acceptance_test_is_reported(self, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
(tmp_path / "test_acc.py").write_text("x")
hm = _built([_node("a")])
node = _node("a")
node.acceptance = ["test_acc.py"]
_, states = _states([node], hm)
assert "acceptance test test_acc.py added" in states["a"].reasons
50 changes: 50 additions & 0 deletions tests/test_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,56 @@ def test_failing_baseline_refuses(self, project, fake_llm):
_build(project, [_node("a", h="v2")], hm)


class TestAcceptanceTests:
def _acceptance(self, node_id="a", body=None):
path = Path("tests/acceptance/test_a_accept.py")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
body
or "from a import VALUE, extra\n\n\ndef test_contract():\n assert extra() == 42\n"
)
node = _node(node_id)
node.acceptance = [str(path)]
return node, path

def test_failing_acceptance_test_drives_repair_until_it_passes(self, project, fake_llm):
node, acc = self._acceptance()
fake_llm.reply(
"a",
"repair",
'<file path="a.py">\nVALUE = "a"\n\n\ndef extra():\n return 42\n</file>',
)

report, hm = _build(project, [node])

assert report.ok
plan_prompt = fake_llm.prompts[fake_llm.calls.index(("a", "plan"))]
assert "# Acceptance tests for this spec" in plan_prompt
assert "assert extra() == 42" in plan_prompt
repair_prompt = fake_llm.prompts[fake_llm.calls.index(("a", "repair"))]
assert "Hand-written acceptance tests failed" in repair_prompt
assert str(acc) not in hm.nodes["a"].generated_files

def test_acceptance_file_cannot_be_written_by_agents(self, project, fake_llm):
node, acc = self._acceptance()
original = acc.read_text()
fake_llm.reply(
"a", "implement", '<file path="../tests/acceptance/test_a_accept.py">\npass\n</file>'
)

report, _ = _build(project, [node], max_retries=0)

assert "escapes output_dir" in report.failed["a"]
assert acc.read_text() == original

def test_missing_acceptance_file_refuses_build(self, project, fake_llm):
node = _node("a")
node.acceptance = ["tests/acceptance/nope.py"]
with pytest.raises(BuildRefused, match="nope.py"):
_build(project, [node])
assert fake_llm.calls == []


class TestHandWrittenFiles:
def test_existing_untracked_file_is_never_overwritten(self, project, fake_llm):
Path("src").mkdir()
Expand Down
Loading