CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 12s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python tests (push) Successful in 1m50s
CI & Build / integration (push) Successful in 2m46s
CI & Build / Build & push image (push) Successful in 24s
answer_reference_holders stepped aside whenever the project's shapes spoke for the idea, leaving the row unassessed until the project's next coverage refresh synced the shapes. A lift makes the reference row new, so those shapes had never been synced onto the idea. It now asks the shape ledger to answer that holder straight away (sync_from_shapes for the reference snippet). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
595 lines
29 KiB
Python
595 lines
29 KiB
Python
"""The promotion engine against real Postgres.
|
|
|
|
What the unit lane can't show: a promotion opens the right ledger rows and
|
|
no others, a veto changes nothing but the log, an undo puts back exactly the
|
|
recorded prior state, and each trigger fires on its fixture and stays silent
|
|
on the near-miss beside it.
|
|
|
|
Precedent search and the repeat trigger both rank by meaning, and the lane
|
|
has no embedding model. The search is stubbed to "nothing similar" for every
|
|
test here (`_no_meaning`); the repeat tests stub it to one hit, to pin what
|
|
the trigger does WITH a hit. The ranking itself is the shared semantic
|
|
search, tested where that lives.
|
|
"""
|
|
import uuid
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
from sqlalchemy import select
|
|
|
|
from grimoire.models import async_session
|
|
from grimoire.models.family import (
|
|
FamilyAdoption, FamilyDecision, FamilyIdea, Platform, ProjectPlatform,
|
|
)
|
|
from grimoire.models.milestone import Milestone
|
|
from grimoire.models.note import Note
|
|
from grimoire.models.project import Project
|
|
from grimoire.models.rulebook import Rule, Rulebook, RulebookTopic
|
|
from grimoire.models.user import User
|
|
from grimoire.services import family as family_svc
|
|
from tests.helpers import ensure_user
|
|
|
|
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
|
|
|
|
OWNER = "family_promotion_owner"
|
|
OUTSIDER = "family_promotion_outsider"
|
|
|
|
CRITERIA = {
|
|
"platform_terms": "stated for any Android app that distributes its own APK",
|
|
"platform_problem": "signature continuity is the platform's rule, not one app's",
|
|
"proven": "shipped and updated in place on a device",
|
|
}
|
|
|
|
|
|
async def _purge(username: str) -> None:
|
|
"""SETUP ONLY, as the backup round-trip siblings do: a database call
|
|
after a `yield` in an autouse fixture orphans a pooled connection."""
|
|
async with async_session() as s:
|
|
for user in (await s.execute(select(User).where(User.username == username))).scalars():
|
|
for note in (await s.execute(select(Note).where(Note.user_id == user.id))).scalars():
|
|
await s.delete(note)
|
|
for project in (await s.execute(select(Project).where(Project.user_id == user.id))).scalars():
|
|
await s.delete(project)
|
|
await s.commit()
|
|
|
|
|
|
@pytest_asyncio.fixture(autouse=True)
|
|
async def _clean():
|
|
await _purge(OWNER)
|
|
await _purge(OUTSIDER)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _no_meaning():
|
|
with patch("grimoire.services.embeddings.semantic_search_notes", AsyncMock(return_value=[])):
|
|
yield
|
|
|
|
|
|
async def _platform_id(slug: str) -> int:
|
|
async with async_session() as s:
|
|
return await s.scalar(select(Platform.id).where(
|
|
Platform.slug == slug, Platform.deleted_at.is_(None)))
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def family():
|
|
"""Three projects: two Android apps and a Go service, the pattern note
|
|
in the first, and an outsider's Android app the owner cannot write."""
|
|
android, go = await _platform_id("android-app"), await _platform_id("go")
|
|
async with async_session() as s:
|
|
owner = await ensure_user(s, OWNER)
|
|
outsider = await ensure_user(s, OUTSIDER)
|
|
a = Project(user_id=owner.id, title="android one")
|
|
b = Project(user_id=owner.id, title="android two")
|
|
c = Project(user_id=owner.id, title="go service")
|
|
theirs = Project(user_id=outsider.id, title="someone else's android app")
|
|
s.add_all([a, b, c, theirs])
|
|
await s.flush()
|
|
s.add_all([
|
|
ProjectPlatform(project_id=a.id, platform_id=android, state="declared"),
|
|
ProjectPlatform(project_id=b.id, platform_id=android, state="detected"),
|
|
ProjectPlatform(project_id=c.id, platform_id=go, state="declared"),
|
|
ProjectPlatform(project_id=theirs.id, platform_id=android, state="declared"),
|
|
])
|
|
pattern = Note(user_id=owner.id, project_id=a.id, title="Signed APK lane",
|
|
body="One keystore, two channels, in-place update.")
|
|
s.add(pattern)
|
|
await s.commit()
|
|
return {"owner": owner.id, "outsider": outsider.id, "a": a.id, "b": b.id,
|
|
"c": c.id, "theirs": theirs.id, "note": pattern.id}
|
|
|
|
|
|
async def _promote(f, **overrides):
|
|
kw = dict(
|
|
applies_when="any Android app that ships its own APK",
|
|
platforms=["android-app"], criteria=CRITERIA,
|
|
evidence=["CI green on the release lane", "verified on a device"],
|
|
reason="built twice, proven, stated for the platform",
|
|
)
|
|
kw.update(overrides)
|
|
return await family_svc.promote(f["owner"], f["note"], **kw)
|
|
|
|
|
|
async def _ledger(note_id: int) -> dict[int, str]:
|
|
# Promotion lifts the idea onto a family record; the project's record id
|
|
# still names it.
|
|
note_id = await family_svc.idea_key(note_id)
|
|
async with async_session() as s:
|
|
rows = (await s.execute(
|
|
select(FamilyAdoption.project_id, FamilyAdoption.status)
|
|
.where(FamilyAdoption.idea_id == note_id)
|
|
)).all()
|
|
return dict(rows)
|
|
|
|
|
|
async def _idea(note_id: int) -> FamilyIdea:
|
|
note_id = await family_svc.idea_key(note_id)
|
|
async with async_session() as s:
|
|
return await s.get(FamilyIdea, note_id)
|
|
|
|
|
|
# --- promotion ------------------------------------------------------------------
|
|
|
|
async def test_promotion_opens_a_row_for_every_member_project_the_promoter_can_write(family):
|
|
out = await _promote(family)
|
|
assert out["promoted"] is True
|
|
# Declared and detected both count as membership; the Go service is not
|
|
# on the platform; the outsider's app is not the promoter's to write.
|
|
assert await _ledger(family["note"]) == {family["a"]: "unassessed",
|
|
family["b"]: "unassessed"}
|
|
idea = await _idea(family["note"])
|
|
assert idea.status == "canon" and idea.canon_version == 1
|
|
decision = out["decision"]
|
|
assert decision["action"] == "promote"
|
|
assert decision["after"]["platforms"] == ["android-app"]
|
|
assert decision["evidence"]["criteria"]["proven"] == CRITERIA["proven"]
|
|
assert decision["evidence"]["ledger_rows_opened"] == 2
|
|
|
|
|
|
@pytest.mark.parametrize("key", list(family_svc.CRITERIA_KEYS))
|
|
async def test_each_criterion_vetoes_on_its_own_and_the_veto_is_logged(family, key):
|
|
out = await _promote(family, criteria={**CRITERIA, key: ""})
|
|
assert out["promoted"] is False and out["vetoed_by"] == [key]
|
|
assert (await _idea(family["note"])).status == "candidate"
|
|
assert await _ledger(family["note"]) == {}
|
|
assert out["decision"]["action"] == "propose"
|
|
assert out["decision"]["evidence"]["vetoed_by"] == [key]
|
|
|
|
|
|
async def test_an_unknown_platform_is_refused_before_anything_is_written(family):
|
|
with pytest.raises(ValueError, match="unknown platform"):
|
|
await _promote(family, platforms=["android-app", "no-such-platform"])
|
|
assert await _idea(family["note"]) is None
|
|
|
|
|
|
async def test_someone_who_cannot_write_the_note_cannot_promote_it(family):
|
|
with pytest.raises(ValueError, match="no write access"):
|
|
await family_svc.promote(
|
|
family["outsider"], family["note"], applies_when="x", platforms=["android-app"],
|
|
criteria=CRITERIA, evidence=["e"], reason="r",
|
|
)
|
|
|
|
|
|
# --- the family record ----------------------------------------------------------------
|
|
|
|
async def test_promotion_lifts_the_idea_onto_a_family_record_and_leaves_the_projects_record_alone(family):
|
|
async with async_session() as s:
|
|
s.add(FamilyIdea(note_id=family["note"], status="candidate"))
|
|
await s.flush()
|
|
s.add(FamilyDecision(idea_id=family["note"], action="propose", reason="repeated",
|
|
decided_via="system", user_id=family["owner"]))
|
|
await s.commit()
|
|
|
|
out = await _promote(family)
|
|
lifted = out["idea"]["note_id"]
|
|
assert lifted != family["note"]
|
|
assert out["lifted"] == {"family_record": lifted, "from": family["note"],
|
|
"note": out["lifted"]["note"]}
|
|
async with async_session() as s:
|
|
record = await s.get(Note, lifted)
|
|
origin = await s.get(Note, family["note"])
|
|
assert await s.get(FamilyIdea, family["note"]) is None
|
|
moved = (await s.execute(select(FamilyDecision.action).where(
|
|
FamilyDecision.idea_id == lifted).order_by(FamilyDecision.id))).scalars().all()
|
|
# The family record has no project, belongs to the same person, and names
|
|
# where it came from; the project's record is unchanged.
|
|
assert record.project_id is None and record.user_id == family["owner"]
|
|
assert record.arose_from_id == family["note"] and record.title == origin.title
|
|
assert f"#{family['note']}" in record.body
|
|
assert origin.project_id == family["a"]
|
|
assert origin.body == "One keystore, two channels, in-place update."
|
|
# Its whole history moved with it, the proposal included.
|
|
assert moved == ["propose", "promote"]
|
|
assert out["decision"]["evidence"]["lifted_from"] == family["note"]
|
|
# The project's record still names the idea everywhere an id is taken.
|
|
assert await family_svc.idea_key(family["note"]) == lifted
|
|
assert (await family_svc.get_idea(family["owner"], family["note"]))["note_id"] == lifted
|
|
with pytest.raises(ValueError, match="already canon"):
|
|
await _promote(family)
|
|
|
|
|
|
async def test_a_snippet_stays_in_its_project_as_a_reference_and_its_project_is_answered_adopted(family):
|
|
async with async_session() as s:
|
|
snippet = Note(user_id=family["owner"], project_id=family["a"], note_type="snippet",
|
|
title="ReleaseSigner", body="fun sign(apk: File) = ...",
|
|
data={"language": "kotlin"})
|
|
s.add(snippet)
|
|
await s.commit()
|
|
await s.refresh(snippet)
|
|
out = await family_svc.promote(
|
|
family["owner"], snippet.id, applies_when="any Android app that ships its own APK",
|
|
platforms=["android-app"], criteria=CRITERIA, evidence=["CI green"], reason="proven",
|
|
)
|
|
lifted = out["idea"]["note_id"]
|
|
async with async_session() as s:
|
|
record = await s.get(Note, lifted)
|
|
# The code stays in the project's snippet; the family record carries the idea.
|
|
assert record.note_type == "note"
|
|
refs = await family_svc._reference_ids(lifted)
|
|
assert refs == {snippet.id}
|
|
# The project that wrote the reference has built the idea; the other
|
|
# member project still owes an answer.
|
|
assert await _ledger(lifted) == {family["a"]: "adopted", family["b"]: "unassessed"}
|
|
assert [a["project_id"] for a in out["answered"]] == [family["a"]]
|
|
async with async_session() as s:
|
|
answer = (await s.execute(select(FamilyDecision).where(
|
|
FamilyDecision.idea_id == lifted, FamilyDecision.project_id == family["a"]))).scalars().one()
|
|
assert answer.decided_via == "system" and answer.evidence["source"] == "reference"
|
|
|
|
|
|
async def test_a_reference_the_shape_ledger_already_holds_is_answered_by_the_shapes_at_promotion(family):
|
|
"""The project's own snippet is already stamped `canonical` in its shape
|
|
ledger, so the shapes answer the idea the moment promotion makes that
|
|
snippet a reference — not at the project's next coverage refresh."""
|
|
from grimoire.models.code_shape import CodeShape
|
|
from grimoire.services import family_adoption
|
|
async with async_session() as s:
|
|
snippet = Note(user_id=family["owner"], project_id=family["a"], note_type="snippet",
|
|
title="ReleaseSigner", body="fun sign(apk: File) = ...",
|
|
data={"language": "kotlin"})
|
|
s.add(snippet)
|
|
await s.flush()
|
|
s.add(CodeShape(project_id=family["a"], repo_key="git.example.com/x/y",
|
|
path="app/src/ReleaseSigner.kt", symbol="sign", kind="sym",
|
|
status="canonical", snippet_id=snippet.id, classified_by="mechanical"))
|
|
await s.commit()
|
|
await s.refresh(snippet)
|
|
out = await family_svc.promote(
|
|
family["owner"], snippet.id, applies_when="any Android app that ships its own APK",
|
|
platforms=["android-app"], criteria=CRITERIA, evidence=["CI green"], reason="proven",
|
|
)
|
|
lifted = out["idea"]["note_id"]
|
|
assert (await _ledger(lifted))[family["a"]] == "adopted"
|
|
assert [a["project_id"] for a in out["answered"]] == [family["a"]]
|
|
async with async_session() as s:
|
|
answer = (await s.execute(select(FamilyDecision).where(
|
|
FamilyDecision.idea_id == lifted, FamilyDecision.project_id == family["a"]))).scalars().one()
|
|
assert answer.decided_via == "system"
|
|
assert answer.evidence["source"] == family_adoption.SHAPE_SOURCE
|
|
|
|
|
|
async def test_an_answer_somebody_gave_is_not_overwritten_by_the_reference(family):
|
|
from grimoire.services import family_adoption
|
|
|
|
async with async_session() as s:
|
|
snippet = Note(user_id=family["owner"], project_id=family["b"], note_type="snippet",
|
|
title="Signer", body="...", data={"language": "kotlin"})
|
|
s.add(snippet)
|
|
await s.commit()
|
|
await s.refresh(snippet)
|
|
out = await _promote(family)
|
|
lifted = out["idea"]["note_id"]
|
|
async with async_session() as s:
|
|
row = (await s.execute(select(FamilyAdoption).where(
|
|
FamilyAdoption.idea_id == lifted, FamilyAdoption.project_id == family["b"]))).scalars().one()
|
|
row.status, row.reason, row.canon_version, row.decided_via = "exempt", "store-installed", 1, "agent"
|
|
await s.commit()
|
|
await family_adoption.set_references(family["owner"], lifted, [snippet.id])
|
|
assert (await _ledger(lifted))[family["b"]] == "exempt"
|
|
|
|
|
|
async def test_whoever_could_read_the_idea_through_its_project_can_read_the_family_record(family):
|
|
from grimoire.models.share import ProjectShare
|
|
from grimoire.services import access
|
|
|
|
async with async_session() as s:
|
|
s.add(ProjectShare(project_id=family["a"], shared_with_user_id=family["outsider"],
|
|
permission="viewer", invited_by=family["owner"]))
|
|
await s.commit()
|
|
out = await _promote(family)
|
|
lifted = out["idea"]["note_id"]
|
|
assert await access.get_note_permission(family["outsider"], lifted) == "viewer"
|
|
|
|
|
|
async def test_a_repeat_of_a_lifted_record_says_it_is_canon_and_opens_nothing_new(family):
|
|
out = await _promote(family)
|
|
repeat = await _note_in(family["b"], family["owner"], "One keystore, two channels.")
|
|
async with async_session() as s:
|
|
original = await s.get(Note, family["note"])
|
|
with patch("grimoire.services.embeddings.semantic_search_notes",
|
|
AsyncMock(return_value=[(0.86, original)])):
|
|
hint = await family_svc.repeat_trigger(family["owner"], repeat)
|
|
assert hint and "already" in hint and "family canon" in hint
|
|
async with async_session() as s:
|
|
ideas = (await s.execute(select(FamilyIdea.note_id))).scalars().all()
|
|
assert family["note"] not in ideas and out["idea"]["note_id"] in ideas
|
|
|
|
|
|
# --- undo and retirement ------------------------------------------------------------
|
|
|
|
async def test_undoing_a_promotion_restores_the_prior_state_and_keeps_judged_rows(family):
|
|
out = await _promote(family)
|
|
async with async_session() as s:
|
|
row = (await s.execute(select(FamilyAdoption).where(
|
|
FamilyAdoption.idea_id == out["idea"]["note_id"],
|
|
FamilyAdoption.project_id == family["a"]))).scalars().one()
|
|
row.status, row.canon_version, row.decided_via = "adopted", 1, "agent"
|
|
await s.commit()
|
|
|
|
await family_svc.undo(family["owner"], out["decision"]["id"], reason="promoted too early")
|
|
idea = await _idea(family["note"])
|
|
# Promoted directly, with no proposal before it: the prior state was "not
|
|
# an idea", which an undo records as retired rather than deleting the
|
|
# idea and its log with it.
|
|
assert idea.status == "retired" and idea.applies_when is None
|
|
# The unjudged row goes; the judged one stays as history.
|
|
assert await _ledger(family["note"]) == {family["a"]: "adopted"}
|
|
|
|
again = await _promote(family)
|
|
# Re-promotion moves PAST every version this idea has held, so the kept
|
|
# answer reads as needing a recheck rather than as still agreeing.
|
|
assert again["idea"]["canon_version"] == 2
|
|
assert await _ledger(family["note"]) == {family["a"]: "adopted", family["b"]: "unassessed"}
|
|
|
|
|
|
async def test_retiring_closes_unjudged_rows_and_undoing_it_reopens_them(family):
|
|
await _promote(family)
|
|
out = await family_svc.retire(family["owner"], family["note"], reason="superseded")
|
|
assert (await _idea(family["note"])).status == "retired"
|
|
assert await _ledger(family["note"]) == {}
|
|
await family_svc.undo(family["owner"], out["decision"]["id"], reason="not superseded after all")
|
|
assert (await _idea(family["note"])).status == "canon"
|
|
assert set((await _ledger(family["note"])).values()) == {"unassessed"}
|
|
|
|
|
|
async def test_only_the_latest_idea_decision_can_be_undone(family):
|
|
first = await _promote(family)
|
|
await family_svc.retire(family["owner"], family["note"], reason="superseded")
|
|
with pytest.raises(ValueError, match="came after it"):
|
|
await family_svc.undo(family["owner"], first["decision"]["id"], reason="r")
|
|
|
|
|
|
async def test_an_undo_names_what_it_reversed_as_its_precedent(family):
|
|
out = await _promote(family)
|
|
undo = await family_svc.undo(family["owner"], out["decision"]["id"], reason="r")
|
|
assert undo["decision"]["action"] == "undo"
|
|
assert undo["decision"]["precedent_ids"] == [out["decision"]["id"]]
|
|
async with async_session() as s:
|
|
actions = (await s.execute(select(FamilyDecision.action).where(
|
|
FamilyDecision.idea_id == out["idea"]["note_id"]).order_by(FamilyDecision.id))).scalars().all()
|
|
assert actions == ["promote", "undo"]
|
|
|
|
|
|
# --- triggers -------------------------------------------------------------------------
|
|
|
|
async def _note_in(project_id: int, owner_id: int, body: str) -> Note:
|
|
async with async_session() as s:
|
|
note = Note(user_id=owner_id, project_id=project_id, title="the second build", body=body)
|
|
s.add(note)
|
|
await s.commit()
|
|
await s.refresh(note)
|
|
return note
|
|
|
|
|
|
async def test_a_cross_project_lineage_citation_opens_an_evaluation(family):
|
|
citing = await _note_in(family["b"], family["owner"],
|
|
f"Release lane, matching the first app (#{family['note']}).")
|
|
hint = await family_svc.citation_trigger(family["owner"], citing)
|
|
assert hint and f"#{family['note']}" in hint
|
|
idea = await _idea(family["note"])
|
|
assert idea is not None and idea.status == "candidate"
|
|
async with async_session() as s:
|
|
d = (await s.execute(select(FamilyDecision).where(
|
|
FamilyDecision.idea_id == family["note"]))).scalars().one()
|
|
assert d.decided_via == "system" and d.evidence["trigger"] == "citation"
|
|
|
|
|
|
async def test_a_citation_without_lineage_or_within_one_project_is_silent(family):
|
|
pointer = await _note_in(family["b"], family["owner"], f"See #{family['note']} for context.")
|
|
same_project = await _note_in(family["a"], family["owner"], f"Matching #{family['note']}.")
|
|
assert await family_svc.citation_trigger(family["owner"], pointer) is None
|
|
assert await family_svc.citation_trigger(family["owner"], same_project) is None
|
|
assert await _idea(family["note"]) is None
|
|
|
|
|
|
async def test_a_repeat_on_a_shared_platform_opens_an_evaluation(family):
|
|
"""The meaning match is stubbed — the lane has no model — so this pins
|
|
what the trigger does with a hit: only a hit in ANOTHER project that
|
|
shares a platform counts."""
|
|
repeat = await _note_in(family["b"], family["owner"], "One keystore, two channels.")
|
|
async with async_session() as s:
|
|
original = await s.get(Note, family["note"])
|
|
with patch("grimoire.services.embeddings.semantic_search_notes",
|
|
AsyncMock(return_value=[(0.86, original)])):
|
|
hint = await family_svc.repeat_trigger(family["owner"], repeat)
|
|
assert hint and f"#{family['note']}" in hint
|
|
assert (await _idea(family["note"])).status == "candidate"
|
|
|
|
|
|
async def test_a_repeat_with_no_shared_platform_is_silent(family):
|
|
unrelated = await _note_in(family["c"], family["owner"], "One keystore, two channels.")
|
|
async with async_session() as s:
|
|
original = await s.get(Note, family["note"])
|
|
with patch("grimoire.services.embeddings.semantic_search_notes",
|
|
AsyncMock(return_value=[(0.86, original)])):
|
|
assert await family_svc.repeat_trigger(family["owner"], unrelated) is None
|
|
assert await _idea(family["note"]) is None
|
|
|
|
|
|
async def test_a_repeat_across_kinds_is_silent(family):
|
|
"""A snippet whose only match is a NOTE is not a repeat: a dated
|
|
release log can score above the bar against a signed-APK CI snippet on
|
|
shared vocabulary alone, and would open as a candidate. The stub hands back the
|
|
cross-kind hit directly, so this pins the trigger's own check, not the
|
|
search filter in front of it."""
|
|
async with async_session() as s:
|
|
snippet = Note(user_id=family["owner"], project_id=family["b"], note_type="snippet",
|
|
title="android-release lane", body="sign with the one release key")
|
|
s.add(snippet)
|
|
await s.commit()
|
|
await s.refresh(snippet)
|
|
original = await s.get(Note, family["note"])
|
|
assert original.note_type == "note"
|
|
with patch("grimoire.services.embeddings.semantic_search_notes",
|
|
AsyncMock(return_value=[(0.86, original)])):
|
|
assert await family_svc.repeat_trigger(family["owner"], snippet) is None
|
|
assert await _idea(family["note"]) is None
|
|
|
|
|
|
async def test_a_milestone_closing_on_a_platform_asks_and_one_off_platform_does_not(family):
|
|
async with async_session() as s:
|
|
on_platform = Milestone(user_id=family["owner"], project_id=family["a"], title="m1")
|
|
bare = Project(user_id=family["owner"], title="no platforms")
|
|
s.add_all([on_platform, bare])
|
|
await s.flush()
|
|
off_platform = Milestone(user_id=family["owner"], project_id=bare.id, title="m2")
|
|
s.add(off_platform)
|
|
await s.commit()
|
|
await s.refresh(on_platform)
|
|
await s.refresh(off_platform)
|
|
hint = await family_svc.milestone_trigger(family["owner"], on_platform)
|
|
assert hint and "Android app" in hint
|
|
assert await family_svc.milestone_trigger(family["owner"], off_platform) is None
|
|
assert await family_svc.milestone_is_open(family["owner"], on_platform.id) is True
|
|
|
|
|
|
# --- the note↔topic link ----------------------------------------------------------
|
|
|
|
@pytest_asyncio.fixture
|
|
async def topics(family):
|
|
"""A topic of the owner's with two rules, a second empty one, and one in
|
|
the outsider's rulebook. Titles carry a nonce: rulebooks are not purged
|
|
with the notes, and a topic's title is unique within its rulebook."""
|
|
nonce = uuid.uuid4().hex[:8]
|
|
async with async_session() as s:
|
|
mine = Rulebook(owner_user_id=family["owner"], title=f"family norms {nonce}")
|
|
theirs = Rulebook(owner_user_id=family["outsider"], title=f"their norms {nonce}")
|
|
s.add_all([mine, theirs])
|
|
await s.flush()
|
|
norms = RulebookTopic(rulebook_id=mine.id, title="distribution")
|
|
spare = RulebookTopic(rulebook_id=mine.id, title="spare")
|
|
foreign = RulebookTopic(rulebook_id=theirs.id, title="theirs")
|
|
s.add_all([norms, spare, foreign])
|
|
await s.flush()
|
|
s.add_all([
|
|
Rule(topic_id=norms.id, title="One release key", statement="Sign with one key.",
|
|
order_index=0),
|
|
Rule(topic_id=norms.id, title="No debug signer", statement="Check the signer.",
|
|
order_index=1),
|
|
])
|
|
await s.commit()
|
|
return {"norms": norms.id, "spare": spare.id, "foreign": foreign.id,
|
|
"rulebook": mine.id}
|
|
|
|
|
|
async def test_an_idea_links_to_its_topic_and_its_reads_name_the_rules(family, topics):
|
|
await _promote(family)
|
|
out = await family_svc.set_topic(family["owner"], family["note"], topics["norms"])
|
|
assert out["topic_id"] == topics["norms"]
|
|
assert [r["title"] for r in out["topic"]["rules"]] == ["One release key", "No debug signer"]
|
|
# Where the norms are found is not what they say: the version holds.
|
|
assert out["canon_version"] == 1
|
|
|
|
idea = await family_svc.get_idea(family["owner"], family["note"])
|
|
assert idea["topic"]["rulebook_id"] == topics["rulebook"]
|
|
assert len(idea["topic"]["rules"]) == 2
|
|
# Promotion lifted the idea onto its family record.
|
|
key = await family_svc.idea_key(family["note"])
|
|
[listed] = [i for i in await family_svc.list_ideas(family["owner"]) if i["note_id"] == key]
|
|
assert listed["topic"] == {"id": topics["norms"], "title": "distribution",
|
|
"rulebook_id": topics["rulebook"]}
|
|
|
|
|
|
async def test_zero_unlinks_the_topic(family, topics):
|
|
await _promote(family)
|
|
await family_svc.set_topic(family["owner"], family["note"], topics["norms"])
|
|
out = await family_svc.set_topic(family["owner"], family["note"], 0)
|
|
assert out["topic_id"] is None and out["topic"] is None
|
|
|
|
|
|
async def test_a_topic_outside_the_callers_rulebooks_is_refused(family, topics):
|
|
await _promote(family)
|
|
with pytest.raises(ValueError, match="rulebook you own"):
|
|
await family_svc.set_topic(family["owner"], family["note"], topics["foreign"])
|
|
assert (await _idea(family["note"])).topic_id is None
|
|
|
|
|
|
async def test_one_topic_carries_one_ideas_norms(family, topics):
|
|
await _promote(family)
|
|
await family_svc.set_topic(family["owner"], family["note"], topics["norms"])
|
|
async with async_session() as s:
|
|
other = Note(user_id=family["owner"], project_id=family["b"], title="Another idea",
|
|
body="something else every Android app needs")
|
|
s.add(other)
|
|
await s.flush()
|
|
s.add(FamilyIdea(note_id=other.id, status="candidate"))
|
|
await s.commit()
|
|
other_id = other.id
|
|
with pytest.raises(ValueError, match="already carries the norms"):
|
|
await family_svc.set_topic(family["owner"], other_id, topics["norms"])
|
|
# Re-linking the same idea to its own topic is not a conflict.
|
|
await family_svc.set_topic(family["owner"], family["note"], topics["norms"])
|
|
|
|
|
|
async def test_someone_who_cannot_write_the_idea_cannot_link_it(family, topics):
|
|
await _promote(family)
|
|
with pytest.raises(ValueError, match="no write access"):
|
|
await family_svc.set_topic(family["outsider"], family["note"], topics["spare"])
|
|
|
|
|
|
async def test_a_citation_of_a_task_or_of_a_projects_own_overview_is_silent(family):
|
|
"""A task is work in one project and an overview describes one project:
|
|
neither carries a shared idea, so citing either with a lineage word opens
|
|
nothing."""
|
|
async with async_session() as s:
|
|
task = Note(user_id=family["owner"], project_id=family["a"], status="todo",
|
|
title="Ship the signed lane", body="do it")
|
|
overview = Note(user_id=family["owner"], project_id=family["a"],
|
|
title="android one: start here", body="what the project is")
|
|
s.add_all([task, overview])
|
|
await s.commit()
|
|
ids = (task.id, overview.id)
|
|
for source in ids:
|
|
citing = await _note_in(family["b"], family["owner"], f"Matching #{source}.")
|
|
assert await family_svc.citation_trigger(family["owner"], citing) is None
|
|
assert await _idea(source) is None
|
|
|
|
|
|
async def test_a_repeat_of_a_projects_own_overview_is_silent(family):
|
|
async with async_session() as s:
|
|
overview = Note(user_id=family["owner"], project_id=family["a"],
|
|
title="android one: start here", body="One keystore, two channels.")
|
|
s.add(overview)
|
|
await s.commit()
|
|
await s.refresh(overview)
|
|
repeat = await _note_in(family["b"], family["owner"], "One keystore, two channels.")
|
|
with patch("grimoire.services.embeddings.semantic_search_notes",
|
|
AsyncMock(return_value=[(0.9, overview)])):
|
|
assert await family_svc.repeat_trigger(family["owner"], repeat) is None
|
|
assert await _idea(overview.id) is None
|
|
|
|
|
|
async def test_a_candidate_counts_as_unevaluated_until_someone_other_than_the_system_decides(family):
|
|
await family_svc.propose(family["owner"], family["note"], reason="opened by a trigger",
|
|
trigger="repeat", decided_via="system")
|
|
got = await family_svc.unevaluated_candidates(family["owner"], family["a"])
|
|
assert got == {"count": 1, "ideas": [{"id": family["note"], "title": "Signed APK lane"}]}
|
|
assert (await family_svc.unevaluated_candidates(family["owner"], family["b"]))["count"] == 0
|
|
# An agent's evaluation that holds it as a candidate is an evaluation.
|
|
await family_svc.promote(family["owner"], family["note"], applies_when="",
|
|
platforms=["android-app"], criteria={}, evidence=[],
|
|
reason="held: not stated for the platform")
|
|
assert (await _idea(family["note"])).status == "candidate"
|
|
assert (await family_svc.unevaluated_candidates(family["owner"], family["a"]))["count"] == 0
|