Read and write each record through the store its config names, and open one for agents with project-record
CI / tests (pull_request) Successful in 2m14s

This commit is contained in:
2026-11-13 23:54:04 +01:00
parent 854eb63407
commit 084bc74b1c
40 changed files with 624 additions and 161 deletions
View File
+42
View File
@@ -0,0 +1,42 @@
"""What every record backend must hold, as tests. A backend's test case inherits RecordStoreContract and unittest.TestCase, and builds its store in new_store."""
import typing
from record_store.stores import held_at, RecordStore
class RecordStoreContract:
"""Runs against the store new_store returns: one that holds no record yet."""
assertEqual: typing.Callable[..., None]
assertIsNone: typing.Callable[..., None]
assertTrue: typing.Callable[..., None]
def new_store(self) -> RecordStore:
raise NotImplementedError
def test_a_record_never_written_reads_empty(self) -> None:
self.assertEqual(self.new_store().read(), "")
def test_reads_back_what_it_wrote_to_the_character(self) -> None:
store = self.new_store()
text = "# Decisions\n\n- Å, 🔴 and a | pipe\n\n\n"
self.assertIsNone(store.write(text))
self.assertEqual(store.read(), text)
def test_a_write_replaces_the_whole_record(self) -> None:
store = self.new_store()
store.write("first\nsecond\n")
self.assertIsNone(store.write("third\n"))
self.assertEqual(store.read(), "third\n")
def test_names_itself_for_a_message(self) -> None:
self.assertTrue(self.new_store().label.strip())
def test_reads_as_it_stands_at_any_revision_where_no_commit_holds_it(self) -> None:
store = self.new_store()
store.write("as it stands\n")
if store.tracked is None:
self.assertEqual(held_at("no-such-revision", store, "/nowhere", run=refuse), "as it stands\n")
def refuse(*args: str, **options: object) -> str:
raise AssertionError(f"git {' '.join(args)} ran for a record no commit holds")
+22
View File
@@ -0,0 +1,22 @@
"""Record stores for tests, held to record_store.contract like every backend."""
import dataclasses
from failure import Failure
@dataclasses.dataclass
class MemoryStore:
"""A record held in memory, as a backend outside git holds one. Set fails to make every read and write fail with that reason."""
text: str = ""
label: str = "the record in memory"
tracked: str | None = None
fails: str | None = None
def read(self) -> str | Failure:
return Failure(self.fails) if self.fails else self.text
def write(self, text: str) -> Failure | None:
if self.fails:
return Failure(self.fails)
self.text = text
return None
+94
View File
@@ -0,0 +1,94 @@
"""The one way a tool reads or writes a project's records: through the store its config names for each.
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, the only backend so far."""
import dataclasses
import pathlib
import typing
from failure import Failure
from git_cli.git_repo import file_at, git, Git
from project_config.settings import ProjectConfig
from text_files.file_writes import replace_file
# The settings in a project's config that each name a record.
RECORDS = ("decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog")
class RecordStore(typing.Protocol):
"""One record, as text. record_store.contract holds every backend to the same behaviour."""
@property
def label(self) -> str:
"""What a message calls the record, such as its path."""
@property
def tracked(self) -> str | None:
"""The record's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a wiki page."""
def read(self) -> str | Failure:
"""The record's text as it stands, empty where it doesn't exist yet."""
def write(self, text: str) -> Failure | None:
"""Replaces the record's whole text, creating the record where it doesn't exist yet."""
@dataclasses.dataclass(frozen=True)
class FileStore:
"""A record kept as a markdown file at path."""
path: pathlib.Path
tracked: str | None
@property
def label(self) -> str:
return str(self.path)
def read(self) -> str | Failure:
try:
# Decoded from bytes, so the text keeps the line ends the file holds.
return self.path.read_bytes().decode("utf-8")
except FileNotFoundError:
return ""
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"cannot read {self.path}: {failure}")
def write(self, text: str) -> Failure | None:
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
except OSError as failure:
return Failure(f"cannot write {self.path}: {failure}")
unwritten = replace_file(self.path, text.encode("utf-8"))
return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else None
def store(config: ProjectConfig, record: str) -> RecordStore:
"""The store config names for record, one of RECORDS."""
if record not in RECORDS:
raise ValueError(f"{record} is not a record; the records are {', '.join(RECORDS)}")
return FileStore(config.paths[record], config.tracked(record))
def held_at(revision: str, record: RecordStore, cwd: str, run: Git = git) -> str | Failure:
"""record's text at revision, read in the checkout at cwd, where its commits hold the record; else as it stands. Empty where there is no such record."""
return record.read() if record.tracked is None else file_at(revision, record.tracked, cwd, run)
def local_file(record: RecordStore, copy: pathlib.Path) -> pathlib.Path | Failure:
"""A file holding record's text, for an agent, which reads and edits files: the record's own file where a file is its backend, else copy, written with the text as it stands. Neither exists where the record doesn't yet. `stored` puts an edited copy back."""
if isinstance(record, FileStore):
return record.path
text = record.read()
if isinstance(text, Failure):
return text
if text and (unwritten := FileStore(copy, None).write(text)):
return unwritten
return copy
def stored(record: RecordStore, copy: pathlib.Path) -> Failure | None:
"""Stores in record the text of copy, the file `local_file` gave for it. Where that is the record's own file, the edit is already the record."""
if isinstance(record, FileStore):
return None
text = FileStore(copy, None).read()
if isinstance(text, Failure):
return text
return record.write(text) if text else Failure(f"{copy} is missing or empty, so nothing is stored in {record.label}; `record open` writes the file to edit")
+150
View File
@@ -0,0 +1,150 @@
import pathlib
import re
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from record_store.fakes import MemoryStore
from project_config.settings import ProjectConfig
from record_store.contract import RecordStoreContract
from record_store import stores
class MemoryStoreContract(RecordStoreContract, unittest.TestCase):
def new_store(self) -> stores.RecordStore:
return MemoryStore()
class FileStoreContract(RecordStoreContract, unittest.TestCase):
def setUp(self) -> None:
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
def new_store(self) -> stores.RecordStore:
return stores.FileStore(self.folder / "docs" / "decisions.md", None)
class FileStoreInACheckoutContract(FileStoreContract):
def new_store(self) -> stores.RecordStore:
return stores.FileStore(self.folder / "docs" / "decisions.md", "docs/decisions.md")
class FileStore(unittest.TestCase):
def setUp(self) -> None:
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
def test_names_its_path(self):
self.assertEqual(stores.FileStore(self.folder / "CHANGELOG.md", "CHANGELOG.md").label, str(self.folder / "CHANGELOG.md"))
def test_a_file_that_is_not_utf8_is_a_failure_naming_it(self):
path = self.folder / "decisions.md"
path.write_bytes(b"\xff\xfe")
read = stores.FileStore(path, None).read()
self.assertIsInstance(read, Failure)
self.assertIn(f"cannot read {path}: ", read.reason)
def test_a_write_that_fails_is_a_failure_naming_it(self):
(self.folder / "docs").write_text("a file where the folder goes")
path = self.folder / "docs" / "decisions.md"
written = stores.FileStore(path, None).write("text\n")
self.assertIsInstance(written, Failure)
self.assertIn(f"cannot write {path}: ", written.reason)
def test_a_write_keeps_the_text_as_given_not_the_platforms_line_ends(self):
path = self.folder / "decisions.md"
stores.FileStore(path, None).write("one\r\ntwo\n")
self.assertEqual(path.read_bytes(), b"one\r\ntwo\n")
self.assertEqual(stores.FileStore(path, None).read(), "one\r\ntwo\n")
class HeldAt(unittest.TestCase):
def setUp(self) -> None:
self.top = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
self.git("init", "-q", "-b", "main")
(self.top / "CHANGELOG.md").write_text("committed\n")
self.git("add", "-A")
self.git("-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-qm", "first")
(self.top / "CHANGELOG.md").write_text("as it stands\n")
def git(self, *args: str) -> None:
subprocess.run(["git", *args], cwd=self.top, check=True, capture_output=True)
def test_a_record_in_the_checkout_reads_as_the_revision_holds_it(self):
store = stores.FileStore(self.top / "CHANGELOG.md", "CHANGELOG.md")
self.assertEqual(stores.held_at("main", store, str(self.top)), "committed\n")
def test_a_record_the_revision_lacks_reads_empty(self):
store = stores.FileStore(self.top / "docs" / "decisions.md", "docs/decisions.md")
self.assertEqual(stores.held_at("main", store, str(self.top)), "")
def test_a_record_outside_the_checkout_reads_as_it_stands(self):
store = stores.FileStore(self.top / "CHANGELOG.md", None)
self.assertEqual(stores.held_at("main", store, str(self.top)), "as it stands\n")
class LocalFile(unittest.TestCase):
def setUp(self) -> None:
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
def test_a_file_record_is_its_own_local_file_and_no_copy_is_made(self):
record = stores.FileStore(self.folder / "decisions.md", None)
record.write("kept\n")
self.assertEqual(stores.local_file(record, self.folder / "copies" / "decisions.md"), self.folder / "decisions.md")
self.assertIsNone(stores.stored(record, self.folder / "copies" / "decisions.md"))
self.assertEqual((record.read(), (self.folder / "copies").exists()), ("kept\n", False))
def test_a_record_outside_files_is_copied_and_an_edited_copy_is_stored_back(self):
record, copy = MemoryStore("# Decisions\n"), self.folder / "copies" / "decisions.md"
self.assertEqual(stores.local_file(record, copy), copy)
self.assertEqual(copy.read_text(), "# Decisions\n")
copy.write_text("# Decisions\n\n- One more\n")
self.assertIsNone(stores.stored(record, copy))
self.assertEqual(record.text, "# Decisions\n\n- One more\n")
def test_a_record_that_does_not_exist_yet_gets_no_copy(self):
copy = self.folder / "decisions.md"
self.assertEqual((stores.local_file(MemoryStore(), copy), copy.exists()), (copy, False))
def test_storing_a_missing_copy_fails_and_leaves_the_record(self):
record = MemoryStore("kept\n")
self.assertIn("is missing or empty", stores.stored(record, self.folder / "decisions.md").reason)
self.assertEqual(record.text, "kept\n")
def test_a_record_that_cannot_be_read_or_written_fails_with_its_reason(self):
record, copy = MemoryStore(fails="the wiki is down"), self.folder / "decisions.md"
self.assertEqual(stores.local_file(record, copy), Failure("the wiki is down"))
copy.write_text("edited\n")
self.assertEqual(stores.stored(record, copy), Failure("the wiki is down"))
class Store(unittest.TestCase):
def config(self, top: pathlib.Path, folder: pathlib.Path) -> ProjectConfig:
paths = {record: top / f"{record}.md" for record in stores.RECORDS} | {"changelog": folder / "CHANGELOG.md", "plan": top / "todo.md"}
return ProjectConfig("acme", folder, top, paths)
def test_a_record_in_the_checkout_is_tracked_by_its_path_from_the_top(self):
store = stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "decisions")
self.assertEqual((store.label, store.tracked), ("/code/acme/decisions.md", "decisions.md"))
def test_a_record_in_the_configs_folder_is_not_tracked(self):
store = stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "changelog")
self.assertEqual((store.label, store.tracked), ("/home/me/.claude-projects/acme/CHANGELOG.md", None))
def test_the_plan_is_not_a_record(self):
with self.assertRaises(ValueError):
stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "plan")
class OneWayIn(unittest.TestCase):
def test_no_tool_reads_a_records_place_from_the_config_itself(self):
bin_folder = pathlib.Path(__file__).resolve().parents[1]
reach = re.compile(r"""(?:paths\[|\.place\(|\.tracked\()["'](?:%s)["']""" % "|".join(stores.RECORDS))
found = [f"{path.relative_to(bin_folder)}:{number}" for path in sorted(bin_folder.rglob("*.py")) if "test_" not in path.name and path.parent.name != "record_store" for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1) if reach.search(line)]
self.assertEqual(found, [], "read and write a record through record_store.stores.store")
if __name__ == "__main__":
unittest.main()