Merge pull request 'Family canon belongs to the family: promotion lifts an idea onto a family record, and family decisions cross no project fence' (#241) from dev into main
CI & Build / TypeScript typecheck (push) Successful in 11s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 1m58s
CI & Build / integration (push) Successful in 2m32s
CI & Build / Build & push image (push) Successful in 58s

This commit was merged in pull request #241.
This commit is contained in:
2026-12-04 15:31:45 -05:00
17 changed files with 863 additions and 38 deletions
+194
View File
@@ -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})
+2 -2
View File
@@ -45,7 +45,7 @@ A task is a note with a status (`todo`, `in_progress`, `done`, `cancelled`), plu
## Family canon ## 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 ## Design systems
@@ -66,7 +66,7 @@ Saved procedures, such as a drift audit or a DRY pass. The plugin syncs each one
The whole store is reachable through the MCP endpoint at `/mcp`, authenticated with an API key. The Claude Code plugin in this repo adds: The whole store is reachable through the MCP endpoint at `/mcp`, authenticated with an API key. The Claude Code plugin in this repo adds:
- hooks for session start, each prompt, before and after tool calls, the end of a turn, compaction and session end, all failing open if Grimoire is unreachable; - hooks for session start, each prompt, before and after tool calls, the end of a turn, compaction and session end, all failing open if Grimoire is unreachable;
- a project fence: a session belongs to the project its starting directory is bound to. Toward any other project it can read anything and file an issue. Editing that project's files, committing or pushing in its repo, or changing its records first asks you, in every permission mode; - a project fence: a session belongs to the project its starting directory is bound to. Toward any other project it can read anything and file an issue. Editing that project's files, committing or pushing in its repo, or changing its records first asks you, in every permission mode. Deciding about a family idea (promoting, revising or retiring it) belongs to the family, so it never asks; a project's answer to an idea stays that project's;
- skills for the working practices: using Grimoire, writing plans, systematic debugging, verification, brainstorming, reporting back, reusing code, shape accounting and family canon; - skills for the working practices: using Grimoire, writing plans, systematic debugging, verification, brainstorming, reporting back, reusing code, shape accounting and family canon;
- your stored processes as skills. - your stored processes as skills.
+12
View File
@@ -37,12 +37,24 @@ export interface FamilyIdea {
title: string; title: string;
note_type: string; note_type: string;
is_task: boolean; 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_id: number | null;
project_title?: string | null;
/** Reference implementations: project snippets a project can start from. */
references?: IdeaReference[];
platforms: string[]; platforms: string[];
created_at: string | null; created_at: string | null;
updated_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. */ /** A state snapshot a decision records — slugs, never ids. */
export interface IdeaSnapshot { export interface IdeaSnapshot {
status: IdeaStatus; status: IdeaStatus;
+16
View File
@@ -266,6 +266,21 @@ onMounted(load);
<span :class="['fam-status', `fam-${idea.status}`]">{{ idea.status }}</span> <span :class="['fam-status', `fam-${idea.status}`]">{{ idea.status }}</span>
<span v-if="idea.status !== 'candidate'" class="fam-muted">v{{ idea.canon_version }}</span> <span v-if="idea.status !== 'candidate'" class="fam-muted">v{{ idea.canon_version }}</span>
</div> </div>
<p class="fam-muted fam-home">
<template v-if="idea.project_id !== null">
Proposed in
<router-link :to="`/projects/${idea.project_id}`">{{ idea.project_title ?? `project ${idea.project_id}` }}</router-link>
</template>
<template v-else>Family record</template>
<template v-if="idea.references?.length">
· Reference{{ idea.references.length > 1 ? "s" : "" }}:
<template v-for="(r, i) in idea.references" :key="r.id">
<template v-if="i">, </template>
<router-link :to="recordHref({ id: r.id, is_task: false, note_type: 'snippet' })">{{ r.title }}</router-link>
<template v-if="r.project_title"> ({{ r.project_title }})</template>
</template>
</template>
</p>
<p v-if="idea.applies_when" class="fam-applies">Applies when: {{ idea.applies_when }}</p> <p v-if="idea.applies_when" class="fam-applies">Applies when: {{ idea.applies_when }}</p>
<div v-if="idea.platforms.length" class="fam-platforms"> <div v-if="idea.platforms.length" class="fam-platforms">
<code v-for="p in idea.platforms" :key="p" class="fam-chip">{{ p }}</code> <code v-for="p in idea.platforms" :key="p" class="fam-chip">{{ p }}</code>
@@ -397,6 +412,7 @@ onMounted(load);
.fam-applies { margin: 0.3rem 0 0; font-size: 0.85rem; color: var(--fs-text-secondary); } .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-platforms { display: flex; flex-wrap: wrap; gap: 0.3rem; margin-top: 0.35rem; }
.fam-topic { margin: 0.35rem 0 0; } .fam-topic { margin: 0.35rem 0 0; }
.fam-home { margin: 0.25rem 0 0; }
.fam-chip { .fam-chip {
font-family: var(--fs-font-mono); font-family: var(--fs-font-mono);
font-size: 0.72rem; font-size: 0.72rem;
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "grimoire", "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).", "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.03.0415", "version": "2026.12.04.1944",
"author": { "author": {
"name": "Bryan Van Deusen" "name": "Bryan Van Deusen"
}, },
+3 -1
View File
@@ -89,7 +89,9 @@ On install you'll be asked for:
reset in its repo (from `git -C`, after `cd`, or in a worktree of it), and a reset in its repo (from `git -C`, after `cd`, or in a worktree of it), and a
Grimoire write that lands in another project each stop on a permission Grimoire write that lands in another project each stop on a permission
prompt naming that project, in every permission mode. Filing an issue there prompt naming that project, in every permission mode. Filing an issue there
(`create_task(kind="issue")`) and every read go ahead. An edit in the (`create_task(kind="issue")`), a decision about a family idea (it changes
the family's state, not the project whose record carries the idea), and
every read go ahead. An edit in the
session's own repo never calls the server. It can't see a non-git shell session's own repo never calls the server. It can't see a non-git shell
write into another repo (`sed -i`, a redirect), but it fences that repo's write into another repo (`sed -i`, a redirect), but it fences that repo's
commit and push. When the instance doesn't answer, the act goes ahead and commit and push. When the instance doesn't answer, the act goes ahead and
+11
View File
@@ -37,6 +37,17 @@ wrote what you wrote:
topic with `set_family_topic`. The note teaches; the topic's rules bind, topic with `set_family_topic`. The note teaches; the topic's rules bind,
and every assessment then reads them beside the idea. 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: A milestone closing on a platform project hints without recording anything:
ask whether what it built is something every project on the platform will ask whether what it built is something every project on the platform will
face, and if so write the note that carries the idea. face, and if so write the note that carries the idea.
+15 -3
View File
@@ -114,6 +114,14 @@ async def promote_family_idea(
canon before, its version moves, so earlier answers read as needing a canon before, its version moves, so earlier answers read as needing a
recheck. 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: Args:
note_id: the record that carries the idea. note_id: the record that carries the idea.
applies_when: when it applies, in platform terms. 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, note_id: int, reason: str, applies_when: str = "", platforms: list[str] | None = None,
evidence: list[str] | None = None, evidence: list[str] | None = None,
) -> dict: ) -> dict:
"""Record that a canon idea's SUBSTANCE changed — you rewrote its note's """Record that a canon idea's SUBSTANCE changed — you rewrote its family
approach, its traps or its checklist, or its applicability or platforms record's approach, its traps or its checklist (update_note on the id
moved. The canon version moves, so every project's answer given against 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. 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 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: Args:
note_id: the family idea. note_id: the family idea.
snippet_ids: snippets implementing it. [] clears the list. 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 []) refs = await adoption_svc.set_references(current_user_id(), note_id, snippet_ids or [])
return {"references": refs} return {"references": refs}
+8
View File
@@ -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 be one more thing reached for interchangeably with rules, processes, snippets
and design systems, and nothing here needs one. 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 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. language; identical code is a by-product and never the test.
+171 -5
View File
@@ -43,12 +43,12 @@ import logging
import re import re
from datetime import datetime, timezone 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 import async_session
from grimoire.models.family import ( from grimoire.models.family import (
FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform, Platform, FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform, FamilyIdeaReference,
ProjectPlatform, Platform, ProjectPlatform,
) )
from grimoire.models.note import Note from grimoire.models.note import Note
from grimoire.models.project import Project 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, """One idea with everything an evaluation reads: its state, platforms,
decision history (newest first), its ledger counts and the criteria. decision history (newest first), its ledger counts and the criteria.
None when the caller cannot read the note or it is not an idea.""" 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): if not await access.can_read_note(user_id, note_id):
return None return None
async with async_session() as session: async with async_session() as session:
@@ -281,6 +282,8 @@ async def list_ideas(
rows = (await session.execute( rows = (await session.execute(
query.order_by(FamilyIdea.updated_at.desc()).limit(limit).offset(offset) query.order_by(FamilyIdea.updated_at.desc()).limit(limit).offset(offset)
)).all() )).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 = [] out = []
for idea, title, note_type, project_id, note_status in rows: for idea, title, note_type, project_id, note_status in rows:
d = idea.to_dict() d = idea.to_dict()
@@ -288,7 +291,10 @@ async def list_ideas(
"title": title, "title": title,
"note_type": note_type or "note", "note_type": note_type or "note",
"is_task": note_status is not None, "is_task": note_status is not None,
# None once the idea is canon: it lives on a family record.
"project_id": project_id, "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), "platforms": await _platform_slugs(session, idea.note_id),
"topic": await _topic(session, user_id, idea.topic_id, rules=False), "topic": await _topic(session, user_id, idea.topic_id, rules=False),
}) })
@@ -296,6 +302,26 @@ async def list_ideas(
return out 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( async def list_decisions(
user_id: int, *, idea_id: int | None = None, project_id: int | None = None, user_id: int, *, idea_id: int | None = None, project_id: int | None = None,
limit: int = 50, offset: int = 0, 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 decision about it should be consistent with. Each idea contributes its
latest idea-level decision. Empty when nothing similar has been decided, latest idea-level decision. Empty when nothing similar has been decided,
or when the embedder is unavailable.""" or when the embedder is unavailable."""
note_id = await idea_key(note_id)
ranked = await nearest_ideas(user_id, note_id, limit) ranked = await nearest_ideas(user_id, note_id, limit)
if not ranked: if not ranked:
return [] return []
@@ -430,6 +457,115 @@ async def precedents(user_id: int, note_id: int, limit: int = 5) -> list[dict]:
return out 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 --------------------------------------------------------------------- # --- writes ---------------------------------------------------------------------
def _log(session, *, idea_id: int, action: str, reason: str, before, after, def _log(session, *, idea_id: int, action: str, reason: str, before, after,
@@ -514,6 +650,7 @@ async def propose(
""" """
if not (reason or "").strip(): if not (reason or "").strip():
raise ValueError("a proposal needs a reason — what makes this a family idea?") 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): if not await access.can_write_note(user_id, note_id):
raise ValueError(f"note {note_id} not found or no write access") raise ValueError(f"note {note_id} not found or no write access")
async with async_session() as session: async with async_session() as session:
@@ -578,6 +715,7 @@ async def promote(
""" """
if not (reason or "").strip(): if not (reason or "").strip():
raise ValueError("a promotion needs a reason") 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): if not await access.can_write_note(user_id, note_id):
raise ValueError(f"note {note_id} not found or no write access") 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} 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, "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 # Re-promotion moves the version PAST every version this idea has ever
# held — including one an undo rolled back from — so no row judged # held — including one an undo rolled back from — so no row judged
# against an earlier canon can read as agreeing with this one. # against an earlier canon can read as agreeing with this one.
@@ -637,15 +778,37 @@ async def promote(
decision = _log( decision = _log(
session, idea_id=note_id, action="promote", reason=reason, session, idea_id=note_id, action="promote", reason=reason,
before=before, after=await _snapshot(session, idea), 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, precedent_ids=precedent_list, decided_via=decided_via, user_id=user_id,
) )
await session.commit() await session.commit()
await session.refresh(decision) await session.refresh(decision)
return { out = {
"promoted": True, "idea": idea.to_dict(), "ledger_rows_opened": opened, "promoted": True, "idea": idea.to_dict(), "ledger_rows_opened": opened,
"decision": decision.to_dict(), "precedents": consulted, "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: async def _promoted_before(session, note_id: int) -> bool:
@@ -707,6 +870,7 @@ async def revise(
""" """
if not (reason or "").strip(): if not (reason or "").strip():
raise ValueError("a revision needs a reason — what changed in the idea?") 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): if not await access.can_write_note(user_id, note_id):
raise ValueError(f"note {note_id} not found or no write access") raise ValueError(f"note {note_id} not found or no write access")
if applies_when is not None and not applies_when.strip(): 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 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 rules before the link and are the same rules after it. Re-linking is the
undo, as with the references.""" undo, as with the references."""
note_id = await idea_key(note_id)
if not await access.can_write_note(user_id, 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") raise ValueError(f"note {note_id} not found or no write access")
async with async_session() as session: 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.""" rows nobody judged are closed. Undoable."""
if not (reason or "").strip(): if not (reason or "").strip():
raise ValueError("retiring an idea needs a reason") 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): if not await access.can_write_note(user_id, note_id):
raise ValueError(f"note {note_id} not found or no write access") raise ValueError(f"note {note_id} not found or no write access")
async with async_session() as session: async with async_session() as session:
+76 -7
View File
@@ -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. 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 Raises ValueError when the idea is not a family idea the caller can read
or has no reference they 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): if not await access.can_read_note(user_id, idea_id):
raise ValueError(f"#{idea_id} is not a family idea you can read") raise ValueError(f"#{idea_id} is not a family idea you can read")
async with async_session() as session: 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 """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 THIS idea in each other project the caller can read, then this project's
latest answers to the ideas nearest this one by meaning.""" 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: async with async_session() as session:
same = (await session.execute( same = (await session.execute(
select(func.max(FamilyDecision.id)) 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 """Everything one assessment reads: the idea, this project's current
answer, the four outcomes, the precedents, and the reference answer, the four outcomes, the precedents, and the reference
implementations with this project's languages.""" 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): if not await access.can_read_project(user_id, project_id):
raise ValueError(f"project {project_id} not found") raise ValueError(f"project {project_id} not found")
idea = await family_svc.get_idea(user_id, idea_id) 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]: 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 """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 one the idea (its family record, the project's record it was lifted from,
the idea was written in this project.""" or a reference) is filed under, or that very System when that record was
written in this project."""
tagged = (await session.execute( tagged = (await session.execute(
select(System.id, System.project_id, System.canonical_id) select(System.id, System.project_id, System.canonical_id)
.join(RecordSystem, RecordSystem.system_id == System.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) refs = await _references(session, row.idea_id)
langs = await _project_languages(session, row.project_id) langs = await _project_languages(session, row.project_id)
platforms = await family_svc._platform_slugs(session, row.idea_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( 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 project_id, idea_id, version = row.project_id, row.idea_id, idea.canon_version
body = ( body = (
f"Family idea #{idea_id} “{note.title}” is canon for " 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 has an open task. The response carries the precedents consulted, and
`owed_task` when there is one. `owed_task` when there is one.
""" """
idea_id = await family_svc.idea_key(idea_id)
evidence = _clean(evidence) evidence = _clean(evidence)
problems = assessment_problems(outcome=outcome, reason=reason, evidence=evidence) problems = assessment_problems(outcome=outcome, reason=reason, evidence=evidence)
if problems: 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 """Replace an idea's reference implementations — the snippets an owed
task points a project at, one per language. Each must be a snippet the task points a project at, one per language. Each must be a snippet the
caller can read; the idea must be theirs to write.""" 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): if not await access.can_write_note(user_id, idea_id):
raise ValueError(f"note {idea_id} not found or no write access") 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)) 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: if sid not in current:
session.add(FamilyIdeaReference(idea_id=idea_id, snippet_id=sid)) session.add(FamilyIdeaReference(idea_id=idea_id, snippet_id=sid))
await session.commit() 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, 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 """Settle two projects that solve the same canon idea differently, by
the conflict order. the conflict order.
`canon_project_id` is the side whose approach the idea's note states `canon_project_id` is the side whose approach the idea's family record
after this — if that is not what the note says now, rewrite the note states after this — if that is not what it says now, rewrite it first
first (update_note); the note is the canon. `other_project_id` is the (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. 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 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 from grimoire.services import notes as notes_svc
idea_id = await family_svc.idea_key(idea_id)
evidence = _clean(evidence) evidence = _clean(evidence)
problems = conflict_problems(ground=ground, grounds_checked=grounds_checked, problems = conflict_problems(ground=ground, grounds_checked=grounds_checked,
evidence=evidence, conditions=conditions, fold=fold) evidence=evidence, conditions=conditions, fold=fold)
+31 -13
View File
@@ -29,7 +29,7 @@ RULE = "rule" # a project rule: its project. A global rule: none
RELATION = "relation" # a rule relation: the projects of its two rules RELATION = "relation" # a rule relation: the projects of its two rules
TRASH = "trash" # a deleted batch: every project its rows belong to TRASH = "trash" # a deleted batch: every project its rows belong to
REPO = "repo" # a repo remote: the project it is bound to REPO = "repo" # a repo remote: the project it is bound to
DECISION = "decision" # a family decision: its project, else its idea's home DECISION = "decision" # a family decision: the project whose answer it is; an idea-level one, none
LOCATORS = frozenset({PROJECT, NOTE, MILESTONE, SYSTEM, RULE, RELATION, TRASH, REPO, DECISION}) LOCATORS = frozenset({PROJECT, NOTE, MILESTONE, SYSTEM, RULE, RELATION, TRASH, REPO, DECISION})
@@ -38,6 +38,7 @@ LOCATORS = frozenset({PROJECT, NOTE, MILESTONE, SYSTEM, RULE, RELATION, TRASH, R
# - install-level settings (moment mappings, retrieval dials); # - install-level settings (moment mappings, retrieval dials);
# - user-level records (processes, design systems, rulebooks, topics, global # - user-level records (processes, design systems, rulebooks, topics, global
# rules and preferences); # rules and preferences);
# - decisions about a family idea, which belong to the family (below);
# - judgments the system asks a session for in any project (a rule's outcome, # - judgments the system asks a session for in any project (a rule's outcome,
# a lesson-to-rule link, moment proposals, a menu verdict). Those describe how # a lesson-to-rule link, moment proposals, a menu verdict). Those describe how
# the corpus is retrieved; they don't change another project's work. # the corpus is retrieved; they don't change another project's work.
@@ -77,14 +78,23 @@ WRITE_TARGETS: dict[str, dict[str, str]] = {
# elsewhere, the project it leaves. # elsewhere, the project it leaves.
"bind_repo": {"project_id": PROJECT, "repo_url": REPO}, "bind_repo": {"project_id": PROJECT, "repo_url": REPO},
"unbind_repo": {"repo_url": REPO}, "unbind_repo": {"repo_url": REPO},
# family canon. An idea is a record in its home project; an adoption is a # family canon. A decision about an idea — proposing, promoting, revising,
# project's answer; a conflict is between the two projects it names. # retiring it, naming its references or its topic — belongs to the family,
"propose_family_idea": {"note_id": NOTE}, # not to the project whose record first carried the idea: it writes only
"promote_family_idea": {"note_id": NOTE}, # the family's own state (status, platforms, version, the decision log,
"retire_family_idea": {"note_id": NOTE}, # the ledger's unassessed rows), never that record. The trigger that opens
"revise_family_idea": {"note_id": NOTE}, # an evaluation fires in the project that built the idea second, so the
"set_family_references": {"note_id": NOTE}, # session deciding is usually not the origin's; locating these at the
"set_family_topic": {"note_id": NOTE}, # origin would put a prompt about a change to that project in front of
# the operator when nothing in it changes. A project's ANSWER is that
# project's: an assessment, a conflict (it writes both projects'
# answers), and undoing an answer.
"propose_family_idea": {},
"promote_family_idea": {},
"retire_family_idea": {},
"revise_family_idea": {},
"set_family_references": {},
"set_family_topic": {},
"undo_family_decision": {"decision_id": DECISION}, "undo_family_decision": {"decision_id": DECISION},
"assess_family_adoption": {"project_id": PROJECT}, "assess_family_adoption": {"project_id": PROJECT},
"resolve_family_conflict": {"canon_project_id": PROJECT, "other_project_id": PROJECT}, "resolve_family_conflict": {"canon_project_id": PROJECT, "other_project_id": PROJECT},
@@ -159,7 +169,15 @@ LOCATOR_NAMES = frozenset({
# Arguments with a locating name that only point at a record, with why each one # Arguments with a locating name that only point at a record, with why each one
# doesn't say where the write lands. # doesn't say where the write lands.
_FAMILY_IDEA = "the family idea the decision is about; it writes the family's state, not the record's project"
REFERENCES: dict[str, dict[str, str]] = { REFERENCES: dict[str, dict[str, str]] = {
"propose_family_idea": {"note_id": _FAMILY_IDEA},
"promote_family_idea": {"note_id": _FAMILY_IDEA},
"retire_family_idea": {"note_id": _FAMILY_IDEA},
"revise_family_idea": {"note_id": _FAMILY_IDEA},
"set_family_references": {"note_id": _FAMILY_IDEA},
"set_family_topic": {"note_id": _FAMILY_IDEA},
"classify_shapes_by_rule": { "classify_shapes_by_rule": {
"snippet_id": "the canon the shapes are judged against; the rows written are project_id's", "snippet_id": "the canon the shapes are judged against; the rows written are project_id's",
}, },
@@ -270,12 +288,12 @@ async def _projects_of(user_id: int, kind: str, value) -> set[int]:
) )
return {p for p in rows.scalars() if p} return {p for p in rows.scalars() if p}
if kind == DECISION: if kind == DECISION:
# An assessment carries the project it answered for; a decision
# about the idea itself carries none and lands in no project.
rows = await session.execute( rows = await session.execute(
select(FamilyDecision.project_id, Note.project_id) select(FamilyDecision.project_id).where(FamilyDecision.id.in_(ids))
.join(Note, Note.id == FamilyDecision.idea_id)
.where(FamilyDecision.id.in_(ids))
) )
return {own or home for own, home in rows.all() if own or home} return {p for p in rows.scalars() if p}
model = {NOTE: Note, MILESTONE: Milestone, SYSTEM: System, RULE: Rule}[kind] model = {NOTE: Note, MILESTONE: Milestone, SYSTEM: System, RULE: Rule}[kind]
rows = await session.execute(select(model.project_id).where(model.id.in_(ids))) rows = await session.execute(select(model.project_id).where(model.id.in_(ids)))
return {p for p in rows.scalars() if p} return {p for p in rows.scalars() if p}
@@ -112,6 +112,8 @@ async def family():
evidence=["CI green on the release lane"], reason="proven, stated for the platform", evidence=["CI green on the release lane"], reason="proven, stated for the platform",
) )
assert out["promoted"] is True 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 return ids
+123 -4
View File
@@ -112,6 +112,9 @@ async def _promote(f, **overrides):
async def _ledger(note_id: int) -> dict[int, str]: 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: async with async_session() as s:
rows = (await s.execute( rows = (await s.execute(
select(FamilyAdoption.project_id, FamilyAdoption.status) 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: async def _idea(note_id: int) -> FamilyIdea:
note_id = await family_svc.idea_key(note_id)
async with async_session() as s: async with async_session() as s:
return await s.get(FamilyIdea, note_id) 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 ------------------------------------------------------------ # --- undo and retirement ------------------------------------------------------------
async def test_undoing_a_promotion_restores_the_prior_state_and_keeps_judged_rows(family): async def test_undoing_a_promotion_restores_the_prior_state_and_keeps_judged_rows(family):
out = await _promote(family) out = await _promote(family)
async with async_session() as s: async with async_session() as s:
row = (await s.execute(select(FamilyAdoption).where( 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() FamilyAdoption.project_id == family["a"]))).scalars().one()
row.status, row.canon_version, row.decided_via = "adopted", 1, "agent" row.status, row.canon_version, row.decided_via = "adopted", 1, "agent"
await s.commit() 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"]] assert undo["decision"]["precedent_ids"] == [out["decision"]["id"]]
async with async_session() as s: async with async_session() as s:
actions = (await s.execute(select(FamilyDecision.action).where( 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"] assert actions == ["promote", "undo"]
@@ -355,8 +473,9 @@ async def test_an_idea_links_to_its_topic_and_its_reads_name_the_rules(family, t
idea = await family_svc.get_idea(family["owner"], family["note"]) idea = await family_svc.get_idea(family["owner"], family["note"])
assert idea["topic"]["rulebook_id"] == topics["rulebook"] assert idea["topic"]["rulebook_id"] == topics["rulebook"]
assert len(idea["topic"]["rules"]) == 2 assert len(idea["topic"]["rules"]) == 2
[listed] = [i for i in await family_svc.list_ideas(family["owner"]) # Promotion lifted the idea onto its family record.
if i["note_id"] == family["note"]] key = await family_svc.idea_key(family["note"])
[listed] = [i for i in await family_svc.list_ideas(family["owner"]) if i["note_id"] == key]
assert listed["topic"] == {"id": topics["norms"], "title": "distribution", assert listed["topic"] == {"id": topics["norms"], "title": "distribution",
"rulebook_id": topics["rulebook"]} "rulebook_id": topics["rulebook"]}
@@ -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()]
+35 -2
View File
@@ -9,6 +9,7 @@ import pytest_asyncio
from sqlalchemy import select from sqlalchemy import select
from grimoire.models import async_session from grimoire.models import async_session
from grimoire.models.family import FamilyDecision, FamilyIdea
from grimoire.models.milestone import Milestone from grimoire.models.milestone import Milestone
from grimoire.models.note import Note from grimoire.models.note import Note
from grimoire.models.project import Project from grimoire.models.project import Project
@@ -45,10 +46,21 @@ async def two_projects():
note_type="note", task_kind="work", status="todo") note_type="note", task_kind="work", status="todo")
trashed = Note(user_id=user.id, project_id=other.id, title="Trashed", body="", trashed = Note(user_id=user.id, project_id=other.id, title="Trashed", body="",
note_type="note", deleted_batch_id=BATCH) note_type="note", deleted_batch_id=BATCH)
s.add_all([theirs, mine, trashed]) idea = Note(user_id=user.id, project_id=other.id, title="Their idea", body="",
note_type="snippet")
s.add_all([theirs, mine, trashed, idea])
await s.flush()
s.add(FamilyIdea(note_id=idea.id, status="candidate"))
await s.flush()
proposed = FamilyDecision(idea_id=idea.id, project_id=None, action="propose",
reason="repeated", decided_via="system", user_id=user.id)
answered = FamilyDecision(idea_id=idea.id, project_id=home.id, action="assess",
reason="exempt here", decided_via="agent", user_id=user.id)
s.add_all([proposed, answered])
await s.commit() await s.commit()
return {"user": user.id, "home": home.id, "other": other.id, "plan": plan.id, return {"user": user.id, "home": home.id, "other": other.id, "plan": plan.id,
"area": area.id, "theirs": theirs.id, "mine": mine.id} "area": area.id, "theirs": theirs.id, "mine": mine.id, "idea": idea.id,
"proposed": proposed.id, "answered": answered.id}
async def test_each_locator_finds_the_project_of_the_row_it_names(two_projects): async def test_each_locator_finds_the_project_of_the_row_it_names(two_projects):
@@ -67,6 +79,27 @@ async def test_each_locator_finds_the_project_of_the_row_it_names(two_projects):
assert await lands("create_rule", topic_id=1) == set() assert await lands("create_rule", topic_id=1) == set()
async def test_a_decision_about_a_family_idea_lands_in_no_project_and_an_answer_in_its_own(two_projects):
# The idea's record lives in the other project, but deciding about the
# idea writes only the family's state; undoing a project's answer writes
# that project's ledger row.
ids = two_projects
uid, home = ids["user"], ids["home"]
async def lands(tool, **args):
return await write_scope.tool_targets(uid, tool, args)
for tool in ("propose_family_idea", "promote_family_idea", "revise_family_idea",
"retire_family_idea", "set_family_references", "set_family_topic"):
assert await lands(tool, note_id=ids["idea"]) == set(), tool
assert await lands("undo_family_decision", decision_id=ids["proposed"]) == set()
assert await lands("undo_family_decision", decision_id=ids["answered"]) == {home}
promote = await write_scope.check_act(uid, home, tool="promote_family_idea",
args={"note_id": ids["idea"]})
assert promote["allowed"] is True
async def test_a_session_in_one_project_is_asked_before_writing_in_the_other(two_projects): async def test_a_session_in_one_project_is_asked_before_writing_in_the_other(two_projects):
ids = two_projects ids = two_projects
uid, home, other = ids["user"], ids["home"], ids["other"] uid, home, other = ids["user"], ids["home"], ids["other"]
+2
View File
@@ -31,6 +31,8 @@ NEEDS_NO_CALLER = {
"design_systems": {}, "design_systems": {},
"family": { "family": {
"next_version": "numbers a canon version inside a write that has checked the caller", "next_version": "numbers a canon version inside a write that has checked the caller",
"idea_key": "translates an id the caller passed to the id its idea is kept under; "
"every caller checks access on the result next",
}, },
"family_adoption": { "family_adoption": {
"family_reference_ids": "the coverage refresh's mechanical read for a project", "family_reference_ids": "the coverage refresh's mechanical read for a project",