"""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})