From 4ed2cbbe22ec40715dcbdaf20fec6f6dbfcace43 Mon Sep 17 00:00:00 2001 From: dannyclarkdev Date: Sun, 13 Sep 2026 15:41:47 -0400 Subject: [PATCH 1/2] docs: plan slice 26, family trees drawn from typed relationships --- .../2026-09-13-feat-family-trees-plan.md | 106 ++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 docs/plans/2026-09-13-feat-family-trees-plan.md diff --git a/docs/plans/2026-09-13-feat-family-trees-plan.md b/docs/plans/2026-09-13-feat-family-trees-plan.md new file mode 100644 index 0000000..d379851 --- /dev/null +++ b/docs/plans/2026-09-13-feat-family-trees-plan.md @@ -0,0 +1,106 @@ +--- +title: "feat: Family trees, drawn from typed relationships" +type: feat +date: 2026-09-13 +status: planned +brainstorm: docs/brainstorms/2026-09-02-demgem-campaign-manager-brainstorm.md +follows: docs/plans/2026-09-13-feat-downtime-plan.md +--- + +# feat: Family trees, drawn from typed relationships + +## Overview + +The brainstorm's world table lists family trees under P3. Slice 11 built relationships: a typed link between two entities with a label from one side and an optional reverse label, gated at both ends. A family is a set of those links with four meanings the app can read. This slice gives a relationship an optional kinship and draws what the kinships say. + +| Feature | What it adds | +|---|---| +| Kinship on a relationship | One nullable column, `kinship`: parent, child, sibling, or spouse, read from the source's side. The labels fill in from it when the GM leaves them blank. | +| The tree | A "Family" card on a character's page: grandparents, parents, siblings, spouses, children, and grandchildren, walked from the typed rows in both directions. | +| The gate | The relations card's own scope, `EntityRelation::visibleTo()`, at both ends. No new gate. | +| The round trip | `kinship` on the relation rows in the export, the reader, the importer, and the API resource. | + +When this slice is done a GM opens Mara Voss and reads that Abbess Corvane is her mother, and the abbess's page reads Mara as her daughter without a second row being written. The GM opens Wren and reads a sister the party has not been told about; the player opens Wren and reads no family at all. + +**On scope.** Phase 0 is the column, the enum, and the form. Phase 1 is the tree. Phase 2 is the round trip, the API, the seeder, the rules, and the pass. + +## Problem Statement + +**"Daughter of" is a label the app cannot read.** A GM writes "mother of" on the abbess and "daughter of" back, and the two pages each show one line. Nothing joins them to the abbess's own mother, so a three-generation house is six lines on six pages and a diagram in the GM's notebook. + +**A family is the one relationship graph every table draws.** Kanka and World Anvil both draw one. The relations card already holds the rows; what it lacks is the four words that make a row a branch. + +**A tree that leaks is worse than no tree.** A family tree walks two hops from a page, and the second hop is where a careless implementation reaches a GM-only aunt through a revealed cousin. The relations scope already refuses a row whose either end the party may not see, and the tree has to walk through that scope and nothing else. + +## Proposed Solution + +**A kinship is one nullable column on the relation, read from the source's side.** `Kinship::Parent` means the source is a parent of the target; `Child`, the reverse; `Sibling` and `Spouse` read the same from both ends. `Kinship::reverse()` gives the other side's word, and the form fills a blank label and a blank reverse label from the two. A GM who types their own words keeps them: the labels are what the row says, and the kinship is what the app knows. + +**The tree is one query and a walk.** The Relations component already renders the card on every entity page. For a character, it loads every kinship row the viewer may see in the campaign, one query through `EntityRelation::visibleTo()` with both ends eager-loaded, and walks up two generations and down two in memory. A campaign's kinship rows are a handful, and one query for the whole graph is what makes the second hop as safe as the first: a row that the scope refused is not in the graph to walk through. + +**Drawn as generations, not as a diagram.** Six rows of name chips, each labelled: grandparents, parents, siblings, spouses, children, grandchildren, with only the rows that have someone in them. A GM's page marks a chip whose row the party has not been told, the relations card's way. + +## Technical Approach + +### No new dependency + +### What slices 1 to 25 give us for free + +| Piece | Reuse | +|---|---| +| `EntityRelation::scopeVisibleTo()` | Both gates, and the tree walks through it. | +| `Entities\Relations` | The card, the form, the controls, and the per-page lookup. The tree is one more section of the same component. | +| `RelateEntities` | Takes the kinship as one more argument. | +| `EntityResource` | Gains the key on both relation lists. | +| `RoundTripTest` | Compares `kinship` in full without a change. | + +### The data + +``` +entity_relations + kinship string(8) nullable parent | child | sibling | spouse +``` + +### Scope and decisions + +| Question | Decision | +|---|---| +| Which types | Any entity may carry a kinship row, because the column is on the relation. The tree is drawn on characters only. | +| The labels | Filled from the kinship when blank. A GM's own words win. | +| The generations | Two up, two down. Siblings and spouses of the page only. A wider walk is a follow-up. | +| A sibling through shared parents | Not inferred. The tree draws what was typed. | +| The card | Shown when at least one kinship row the viewer may see touches the character. | +| The API | `kinship` on both relation lists of the show route. The API does not write relations today and this slice does not change that. | +| The vault | Unchanged. The label already carries the word. | +| Changing a kinship | Remove the row and relate again, as with a label. | + +### Screens + +- **The relations card** gains a "Kinship" select on the form, and a "Family" card above the list on a character's page. + +### The round trip + +- `kinship` on each relation row. The reader accepts an absent key and refuses a value it does not know. No version bump. + +## Verification + + php artisan test --compact tests/Feature/Entities/FamilyTreeTest.php + php artisan test --compact tests/Feature/Entities/RelationsTest.php tests/Feature/Entities/RelationVisibilityTest.php + php artisan test --compact tests/Feature/Api + php artisan test --compact --filter=RoundTrip + php artisan test --compact --filter=DemoSeeder + vendor/bin/pint --dirty --format agent + vendor/bin/phpstan analyse + +Then the full suite with `memory_limit=1G`, and a browser pass: as the GM, relate Abbess Corvane as parent of Mara Voss and read the family on both pages; open Wren and read the hidden sister; as the player, open Wren and find no family card, and Mara with the abbess. + +## Open Questions + +1. **Should the tree draw an SVG with lines?** Recommendation: not now. Generations as rows read on a phone; a diagram does not. +2. **Should a kinship row show on the timeline or a calendar?** Recommendation: no. Birth dates are a field, not this slice. + +## References + +- `.ai/rules/entities.md` — relationships are a GM's to write; the target picker and the per-page lookup. +- `.ai/rules/models.md` — a relationship is gated at both ends, in the scope. +- `.ai/rules/api.md` — an added key on a resource. From be5b6874445c1f9ef95d2a261c5089ac6ac9a55a Mon Sep 17 00:00:00 2001 From: dannyclarkdev Date: Sun, 13 Sep 2026 15:46:59 -0400 Subject: [PATCH 2/2] feat: family trees, drawn from typed relationships A relationship may carry a kinship: parent, child, sibling, or spouse, read from the side it was written on, with Kinship::reverse() as the other side's word. The labels fill in from it when the GM leaves them blank, and typed ones win; a plain relationship still needs a label. A character's page draws a Family card from the typed rows, two generations up and two down. Relations::family() loads every kinship row the viewer may see in one query through EntityRelation::visibleTo(), both ends eager-loaded, and walks in memory, so a row the scope refused is never a hop: a GM-only grandmother cannot be reached through a revealed mother. A GM reads a mark on anyone the party would not see. The kinship travels on every relation row in the export, the reader accepts an older file and refuses a kinship it does not know, and both API relation lists carry it. The demo world gains Wren's sister, a GM-only page on a hidden sibling row, and the abbess as Mara's mother. --- .ai/rules/entities.md | 3 + README.md | 2 + app/Actions/Campaigns/ExportCampaign.php | 1 + app/Actions/Campaigns/ImportCampaign.php | 1 + app/Actions/Campaigns/ReadCampaignFile.php | 3 + app/Actions/Entities/RelateEntities.php | 4 +- app/Enums/Kinship.php | 51 ++++ app/Http/Resources/Api/V1/EntityResource.php | 3 + app/Livewire/Entities/Relations.php | 113 ++++++++- app/Models/EntityRelation.php | 7 +- ..._add_kinship_to_entity_relations_table.php | 27 +++ database/seeders/DemoCampaignSeeder.php | 18 +- .../2026-09-13-feat-family-trees-plan.md | 31 ++- .../livewire/entities/relations.blade.php | 33 ++- tests/Feature/Entities/FamilyTreeTest.php | 226 ++++++++++++++++++ tests/Feature/Entities/RelationsTest.php | 1 + 16 files changed, 513 insertions(+), 11 deletions(-) create mode 100644 app/Enums/Kinship.php create mode 100644 database/migrations/2026_09_13_194148_add_kinship_to_entity_relations_table.php create mode 100644 tests/Feature/Entities/FamilyTreeTest.php diff --git a/.ai/rules/entities.md b/.ai/rules/entities.md index f174eb8..aba1fd5 100644 --- a/.ai/rules/entities.md +++ b/.ai/rules/entities.md @@ -20,3 +20,6 @@ Entity templates belong to one campaign and one entity type, carry only a name a ## A journal is the one entity a player creates, and player_user_id is its author `EntityType::Journal` is the only type `isPlayerWritable()`. `EntityPolicy::create()` takes the type as a third argument; pass it everywhere (`[Entity::class, $campaign, $type]`), because a create check without one stays a GM's. The author is `player_user_id`, set at birth from the actor and never moved: the form strips the DM card's `player_user_id`/`is_pc` on a journal so a GM's edit cannot wipe it. No new gate: `Entity::visibleTo()` already shows a row to its player, so Dm means "me and the GM" and Players means "the party". The author sets that one switch through its own rule set (`Rule::enum(Visibility)->only([Dm, Players])`), outside `updateDmFields()`, in the form and in `EntityController::rules()`. Selected stays a DM-card decision. The author may delete their own; other DM fields from a non-DM are never read, as on a PC's form. + +## The family tree is one query through the relations scope and a walk in memory +entity_relations.kinship (Kinship: parent, child, sibling, spouse) is read from the source's side, and Kinship::reverse() is the target's word. Relations::family() loads every kinship row the viewer may see in the campaign through EntityRelation::visibleTo(), both ends eager-loaded, and walks two generations up and down in memory. That is the whole leak design: a row the scope refused is not in the graph, so a GM-only grandmother is never reached through a revealed mother. Do not walk hop by hop with per-hop queries, and do not infer siblings from shared parents. The "hidden" mark is for a GM and means the party would not see the row or the relative. The labels fill in from the kinship when blank and a GM's own words win; a plain relationship still requires a label (required_without:kinship). diff --git a/README.md b/README.md index 238f49c..b7d7901 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,8 @@ Slice 24 adds **the player screen**, for the television at the end of the table. Slice 25 adds **downtime**, what each character did between sessions. A row is what they did, how many days it cost, an optional note in Markdown, the session it happened around, and, when the campaign has a calendar, the day in the world it began, from which the page prints the range it covered. A player writes their own PC's rows and a GM writes anyone's; whoever may see the character reads them, and there is no second switch. The same log sits on the character's page, on the session's page, and at `/downtime`, where the days are summed per character on every read. It travels in the export and lands on the character's page in the vault. +Slice 26 adds **family trees**. A relationship may carry a kinship, parent, child, sibling, or spouse, read from the side it was written on, and the labels fill in from it when the GM leaves them blank. A character's page draws a "Family" card from the typed rows, two generations up and two down, walked through the relations card's own gate at both ends: a hidden row or a GM-only relative never reaches the party's tree, and the GM reads a mark on each. The kinship travels in the export and on both relation lists of the API. + Your creatures travel in your export with the prose you wrote. A shipped creature never does — it is named in the file and nothing more, exactly as before. The CC BY notice follows the words rather than the table: a creature you wrote carries none, and a copy of a shipped one keeps the source and licence it came from, so the credit travels with the text. ## Local setup diff --git a/app/Actions/Campaigns/ExportCampaign.php b/app/Actions/Campaigns/ExportCampaign.php index f67d358..1fbdf6a 100644 --- a/app/Actions/Campaigns/ExportCampaign.php +++ b/app/Actions/Campaigns/ExportCampaign.php @@ -404,6 +404,7 @@ private function entities(Campaign $campaign): iterable 'target_entity_id' => $relation->target_entity_id, 'label' => $relation->label, 'reverse_label' => $relation->reverse_label, + 'kinship' => $relation->kinship?->value, 'player_visible' => $relation->player_visible, 'position' => $relation->position, ])->values()->all(), diff --git a/app/Actions/Campaigns/ImportCampaign.php b/app/Actions/Campaigns/ImportCampaign.php index 0f372b5..e92f5fc 100644 --- a/app/Actions/Campaigns/ImportCampaign.php +++ b/app/Actions/Campaigns/ImportCampaign.php @@ -399,6 +399,7 @@ private function children(array $document, IdMap $ids): void 'target_entity_id' => $ids->newFor($relation['target_entity_id']), 'label' => $relation['label'], 'reverse_label' => $relation['reverse_label'], + 'kinship' => $relation['kinship'] ?? null, 'player_visible' => $relation['player_visible'], 'position' => $relation['position'], ]); diff --git a/app/Actions/Campaigns/ReadCampaignFile.php b/app/Actions/Campaigns/ReadCampaignFile.php index 53c0a46..336cf61 100644 --- a/app/Actions/Campaigns/ReadCampaignFile.php +++ b/app/Actions/Campaigns/ReadCampaignFile.php @@ -6,6 +6,7 @@ use App\Actions\Maps\Coordinate; use App\Enums\EncounterStatus; use App\Enums\EntityType; +use App\Enums\Kinship; use App\Enums\LedgerKind; use App\Enums\PrepRole; use App\Enums\QuestStatus; @@ -534,6 +535,8 @@ private function relations(array $row): array 'target_entity_id' => $this->reference($relation, 'target_entity_id'), 'label' => $this->text($relation, 'label', EntityRelation::MAX_LABEL_LENGTH) ?? 'related to', 'reverse_label' => $this->text($relation, 'reverse_label', EntityRelation::MAX_LABEL_LENGTH), + // Absent from a file older than slice 26, and null is what that means. + 'kinship' => isset($relation['kinship']) ? $this->enum(Kinship::class, $relation, 'kinship', 'a relationship') : null, 'player_visible' => (bool) ($relation['player_visible'] ?? false), 'position' => $this->integer($relation, 'position') ?? $index, ]; diff --git a/app/Actions/Entities/RelateEntities.php b/app/Actions/Entities/RelateEntities.php index a7864a7..1dff4f0 100644 --- a/app/Actions/Entities/RelateEntities.php +++ b/app/Actions/Entities/RelateEntities.php @@ -2,6 +2,7 @@ namespace App\Actions\Entities; +use App\Enums\Kinship; use App\Models\Entity; use App\Models\EntityRelation; @@ -11,7 +12,7 @@ class RelateEntities * Writes one row from $source's side. The caller has already checked that the * target is in the same campaign and is not the source itself. */ - public function handle(Entity $source, Entity $target, string $label, ?string $reverseLabel, bool $playerVisible = false): EntityRelation + public function handle(Entity $source, Entity $target, string $label, ?string $reverseLabel, bool $playerVisible = false, ?Kinship $kinship = null): EntityRelation { $position = $source->relations()->exists() ? (int) $source->relations()->max('position') + 1 : 0; @@ -20,6 +21,7 @@ public function handle(Entity $source, Entity $target, string $label, ?string $r 'target_entity_id' => $target->id, 'label' => $label, 'reverse_label' => $reverseLabel, + 'kinship' => $kinship, 'player_visible' => $playerVisible, 'position' => $position, ]); diff --git a/app/Enums/Kinship.php b/app/Enums/Kinship.php new file mode 100644 index 0000000..b8361af --- /dev/null +++ b/app/Enums/Kinship.php @@ -0,0 +1,51 @@ +value.' of'; + } + + /** + * The same row read from the target's side. + */ + public function reverse(): self + { + return match ($this) { + self::Parent => self::Child, + self::Child => self::Parent, + self::Sibling, self::Spouse => $this, + }; + } + + /** + * The heading a generation gets on the tree. + */ + public function plural(): string + { + return match ($this) { + self::Parent => 'Parents', + self::Child => 'Children', + self::Sibling => 'Siblings', + self::Spouse => 'Spouses', + }; + } +} diff --git a/app/Http/Resources/Api/V1/EntityResource.php b/app/Http/Resources/Api/V1/EntityResource.php index dc82400..60a7c76 100644 --- a/app/Http/Resources/Api/V1/EntityResource.php +++ b/app/Http/Resources/Api/V1/EntityResource.php @@ -85,12 +85,15 @@ public function toArray(Request $request): array 'id' => $relation->id, 'label' => $relation->label, 'reverse_label' => $relation->reverse_label, + 'kinship' => $relation->kinship?->value, 'target' => self::link($relation->target), ])->values()->all()); $data['incoming_relations'] = $this->whenLoaded('incomingRelations', fn () => $this->incomingRelations ->map(fn (EntityRelation $relation) => [ 'id' => $relation->id, 'label' => $relation->readsFromTargetAs(), + // From this page's side, like the label above it. + 'kinship' => $relation->kinship?->reverse()->value, 'source' => self::link($relation->source), ])->values()->all()); diff --git a/app/Livewire/Entities/Relations.php b/app/Livewire/Entities/Relations.php index 5b4f87a..c21576a 100644 --- a/app/Livewire/Entities/Relations.php +++ b/app/Livewire/Entities/Relations.php @@ -5,6 +5,9 @@ use App\Actions\Entities\RelateEntities; use App\Actions\Entities\RemoveRelation; use App\Actions\Entities\SetRelationVisibility; +use App\Enums\CampaignRole; +use App\Enums\Kinship; +use App\Enums\Visibility; use App\Livewire\Concerns\InteractsWithCampaign; use App\Models\Campaign; use App\Models\Entity; @@ -12,6 +15,8 @@ use App\Models\User; use Illuminate\Contracts\View\View; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Support\Collection as SupportCollection; +use Illuminate\Validation\Rule; use Livewire\Component; /** @@ -31,6 +36,9 @@ class Relations extends Component public string $reverseLabel = ''; + /** A Kinship value, or '' for a relationship that is not family. */ + public string $kinship = ''; + public bool $showParty = false; public function mount(Campaign $campaign, Entity $entity): void @@ -45,15 +53,21 @@ public function relate(RelateEntities $relateEntities): void { $this->authorize('manageRelations', $this->entity); + // The labels fill in from the kinship when the GM leaves them blank, so a + // kinship row needs no words; a plain relationship still does. $validated = $this->validate([ 'targetId' => ['required', 'string', 'different:entity.id'], - 'label' => ['required', 'string', 'max:'.EntityRelation::MAX_LABEL_LENGTH], + 'kinship' => ['nullable', Rule::enum(Kinship::class)], + 'label' => ['required_without:kinship', 'nullable', 'string', 'max:'.EntityRelation::MAX_LABEL_LENGTH], 'reverseLabel' => ['nullable', 'string', 'max:'.EntityRelation::MAX_LABEL_LENGTH], 'showParty' => ['boolean'], ], [ 'targetId.different' => 'A page cannot be related to itself.', + 'label.required_without' => 'Say what this page is to the other, or pick a kinship.', ]); + $kinship = filled($validated['kinship'] ?? null) ? Kinship::from($validated['kinship']) : null; + if ($validated['targetId'] === $this->entity->id) { $this->addError('targetId', 'A page cannot be related to itself.'); @@ -73,12 +87,13 @@ public function relate(RelateEntities $relateEntities): void $relateEntities->handle( $this->entity, $target, - trim($validated['label']), - filled($validated['reverseLabel']) ? trim($validated['reverseLabel']) : null, + filled($validated['label']) ? trim((string) $validated['label']) : (string) $kinship?->label(), + filled($validated['reverseLabel']) ? trim((string) $validated['reverseLabel']) : $kinship?->reverse()->label(), (bool) $validated['showParty'], + $kinship, ); - $this->reset('targetId', 'label', 'reverseLabel', 'showParty'); + $this->reset('targetId', 'label', 'reverseLabel', 'kinship', 'showParty'); } public function remove(string $relationId, RemoveRelation $removeRelation): void @@ -107,9 +122,99 @@ public function render(): View 'incoming' => $this->entity->incomingRelations()->visibleTo($user, $role)->with('source')->orderBy('created_at')->get(), 'canManage' => $canManage, 'targetOptions' => $canManage ? $this->targetOptions() : collect(), + 'kinships' => Kinship::cases(), + 'family' => $this->family($user, $role), ]); } + /** + * The family, walked from this character two generations up and two down. + * + * One query for every kinship row this viewer may see in the campaign, through + * the relations scope, and then a walk in memory. That is what makes the second + * hop as safe as the first: a row the scope refused is not in the graph, so a + * GM-only grandmother is never reached through a revealed mother. A campaign's + * kinship rows are a handful, and one query for all of them is cheaper than a + * query per hop. + * + * A row is read from either end: the source is its kinship of the target, and + * the target is the reverse of the source. The "hidden" mark is for a GM, who + * reads every row, and says the party would not: the row is unrevealed or the + * relative is not a page the party may see. + * + * @return array>|null + */ + private function family(User $user, CampaignRole $role): ?array + { + if (! $this->entity->isCharacter()) { + return null; + } + + $rows = EntityRelation::query() + ->visibleTo($user, $role) + ->whereNotNull('kinship') + ->with(['source', 'target']) + ->get(); + + if ($rows->isEmpty()) { + return null; + } + + /** @var array> $edges */ + $edges = []; + + foreach ($rows as $row) { + if ($row->kinship === null) { + continue; + } + + $edges[$row->target_entity_id][] = ['kinship' => $row->kinship, 'entity' => $row->source, 'hidden' => ! $row->player_visible || $row->source->visibility !== Visibility::Players]; + $edges[$row->entity_id][] = ['kinship' => $row->kinship->reverse(), 'entity' => $row->target, 'hidden' => ! $row->player_visible || $row->target->visibility !== Visibility::Players]; + } + + $me = $this->entity->id; + + if (! isset($edges[$me])) { + return null; + } + + /** @return SupportCollection */ + $of = function (string $id, Kinship $kinship, bool $throughHidden = false) use ($edges): SupportCollection { + return collect($edges[$id] ?? []) + ->filter(fn (array $edge) => $edge['kinship'] === $kinship) + ->map(fn (array $edge) => ['entity' => $edge['entity'], 'hidden' => $edge['hidden'] || $throughHidden]) + ->values(); + }; + + $parents = $of($me, Kinship::Parent); + $children = $of($me, Kinship::Child); + + $generations = [ + 'Grandparents' => $parents->flatMap(fn (array $parent) => $of($parent['entity']->id, Kinship::Parent, $parent['hidden'])), + 'Parents' => $parents, + 'Siblings' => $of($me, Kinship::Sibling), + 'Spouses' => $of($me, Kinship::Spouse), + 'Children' => $children, + 'Grandchildren' => $children->flatMap(fn (array $child) => $of($child['entity']->id, Kinship::Child, $child['hidden'])), + ]; + + $family = []; + + foreach ($generations as $heading => $people) { + $people = $people + ->reject(fn (array $person) => $person['entity']->id === $me) + ->unique(fn (array $person) => $person['entity']->id) + ->sortBy(fn (array $person) => $person['entity']->name) + ->values(); + + if ($people->isNotEmpty()) { + $family[$heading] = $people; + } + } + + return $family === [] ? null : $family; + } + /** * What a relationship may point at: anything in the campaign the viewer may see, * this page excluded. diff --git a/app/Models/EntityRelation.php b/app/Models/EntityRelation.php index 126fe14..af8c461 100644 --- a/app/Models/EntityRelation.php +++ b/app/Models/EntityRelation.php @@ -3,6 +3,7 @@ namespace App\Models; use App\Enums\CampaignRole; +use App\Enums\Kinship; use App\Models\Concerns\BelongsToCampaign; use Database\Factories\EntityRelationFactory; use Illuminate\Database\Eloquent\Attributes\Fillable; @@ -21,7 +22,8 @@ * It adds one gate the pin does not need, on the source, because the incoming list * on the target's page is built from rows whose source is somebody else. * - * @property string $id + * @property string|null $reverse_label + * @property Kinship|null $kinship What the row means when it is family, from the source's side. * @property string $campaign_id * @property string $entity_id * @property string $target_entity_id @@ -36,7 +38,7 @@ * @property-read Entity $target */ #[Fillable([ - 'campaign_id', 'entity_id', 'target_entity_id', 'label', 'reverse_label', 'player_visible', 'position', + 'campaign_id', 'entity_id', 'target_entity_id', 'label', 'reverse_label', 'kinship', 'player_visible', 'position', ])] class EntityRelation extends Model { @@ -50,6 +52,7 @@ class EntityRelation extends Model protected function casts(): array { return [ + 'kinship' => Kinship::class, 'player_visible' => 'boolean', 'position' => 'integer', ]; diff --git a/database/migrations/2026_09_13_194148_add_kinship_to_entity_relations_table.php b/database/migrations/2026_09_13_194148_add_kinship_to_entity_relations_table.php new file mode 100644 index 0000000..7a06ab1 --- /dev/null +++ b/database/migrations/2026_09_13_194148_add_kinship_to_entity_relations_table.php @@ -0,0 +1,27 @@ +string('kinship', 8)->nullable()->after('reverse_label'); + }); + } + + public function down(): void + { + Schema::table('entity_relations', function (Blueprint $table) { + $table->dropColumn('kinship'); + }); + } +}; diff --git a/database/seeders/DemoCampaignSeeder.php b/database/seeders/DemoCampaignSeeder.php index 8fe8078..bf15cf5 100644 --- a/database/seeders/DemoCampaignSeeder.php +++ b/database/seeders/DemoCampaignSeeder.php @@ -43,6 +43,7 @@ use App\Actions\Table\SetScreen; use App\Enums\CampaignRole; use App\Enums\EntityType; +use App\Enums\Kinship; use App\Enums\PrepRole; use App\Enums\QuestStatus; use App\Enums\Rsvp; @@ -213,7 +214,7 @@ public function run(): void $this->seedGenerators($campaign, $dm); $this->seedDiceLog($campaign, $dm, $player); $this->seedMaps($campaign, $dm); - $this->seedRelations($campaign); + $this->seedRelations($campaign, $dm); $this->seedClocks($campaign); $this->seedHandouts($campaign, $dm); @@ -285,11 +286,24 @@ private function seedEvents(\Closure $make): void /** * Who is what to whom. One of them the party has not been told. */ - private function seedRelations(Campaign $campaign): void + private function seedRelations(Campaign $campaign, User $dm): void { $named = fn (string $name): Entity => $campaign->entities()->where('name', $name)->firstOrFail(); $relate = app(RelateEntities::class); + // The family. The abbess is Mara's mother and the party knows it; Wren's + // sister is a GM-only page, so the sibling row is a tree the GM alone reads. + $iselle = app(CreateEntity::class)->handle($campaign, $dm, [ + 'type' => EntityType::Character, + 'name' => 'Iselle Ashgrove', + 'visibility' => Visibility::Dm, + 'body' => "[[Wren Ashgrove]]'s sister. Alive, underwater, at [[The Drowned Duke]]'s right hand.", + 'tags' => ['npc'], + ]); + + $relate->handle($named('Abbess Corvane'), $named('Mara Voss'), 'mother of', 'daughter of', true, Kinship::Parent); + $relate->handle($iselle, $named('Wren Ashgrove'), 'sister of', 'sister of', false, Kinship::Sibling); + $relate->handle($named('Mara Voss'), $named('Tidewarden Signet'), 'keeper of', 'kept by', true); $relate->handle($named('The Drowned Duke'), $named('Mara Voss'), 'employer of', 'secretly works for', false); $relate->handle($named('Mara Voss'), $named('Wren Ashgrove'), 'trusts', 'trusted by', true); diff --git a/docs/plans/2026-09-13-feat-family-trees-plan.md b/docs/plans/2026-09-13-feat-family-trees-plan.md index d379851..0cb7905 100644 --- a/docs/plans/2026-09-13-feat-family-trees-plan.md +++ b/docs/plans/2026-09-13-feat-family-trees-plan.md @@ -2,7 +2,7 @@ title: "feat: Family trees, drawn from typed relationships" type: feat date: 2026-09-13 -status: planned +status: implemented brainstorm: docs/brainstorms/2026-09-02-demgem-campaign-manager-brainstorm.md follows: docs/plans/2026-09-13-feat-downtime-plan.md --- @@ -104,3 +104,32 @@ Then the full suite with `memory_limit=1G`, and a browser pass: as the GM, relat - `.ai/rules/entities.md` — relationships are a GM's to write; the target picker and the per-page lookup. - `.ai/rules/models.md` — a relationship is gated at both ends, in the scope. - `.ai/rules/api.md` — an added key on a resource. + +## Implementation Results — 2026-09-13 + +Implemented in full. 8 new tests; the suite is 1442 tests, 1441 passing, 1 skipped, with Larastan clean and Pint clean. + +### What shipped, against the plan + +| Planned | Shipped | +|---|---| +| `entity_relations.kinship` | As planned, cast to `Kinship`, with `label()`, `reverse()`, and `plural()` on the enum. | +| The labels from the kinship | `required_without:kinship` on the label; a blank label and a blank reverse label take the two words, and typed ones win. | +| The tree as one query and a walk | `Relations::family()`: every kinship row the viewer may see, both ends eager-loaded, walked two up and two down in memory. The leak test reads a hidden spouse and a GM-only sister from the player's seat and finds neither in the markup or the snapshot. | +| The card | A "Family" card above "Relationships" on a character's page, generations as rows of name chips, with a "Hidden" mark for a GM. | +| The round trip and the API | `kinship` on every relation row; the reader accepts an absent key and refuses a value it does not know; both API relation lists carry it, the incoming one from the page's side. | +| The demo world | Abbess Corvane is Mara's mother, revealed; Iselle Ashgrove is a new GM-only page, Wren's sister, on a hidden row. | + +### Deviations + +| Planned | Shipped | Why | +|---|---|---| +| `RelationsTest` unchanged | One expected array gained `kinship: null` | The test compares the exported relation row in full, and an added key is the export policy. | + +### Browser checks + +Driven end to end on the seeded world at 1400px as the GM and 1024px as the player: + +- On Mara Voss the GM picks Abbess Corvane, "Child of", and "Show the party", with both labels blank. The row reads "child of Abbess Corvane" and the Family card reads "Parents: Abbess Corvane". +- The abbess's page reads "parent of Mara Voss" and "Children: Mara Voss" without a second row. +- The player opens Mara and reads the same Family card, and no picker. diff --git a/resources/views/livewire/entities/relations.blade.php b/resources/views/livewire/entities/relations.blade.php index c6d13cb..10fef7e 100644 --- a/resources/views/livewire/entities/relations.blade.php +++ b/resources/views/livewire/entities/relations.blade.php @@ -1,4 +1,29 @@ -
+
+ {{-- The family, as generations. Every person here came through the relations + scope, both ends gated, and the walk never left the rows it loaded. A GM + reads a mark on anyone the party would not see. --}} + @if ($family !== null) + +
    + @foreach ($family as $heading => $people) +
  1. + {{ $heading }} + +
  2. + @endforeach +
+
+ @endif + @if ($outgoing->isNotEmpty() || $incoming->isNotEmpty() || $canManage) @if ($outgoing->isEmpty() && $incoming->isEmpty()) @@ -37,6 +62,12 @@ @endforeach + + + @foreach ($kinships as $option) + + @endforeach +
Relate diff --git a/tests/Feature/Entities/FamilyTreeTest.php b/tests/Feature/Entities/FamilyTreeTest.php new file mode 100644 index 0000000..62923ff --- /dev/null +++ b/tests/Feature/Entities/FamilyTreeTest.php @@ -0,0 +1,226 @@ +create(); + $player = memberOf($campaign, CampaignRole::Player); + + $character = fn (string $name, string $slug) => Entity::factory()->for($campaign)->type(EntityType::Character)->forPlayers() + ->create(['name' => $name, 'slug' => $slug]); + + $old = $character('Old Corvane', 'old-corvane'); + $abbess = $character('Abbess Corvane', 'abbess-corvane'); + $mara = $character('Mara Voss', 'mara-voss'); + $sten = $character('Sten Voss', 'sten-voss'); + $little = $character('Little Voss', 'little-voss'); + $tide = $character('Tide Voss', 'tide-voss'); + $wren = Entity::factory()->for($campaign)->pcOf($player)->forPlayers()->create(['name' => 'Wren Ashgrove', 'slug' => 'wren-ashgrove']); + $iselle = Entity::factory()->for($campaign)->type(EntityType::Character)->dmOnly()->create(['name' => 'Iselle Ashgrove', 'slug' => 'iselle-ashgrove']); + + $kin = fn (Entity $source, Entity $target, Kinship $kinship, bool $shown = true) => EntityRelation::factory() + ->between($source, $target) + ->create([ + 'label' => $kinship->label(), + 'reverse_label' => $kinship->reverse()->label(), + 'kinship' => $kinship, + 'player_visible' => $shown, + ]); + + // Written from both directions on purpose: the tree reads a row whichever + // side the GM happened to write it from. + $kin($old, $abbess, Kinship::Parent); + $kin($abbess, $mara, Kinship::Parent); + $kin($mara, $little, Kinship::Parent); + $kin($tide, $little, Kinship::Child); + $kin($sten, $mara, Kinship::Spouse, false); + $kin($iselle, $wren, Kinship::Sibling); + + return compact('campaign', 'player', 'old', 'abbess', 'mara', 'sten', 'little', 'tide', 'wren', 'iselle'); +} + +function relationsCardOf(Entity $entity, ?User $viewer = null) +{ + return Livewire::actingAs($viewer ?? ownerOf($entity->campaign)) + ->test(Relations::class, ['campaign' => $entity->campaign, 'entity' => $entity]); +} + +it('fills the labels from the kinship when the GM leaves them blank, and keeps typed ones', function () { + ['abbess' => $abbess, 'mara' => $mara, 'old' => $old] = houseOfVoss(); + + relationsCardOf($mara) + ->set('targetId', $old->id) + ->set('kinship', 'child') + ->call('relate') + ->assertHasNoErrors(); + + $row = EntityRelation::withoutGlobalScopes()->where('entity_id', $mara->id)->where('target_entity_id', $old->id)->firstOrFail(); + + expect($row->kinship)->toBe(Kinship::Child) + ->and($row->label)->toBe('child of') + ->and($row->reverse_label)->toBe('parent of'); + + relationsCardOf($abbess) + ->set('targetId', $old->id) + ->set('kinship', 'child') + ->set('label', 'youngest daughter of') + ->set('reverseLabel', 'mother of') + ->call('relate') + ->assertHasNoErrors(); + + $typed = EntityRelation::withoutGlobalScopes()->where('entity_id', $abbess->id)->where('target_entity_id', $old->id)->firstOrFail(); + + expect($typed->kinship)->toBe(Kinship::Child) + ->and($typed->label)->toBe('youngest daughter of') + ->and($typed->reverse_label)->toBe('mother of'); +}); + +it('still wants a label when there is no kinship to take one from', function () { + ['mara' => $mara, 'old' => $old] = houseOfVoss(); + + relationsCardOf($mara) + ->set('targetId', $old->id) + ->set('kinship', '') + ->set('label', '') + ->call('relate') + ->assertHasErrors('label'); +}); + +it('draws the generations from typed rows, whichever side they were written from', function () { + ['mara' => $mara] = houseOfVoss(); + + relationsCardOf($mara) + ->assertSee('Family') + ->assertSeeInOrder([ + 'Grandparents', 'Old Corvane', + 'Parents', 'Abbess Corvane', + 'Spouses', 'Sten Voss', + 'Children', 'Little Voss', + 'Grandchildren', 'Tide Voss', + ]) + ->assertDontSee('Siblings'); +}); + +it('reads the same family from the other end of the rows', function () { + ['abbess' => $abbess, 'tide' => $tide] = houseOfVoss(); + + // The family data rather than the markup, because the target picker under the + // card names every character in the campaign. + $names = fn (Entity $entity): array => collect(relationsCardOf($entity)->viewData('family')) + ->map(fn ($people) => $people->pluck('entity.name')->all()) + ->all(); + + expect($names($abbess))->toBe([ + 'Parents' => ['Old Corvane'], + 'Children' => ['Mara Voss'], + 'Grandchildren' => ['Little Voss'], + ])->and($names($tide))->toBe([ + 'Grandparents' => ['Mara Voss'], + 'Parents' => ['Little Voss'], + ]); +}); + +it('never shows the party a hidden row or a GM-only relative, and marks both for the GM', function () { + ['campaign' => $campaign, 'player' => $player, 'mara' => $mara, 'wren' => $wren] = houseOfVoss(); + + $component = relationsCardOf($mara, $player) + ->assertSee('Family') + ->assertSee('Abbess Corvane') + ->assertSee('Little Voss') + ->assertDontSee('Sten Voss') + ->assertDontSee('Spouses'); + + expect(json_encode($component->snapshot))->not->toContain('Sten Voss'); + + $wrens = relationsCardOf($wren, $player) + ->assertDontSee('Family') + ->assertDontSee('Iselle Ashgrove'); + + expect(json_encode($wrens->snapshot))->not->toContain('Iselle'); + + relationsCardOf($wren, ownerOf($campaign)) + ->assertSeeInOrder(['Family', 'Siblings', 'Iselle Ashgrove']) + ->assertSee('Hidden'); +}); + +it('draws no family card without a kinship row', function () { + ['campaign' => $campaign, 'mara' => $mara] = houseOfVoss(); + + $duke = Entity::factory()->for($campaign)->type(EntityType::Character)->forPlayers()->create(['name' => 'The Drowned Duke', 'slug' => 'drowned-duke']); + EntityRelation::factory()->between($duke, $mara)->shownToPlayers()->create(['label' => 'employer of']); + + relationsCardOf($duke) + ->assertSee('employer of') + ->assertDontSee('Family'); +}); + +it('travels in the export and the API, and the reader refuses a kinship it does not know', function () { + ['campaign' => $campaign, 'player' => $player, 'abbess' => $abbess, 'mara' => $mara] = houseOfVoss(); + + $document = exportedArray($campaign); + $abbessRow = collect($document['entities'])->firstWhere('slug', 'abbess-corvane'); + + expect(collect($abbessRow['relations'])->firstWhere('target_entity_id', $mara->id)['kinship'])->toBe('parent'); + + $copy = app(ImportCampaign::class)->handle( + app(ReadCampaignFile::class)->handle(json_encode($document, JSON_THROW_ON_ERROR))->document, + User::factory()->create(), + ); + + $newAbbess = Entity::withoutGlobalScopes()->where('campaign_id', $copy->id)->where('slug', 'abbess-corvane')->firstOrFail(); + + expect(EntityRelation::withoutGlobalScopes()->where('entity_id', $newAbbess->id)->firstOrFail()->kinship)->toBe(Kinship::Parent); + + asKey($player) + ->getJson("/api/v1/campaigns/{$campaign->id}/entities/{$abbess->id}") + ->assertOk() + ->assertJsonPath('data.relations.0.kinship', 'parent') + ->assertJsonPath('data.incoming_relations.0.kinship', 'child'); + + $document['entities'] = array_map(function (array $row): array { + $row['relations'] = array_map(fn (array $relation) => [...$relation, 'kinship' => 'cousin'], $row['relations']); + + return $row; + }, $document['entities']); + + $read = app(ReadCampaignFile::class)->handle(json_encode($document, JSON_THROW_ON_ERROR)); + + expect($read->succeeded())->toBeFalse() + ->and(implode(' ', $read->errors))->toContain('cousin'); +}); + +it('reads an older file whose relations carry no kinship', function () { + ['campaign' => $campaign] = houseOfVoss(); + + $document = exportedArray($campaign); + $document['entities'] = array_map(function (array $row): array { + $row['relations'] = array_map(function (array $relation): array { + unset($relation['kinship']); + + return $relation; + }, $row['relations']); + + return $row; + }, $document['entities']); + + $read = app(ReadCampaignFile::class)->handle(json_encode($document, JSON_THROW_ON_ERROR)); + + expect($read->succeeded())->toBeTrue() + ->and(collect($read->document['entities'])->flatMap(fn (array $row) => $row['relations'])->pluck('kinship')->unique()->all())->toBe([null]); +}); diff --git a/tests/Feature/Entities/RelationsTest.php b/tests/Feature/Entities/RelationsTest.php index 57108a1..2c90c0b 100644 --- a/tests/Feature/Entities/RelationsTest.php +++ b/tests/Feature/Entities/RelationsTest.php @@ -120,6 +120,7 @@ function relationsOf(Entity $entity) 'target_entity_id' => $mara->id, 'label' => 'employer of', 'reverse_label' => 'works for', + 'kinship' => null, 'player_visible' => true, 'position' => 0, ]]);