diff --git a/plugin/skills/family-canon/SKILL.md b/plugin/skills/family-canon/SKILL.md index c3e1d62e..890a1117 100644 --- a/plugin/skills/family-canon/SKILL.md +++ b/plugin/skills/family-canon/SKILL.md @@ -45,6 +45,10 @@ face, and if so write the note that carries the idea. enter_project's `family` key counts what this project owes the family: `unassessed`, `owed`, `needs_recheck`, each with the call that lists them. +It also names this project's own records that a trigger proposed and nobody +evaluated (`candidates`): you hold their context, so evaluate each as above, +or `retire_family_idea` one that is not an idea at all (a task, a note about +this project alone). Answer an idea **when your work reaches its area**, not as a chore list at session start — the count is there so it is never invisible, not so it preempts the operator's task. diff --git a/src/grimoire/mcp/tools/projects.py b/src/grimoire/mcp/tools/projects.py index 2ea28a5f..2156c458 100644 --- a/src/grimoire/mcp/tools/projects.py +++ b/src/grimoire/mcp/tools/projects.py @@ -140,7 +140,10 @@ async def enter_project(project_id: int) -> dict: version (`needs_recheck`) — each with the list_family_adoptions call that lists them. Answer an unassessed idea when your work reaches its area (get_family_adoption, then assess_family_adoption, or classify the code - against it); the family-canon skill has the order. + against it); the family-canon skill has the order. It also counts this + project's own records that a trigger proposed as family ideas and nobody + has evaluated (`candidates`), naming them: this project's session holds + their context, so it is the one asked to promote or retire each. `inception` appears ONLY when the project is yours and nobody has decided what it inherits: it carries the current defaults diff --git a/src/grimoire/services/family.py b/src/grimoire/services/family.py index f457aa98..69a2d1c4 100644 --- a/src/grimoire/services/family.py +++ b/src/grimoire/services/family.py @@ -115,6 +115,9 @@ _LINEAGE = re.compile( ) # How far before a `#N` the lineage word may sit: the same clause, roughly. _LINEAGE_WINDOW = 80 +# A quoted title, straight or curly quotes, on one line. Bounded so a stray +# quote mark cannot blank a whole paragraph. +_QUOTED = re.compile(r'"[^"\n]{1,200}"|\u201c[^\u201d\n]{1,200}\u201d') # Note kinds the repeat trigger compares: recorded knowledge and shapes, not # the to-do list — and each only against its own kind. A repeat is the same @@ -127,6 +130,38 @@ _LINEAGE_WINDOW = 80 # once the idea is canon. _REPEAT_KINDS = ("snippet", "note") + +def about_its_own_project(title: str | None, project_title: str | None) -> bool: + """Whether a record's title opens with its own project's name. + + "Storehouse: start here", "Torn Stars — Economy System": a record named + for its project describes that project — its overview, its founding + decisions, one system of one game — and cannot carry an idea every + project on a platform shares, however closely another project's + overview resembles it. The name must end at a word boundary, so a + project called "Sync" does not claim "Syncthing relay". + """ + t = (title or "").strip().casefold() + p = (project_title or "").strip().casefold() + if not p or not t.startswith(p): + return False + return len(t) == len(p) or not t[len(p)].isalnum() + + +def can_carry_idea(*, is_task: bool, note_type: str | None, title: str | None, + project_title: str | None) -> bool: + """Whether a record is the kind a trigger may open as a family candidate. + + A task is a unit of work in one project, so it is never the idea itself: + an idea it carries is written up as a note and proposed. Only recorded + knowledge and shapes (`_REPEAT_KINDS`) qualify, and not a record about + its own project (`about_its_own_project`). The triggers open candidates + without anyone reading them, so they hold to this; an agent who has read + a record may still propose it by hand.""" + if is_task or (note_type or "note") not in _REPEAT_KINDS: + return False + return not about_its_own_project(title, project_title) + MEMBER_STATES = ("declared", "detected") _IDEA_ACTIONS = ("propose", "promote", "revise", "retire") @@ -862,9 +897,15 @@ def lineage_citations(text: str | None) -> list[int]: from grimoire.services.record_refs import REF_RE found: list[int] = [] - for m in REF_RE.finditer(text or ""): + text = text or "" + # A quoted span is a record's TITLE, written beside its id by convention + # (#12 "Release parsing and matching"). Its words describe that record, + # not this one's lineage, so they are blanked before the window is read; + # blanked to the same length, so match positions stay valid. + bare = _QUOTED.sub(lambda q: " " * len(q.group(0)), text) + for m in REF_RE.finditer(text): start = max(0, m.start() - _LINEAGE_WINDOW) - window = text[start:m.start()] + window = bare[start:m.start()] window = re.split(r"[\n.;]", window)[-1] if _LINEAGE.search(window): n = int(m.group(1)) @@ -873,6 +914,41 @@ def lineage_citations(text: str | None) -> list[int]: return found +async def _project_titles(session, project_ids: set[int]) -> dict[int, str]: + return dict((await session.execute( + select(Project.id, Project.title).where(Project.id.in_(project_ids)) + )).all()) + + +async def unevaluated_candidates(user_id: int, project_id: int, *, limit: int = 5) -> dict: + """This project's own records that are family candidates nobody has + evaluated: every decision on them so far is the system's own proposal. + + The triggers open candidates; nothing else asks anyone to evaluate one, + so without a reader they only accumulate. The project a candidate lives + in is where its context is, so its own sessions are asked, on entering. + {count, ideas: [{id, title}]}, oldest first, up to ``limit`` named.""" + judged = select(FamilyDecision.idea_id).where( + FamilyDecision.idea_id == FamilyIdea.note_id, + FamilyDecision.decided_via != "system", + ).exists() + where = ( + FamilyIdea.status == "candidate", Note.project_id == project_id, + Note.deleted_at.is_(None), access.readable_notes_clause(user_id), ~judged, + ) + async with async_session() as session: + count = (await session.execute( + select(func.count()).select_from(FamilyIdea) + .join(Note, Note.id == FamilyIdea.note_id).where(*where) + )).scalar() or 0 + rows = (await session.execute( + select(Note.id, Note.title).select_from(FamilyIdea) + .join(Note, Note.id == FamilyIdea.note_id).where(*where) + .order_by(FamilyIdea.created_at.asc()).limit(limit) + )).all() if count else [] + return {"count": int(count), "ideas": [{"id": i, "title": t} for i, t in rows]} + + async def _member_platform_ids(session, project_id: int) -> set[int]: return set((await session.execute( select(ProjectPlatform.platform_id).where( @@ -902,14 +978,20 @@ async def citation_trigger(user_id: int, note) -> str | None: return None async with async_session() as session: rows = (await session.execute( - select(Note.id, Note.title, Note.project_id, Project.title) + select(Note.id, Note.title, Note.project_id, Project.title, + Note.status, Note.note_type) .join(Project, Project.id == Note.project_id) .where( Note.id.in_(cited), Note.deleted_at.is_(None), Note.project_id.is_not(None), Note.project_id != note.project_id, ) )).all() - for source_id, source_title, _pid, project_title in sorted(rows, key=lambda r: cited.index(r[0])): + for source_id, source_title, _pid, project_title, status, note_type in sorted( + rows, key=lambda r: cited.index(r[0]), + ): + if not can_carry_idea(is_task=status is not None, note_type=note_type, + title=source_title, project_title=project_title): + continue if not await access.can_write_note(user_id, source_id): continue idea, created = await propose( @@ -944,6 +1026,9 @@ async def repeat_trigger(user_id: int, note) -> str | None: if not getattr(note, "project_id", None) or note.is_task or kind not in _REPEAT_KINDS: return None async with async_session() as session: + titles = await _project_titles(session, {note.project_id}) + if about_its_own_project(note.title, titles.get(note.project_id)): + return None mine = await _member_platform_ids(session, note.project_id) if not mine: return None @@ -958,6 +1043,10 @@ async def repeat_trigger(user_id: int, note) -> str | None: if (other.note_type or "note") != kind: continue async with async_session() as session: + other_project = (await _project_titles(session, {other.project_id})).get(other.project_id) + if not can_carry_idea(is_task=other.is_task, note_type=other.note_type, + title=other.title, project_title=other_project): + continue shared = mine & await _member_platform_ids(session, other.project_id) if not shared or not await access.can_write_note(user_id, other.id): continue diff --git a/src/grimoire/services/family_adoption.py b/src/grimoire/services/family_adoption.py index e8ff5c79..75659a31 100644 --- a/src/grimoire/services/family_adoption.py +++ b/src/grimoire/services/family_adoption.py @@ -1222,10 +1222,13 @@ async def _shapes_follow(user_id: int, project_id: int, idea_id: int, outcome: s # ideas themselves by retrieval, and the owed answers filed while a task was # open, handed back when it closes. -def family_line(project_id: int, cells: list[dict]) -> dict | None: +def family_line(project_id: int, cells: list[dict], + candidates: dict | None = None) -> dict | None: """The `family` line enter_project carries: what this project has not - answered, owes, or answered against an older canon version. None when - all three are zero — the key is attached only when it asks something. + answered, owes, or answered against an older canon version — and which + of its own records are family candidates nobody has evaluated + (`family.unevaluated_candidates`). None when all are zero — the key is + attached only when it asks something. Shown on EVERY entry (the step settled this), not only when a session touches a platform: entering is when the agent chooses what to work on, @@ -1234,7 +1237,9 @@ def family_line(project_id: int, cells: list[dict]) -> dict | None: unassessed = sum(1 for c in cells if c["in_scope"] and c["status"] == "unassessed") owed = sum(1 for c in cells if c["status"] == "owed") recheck = sum(1 for c in cells if c["needs_recheck"]) - if not (unassessed or owed or recheck): + candidates = candidates or {} + n_cand = int(candidates.get("count") or 0) + if not (unassessed or owed or recheck or n_cand): return None parts, calls = [], {} if unassessed: @@ -1246,9 +1251,23 @@ def family_line(project_id: int, cells: list[dict]) -> dict | None: if recheck: parts.append(f"{recheck} to recheck") calls["needs_recheck"] = f"list_family_adoptions(project_id={project_id}, needs_recheck=true)" + if n_cand: + # Named by id: the list tool pages every project's ideas, and these + # are the few that this project's own session is placed to judge. + named = ", ".join(f"#{c['id']} \"{c['title']}\"" for c in candidates.get("ideas") or []) + more = n_cand - len(candidates.get("ideas") or []) + parts.append(f"{n_cand} of this project's own record{'s' if n_cand != 1 else ''} " + "proposed as family ideas, never evaluated") + calls["candidates"] = ( + f"get_family_idea(id) for each — {named}" + + (f", and {more} more (list_family_ideas(status=\"candidate\"))" if more > 0 else "") + + "; then promote_family_idea if all three criteria hold, or " + "retire_family_idea if it is not an idea at all" + ) return { "line": "family canon on this project's platforms: " + " · ".join(parts), "unassessed": unassessed, "owed": owed, "needs_recheck": recheck, + "candidates": n_cand, "calls": calls, "answer_with": ("get_family_adoption(project_id, idea_id) reads one with its " "precedents; assess_family_adoption answers it — or classify_shapes " @@ -1257,8 +1276,11 @@ def family_line(project_id: int, cells: list[dict]) -> dict | None: async def family_readout(user_id: int, project_id: int) -> dict | None: + from grimoire.services import family as family_svc + matrix = await adoption_matrix(user_id, project_id=project_id) - return family_line(project_id, matrix["cells"]) + candidates = await family_svc.unevaluated_candidates(user_id, project_id) + return family_line(project_id, matrix["cells"], candidates) # --- whether the line reached the project --------------------------------------- @@ -1285,7 +1307,8 @@ async def record_entry(user_id: int, project_id: int, line: dict | None, *, if failed: details["readout_failed"] = True if line: - details.update({k: int(line.get(k) or 0) for k in ("unassessed", "owed", "needs_recheck")}) + details.update({k: int(line.get(k) or 0) + for k in ("unassessed", "owed", "needs_recheck", "candidates")}) try: async with async_session() as session: session.add(AppLog( diff --git a/tests/test_family.py b/tests/test_family.py index f11ae610..5dc66c10 100644 --- a/tests/test_family.py +++ b/tests/test_family.py @@ -161,3 +161,39 @@ async def test_re_saving_a_closed_milestone_asks_nothing(): out = await update_milestone(project_id=3, milestone_id=5, status="done") assert "family_hint" not in out trigger.assert_not_awaited() + + +def test_a_lineage_word_inside_a_quoted_title_is_not_lineage(): + """Records are cited with their titles beside them; a title's words + describe THAT record, so they cannot claim the next citation's lineage.""" + text = ('- Tasks: #3510 "Release parsing and matching, verified", #7407 "Downloads", ' + '#20 “mirrors the old flow”, #30') + assert lineage_citations(text) == [] + # The convention itself still reads: a lineage word outside the quotes. + assert lineage_citations('Ported from #12 "Signed APK lane".') == [12] + + +@pytest.mark.parametrize(("title", "project", "about"), [ + ("Storehouse: start here", "Storehouse", True), + ("Torn Stars — Economy System", "Torn Stars", True), + ("storehouse", "Storehouse", True), + ("Syncthing relay", "Sync", False), + ("Signed APK lane", "Storehouse", False), + ("Storehouse: start here", "", False), +]) +def test_a_record_named_for_its_own_project_is_about_that_project(title, project, about): + from grimoire.services.family import about_its_own_project + + assert about_its_own_project(title, project) is about + + +def test_only_knowledge_and_shapes_not_about_one_project_can_carry_an_idea(): + from grimoire.services.family import can_carry_idea + + kw = dict(title="Signed APK lane", project_title="android one") + assert can_carry_idea(is_task=False, note_type="note", **kw) + assert can_carry_idea(is_task=False, note_type="snippet", **kw) + assert not can_carry_idea(is_task=True, note_type="note", **kw) + assert not can_carry_idea(is_task=False, note_type="lesson", **kw) + assert not can_carry_idea(is_task=False, note_type="note", + title="android one: start here", project_title="android one") diff --git a/tests/test_family_delivery.py b/tests/test_family_delivery.py index c207e465..1ad405b1 100644 --- a/tests/test_family_delivery.py +++ b/tests/test_family_delivery.py @@ -97,3 +97,15 @@ def test_every_surface_that_meets_family_canon_points_at_the_skill(): assert "`family`" in tool_doc("grimoire.mcp.tools.projects", "enter_project") assert "family_owed" in tool_doc("grimoire.mcp.tools.tasks", "update_task") assert "family_owed" in skill_text("reporting-back") + + +def test_the_line_names_this_projects_own_unevaluated_candidates(): + cand = {"count": 3, "ideas": [{"id": 7, "title": "Signed APK lane"}, + {"id": 9, "title": "Outbox"}]} + line = family_line(5, [], cand) + assert line["candidates"] == 3 + assert line["line"].endswith("3 of this project's own records proposed as family ideas, never evaluated") + call = line["calls"]["candidates"] + assert '#7 "Signed APK lane", #9 "Outbox"' in call and "and 1 more" in call + assert "promote_family_idea" in call and "retire_family_idea" in call + assert family_line(5, [], {"count": 0, "ideas": []}) is None diff --git a/tests/test_integration_family_promotion.py b/tests/test_integration_family_promotion.py index 618b1347..cac35e4b 100644 --- a/tests/test_integration_family_promotion.py +++ b/tests/test_integration_family_promotion.py @@ -396,3 +396,49 @@ 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