diff --git a/alembic/versions/0141_family_records.py b/alembic/versions/0141_family_records.py new file mode 100644 index 00000000..3f16ca41 --- /dev/null +++ b/alembic/versions/0141_family_records.py @@ -0,0 +1,194 @@ +"""Family canon gets a family home: every promoted idea moves off the project +record it was written on and onto a family record with no project. + +Revision ID: 0141 +Revises: 0140 +Create Date: 2026-12-04 + +Promotion now lifts an idea (services/family.py `_lift`); this does the same +for every idea promoted before it did. For each idea with a `promote` +decision whose note still belongs to a project: + +- a note with no project is made, owned by the same person, carrying the + project record's text and a closing line naming it (`arose_from_id`); + a snippet's family record is a note, because the code stays in the + project's snippet; +- the idea's state, platforms, references, ledger and decision log move + onto it; +- the project's record, when it is a snippet, becomes a reference + implementation; +- the project record's shares and its project's shares become shares of the + family record, at the highest permission each target held; +- a project that holds a reference snippet and has not answered the idea + (and whose shapes say nothing about it) is answered `adopted` by the + system, naming the snippet. + +Candidates are left on their project's record: proposing writes nothing a +project owns, and they lift when promoted. The family records get their +embeddings from the startup backfill, which indexes any note without one. + +Downgrade moves each idea back onto the record it came from and deletes the +family record. The answers given here stay: they are true either way. +""" +import json + +import sqlalchemy as sa +from alembic import op + +revision = "0141" +down_revision = "0140" +branch_labels = None +depends_on = None + +_RANK = {"viewer": 1, "editor": 2, "admin": 3, "owner": 4} +_SHAPE_ANSWERS = ("instance", "variant", "canonical") + + +def _family_body(body: str, origin_id: int, title: str, project_title: str | None, + is_snippet: bool) -> str: + # Kept equal to services/family._family_body. + where = f" ({project_title})" if project_title else "" + kind = "reference implementation" if is_snippet else "original record" + return (f"{(body or '').rstrip()}\n\n---\n" + f"Lifted from #{origin_id} “{title}”{where}, its {kind}.\n") + + +def _move(conn, old: int, new: int) -> None: + topic = conn.execute(sa.text( + "SELECT topic_id FROM family_ideas WHERE note_id = :old"), {"old": old}).scalar() + # One idea per topic (uq_family_ideas_topic): release it first. + conn.execute(sa.text("UPDATE family_ideas SET topic_id = NULL WHERE note_id = :old"), + {"old": old}) + conn.execute(sa.text( + "INSERT INTO family_ideas (note_id, status, applies_when, canon_version, topic_id, " + "created_at, updated_at) SELECT :new, status, applies_when, canon_version, :topic, " + "created_at, now() FROM family_ideas WHERE note_id = :old"), + {"old": old, "new": new, "topic": topic}) + for table, column in (("family_idea_platforms", "note_id"), + ("family_idea_references", "idea_id"), + ("family_adoptions", "idea_id"), + ("family_decisions", "idea_id")): + conn.execute(sa.text(f"UPDATE {table} SET {column} = :new WHERE {column} = :old"), + {"old": old, "new": new}) + conn.execute(sa.text("DELETE FROM family_ideas WHERE note_id = :old"), {"old": old}) + + +def _copy_shares(conn, origin_id: int, project_id: int, family_id: int) -> None: + rows = conn.execute(sa.text( + "SELECT shared_with_user_id, shared_with_group_id, permission, invited_by " + "FROM note_shares WHERE note_id = :n " + "UNION ALL " + "SELECT shared_with_user_id, shared_with_group_id, permission, invited_by " + "FROM project_shares WHERE project_id = :p"), + {"n": origin_id, "p": project_id}).all() + best: dict[tuple, tuple[str, int]] = {} + for user, group, perm, invited_by in rows: + held = best.get((user, group)) + if held is None or _RANK.get(perm, 0) > _RANK.get(held[0], 0): + best[(user, group)] = (perm, invited_by) + for (user, group), (perm, invited_by) in best.items(): + conn.execute(sa.text( + "INSERT INTO note_shares (note_id, shared_with_user_id, shared_with_group_id, " + "permission, invited_by, created_at, updated_at) " + "VALUES (:n, :u, :g, :perm, :by, now(), now())"), + {"n": family_id, "u": user, "g": group, "perm": perm, "by": invited_by}) + + +def _answer_reference_holders(conn, idea_id: int, user_id: int) -> None: + # Kept equal to services/family_adoption.answer_reference_holders. + status, version = conn.execute(sa.text( + "SELECT status, canon_version FROM family_ideas WHERE note_id = :i"), + {"i": idea_id}).one() + if status != "canon": + return + holders = conn.execute(sa.text( + "SELECT DISTINCT ON (n.project_id) n.project_id, n.id, n.title, p.title " + "FROM family_idea_references r JOIN notes n ON n.id = r.snippet_id " + "JOIN projects p ON p.id = n.project_id " + "WHERE r.idea_id = :i AND n.deleted_at IS NULL ORDER BY n.project_id, n.id"), + {"i": idea_id}).all() + for project_id, snippet_id, snippet_title, project_title in holders: + row = conn.execute(sa.text( + "SELECT id, status FROM family_adoptions WHERE project_id = :p AND idea_id = :i"), + {"p": project_id, "i": idea_id}).first() + if row is None or row[1] != "unassessed": + continue + spoken = conn.execute(sa.text( + "SELECT 1 FROM code_shapes WHERE project_id = :p AND vanished_at IS NULL " + "AND status = ANY(:statuses) AND snippet_id IN " + "(SELECT snippet_id FROM family_idea_references WHERE idea_id = :i) LIMIT 1"), + {"p": project_id, "i": idea_id, "statuses": list(_SHAPE_ANSWERS)}).first() + if spoken: + continue + reason = (f"{project_title} holds a reference implementation of this idea: " + f"#{snippet_id} “{snippet_title}”.") + conn.execute(sa.text( + "UPDATE family_adoptions SET status = 'adopted', reason = :reason, " + "canon_version = :v, assessed_at = now(), decided_via = 'system', " + "updated_at = now() WHERE id = :id"), + {"reason": reason, "v": version, "id": row[0]}) + conn.execute(sa.text( + "INSERT INTO family_decisions (idea_id, project_id, action, reason, before, after, " + "evidence, precedent_ids, decided_via, user_id, created_at) VALUES " + "(:i, :p, 'assess', :reason, CAST(:before AS jsonb), CAST(:after AS jsonb), " + "CAST(:evidence AS jsonb), '[]'::jsonb, 'system', :u, now())"), + {"i": idea_id, "p": project_id, "reason": reason, "u": user_id, + "before": json.dumps({"status": "unassessed", "reason": "", "canon_version": None}), + "after": json.dumps({"status": "adopted", "reason": reason, + "canon_version": version}), + "evidence": json.dumps({"evidence": [f"#{snippet_id} {snippet_title}"], + "source": "reference"})}) + + +def lift_promoted_ideas(conn) -> list[tuple[int, int]]: + """Lift every promoted idea still on a project's record. Returns + (project record, family record) pairs. Safe to run twice: a lifted idea + has no project and is skipped.""" + ideas = conn.execute(sa.text( + "SELECT n.id, n.user_id, n.project_id, n.title, n.body, n.tags, n.note_type, " + "p.title FROM family_ideas fi JOIN notes n ON n.id = fi.note_id " + "LEFT JOIN projects p ON p.id = n.project_id " + "WHERE n.project_id IS NOT NULL AND n.deleted_at IS NULL AND EXISTS (" + " SELECT 1 FROM family_decisions d WHERE d.idea_id = fi.note_id " + " AND d.action = 'promote') ORDER BY n.id")).all() + moved = [] + for origin_id, user_id, project_id, title, body, tags, note_type, project_title in ideas: + is_snippet = note_type == "snippet" + new = conn.execute(sa.text( + "INSERT INTO notes (user_id, title, body, tags, note_type, task_kind, " + "arose_from_id, project_id, created_at, updated_at) VALUES " + "(:u, :title, :body, :tags, :kind, 'work', :origin, NULL, now(), now()) " + "RETURNING id"), + {"u": user_id, "title": title, + "body": _family_body(body, origin_id, title, project_title, is_snippet), + "tags": list(tags or []), "kind": "note" if is_snippet else (note_type or "note"), + "origin": origin_id}).scalar() + _move(conn, origin_id, new) + if is_snippet: + conn.execute(sa.text( + "INSERT INTO family_idea_references (idea_id, snippet_id, created_at) " + "VALUES (:i, :s, now()) ON CONFLICT DO NOTHING"), + {"i": new, "s": origin_id}) + _copy_shares(conn, origin_id, project_id, new) + _answer_reference_holders(conn, new, user_id) + moved.append((origin_id, new)) + return moved + + +def upgrade() -> None: + lift_promoted_ideas(op.get_bind()) + + +def downgrade() -> None: + conn = op.get_bind() + pairs = conn.execute(sa.text( + "SELECT n.id, n.arose_from_id FROM family_ideas fi JOIN notes n ON n.id = fi.note_id " + "JOIN notes origin ON origin.id = n.arose_from_id " + "WHERE n.project_id IS NULL AND origin.project_id IS NOT NULL " + "AND NOT EXISTS (SELECT 1 FROM family_ideas o WHERE o.note_id = origin.id)")).all() + for family_id, origin_id in pairs: + conn.execute(sa.text( + "DELETE FROM family_idea_references WHERE idea_id = :f AND snippet_id = :o"), + {"f": family_id, "o": origin_id}) + _move(conn, family_id, origin_id) + conn.execute(sa.text("DELETE FROM notes WHERE id = :f"), {"f": family_id}) diff --git a/docs/features.md b/docs/features.md index ef094875..ccc575ad 100644 --- a/docs/features.md +++ b/docs/features.md @@ -45,7 +45,7 @@ A task is a note with a status (`todo`, `in_progress`, `done`, `cancelled`), plu ## Family canon -Projects on the same platform (Android apps, Go services, ...) share good ideas. An idea promoted to the family's canon reaches every project on that platform, and each answers it: adopted, a variant with its reason, or owed (filed as a task). `/family` shows the ideas and every project's answers. +Projects on the same platform (Android apps, Go services, ...) share good ideas. An idea promoted to the family's canon moves onto a family record that belongs to no project, so the family owns it and the project that first wrote it keeps its own record as a reference. It reaches every project on that platform, and each answers it: adopted, a variant with its reason, or owed (filed as a task). `/family` shows the ideas and every project's answers. ## Design systems diff --git a/frontend/src/api/family.ts b/frontend/src/api/family.ts index 9f8b654b..9869b353 100644 --- a/frontend/src/api/family.ts +++ b/frontend/src/api/family.ts @@ -37,12 +37,24 @@ export interface FamilyIdea { title: string; note_type: string; is_task: boolean; + /** The project whose record carries the idea — a candidate's. Null once + * the idea is promoted: canon lives on a family record with no project. */ project_id: number | null; + project_title?: string | null; + /** Reference implementations: project snippets a project can start from. */ + references?: IdeaReference[]; platforms: string[]; created_at: string | null; updated_at: string | null; } +export interface IdeaReference { + id: number; + title: string; + project_id: number | null; + project_title: string | null; +} + /** A state snapshot a decision records — slugs, never ids. */ export interface IdeaSnapshot { status: IdeaStatus; diff --git a/frontend/src/views/FamilyView.vue b/frontend/src/views/FamilyView.vue index 7c039b82..ac0da208 100644 --- a/frontend/src/views/FamilyView.vue +++ b/frontend/src/views/FamilyView.vue @@ -266,6 +266,21 @@ onMounted(load); {{ idea.status }} v{{ idea.canon_version }} +
+
+ Proposed in
+
Applies when: {{ idea.applies_when }}
{{ p }}
@@ -397,6 +412,7 @@ onMounted(load);
.fam-applies { margin: 0.3rem 0 0; font-size: 0.85rem; color: var(--fs-text-secondary); }
.fam-platforms { display: flex; flex-wrap: wrap; gap: 0.3rem; margin-top: 0.35rem; }
.fam-topic { margin: 0.35rem 0 0; }
+.fam-home { margin: 0.25rem 0 0; }
.fam-chip {
font-family: var(--fs-font-mono);
font-size: 0.72rem;
diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json
index 75f46932..cd452eb3 100644
--- a/plugin/.claude-plugin/plugin.json
+++ b/plugin/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon, reviewing-tests), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
- "version": "2026.12.04.1936",
+ "version": "2026.12.04.1944",
"author": {
"name": "Bryan Van Deusen"
},
diff --git a/plugin/skills/family-canon/SKILL.md b/plugin/skills/family-canon/SKILL.md
index 890a1117..23f48b95 100644
--- a/plugin/skills/family-canon/SKILL.md
+++ b/plugin/skills/family-canon/SKILL.md
@@ -37,6 +37,17 @@ wrote what you wrote:
topic with `set_family_topic`. The note teaches; the topic's rules bind,
and every assessment then reads them beside the idea.
+The candidate usually lives in another project; deciding about it is still
+yours to do from here. A decision about an idea changes the family's state,
+not the project that wrote it down, so it needs nobody's permission.
+
+**Promotion gives the idea a family home.** The idea moves onto a family
+record with no project, and the response's `lifted` names it. The project's
+record stays as it was; a snippet becomes a reference implementation, and
+its project is answered `adopted`. From then on the family record is the
+canon: to revise the idea, edit that record and `revise_family_idea` it. Any
+project's record id still names the idea in the family tools.
+
A milestone closing on a platform project hints without recording anything:
ask whether what it built is something every project on the platform will
face, and if so write the note that carries the idea.
diff --git a/src/grimoire/mcp/tools/family.py b/src/grimoire/mcp/tools/family.py
index a78f28ee..0f170932 100644
--- a/src/grimoire/mcp/tools/family.py
+++ b/src/grimoire/mcp/tools/family.py
@@ -114,6 +114,14 @@ async def promote_family_idea(
canon before, its version moves, so earlier answers read as needing a
recheck.
+ An idea on a project's record moves onto a FAMILY RECORD with no project
+ (`lifted` in the response names it): the family owns canon, so revising
+ it edits that record, never a project's. The project's record stays its
+ own; a snippet becomes a reference implementation, and its project is
+ answered `adopted`. Its id still names the idea in every family call.
+ Deciding about an idea from any project's session needs no permission:
+ it changes the family's state, not the project the record came from.
+
Args:
note_id: the record that carries the idea.
applies_when: when it applies, in platform terms.
@@ -188,9 +196,10 @@ async def revise_family_idea(
note_id: int, reason: str, applies_when: str = "", platforms: list[str] | None = None,
evidence: list[str] | None = None,
) -> dict:
- """Record that a canon idea's SUBSTANCE changed — you rewrote its note's
- approach, its traps or its checklist, or its applicability or platforms
- moved. The canon version moves, so every project's answer given against
+ """Record that a canon idea's SUBSTANCE changed — you rewrote its family
+ record's approach, its traps or its checklist (update_note on the id
+ get_family_idea returns, which has no project), or its applicability or
+ platforms moved. The canon version moves, so every project's answer given against
the old version reads `needs_recheck` until it is assessed again.
A typo fix is not a revision. A change a project that adopted the old
@@ -368,6 +377,9 @@ async def set_family_references(note_id: int, snippet_ids: list[int]) -> dict:
Args:
note_id: the family idea.
snippet_ids: snippets implementing it. [] clears the list.
+
+ A project that owns one of these snippets and has not answered the idea
+ is answered `adopted` with the snippet as evidence.
"""
refs = await adoption_svc.set_references(current_user_id(), note_id, snippet_ids or [])
return {"references": refs}
diff --git a/src/grimoire/models/family.py b/src/grimoire/models/family.py
index dbe61d3d..b9f5fd3d 100644
--- a/src/grimoire/models/family.py
+++ b/src/grimoire/models/family.py
@@ -9,6 +9,14 @@ are the reference implementations, one per language. A new record type would
be one more thing reached for interchangeably with rules, processes, snippets
and design systems, and nothing here needs one.
+A CANDIDATE sits on the project record that a trigger or a session proposed.
+CANON sits on a FAMILY RECORD: a note with no project, made when the idea is
+promoted (services/family.py `_lift`), whose `arose_from_id` names the project
+record it came from. The family owns canon, so revising it or folding a
+conflict into it writes no project's record, and a project's own record stays
+its own (a snippet as a reference implementation). The project record's id
+still names the idea in every family call (`family.idea_key`).
+
What is shared is the IDEA, not the code. Each project implements it in its own
language; identical code is a by-product and never the test.
diff --git a/src/grimoire/services/family.py b/src/grimoire/services/family.py
index 69a2d1c4..79b93e7c 100644
--- a/src/grimoire/services/family.py
+++ b/src/grimoire/services/family.py
@@ -43,12 +43,12 @@ import logging
import re
from datetime import datetime, timezone
-from sqlalchemy import delete, func, select
+from sqlalchemy import delete, func, select, update
from grimoire.models import async_session
from grimoire.models.family import (
- FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform, Platform,
- ProjectPlatform,
+ FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform, FamilyIdeaReference,
+ Platform, ProjectPlatform,
)
from grimoire.models.note import Note
from grimoire.models.project import Project
@@ -226,6 +226,7 @@ async def get_idea(user_id: int, note_id: int) -> dict | None:
"""One idea with everything an evaluation reads: its state, platforms,
decision history (newest first), its ledger counts and the criteria.
None when the caller cannot read the note or it is not an idea."""
+ note_id = await idea_key(note_id)
if not await access.can_read_note(user_id, note_id):
return None
async with async_session() as session:
@@ -281,6 +282,8 @@ async def list_ideas(
rows = (await session.execute(
query.order_by(FamilyIdea.updated_at.desc()).limit(limit).offset(offset)
)).all()
+ titles = await _project_titles(session, {r[3] for r in rows if r[3]})
+ refs = await _readable_references(session, user_id, [r[0].note_id for r in rows])
out = []
for idea, title, note_type, project_id, note_status in rows:
d = idea.to_dict()
@@ -288,7 +291,10 @@ async def list_ideas(
"title": title,
"note_type": note_type or "note",
"is_task": note_status is not None,
+ # None once the idea is canon: it lives on a family record.
"project_id": project_id,
+ "project_title": titles.get(project_id) if project_id else None,
+ "references": refs.get(idea.note_id, []),
"platforms": await _platform_slugs(session, idea.note_id),
"topic": await _topic(session, user_id, idea.topic_id, rules=False),
})
@@ -296,6 +302,26 @@ async def list_ideas(
return out
+async def _readable_references(session, user_id: int, idea_ids: list[int]) -> dict[int, list[dict]]:
+ """Each idea's reference implementations the caller can read, with the
+ project each lives in: {idea_id: [{id, title, project_id, project_title}]}."""
+ if not idea_ids:
+ return {}
+ rows = (await session.execute(
+ select(FamilyIdeaReference.idea_id, Note.id, Note.title, Note.project_id, Project.title)
+ .join(Note, Note.id == FamilyIdeaReference.snippet_id)
+ .outerjoin(Project, Project.id == Note.project_id)
+ .where(FamilyIdeaReference.idea_id.in_(idea_ids), Note.deleted_at.is_(None),
+ access.readable_notes_clause(user_id))
+ .order_by(Note.id.asc())
+ )).all()
+ out: dict[int, list[dict]] = {}
+ for idea_id, nid, title, project_id, project_title in rows:
+ out.setdefault(idea_id, []).append(
+ {"id": nid, "title": title, "project_id": project_id, "project_title": project_title})
+ return out
+
+
async def list_decisions(
user_id: int, *, idea_id: int | None = None, project_id: int | None = None,
limit: int = 50, offset: int = 0,
@@ -410,6 +436,7 @@ async def precedents(user_id: int, note_id: int, limit: int = 5) -> list[dict]:
decision about it should be consistent with. Each idea contributes its
latest idea-level decision. Empty when nothing similar has been decided,
or when the embedder is unavailable."""
+ note_id = await idea_key(note_id)
ranked = await nearest_ideas(user_id, note_id, limit)
if not ranked:
return []
@@ -430,6 +457,115 @@ async def precedents(user_id: int, note_id: int, limit: int = 5) -> list[dict]:
return out
+# --- the family record -------------------------------------------------------------
+#
+# Canon belongs to the family, not to the project that happened to write the
+# idea down first. A candidate is state on a project's own record; promoting
+# it LIFTS the idea onto a family record with no project: a note carrying the
+# idea, its family state moved onto it, the project's record left untouched
+# and, when it is a snippet, kept as a reference implementation. From then on
+# revising the idea or folding a conflict into it edits the family record, and
+# no project's record changes when the family decides something.
+
+async def idea_key(note_id: int) -> int:
+ """The id a family idea is kept under. A project's record that was lifted
+ onto a family record is still how sessions in that project, triggers and
+ older references name the idea, so its id resolves to the family record
+ (the lifted note's `arose_from_id`). Any other id comes back as given."""
+ async with async_session() as session:
+ if await session.get(FamilyIdea, note_id) is not None:
+ return note_id
+ lifted = await session.scalar(
+ select(FamilyIdea.note_id)
+ .join(Note, Note.id == FamilyIdea.note_id)
+ .where(Note.arose_from_id == note_id, Note.project_id.is_(None),
+ Note.deleted_at.is_(None))
+ .order_by(FamilyIdea.note_id.asc()).limit(1)
+ )
+ return lifted or note_id
+
+
+def _family_body(origin: Note, project_title: str | None) -> str:
+ """The family record's opening text: the project's own write-up of the
+ idea, and where it came from. Revisions edit this record from here on."""
+ where = f" ({project_title})" if project_title else ""
+ kind = "reference implementation" if origin.note_type == "snippet" else "original record"
+ return (
+ f"{(origin.body or '').rstrip()}\n\n---\n"
+ f"Lifted from #{origin.id} \u201c{origin.title}\u201d{where}, its {kind}.\n"
+ )
+
+
+async def _copy_shares(session, origin: Note, family_id: int) -> None:
+ """Whoever could read or edit the idea on its project's record can on the
+ family record: the record's own shares and its project's shares become
+ shares of the family record, at the highest permission each target held."""
+ from grimoire.models.share import NoteShare, ProjectShare
+
+ best: dict[tuple, tuple[str, int]] = {}
+ rows = list((await session.execute(
+ select(NoteShare).where(NoteShare.note_id == origin.id))).scalars().all())
+ rows += list((await session.execute(
+ select(ProjectShare).where(ProjectShare.project_id == origin.project_id))).scalars().all())
+ for r in rows:
+ target = (r.shared_with_user_id, r.shared_with_group_id)
+ held = best.get(target)
+ perm = access._higher(held[0] if held else None, r.permission)
+ best[target] = (perm, r.invited_by)
+ for (user, group), (perm, invited_by) in best.items():
+ session.add(NoteShare(note_id=family_id, shared_with_user_id=user,
+ shared_with_group_id=group, permission=perm,
+ invited_by=invited_by))
+
+
+async def _lift(session, idea: FamilyIdea) -> tuple[FamilyIdea, Note | None]:
+ """Move a project-owned idea onto a new family record (project_id NULL,
+ owned by the same person, `arose_from_id` naming the project's record).
+ Every family row keyed on the record — platforms, references, ledger,
+ decision log — moves with it. Returns (idea, family note), or (idea,
+ None) when the idea already has no project. The caller commits, then
+ embeds the family note."""
+ from grimoire.services import notes as notes_svc
+
+ origin = await session.get(Note, idea.note_id)
+ if origin is None or origin.project_id is None:
+ return idea, None
+ project_title = await session.scalar(
+ select(Project.title).where(Project.id == origin.project_id))
+ family = notes_svc.build_note(
+ origin.user_id, title=origin.title, body=_family_body(origin, project_title),
+ tags=list(origin.tags or []),
+ # The code stays in the project's snippet, which becomes a reference;
+ # the family record carries the idea, so it is a note.
+ note_type="note" if origin.note_type == "snippet" else (origin.note_type or "note"),
+ arose_from_id=origin.id,
+ )
+ session.add(family)
+ await session.flush()
+ old, new = origin.id, family.id
+ state = {"status": idea.status, "applies_when": idea.applies_when,
+ "canon_version": idea.canon_version, "topic_id": idea.topic_id,
+ "created_at": idea.created_at}
+ # One idea per topic (uq_family_ideas_topic): release it before the new
+ # row takes it.
+ idea.topic_id = None
+ await session.flush()
+ session.add(FamilyIdea(note_id=new, **state))
+ await session.flush()
+ for column in (FamilyIdeaPlatform.note_id, FamilyIdeaReference.idea_id,
+ FamilyAdoption.idea_id, FamilyDecision.idea_id):
+ await session.execute(
+ update(column.class_).where(column == old).values({column.key: new})
+ .execution_options(synchronize_session=False))
+ session.expunge(idea)
+ await session.execute(delete(FamilyIdea).where(FamilyIdea.note_id == old))
+ if origin.note_type == "snippet" and await session.get(FamilyIdeaReference, (new, old)) is None:
+ session.add(FamilyIdeaReference(idea_id=new, snippet_id=old))
+ await _copy_shares(session, origin, new)
+ await session.flush()
+ return await session.get(FamilyIdea, new), family
+
+
# --- writes ---------------------------------------------------------------------
def _log(session, *, idea_id: int, action: str, reason: str, before, after,
@@ -514,6 +650,7 @@ async def propose(
"""
if not (reason or "").strip():
raise ValueError("a proposal needs a reason — what makes this a family idea?")
+ note_id = await idea_key(note_id)
if not await access.can_write_note(user_id, note_id):
raise ValueError(f"note {note_id} not found or no write access")
async with async_session() as session:
@@ -578,6 +715,7 @@ async def promote(
"""
if not (reason or "").strip():
raise ValueError("a promotion needs a reason")
+ note_id = await idea_key(note_id)
if not await access.can_write_note(user_id, note_id):
raise ValueError(f"note {note_id} not found or no write access")
criteria = {k: str((criteria or {}).get(k) or "").strip() for k in CRITERIA_KEYS}
@@ -623,6 +761,9 @@ async def promote(
"decision": decision.to_dict(), "precedents": consulted,
}
+ lifted_from = note_id
+ idea, family_note = await _lift(session, idea)
+ note_id = idea.note_id
# Re-promotion moves the version PAST every version this idea has ever
# held — including one an undo rolled back from — so no row judged
# against an earlier canon can read as agreeing with this one.
@@ -637,15 +778,37 @@ async def promote(
decision = _log(
session, idea_id=note_id, action="promote", reason=reason,
before=before, after=await _snapshot(session, idea),
- evidence={**record, "ledger_rows_opened": opened},
+ evidence={**record, "ledger_rows_opened": opened,
+ **({"lifted_from": lifted_from} if family_note is not None else {})},
precedent_ids=precedent_list, decided_via=decided_via, user_id=user_id,
)
await session.commit()
await session.refresh(decision)
- return {
+ out = {
"promoted": True, "idea": idea.to_dict(), "ledger_rows_opened": opened,
"decision": decision.to_dict(), "precedents": consulted,
}
+ if family_note is not None:
+ from grimoire.services.notes import embed_note
+ embed_note(family_note)
+ as_reference = lifted_from in await _reference_ids(note_id)
+ out["lifted"] = {
+ "family_record": family_note.id, "from": lifted_from,
+ "note": (f"The idea now lives on family record #{family_note.id}, outside any "
+ f"project, and that is the record to revise. #{lifted_from} stays its "
+ "project's own record" + (", as a reference implementation."
+ if as_reference else ".")),
+ }
+ from grimoire.services import family_adoption
+ out["answered"] = await family_adoption.answer_reference_holders(user_id, note_id)
+ return out
+
+
+async def _reference_ids(idea_id: int) -> set[int]:
+ async with async_session() as session:
+ return set((await session.execute(
+ select(FamilyIdeaReference.snippet_id).where(FamilyIdeaReference.idea_id == idea_id)
+ )).scalars().all())
async def _promoted_before(session, note_id: int) -> bool:
@@ -707,6 +870,7 @@ async def revise(
"""
if not (reason or "").strip():
raise ValueError("a revision needs a reason — what changed in the idea?")
+ note_id = await idea_key(note_id)
if not await access.can_write_note(user_id, note_id):
raise ValueError(f"note {note_id} not found or no write access")
if applies_when is not None and not applies_when.strip():
@@ -751,6 +915,7 @@ async def set_topic(user_id: int, note_id: int, topic_id: int) -> dict:
Not a change of substance, so the version does not move: the norms were
rules before the link and are the same rules after it. Re-linking is the
undo, as with the references."""
+ note_id = await idea_key(note_id)
if not await access.can_write_note(user_id, note_id):
raise ValueError(f"note {note_id} not found or no write access")
async with async_session() as session:
@@ -797,6 +962,7 @@ async def retire(user_id: int, note_id: int, *, reason: str, decided_via: str =
rows nobody judged are closed. Undoable."""
if not (reason or "").strip():
raise ValueError("retiring an idea needs a reason")
+ note_id = await idea_key(note_id)
if not await access.can_write_note(user_id, note_id):
raise ValueError(f"note {note_id} not found or no write access")
async with async_session() as session:
diff --git a/src/grimoire/services/family_adoption.py b/src/grimoire/services/family_adoption.py
index 75659a31..8ae8a197 100644
--- a/src/grimoire/services/family_adoption.py
+++ b/src/grimoire/services/family_adoption.py
@@ -397,6 +397,7 @@ async def reference_for(user_id: int, idea_id: int, path: str) -> int:
Python shape can be an instance of an idea whose only reference is Go.
Raises ValueError when the idea is not a family idea the caller can read
or has no reference they can read."""
+ idea_id = await family_svc.idea_key(idea_id)
if not await access.can_read_note(user_id, idea_id):
raise ValueError(f"#{idea_id} is not a family idea you can read")
async with async_session() as session:
@@ -518,6 +519,7 @@ async def assessment_precedents(user_id: int, project_id: int, idea_id: int,
"""What an assessment should be consistent with: the latest answer to
THIS idea in each other project the caller can read, then this project's
latest answers to the ideas nearest this one by meaning."""
+ idea_id = await family_svc.idea_key(idea_id)
async with async_session() as session:
same = (await session.execute(
select(func.max(FamilyDecision.id))
@@ -708,6 +710,7 @@ async def get_adoption(user_id: int, project_id: int, idea_id: int) -> dict:
"""Everything one assessment reads: the idea, this project's current
answer, the four outcomes, the precedents, and the reference
implementations with this project's languages."""
+ idea_id = await family_svc.idea_key(idea_id)
if not await access.can_read_project(user_id, project_id):
raise ValueError(f"project {project_id} not found")
idea = await family_svc.get_idea(user_id, idea_id)
@@ -747,8 +750,9 @@ def _reference_line(refs: list[dict], langs: list[str], idea_id: int) -> str:
async def _matching_systems(session, project_id: int, note_ids: list[int]) -> list[int]:
"""The project's Systems matching the idea's: the same canonical area as
- one the idea (or a reference) is filed under, or that very System when
- the idea was written in this project."""
+ one the idea (its family record, the project's record it was lifted from,
+ or a reference) is filed under, or that very System when that record was
+ written in this project."""
tagged = (await session.execute(
select(System.id, System.project_id, System.canonical_id)
.join(RecordSystem, RecordSystem.system_id == System.id)
@@ -776,8 +780,11 @@ async def _file_owed_task(user_id: int, row_id: int, reason: str) -> Note:
refs = await _references(session, row.idea_id)
langs = await _project_languages(session, row.project_id)
platforms = await family_svc._platform_slugs(session, row.idea_id)
+ # A family record has no project and so no Systems; the project's
+ # record it was lifted from still carries the areas it is about.
+ lifted_from = [note.arose_from_id] if note.project_id is None and note.arose_from_id else []
systems = await _matching_systems(
- session, row.project_id, [row.idea_id] + [r["id"] for r in refs])
+ session, row.project_id, [row.idea_id, *lifted_from] + [r["id"] for r in refs])
project_id, idea_id, version = row.project_id, row.idea_id, idea.canon_version
body = (
f"Family idea #{idea_id} “{note.title}” is canon for "
@@ -906,6 +913,7 @@ async def assess(
has an open task. The response carries the precedents consulted, and
`owed_task` when there is one.
"""
+ idea_id = await family_svc.idea_key(idea_id)
evidence = _clean(evidence)
problems = assessment_problems(outcome=outcome, reason=reason, evidence=evidence)
if problems:
@@ -1015,6 +1023,7 @@ async def set_references(user_id: int, idea_id: int, snippet_ids: list[int]) ->
"""Replace an idea's reference implementations — the snippets an owed
task points a project at, one per language. Each must be a snippet the
caller can read; the idea must be theirs to write."""
+ idea_id = await family_svc.idea_key(idea_id)
if not await access.can_write_note(user_id, idea_id):
raise ValueError(f"note {idea_id} not found or no write access")
wanted = list(dict.fromkeys(int(i) for i in snippet_ids or [] if i))
@@ -1040,7 +1049,65 @@ async def set_references(user_id: int, idea_id: int, snippet_ids: list[int]) ->
if sid not in current:
session.add(FamilyIdeaReference(idea_id=idea_id, snippet_id=sid))
await session.commit()
- return await _references(session, idea_id)
+ refs = await _references(session, idea_id)
+ await answer_reference_holders(user_id, idea_id)
+ return refs
+
+
+REFERENCE_SOURCE = "reference"
+
+
+async def answer_reference_holders(user_id: int, idea_id: int) -> list[dict]:
+ """A project whose own snippet is one of a canon idea's reference
+ implementations has built the idea, so its unassessed row is answered
+ `adopted` (decided_via system, the snippet as evidence). Only an
+ unassessed row is answered — an answer somebody gave stands — and only
+ where the project's shapes say nothing about the idea, because the shape
+ ledger's answer and this one must never disagree. Returns the answers
+ given: {project_id, idea_id, snippet_id, decision_id}."""
+ async with async_session() as session:
+ idea = await session.get(FamilyIdea, idea_id)
+ if idea is None or idea.status != "canon":
+ return []
+ holders = (await session.execute(
+ select(Note.project_id, Note.id, Note.title, Project.title)
+ .join(FamilyIdeaReference, FamilyIdeaReference.snippet_id == Note.id)
+ .join(Project, Project.id == Note.project_id)
+ .where(FamilyIdeaReference.idea_id == idea_id, Note.deleted_at.is_(None))
+ .order_by(Note.id.asc())
+ )).all()
+ given: list[dict] = []
+ seen: set[int] = set()
+ for project_id, snippet_id, snippet_title, project_title in holders:
+ if project_id in seen or not await access.can_write_project(user_id, project_id):
+ continue
+ seen.add(project_id)
+ async with async_session() as session:
+ row = await _row(session, project_id, idea_id)
+ if row is None and not await _is_member(session, project_id, idea_id):
+ continue
+ if row is not None and row.status != "unassessed":
+ continue
+ if shapes_say(await _shape_evidence(session, project_id, idea_id)):
+ continue
+ row = row or await _row_for_write(session, project_id, idea_id)
+ reason = (f"{project_title} holds a reference implementation of this idea: "
+ f"#{snippet_id} \u201c{snippet_title}\u201d.")
+ before = _row_state(row)
+ _answer(row, status="adopted", reason=reason, version=idea.canon_version,
+ decided_via="system")
+ decision = family_svc._log(
+ session, idea_id=idea_id, project_id=project_id, action="assess",
+ reason=reason, before=before, after=_row_state(row),
+ evidence={"evidence": [f"#{snippet_id} {snippet_title}"],
+ "source": REFERENCE_SOURCE},
+ precedent_ids=None, decided_via="system", user_id=user_id,
+ )
+ await session.commit()
+ await session.refresh(decision)
+ given.append({"project_id": project_id, "idea_id": idea_id,
+ "snippet_id": snippet_id, "decision_id": decision.id})
+ return given
def _fold_section(*, ground: str, fold: str, conditions: dict | None,
@@ -1071,9 +1138,10 @@ async def resolve_conflict(
"""Settle two projects that solve the same canon idea differently, by
the conflict order.
- `canon_project_id` is the side whose approach the idea's note states
- after this — if that is not what the note says now, rewrite the note
- first (update_note); the note is the canon. `other_project_id` is the
+ `canon_project_id` is the side whose approach the idea's family record
+ states after this — if that is not what it says now, rewrite it first
+ (update_note); the family record is the canon, and no project's record
+ is written here. `other_project_id` is the
side that loses, or in a split, the side whose condition is the branch.
Effects, in order: the losing side's reasoning (`fold`) is appended to
@@ -1088,6 +1156,7 @@ async def resolve_conflict(
"""
from grimoire.services import notes as notes_svc
+ idea_id = await family_svc.idea_key(idea_id)
evidence = _clean(evidence)
problems = conflict_problems(ground=ground, grounds_checked=grounds_checked,
evidence=evidence, conditions=conditions, fold=fold)
diff --git a/tests/test_integration_family_adoption.py b/tests/test_integration_family_adoption.py
index 333f6705..f2f63378 100644
--- a/tests/test_integration_family_adoption.py
+++ b/tests/test_integration_family_adoption.py
@@ -112,6 +112,8 @@ async def family():
evidence=["CI green on the release lane"], reason="proven, stated for the platform",
)
assert out["promoted"] is True
+ # Promotion lifted the idea onto a family record; the ledger is keyed on it.
+ ids["origin"], ids["note"] = ids["note"], out["idea"]["note_id"]
return ids
diff --git a/tests/test_integration_family_promotion.py b/tests/test_integration_family_promotion.py
index cac35e4b..9f2e87a3 100644
--- a/tests/test_integration_family_promotion.py
+++ b/tests/test_integration_family_promotion.py
@@ -112,6 +112,9 @@ async def _promote(f, **overrides):
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)
@@ -121,6 +124,7 @@ async def _ledger(note_id: int) -> dict[int, str]:
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)
@@ -167,13 +171,127 @@ async def test_someone_who_cannot_write_the_note_cannot_promote_it(family):
)
+# --- 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_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 == family["note"],
+ 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()
@@ -218,7 +336,7 @@ async def test_an_undo_names_what_it_reversed_as_its_precedent(family):
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 == family["note"]).order_by(FamilyDecision.id))).scalars().all()
+ FamilyDecision.idea_id == out["idea"]["note_id"]).order_by(FamilyDecision.id))).scalars().all()
assert actions == ["promote", "undo"]
diff --git a/tests/test_integration_family_records_migration.py b/tests/test_integration_family_records_migration.py
new file mode 100644
index 00000000..a7ac855e
--- /dev/null
+++ b/tests/test_integration_family_records_migration.py
@@ -0,0 +1,161 @@
+"""Migration 0141 against real Postgres: every promoted idea still on a
+project's record moves onto a family record with no project.
+
+The lane migrates an empty database, so the migration's work is driven here
+directly: rows are seeded the way a promotion made them before promotion
+lifted, then the migration's own function runs on the test connection.
+"""
+import importlib.util
+from pathlib import Path
+
+import pytest
+import pytest_asyncio
+from sqlalchemy import select
+
+from grimoire.models import async_session
+from grimoire.models.family import (
+ FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform, FamilyIdeaReference,
+ Platform, ProjectPlatform,
+)
+from grimoire.models.note import Note
+from grimoire.models.project import Project
+from grimoire.models.share import NoteShare, ProjectShare
+from grimoire.models.user import User
+from grimoire.services import access
+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_records_owner"
+READER = "family_records_reader"
+_MIGRATION = Path(__file__).resolve().parents[1] / "alembic" / "versions" / "0141_family_records.py"
+
+
+def _migration():
+ spec = importlib.util.spec_from_file_location("migration_0141", _MIGRATION)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+async def _purge(username: str) -> None:
+ """SETUP ONLY: a database call after a `yield` in a fixture orphans a
+ pooled connection. Notes and projects cascade to every family row."""
+ 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
+async def promoted():
+ """A Kotlin snippet in the first of two Android apps, promoted to canon
+ the way promotion stored it before it lifted: the idea on the snippet,
+ an unassessed row for each app, the first app shared with a reader."""
+ await _purge(OWNER)
+ await _purge(READER)
+ async with async_session() as s:
+ android = await s.scalar(select(Platform.id).where(
+ Platform.slug == "android-app", Platform.deleted_at.is_(None)))
+ owner = await ensure_user(s, OWNER)
+ reader = await ensure_user(s, READER)
+ a = Project(user_id=owner.id, title="android one")
+ b = Project(user_id=owner.id, title="android two")
+ s.add_all([a, b])
+ 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="declared"),
+ ProjectShare(project_id=a.id, shared_with_user_id=reader.id,
+ permission="viewer", invited_by=owner.id)])
+ snippet = Note(user_id=owner.id, project_id=a.id, note_type="snippet",
+ title="ReleaseSigner", body="fun sign(apk: File) = ...",
+ tags=["android"], data={"language": "kotlin"})
+ candidate = Note(user_id=owner.id, project_id=b.id, note_type="snippet",
+ title="Unproven", body="...")
+ s.add_all([snippet, candidate])
+ await s.flush()
+ s.add_all([
+ FamilyIdea(note_id=snippet.id, status="canon", canon_version=1,
+ applies_when="any Android app that ships its own APK"),
+ FamilyIdea(note_id=candidate.id, status="candidate"),
+ ])
+ await s.flush()
+ s.add_all([
+ FamilyIdeaPlatform(note_id=snippet.id, platform_id=android),
+ FamilyAdoption(project_id=a.id, idea_id=snippet.id, status="unassessed"),
+ FamilyAdoption(project_id=b.id, idea_id=snippet.id, status="unassessed"),
+ FamilyDecision(idea_id=snippet.id, action="propose", reason="repeated",
+ decided_via="system", user_id=owner.id),
+ FamilyDecision(idea_id=snippet.id, action="promote", reason="proven",
+ decided_via="agent", user_id=owner.id),
+ FamilyDecision(idea_id=candidate.id, action="propose", reason="repeated",
+ decided_via="system", user_id=owner.id),
+ ])
+ await s.commit()
+ return {"owner": owner.id, "reader": reader.id, "a": a.id, "b": b.id,
+ "snippet": snippet.id, "candidate": candidate.id}
+
+
+async def _lift() -> list[tuple[int, int]]:
+ module = _migration()
+ async with async_session() as s:
+ conn = await s.connection()
+ moved = await conn.run_sync(module.lift_promoted_ideas)
+ await s.commit()
+ return moved
+
+
+async def test_a_promoted_idea_moves_onto_a_family_record_and_a_candidate_stays(promoted):
+ moved = await _lift()
+ [(origin, family_id)] = [m for m in moved if m[0] == promoted["snippet"]]
+ async with async_session() as s:
+ record = await s.get(Note, family_id)
+ snippet = await s.get(Note, origin)
+ assert await s.get(FamilyIdea, origin) is None
+ assert (await s.get(FamilyIdea, family_id)).status == "canon"
+ assert (await s.get(FamilyIdea, promoted["candidate"])).status == "candidate"
+ actions = (await s.execute(select(FamilyDecision.action).where(
+ FamilyDecision.idea_id == family_id, FamilyDecision.project_id.is_(None))
+ .order_by(FamilyDecision.id))).scalars().all()
+ platforms = (await s.execute(select(FamilyIdeaPlatform.note_id))).scalars().all()
+ refs = (await s.execute(select(FamilyIdeaReference.snippet_id).where(
+ FamilyIdeaReference.idea_id == family_id))).scalars().all()
+ assert record.project_id is None and record.user_id == promoted["owner"]
+ assert record.note_type == "note" and record.arose_from_id == origin
+ assert record.tags == ["android"] and f"#{origin}" in record.body
+ assert snippet.project_id == promoted["a"] and snippet.body == "fun sign(apk: File) = ..."
+ assert actions == ["propose", "promote"]
+ assert family_id in platforms and origin not in platforms
+ assert refs == [origin]
+ assert await family_svc.idea_key(origin) == family_id
+
+
+async def test_the_project_holding_the_reference_is_answered_and_the_other_still_owes(promoted):
+ [(_, family_id)] = [m for m in await _lift() if m[0] == promoted["snippet"]]
+ async with async_session() as s:
+ rows = dict((await s.execute(select(FamilyAdoption.project_id, FamilyAdoption.status)
+ .where(FamilyAdoption.idea_id == family_id))).all())
+ answer = (await s.execute(select(FamilyDecision).where(
+ FamilyDecision.idea_id == family_id,
+ FamilyDecision.project_id == promoted["a"]))).scalars().one()
+ assert rows == {promoted["a"]: "adopted", promoted["b"]: "unassessed"}
+ assert answer.decided_via == "system" and answer.evidence["source"] == "reference"
+ assert answer.after["status"] == "adopted" and answer.before["status"] == "unassessed"
+
+
+async def test_whoever_read_it_through_its_project_reads_the_family_record(promoted):
+ [(_, family_id)] = [m for m in await _lift() if m[0] == promoted["snippet"]]
+ assert await access.get_note_permission(promoted["reader"], family_id) == "viewer"
+ async with async_session() as s:
+ shares = (await s.execute(select(NoteShare).where(NoteShare.note_id == family_id))).scalars().all()
+ assert [(sh.shared_with_user_id, sh.permission) for sh in shares] == [(promoted["reader"], "viewer")]
+
+
+async def test_running_it_again_lifts_nothing(promoted):
+ first = await _lift()
+ assert promoted["snippet"] in [o for o, _ in first]
+ assert promoted["snippet"] not in [o for o, _ in await _lift()]