Files
FabledScribe/tests/test_snippet_notes.py
T
bvandeusenandClaude Opus 5.5 914f31359c
CI & Build / Python lint (push) Successful in 5s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / TypeScript typecheck (push) Successful in 57s
CI & Build / integration (push) Successful in 1m19s
CI & Build / Python tests (push) Successful in 2m2s
CI & Build / Build & push image (push) Successful in 15s
docs(6209): the remaining test files — lessons, reply moment and shape, retrieval specs and scopes, rule doors and judgments, services, snippets, search scope; five tests renamed to their property
Docstrings, section headers and assertion messages drop the record number,
milestone or step that introduced the behaviour, and incident accounts are
restated as the present-tense failure shape. A dead pointer to a design doc
that is not in the repo is removed.

Renamed to the property they check:
  test_the_old_shape_would_be_caught -> test_a_rank_then_scope_query_is_caught
  test_a_ledger_repeat_no_longer_produces_that_case_at_all -> test_a_ledger_repeat_is_counted_not_withheld
  test_the_header_no_longer_promises_once_per_session -> test_the_header_explains_the_seen_marker
  test_the_portal_case_no_longer_stamps_one_canon_onto_a_whole_file -> test_one_canon_is_not_stamped_onto_a_whole_file
  test_the_repos_own_prose_no_longer_defines_with -> test_the_repos_own_prose_does_not_define_with
  test_the_original_regression_create_note_with_content -> test_the_real_server_refuses_content_on_create_note

Fixture and example ids stay: "note 5" in a supersession chain, "rule 156"
in an illustrative question, `#2275` as the hex-versus-citation case,
`#3244` as the example of a bare number, fixed dates in date-filter tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 21:44:58 -04:00

155 lines
6.0 KiB
Python

"""A snippet's notes — where the explanation goes.
A snippet has name, code, signature, locations and `when_to_use`. Without a
place for prose, what a session learned about a snippet goes into
`when_to_use` — the trigger, joined onto the title of every chunk the snippet
is embedded as — so a multi-paragraph write-up there blurs the one situation
it is ranked on.
The rules pinned here, each with a way to rot silently:
- Notes live in the BODY, after the code, under `## Notes`, and read back
from it. A `## Notes` line inside the code is code, not the section.
- A snippet with no notes composes the body it always did, byte for byte —
no re-embed for the corpus that has none.
- Every path that rebuilds the body CARRIES the notes. `update_snippet`,
merge and un-merge all compose the body from scratch, so a field one of
them forgets is erased by any edit to something else.
- `trigger_advice` speaks for a write-up and stays quiet for a situation.
"""
import pytest
import pytest_asyncio
from tests.helpers import ensure_user
from scribe.services import snippets as s
CODE = "def helper():\n return 1"
NOTES = "Shaped this way because the caller owns the session.\n\nSuperseded #12."
# --- unit: the body convention -----------------------------------------------
def test_notes_follow_the_code_under_their_heading():
body = s.compose_body(code=CODE, language="python", when_to_use="a helper", notes=NOTES)
code_at = body.index("```python")
notes_at = body.index(s.NOTES_HEADING)
assert code_at < notes_at
assert body.rstrip().endswith("Superseded #12.")
def test_notes_round_trip_through_the_body():
body = s.compose_body(code=CODE, language="python", notes=NOTES)
got = s.parse_snippet_fields("helper", body, ["python", "snippet"])
assert got["notes"] == NOTES
assert got["code"] == CODE
def test_a_snippet_without_notes_composes_the_body_it_always_did():
"""No trailing section, no extra blank line: the corpus that has no notes
must embed exactly as before."""
body = s.compose_body(code=CODE, language="python", when_to_use="a helper")
assert body == "**When to use:** a helper\n\n```python\n" + CODE + "\n```\n"
assert s.parse_snippet_fields("helper", body)["notes"] == ""
def test_a_notes_heading_inside_the_code_is_code():
md = "# Title\n\n## Notes\n\nthis is markdown being recorded"
body = s.compose_body(code=md, language="markdown")
got = s.parse_snippet_fields("md_template", body)
assert got["notes"] == ""
assert got["code"] == md
def test_notes_after_code_that_itself_contains_the_heading():
md = "## Notes\ninside"
body = s.compose_body(code=md, language="markdown", notes="the real notes")
got = s.parse_snippet_fields("md_template", body)
assert got["notes"] == "the real notes"
assert got["code"] == md
def test_long_notes_are_chunked_apart_from_the_code():
"""The heading is the chunker's split point, so a long explanation gets
vectors of its own instead of averaging into the code's."""
from scribe.services.embeddings import chunk_document
long_notes = "\n\n".join(["An explanatory paragraph about the history. " * 12] * 4)
body = s.compose_body(code=CODE, language="python", when_to_use="a helper",
notes=long_notes)
chunks = chunk_document("helper — a helper", body)
assert len(chunks) > 1
assert "```python" in chunks[0]
assert "```python" not in chunks[-1]
# --- unit: the advice ---------------------------------------------------------
def test_a_situation_draws_no_advice():
assert s.trigger_advice("Debouncing a reactive input before it fetches.") is None
assert s.trigger_advice("") is None
assert s.trigger_advice(None) is None
def test_a_long_trigger_is_advised_toward_notes():
advice = s.trigger_advice("x" * (s.TRIGGER_ADVISE_CHARS + 1))
assert advice and "notes" in advice
assert f"{s.TRIGGER_ADVISE_CHARS + 1} characters" in advice
def test_a_headed_or_multi_paragraph_trigger_is_advised_even_when_short():
assert "headings" in s.trigger_advice("When adding a record.\n\n## Why\nbecause")
assert "paragraphs" in s.trigger_advice("When adding a record.\n\nAlso, history.")
# --- integration: every body rebuild carries the notes ------------------------
@pytest_asyncio.fixture
async def user_id(_dispose_engine):
from scribe.models import async_session
async with async_session() as session:
uid = (await ensure_user(session, "snippet_notes_itest")).id
await session.commit()
return uid
async def _fields(uid, note_id):
return s.snippet_fields(await s.get_snippet(uid, note_id))
@pytest.mark.integration
async def test_an_edit_to_another_field_keeps_the_notes(user_id):
note = await s.create_snippet(
user_id, name="notes_keep", code=CODE, language="python",
when_to_use="a helper", notes=NOTES,
)
assert (await _fields(user_id, note.id))["notes"] == NOTES
await s.update_snippet(user_id, note.id, when_to_use="a sharper situation")
got = await _fields(user_id, note.id)
assert got["notes"] == NOTES
assert got["when_to_use"] == "a sharper situation"
# And an empty string clears them, like every other field.
await s.update_snippet(user_id, note.id, notes="")
assert (await _fields(user_id, note.id))["notes"] == ""
@pytest.mark.integration
async def test_a_merge_keeps_the_survivors_notes(user_id):
survivor = await s.create_snippet(
user_id, name="notes_merge_a", code=CODE, language="python",
repo="R", path="a.py", symbol="helper", notes=NOTES,
)
source = await s.create_snippet(
user_id, name="notes_merge_b", code=CODE + " # variant", language="python",
repo="R", path="b.py", symbol="helper",
)
await s.merge_snippets(user_id, survivor.id, [source.id])
assert (await _fields(user_id, survivor.id))["notes"] == NOTES
await s.unmerge_snippet(user_id, survivor.id, source.id)
assert (await _fields(user_id, survivor.id))["notes"] == NOTES