feat(8565,8566,8567,8568): promoting a family idea lifts it onto a family record with no project
CI & Build / TypeScript typecheck (push) Successful in 14s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Failing after 1m55s
CI & Build / integration (push) Failing after 2m33s
CI & Build / Build & push image (push) Skipped

Canon now belongs to the family. Promotion moves an idea off the project
record it was written on and onto a note with no project (owned by the same
person, arose_from_id naming the project record), carrying its state,
platforms, references, ledger and decision log. The project record stays its
own; a snippet becomes a reference implementation. Revising the idea or
folding a conflict into it now edits the family record, never a project's.
The project record's id still names the idea in every family call
(family.idea_key).

- A project that owns a reference snippet and has not answered the idea is
  answered adopted by the system, naming the snippet, unless its shapes
  already speak for it (on promotion and on set_family_references).
- The family record takes the project record's shares and its project's
  shares, so whoever could read the idea still can.
- An owed task still finds its Systems through the project record the idea
  was lifted from.
- Migration 0141 lifts every idea promoted before this, the same way.
- The Family page shows where each idea lives and its reference
  implementations; the skill, tool descriptions, model docstring and
  features doc describe the family record. Plugin minted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 14:44:56 -05:00
co-authored by Claude Opus 5.5
parent 0d9fe5d3c5
commit 6c0481ef9c
13 changed files with 788 additions and 19 deletions
+171 -5
View File
@@ -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: