Compare commits

..

86 Commits

Author SHA1 Message Date
Sylvain Duchesne 05ee576d7d refactor(comments): retirer les raisonnements sur l'état de NextGraph du code app
Application de la règle qu'on vient de durcir : l'app IGNORE entièrement l'état
d'implémentation de NextGraph. Le CODE était légitime — `inbox.readSynced` est
une surface SDK exportée ; ce sont les JUSTIFICATIONS qui fautaient, en
expliquant les choix par des internes du cœur.

Réécrit en termes de CONTRAT :
- registration.ts / FestipodDataContext : « barrier-gated read, le repo d'inbox
  n'est pas encore ouvert dans le verifier, un read ancré renverrait 0 » devient
  « `read` rend ce qui est connu localement maintenant, `readSynced` rend une
  fois les dépôts synchronisés visibles ; ce site a besoin du second parce qu'il
  lit depuis une session froide ».
- ngBootstrap : « le verifier sérialise les créations » devient « `docCreate` est
  un aller-retour qui ne recouvre pas le suivant, donc le coût du seed croît
  LINÉAIREMENT avec le nombre de documents ». Le ~2s mesuré est conservé, mais
  explicitement comme une observation, pas comme un contrat.
- entityWrites : description de lecture périmée (ORM fan-out, ngSet couplé au
  scope) remplacée par la vue réactive.

La distinction read/readSynced vit désormais là où elle est légitime :
knowledge_sdk-surface, avec le critère de choix (`read` dans une session qui
observe déjà l'inbox, `readSynced` dès que la justesse dépend d'une session
froide voyant le dépôt d'une autre identité). knowledge_context-internals cesse
d'expliquer le fix par `ensureRepoOpen`/premier `State` et pointe le contrat.

Laissé tel quel : `src/shared/support/hooks.ts` et les steps e2e — le harness de
test connaît légitimement la plomberie ; la règle vise l'app. Et le « no
cross-account fan-out » de FestipodDataContext, qui décrit le périmètre de l'app
et non NextGraph.

tsc : 0 erreur.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-28 17:17:47 +02:00
Sylvain Duchesne 7459d49e83 docs+fix: recadrer le polyfill comme compensateur d'écart, corriger la doctrine périmée
RECADRAGE — la doctrine était trop étroite. rule_app-uses-sdk-surface-only
disait « le polyfill existe pour le WALLET VIRTUEL » : juste sur le fond, mais à
la lettre l'émulation des caps qu'on vient de livrer n'entrait pas dans son
mandat. Nouvelle formulation, portée aussi dans AGENTS.md :

  @ng-eventually/client est un POLYFILL, et ce mot dit toute sa mission :
  compenser l'écart entre le SDK tel qu'il devrait être et ce que NextGraph
  fournit aujourd'hui. Le wallet virtuel en est la plus grosse pièce, pas la
  totalité.

Avec la conséquence opérationnelle : quand quelque chose ne marche pas, la
question n'est jamais « comment contourner dans l'app » mais « qu'est-ce que le
polyfill doit compenser ». Un contournement côté app est une violation même
quand il fonctionne — il grave un état temporaire de NextGraph dans du code qui
doit lui survivre. Et l'ignorance de l'état d'implémentation est durcie :
ENTIÈREMENT, pas « sauf quand ça mord ».

NOUVEAU — data-layer/knowledge_sdk-surface : le contrat SDK cible, écrit dans CE
repo pour qu'un agent n'ait jamais à ouvrir le repo du polyfill. Couvre lectures
réactives, écritures, placement par scope, inbox, discovery, capabilities
(capFor/shareCap/publishRepoLink, livrées avec P1a), identité, sûreté SPARQL —
et les surfaces exportées mais interdites à l'app.

DOCTRINE PÉRIMÉE corrigée, après vérification dans le code :
- rule_document-per-entity décrivait la lecture via readEntities/readUnion/
  registerDoc/bumpRead : ZÉRO site d'appel, readEntities.ts supprimé. Réécrite
  sur watchShape/useShapeQuery. Le fond (un document par entité) est intact.
- brief_2026-07-06 §P3 réaffirmait une phrase que son propre encadré déclare
  fausse : rétractée explicitement.
- knowledge_data-modes citait useShapeWithDefaults(), qui n'existe nulle part.
- ConnectScreen : les fiches avaient raison mais étaient vagues — l'écran existe,
  est routé et monté, et est bien absent du registre. Précisé.

FIX CODE — build:orm était CASSÉ : il pointait ./src/shapes/, qui n'existe pas
(les shapes vivent sous src/shared/shapes/), et sortait en erreur. Donc la
commande que la doctrine prescrit après tout changement de .shex ne marchait
pas. Corrigé et vérifié : exit 0. La fiche avait raison, c'est le code qui était
faux — le point 4 approuvé, simplement situé dans l'autre fichier.

Régénération NON embarquée : lancer build:orm reformate les bindings et retire
l'annotation `: Schema`. C'est une montée de version d'outil, pas une correction
de contenu — elle mérite son propre changement validé, pas un passage clandestin.
Noté dans la fiche.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-28 16:49:27 +02:00
Sylvain Duchesne b6a6b14fad docs(concept): passer les 59 fiches de doctrine en anglais
Convention du projet pour la documentation projet. Traduction fidèle, sans
changement de fond : mêmes fiches, mêmes sections, mêmes liens. Le lint est
identique à la baseline (59 leaves, 0 nouveau lien cassé, wikilinks bit-à-bit
inchangés) et aucun `.feature` n'a été touché.

Le `summary:` du frontmatter est traduit lui aussi — c'est ce que le hook affiche
dans l'index, il porte autant que le corps.

RESTENT EN FRANÇAIS, délibérément :
- les fichiers .feature (convention explicite du projet : Etant donné/Quand/Alors)
  et le bloc Gherkin cité dans brief_2026-07-06 ;
- les libellés d'interface cités en prose (« Entrer », « ✓ Je participe »,
  « Voir tous les participants », « participant inconnu »…) : ce sont des chaînes
  réelles de l'app, pas de la prose ;
- les noms de scénarios BDD ;
- les `triggers.keywords` des _overview : jetons de matching du hook, et la
  conversation reste en français — les traduire aurait cassé la livraison.

EFFET SECONDAIRE UTILE : relire intégralement a fait remonter des contradictions
et des péremptions que personne ne voyait section par section. Notées, non
corrigées (hors périmètre de la traduction) :
- rule_document-per-entity décrit la lecture via readEntities/readUnion/
  registerDoc/bumpRead, que rule_app-uses-sdk-surface-only déclare SUPPRIMÉS au
  profit de watchShape/useShapeQuery. Une règle qui décrit des APIs retirées est
  activement trompeuse — à traiter en priorité.
- brief_2026-07-06 §P3 réaffirme « prouvé par l'e2e D.2, sans reload » juste
  après l'encadré qui déclare cette phrase fausse et sur-cadrée.
- knowledge_data-modes cite useShapeWithDefaults() là où useShapeQuery est
  documenté ailleurs.
- knowledge_stack-and-commands : build:orm pointe ./src/shapes/* alors que les
  shapes vivent sous src/shared/shapes/.
- knowledge_screens / knowledge_routing : ConnectScreen décrit comme absent du
  registre mais présent en route.
- brief_2026-05-18 : « identifié si connecté » était ambigu en français (session
  ouverte vs est une connexion) ; l'anglais a forcé à trancher — rendu par
  « if a connection », à confirmer côté produit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-28 16:27:24 +02:00
Sylvain Duchesne 3ec3b37a65 docs(concept): poser le principe de lecture publique non récursive
Remplace le point « validation d'existence impossible » — qui traînait une
préoccupation de forgerie hors périmètre — par le principe qui fait réellement
tenir le modèle :

  Un élément du store public est public : qui a l'URL lit le contenu.
  Mais PAS récursivement — un contenu public peut référencer du contenu privé.

C'est exactement notre cas. Le créateur lit la Participation (publique) et ne
peut pas suivre la référence vers le profil (protected). Lecture par le créateur
ET anonymat vis-à-vis de lui, sans aucun mécanisme supplémentaire.

Le compteur est Set.size. Rien d'autre à en dire.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-27 17:05:39 +02:00
Sylvain Duchesne e2adfacb0b docs(concept): la validation d'existence est IMPOSSIBLE, pas optionnelle
Le brief inscriptions disait que le créateur pouvait vérifier qu'un did pointe
sur un objet réel sans détenir la clé, et rangeait ça en durcissement optionnel.
Faux : le contrôle d'accès en lecture laisse bien passer, mais l'ADRESSAGE
présuppose le cap — aucune commande d'existence au niveau SDK, et une référence
cap-less n'a ni les identifiants de blocs ni l'overlay nécessaires.

Conséquence assumée, écrite noir sur blanc : le créateur ajoute la référence SUR
PAROLE, donc le compteur est déclaratif et forgeable. Hors périmètre sécurité,
mais cette étape ne doit pas être présentée comme une validation.

Le modèle lui-même n'en dépendait pas — il était déjà noté comme non requis.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-27 16:08:15 +02:00
Sylvain Duchesne 96e28a702f docs(concept): solder la doc-debt des 6 concepts
Dette accumulée depuis le 13/07 (27 marqueurs). Au-delà du vidage, trois
corrections de doctrine réellement fausse — c'est ce que le reconcile devait
attraper :

- app-security : `sharedWallet.ts` capture le mot de passe à l'ÉVALUATION du
  module. Tant qu'un repli existait, un global posé trop tard ne faisait que
  dégrader ; depuis que le wallet partagé est l'unique mode, il rend la barrière
  INUTILISABLE (écran d'erreur, aucun champ). Conséquence non anticipée de la
  décision shared-wallet-only → nouveau caveat.
- bdd-testing : la doctrine rendait des tests faux-verts. `ctx.newPage()` sur le
  profil persistant relit l'IndexedDB local et ne prouve JAMAIS la durabilité
  broker ; seul un contexte partagé neuf tranche. Un agent suivant la doctrine
  écrivait un test qui passe sans rien vérifier → nouveau caveat.
- app-architecture : `knowledge_routing` décrivait encore une route `/login`
  disparue, et `knowledge_screen-pattern` citait `LoginScreen` qui n'existe
  plus. Nouveau caveat sur les deux espaces d'id vus depuis un écran.

Aussi : data-layer/knowledge_context-internals décrit la jointure
participation→profil et corrige un mécanisme de changement d'identité périmé ;
tech-stack raccroche la table des scripts au vrai point d'entrée cucumber ;
functional-domain note qu'« implémenté » ≠ « durable ».

Trois marqueurs soldés comme sans objet : ils visaient
`reconnexion-socket-mort.{feature,steps.ts}`, absents de l'arbre ET de tout
l'historique — expérience abandonnée avant tout commit. Ce qu'elle devait
établir est capturé ailleurs (caveat de durabilité, post-mortem polyfill, fiche
INBOX socket-death).

Liens morts vers une décision disparue avec le concept `nextgraph-platform`
réparés. Reste au lint : le brief 07-06 (superseded) porte des file:line et des
références aux internes NextGraph — laissé intact, il décrit l'Option-B encore
implémentée et se dissoudra à la graduation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-27 14:43:09 +02:00
Sylvain Duchesne a8401bd143 docs(concept): inscriptions — Participation lisible + drapeau active, purge par le créateur
Affinement PO du 2026-07-27. La Participation devient LISIBLE par tous et se
réduit à trois choses : référence à l'événement, booléen `active`, did cap-less
vers le profil protected du participant. Pas de description pour l'instant.

Ce que ça débloque : une suppression n'est pas détectable sans la clé (vérifié),
ce qui imposait un nudge forgeable pour la désinscription. Un objet lisible avec
un drapeau change la nature du problème — l'annulation n'est plus à DÉTECTER,
elle est à LIRE. Le blocage disparaît au lieu d'être contourné.

Le principe qui tient l'ensemble : la vérité est dans l'objet que le participant
contrôle, tout message n'est qu'un indice. Un faux « purge X » conduit le
créateur à lire X, la voir active, et ne rien faire. La forgerie devient
structurellement inoffensive — d'où l'absence de besoin de signer les dépôts
d'inbox, ce qui tombe bien : NextGraph ne l'offre pas (inbox non authentifiée,
vérification de signature non implémentée et exigeant de déchiffrer).

Le pointeur d'identité vise le profil protected existant, pas un second document
par participation : les connexions en détiennent déjà le cap. Ajouter une
connexion ne réécrit donc rien — on scelle une fois, durablement. Un champ
chiffré dans la Participation aurait exigé de re-sceller à N destinataires et de
réécrire à chaque nouvelle connexion (et n'est pas un primitif NextGraph : la
granularité de chiffrement est le document, en tout-ou-rien).

Arbitrages assumés : pas de filtrage à la lecture (Set.size est une borne haute,
exacte après purge — obsolescence acceptée pour garder la lecture en O(1)) ;
la purge incombe au créateur ; pas de description.

Point ouvert noté : Participation passe en scope public alors que la doctrine
produit la place en protected. Ce leaf décrit l'implémenté — à mettre à jour à
la graduation du brief, pas avant.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-27 13:49:18 +02:00
Sylvain Duchesne ab077d8080 docs(concept): réserve durable sur le pseudonyme permanent de l'overlay
app-security/caveat_stable-overlay-pseudonym (nouveau) — toute référence
cap-less vers un document protected expose le `✌️` du store, identique partout
et pour toujours. BLAKE3 non inversible le rend OPAQUE, d'où la tentation de le
croire INOFFENSIF : ce sont deux choses différentes. C'est la constance qui
expose, pas la lisibilité. Un seul recoupement, une seule fois, et tout
l'historique bascule — y compris ce qui a été publié des années plus tôt.

Aucune porte de sortie, vérifié sur quatre axes : pas de rotation d'overlay,
store id généré une fois pour toutes, aucune migration de contenu, aucune forme
de référence n'évitant d'exposer l'overlay. Le renouvellement de capabilities
ne toucherait que l'inner ; l'outer y survit.

Placé en app-security et non dans le brief inscriptions : un brief se dissout à
sa graduation, la réserve doit lui survivre. Le brief n'en garde qu'un résumé
et pointe dessus. Déclencheurs élargis (anonymat, pseudonyme, traçage,
corrélation, overlay, cap-less) pour qu'elle remonte quand on s'apprête à
concevoir de l'« anonyme ».

Consigne pratique qui en découle : ne jamais présenter une action comme
« anonyme » si elle fait circuler une référence cap-less — c'est pseudonyme,
et le pseudonyme est permanent.

Dédup par `✌️` validée par le PO ; le brief le note.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-27 12:31:55 +02:00
Sylvain Duchesne 42dbfd0c34 docs(concept): modèle d'inscription recalé + l'inbox NextGraph suit aussi les manques
Le brief inscriptions est réécrit sur le modèle reposé par le PO : tout est
clés et URLs, sans notion d'appartenance. Le participant crée une Participation
chiffrée, dépose son did (URI sans ReadCap) dans l'inbox de l'événement ; le
créateur traite l'inbox automatiquement, déduplique sans pouvoir lire, et range
la référence dans un Set porté par l'événement ; compteur = Set.size ; seules
les connexions détiennent la clé et reconnaissent la personne.

La dédup s'appuie sur un fait vérifié dans nextgraph-rs : l'overlay (segment
`✌️` d'un NURI) est STORE-scopé, jamais document-scopé. Deux Participations
d'une même personne portent donc le même `✌️`. Contrepartie actée dans le
brief : ce `✌️` est un pseudonyme stable et permanent — c'est le MÊME bit
d'information qui permet de dédupliquer sans lire et de tracer d'un événement
à l'autre ; on ne peut pas garder l'un sans l'autre.

Retiré du brief : le trilemme et la piste de dédup par vérification de
signature. Ils reposaient sur une notion de membership importée de l'état
courant du source Rust, où elle est un échafaudage inerte — erreur de méthode
désormais consignée en règle.

Règles :
- rule_capture-nextgraph-findings (nouvelle) — toute connaissance établie sur
  le fonctionnement réel de NextGraph se consigne AU MOMENT de la découverte
  dans la doc du polyfill ; distinguer VÉRIFIÉ d'INFÉRÉ ; ne jamais déduire la
  forme cible de l'état courant du source.
- rule_file-nextgraph-bugs → rule_nextgraph-inbox — l'inbox reçoit désormais
  DEUX familles : les dysfonctionnements ET les manques dont on a besoin. Une
  fiche de manque dit ce que le polyfill émule en attendant et ce qu'il faudra
  en RETIRER quand ça atterrit en amont : l'inbox devient un suivi de
  l'avancement de NextGraph, pas un simple bug-tracker.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-27 12:07:06 +02:00
Sylvain Duchesne 5b536ff981 docs(concept): brief inscriptions par Set + règle de report des bugs NextGraph
- data-layer/brief_2026-07-20_attendance-set-model : réaligner les inscriptions
  sur la vision initiale — objet participation auto-possédé (la vérité) + Set
  curé de références cap-less sur l'événement + cap scellé aux seules
  connexions ⇒ compteur = `Set.size`, présence anonyme par défaut, personne ne
  désinscrit autrui. Inclut la revue adverse (trilemme anonyme/dédup/inviolable)
  et les verdicts du spike P0 vérifiés dans `nextgraph-rs` :
  fetch d'existence sans clé = OUI, détection de suppression sans clé = NON
  (⇒ la désinscription passe par un nudge), confidentialité = OUI.
  Statut : direction cible, PAS un pivot immédiat.
- data-layer/rule_file-nextgraph-bugs : tout dysfonctionnement NextGraph
  identifié donne lieu à une fiche dans `../../nextgraph/orm-tests/INBOX/`.
- to-discuss : alignement ReadCap/WriteCap, terminologie identité NextGraph.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-27 11:30:12 +02:00
Sylvain Duchesne c5e627c5fc fix(participants): joindre participation→profil à travers les deux espaces d'id
Une Participation stocke son user comme principal stable
`urn:festipod:user:<clé>`, alors qu'un UserProfile a pour `id` son NURI
`did🆖`. La jointure brute `partUserIds.includes(u.id)` ne matchait donc
jamais en mode connecté → chaque participant s'affichait « inconnu ».

- `resolveParticipantUser` : match direct (espace seed demo) puis, à défaut,
  match sur `normalizeIdentifier(username)` après retrait du préfixe principal.
- `USER_PRINCIPAL_PREFIX` : source unique du préfixe, partagée par l'écriture
  (`currentUserId`) et la lecture, pour qu'elles ne divergent pas.
- EventDetailScreen : filtrer soi-même sur `currentUser?.id` (id de profil,
  même espace que `p.id`) et non sur `currentUserId` (principal).

Aussi : épingle `packageManager` pnpm (l'install passe par pnpm, cf.
rule_bun-first) — le runtime/test/build restent Bun.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-27 11:30:00 +02:00
Sylvain Duchesne 7e65a83d42 fix(test): cucumber via l'entrée JS réelle (@cucumber/cucumber/bin) — pnpm casse le shim .bin
pnpm installe node_modules/.bin/cucumber-js comme shim shell (pas du JS) → 'node --import tsx/esm node_modules/.bin/cucumber-js' échoue. Pointer sur l'entrée JS réelle du paquet. Répare test:data et cucumber:run.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-20 13:17:36 +02:00
Sylvain Duchesne 3a49376f17 test(reconnexion): repro à froid sans état local (@wip) + persistance/pause (@wip)
reconnexion-froide-sans-local = test décisif broker-vs-local (verdict LOCAL-ONLY), @wip. persistance-e2e + pause @wip. rename identifiant dans reconnexion/isolation/harness-ng.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-20 13:16:04 +02:00
Sylvain Duchesne e326bebd42 feat(auth): wallet partagé = seul mode + purge identifiant-wallet↔username
AccessGateScreen 3-branches (erreur config si pas de wallet partagé) ; renommage username→identifier de l'identité du wallet (registration, ngSession, hooks, steps auth) sans toucher UserProfile.username ; .env.example.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-20 13:16:04 +02:00
Sylvain Duchesne 46ed894621 feat(data): logs [app][data] identité-first + participantCount avant→après
Préfixe identité-first ; label participation ; valeur compteur avant/après écriture owner + lecture affichage. Additif.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-20 13:16:04 +02:00
Sylvain Duchesne a21d9b0735 docs(concept): durabilité écriture↔déconnexion, décision wallet-partagé-unique, rule_bun-first (install pnpm)
caveat_write-durability-across-disconnect + decision_2026-07-20 (wallet partagé = seul mode ; identifiant ≠ username profil) + amendement bun-first. Marqueurs _debt.md inclus (voyagent avec la branche, à réconcilier avant push).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-20 13:16:04 +02:00
Sylvain Duchesne f6fc3c262e chore: install via pnpm + polyfill depuis Gitea (git-https) + lien local réactif
Passe l'installation de bun à pnpm (runtime/build/test restent bun).
Dépendance prod @ng-eventually/client résolue depuis le Gitea public en
git+https (committée, reproductible via pnpm-lock.yaml). Script
link:polyfill (S2 copie-overlay + watcher) pour un lien local réactif
préservant l'instance @ng-org unique. bun (peer de bun-plugin-tailwind)
approuvé au build (pnpm.onlyBuiltDependencies) pour que
node_modules/.bin/bun soit un vrai binaire. Dockerfile: install pnpm
avec git + node dans l'image, runtime bun inchangé. Doctrine tech-stack
(deployment, stack-and-commands) mise à jour.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014GbGgNEHRejVKoREvFuDFg
2026-07-14 12:52:30 +02:00
Sylvain Duchesne 62693667a8 chore(data): provisionRetry → pointerGuard (résolution de compte barrière-autoritative)
Le polyfill ne fait plus de retry sur la résolution des comptes (désormais gated sur
la barrière first-State du doc-shim). L'app n'injecte plus qu'un micro-garde borné
(pointerGuard) sur la seule lecture du pointeur écrit-une-fois. Aucune mitigation de
fork/retry côté app — cette responsabilité vit entièrement dans le SDK.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 17:46:16 +02:00
Sylvain Duchesne 82004a30b0 fix(data): participantCount fiable à la connexion du propriétaire + source unique
Bug: user2 crée un événement, user1 s'inscrit et voit "1", mais user2 (créateur)
reste à 0. Recadrage (spec existante): l'exigence est "le propriétaire traite son
inbox à sa PROCHAINE CONNEXION", pas une notif live temps-réel.

Cause: le owner-materializer lisait l'inbox AVANT sa synchronisation → active=0 →
écrit 0 → mémoïse 0 → ne retraite plus.

Fix:
- Lecture inbox gated sur barrière: inbox.readSynced (ensureRepoOpen attend le 1er
  State, puis read — comme discovery.readIndex) au lieu de inbox.read. Un dépôt déjà
  synchronisé EST vu à la connexion. Pas de polling.
- Materializer déclenché directement à la connexion ([ready, ownedKey]).
- materializedCountRef ne verrouille plus un 0 prématuré (rôle = anti-boucle seul).
- Source UNIQUE du nombre = event.participantCount: le littéral participantCount:1
  de CreateEventScreen retiré (démarre à 0), l'affichage ne calcule plus de nombre
  local (ParticipantsListScreen). Le statut "Je participe" optimiste est intact.
- Logs [Attendance] sur tout le chemin dépôt→matérialisation→écriture.

Test: e2e-multibrowser "converge à la prochaine connexion" reframé + dé-@wip,
ROUGE avant / VERT après sur profil frais. Non-régression @multibrowser 4/4, @data 7/7.

Doctrine: knowledge_context-internals (caveat BUG ACTIF → CORRIGÉ), brief_2026-07-06
(cadrage "sans reload" = sur-cadrage; exigence = fiable à la connexion).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 16:40:37 +02:00
Sylvain Duchesne 0958d70132 docs(tech-stack): caveat Firefox 151+ LNA bloque l'iframe app du broker en dev
Piège coûteux : iframe blanche + zéro log app + aucune erreur = pas un bug
Festipod, c'est Local Network Access de Firefox qui bloque le broker public
d'embarquer l'app locale. Fix navigateur (network.lna.enabled=false). HTTPS
n'y change rien ; le top-level charge quand même ; le smoke ne peut pas l'attraper.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 16:06:08 +02:00
Sylvain Duchesne c0fd69344b feat(data): auto-seed opt-in (FESTIPOD_AUTO_SEED) + logs data lisibles; diag bug participantCount
Seed: l'auto-seed sur wallet vide est désormais OPT-IN, OFF par défaut — ne se
déclenche que si FESTIPOD_AUTO_SEED=1 (livré en dev via /festipod-config.json +
define build.ts, comme le shared-wallet). Le seed répété bloatait le wallet
(lenteurs de lecture). Seed explicite (loadTestData, tests @data) inchangé.

Logs: chaque useShapeQuery logge à la réception du set le nombre d'objets + le
type + des compteurs globaux cumulés :
  [FestipodData] set reçu: 9 objets Event (public) en 1234ms
  [FestipodData] totaux — Event: 9, Participation: 3, UserProfile: 10 (5 sets)
(polyfill docs.ts: "N rows" -> "N triple-rows" pour clarifier que ce sont des
triplets RDF, pas des objets métier.)

Diagnostic bug participantCount (NON corrigé, design-sensible): le propriétaire
d'un événement reste à participantCount=0 quand un inscrit d'un AUTRE verifier
dépose. Cause: le owner-materializer n'est re-déclenché que par ownedKey, jamais
par un push d'inbox — doc_subscribe ne délivre aucun Patch cross-session. Le
bloat de wallet MASQUAIT le bug (faux-vert). La théorie "StorageError" était
fausse. Scénario réactif @wip = test ROUGE qui documente le bug.

Doctrine: knowledge_context-internals (caveat BUG ACTIF + auto-seed opt-in),
brief_2026-07-06 (claim D.2 "prouvé vert" REFUTÉ), build-pipeline (nouvelle var).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 14:38:38 +02:00
Sylvain Duchesne 39b67feea0 feat(ui): spinner global près du titre Festipod + log du délai des requêtes
Chaque useShapeQuery s'enregistre dans un store module-level pendingQueries au
début de son cycle et se résout à son premier résultat (isPending→isSuccess|isError,
équivalent readPromise). HomeScreen affiche un Spinner à côté du titre "Festipod"
tant qu'au moins une requête est en attente ; il ne s'arrête que quand TOUTES ont
reçu leur premier résultat. Toute future useShapeQuery y contribue automatiquement.

À la 1re résolution, chaque cycle logge son délai :
  [FestipodData] <shape>/<scope> premier résultat en <N>ms (n=<len>)
→ le délai d'obtention des événements (Event/public) est visible nommément.

Store idempotent (Set d'ids, sûr sous StrictMode) ; cycleId mémoïsé sur
[shapeKey, scope] → re-begin sur switch d'identité, cleanup résout au démontage
(spinner jamais bloqué). Spinner = Loader2 lucide + @keyframes app-spin dans index.css.

Tests: pendingQueries.test.ts (6, dont "off seulement quand toutes résolues").
Doctrine: data-layer/knowledge_context-internals.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 13:51:36 +02:00
Sylvain Duchesne c7e924abe7 fix(auth): porter l'identité par param d'URL (?id=), pas localStorage; renommer username→identifier
Cause racine du décalage d'identité : l'app tourne dans DEUX contextes avec DEUX
partitions de localStorage — top-level (127.0.0.1:3000 direct, barrière) et iframe
(embarquée sous nextgraph.net après le round-trip broker). Le navigateur partitionne
le storage par site top-level, donc l'identifiant saisi en top-level n'est jamais
celui que l'app connectée lit dans l'iframe (symptôme: deux valeurs divergentes).

Fix : le param d'URL ?id= devient la SOURCE DE VÉRITÉ. Le SDK redirige avec
encodeURIComponent(window.location.href) (URL app complète, query comprise), donc
un param d'URL TRAVERSE la frontière contrairement à localStorage. AuthGate écrit
?id=<identifiant> (replaceState) avant connect(); AccountContext résout par priorité
(1) ?id= puis (2) localStorage (préremplissage same-partition seulement).

Renommage username→identifier (champ useAccount, normalizeIdentifier, clé
festipod.account.identifier) — c'est un id technique d'espace, pas un username.
Le username de PROFIL (nom d'affichage) est laissé intact.

Test garde-fou @ui (identifiant-resolution.feature) : la priorité param>localStorage,
rouge si on l'inverse. Le flux de barrière étant désactivé en @e2e, ces @ui sont la
seule couche qui le garde.

Doctrine: knowledge_authentication (porteur URL + partition) + knowledge_context-internals (vocab).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 11:55:09 +02:00
Sylvain Duchesne 13da2d9e03 fix(auth): préremplir l'identifiant à la barrière — plus de re-saisie à l'arrivée
Symptôme (vraie app) : au retour dans Festipod, la barrière redemandait un
identifiant NU et VIDE alors qu'il était déjà choisi/stocké.

Cause racine (pas une perte de localStorage — l'identifiant survit au round-trip) :
au rechargement, AccountProvider restaure `username` depuis le store, mais
NextGraphContext repart en `disconnected`, donc AuthGate réaffiche la barrière ;
et AccessGateScreen initialisait son champ à useState('') → vide malgré le stocké.

Fix : AuthGate passe `initialIdentifier={username}` ; AccessGateScreen préremplit
le champ. L'identifiant est saisi UNE FOIS au premier accès, persisté, puis
prérempli au retour — jamais retapé.

Test garde-fou @ui (barriere-acces-identifiant.feature) : prérempli / vide au
premier accès / Entrer remonte la valeur. Rouge si on remet useState(''). Utile
car le flux de barrière est désactivé en @e2e (__FESTIPOD_ACCESS_GATE_DISABLED__),
donc invisible à cette couche. renderElement() ajouté au harness @ui pour rendre
un composant prop-driven hors registre/providers.

Doctrine: app-security/knowledge_authentication documente la saisie-unique + prérempli.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 11:13:50 +02:00
Sylvain Duchesne 7302936502 test(e2e): smoke @smoke garde la classe "page blanche une fois connecté"
Boote le VRAI App via le broker (hook Before @e2e existant), navigue vers
l'accueil connecté et asserte deux choses fortes : HomeScreen a réellement
monté (.app-navbar + bouton "Relayer", absents d'un spinner/bandeau broker)
ET aucune erreur runtime (pageerror/console.error) n'a été émise pendant le
boot connecté. Le World collecte désormais les pageErrors (réinitialisés par
scénario, logging existant préservé). Câblé dans `bun run validate` (run par
défaut) via @smoke and not @wip, avec nettoyage Chromium.

Preuve: un throw dans HomeScreen fait virer le smoke au rouge; sans lui, vert.
Comble le trou qui laissait passer la régression page-blanche (aucune suite
n'exécutait @e2e et aucune assertion ne gardait le rendu connecté).

Doctrine: bdd-testing/knowledge_e2e-layer documente le smoke @smoke + pageErrors.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 19:03:21 +02:00
Sylvain Duchesne 4ffa055d62 test(@data): dé-poller les steps — attendre l'état réactif, plus de boucle broker
Applique rule_no-broker-polling aux steps @data : les boucles
`for (i<N){ authParticipationCount()/getEventParticipants(); sleep }` (re-lecture
broker) sont remplacées par le pattern correct — attendre que l'ÉTAT RÉACTIF se
settle (waitForFunction sur isParticipating/homeEventTitles, alimentés par le push
watchShape, PAS de lecture broker dans la boucle), PUIS UNE lecture autoritative
unique quand l'assertion vérifie la vérité broker.

Aucune assertion affaiblie. Un poll masquait un cold-read cassé en « lent-mais-vert »
→ ce pattern expose les vraies non-convergences. Vérifié : rien n'est exposé (ça
converge dans les bornes) et le baseline reste vert.

Steps : createur, reconnexion, isolation, inscription, inscription-inbox.
gate : bun run validate = ALL STEPS PASSED ; tsc propre.
Suivi : multibrowser-features.steps.ts:85 (readInboxDeposits dans un waitForFunction)
= même classe, hors scope @data, passe dédiée à faire.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 17:57:13 +02:00
Sylvain Duchesne 0fc8479e22 tooling(validate): nettoyage SingletonLock + @multibrowser réactif @wip (limite wallet-partagé)
- validate.ts : `cleanSingletons()` retire SingletonLock/Cookie/Socket avant
  polyfill:e2e (et à la rotation) → fiabilise polyfill:e2e (fini le faux rouge
  ProcessSingleton). @multibrowser lancé en `@multibrowser and not @wip`.
- e2e-multibrowser : le scénario réactif « Un participant apparaît réactivement »
  passe @wip, commentaire d'en-tête expliquant la LIMITE : en wallet-partagé A et B
  partagent UNE identité NG → B voit l'événement de A comme possédé → son
  owner-materializer écrit le doc de A → StorageError. PAS un bug produit (prod =
  wallets distincts). Vrai fix = isolation distinct-wallets (chantier T02.d/g).
  Réserve : ce scénario était vert (517045c) ; à re-vérifier lors de l'isolation
  distinct-wallets (peut masquer une interaction phase-B).

Baseline validate visé : vert sauf ce @multibrowser documenté.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 17:17:18 +02:00
Sylvain Duchesne 7dab6e44e2 tooling(validate): sous-ensemble @data clé rapide par défaut + flag --full + budgets
`bun run validate` finissait en timeout (@data complet >14min). Désormais : par
défaut un SOUS-ENSEMBLE CLÉ de 8 scénarios @data (les couvertures des bugs terrain :
inscription, désinscription, isolation, reconnexion, créateur, compteur, auth×2) en
une invocation → finit en ~8m30. Flag `--full` pour toute la suite @data (budget
élargi 35min). Rotation profil avant @data/@multibrowser, matrice + exit non-zéro.

Baseline actuel : 8/8 @data clé VERTS (les fixes watchShape/optimiste/reconnexion/
anti-fork tiennent) ; polyfill:unit 123 ; rouges = SingletonLock (infra) + un
@multibrowser (limite wallet-partagé A/B).

Note : gate pre-push rapide (tsc+build+polyfill unit) ajouté dans .git/hooks/pre-push
(local, non versionné — pour partage : script tracké + install, suivi).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 17:06:40 +02:00
Sylvain Duchesne 91ee3567aa test: reconnexion « relit ses propres données » — VERT, retrait de @wip (bug résolu)
Le bug de reconnexion (page fraîche même identité relit vide) est RÉSOLU côté lib
(résolution de compte déterministe + dé-dup des ensureAccount concurrents). Le
scénario passe 2/2 sur broker réel → retrait de @wip (redevient @data bloquant),
en-tête corrigé. `storeRegistry.ts` : config `provisionRetry` (retry anti-fork).

Non-régression vérifiée : isolation + inscription verts.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 11:30:13 +02:00
Sylvain Duchesne f366ee29a7 doctrine(data-layer): context-internals — lecture via watchShape + overlay optimiste + auto-seed sur isSuccess
Rafraîchit les sections périmées : la lecture passe par `useShapeQuery`/`watchShape`
(plus readEntities/subscribeDocs/bumpRead/relist) ; visibilité immédiate des
mutations par overlay optimiste (plus registerDoc) ; auto-seed gardé sur `isSuccess`
(plus le setTimeout 3s qui causait le re-seed à chaque reconnexion).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 01:19:45 +02:00
Sylvain Duchesne 04a2de0b17 fix(app): visibilité immédiate des mutations — overlay optimiste sur watchShape
Répare 2 régressions de `38266d9` (les lectures 100% watchShape avaient perdu la
visibilité immédiate post-mutation, ce que faisait `registerDoc`) : après
`createEvent` l'événement n'apparaissait qu'après le push broker ; après
`leaveEvent` le partant restait listé jusqu'au push.

Fix = mise à jour OPTIMISTE (pattern mutations useQuery ; PAS de polling) dans
`useNgData` : overlay `pendingAddEvents`/`pendingAddParticipations`/
`pendingRemoveIds`. État exposé = merge(réactif, adds) moins removes, dédupé par id.
Réconciliation auto : un add dont l'id apparaît dans le réactif est retiré ; un
remove dont l'id disparaît du réactif est retiré → auto-nettoyage au push, jamais
de poll. Vidé au changement d'identité. Pas de registerDoc/readModel réintroduit.

Trouvé PAR `bun run validate` + chasse à la régression — « l'agent trouve les
problèmes sans test manuel ».

gate : tsc propre, build OK. 6 scénarios @data verts (créateur + désinscription
régressés → verts ; inscription/isolation/compteur → verts).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 01:18:34 +02:00
Sylvain Duchesne 9e62bdea53 tooling: commande bun run validate — validation complète 2 niveaux
Fondation « l'agent valide tout d'un coup » (audit couverture, levier C1). Enchaîne
et agrège : polyfill unit + polyfill e2e réel + Festipod @data + @multibrowser
(profils frais/rotation), matrice finale + exit non-zéro si rouge, passe @wip
informative.

Baseline établi (premier run réel) : polyfill unit 120 , polyfill e2e 42/42 
(broker réel), @multibrowser 1 rouge (limite wallet-partagé A/B), @data 4 rouges
dont 2 régressions phase B confirmées. → a trouvé les problèmes tout seul.

À TUNER (suivi) : le budget @data (~14min) est trop court → la suite complète est
tuée par timeout ; augmenter le budget OU exécuter un sous-ensemble clé rapide.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 01:04:57 +02:00
Sylvain Duchesne 38266d96f8 refactor(app): l'app lit via watchShape (useShapeQuery), plus de machinerie bespoke
Phase B — FestipodDataContext lit désormais via la surface SDK `watchShape`
(binding `useSyncExternalStore` dans `useShapeQuery`) + adaptateurs Fp
(`shapeAdapters.ts`), au lieu de sa machinerie maison. Applique
rule_app-uses-sdk-surface-only : l'app ne consomme que la surface SDK.

Supprimé : `readEntities.ts`, `subscribeDocs`+`bumpRead`+`readTick`+`readDocKey`,
le listing manuel (`publicDocs`/`protectedDocs`/`registerDoc` pour la lecture,
`readDiscoveredEvents`), et les commentaires raisonnant sur le hang ORM. Gardé
découplé : `listMyEntityDocs(owner,'public')` → `ownedEventIds` pour le seul
matérialiseur propriétaire.

Auto-seed : chronomètre 3 s → gate `isSuccess` (seed uniquement si synchronisé ET
vide) — fix du re-seed « First time… » au 3ᵉ connect. Mode démo inchangé.

Non-régression VÉRIFIÉE (broker réel, wallet frais) : inscription (1 passed),
isolation « identité fraîche ne voit pas » (re-run local, 5 steps passed), compteur
dérivé/Q4 (1 passed). tsc propre, build OK.

Résiduel PRÉ-EXISTANT (pas causé par ce refactor, vérifié par stash sur baseline) :
- reconnexion « relit ses propres données » → RE-@wip : défaut cold-read de l'index
  de scope PUBLIC côté lib (une page fraîche relit vide) — prochaine cible.
- un @AUTH « données pas rechargées » (timing loadFire-and-forget vs step 30 s).

Doctrine : rule_app-uses-sdk-surface-only « déviation résolue ».

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 23:47:03 +02:00
Sylvain Duchesne 2295af610a doctrine+dev: règle « app = surface SDK seule » + access-log par défaut
- rule_app-uses-sdk-surface-only : l'app se comporte comme si NextGraph était fini
  et sans défaut ; elle lit via `useShape` (scopé wallet virtuel, fourni par le
  polyfill), jamais via des internes (readModel/subscribeDoc) ni en raisonnant sur
  un problème NextGraph. Raison d'être du polyfill = le WALLET VIRTUEL (pas le hang
  ORM, qui n'est qu'un détail interne). Cible : `useShape` polyfill à la forme
  TanStack useQuery (data + isPending/isSuccess…), en anticipation de la mise à jour
  prévue de useShape par NextGraph — distingue nativement sync-en-cours de vide.
  Déviation actuelle notée : readEntities/subscribeDocs/bumpRead côté app.
- ngSession : access-log ON par défaut (le toggle opt-in était fragile), opt-out via
  localStorage festipod.debug.accessLog=0 ; ligne de diagnostic au démarrage.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 22:36:29 +02:00
Sylvain Duchesne 4c80ada3de doctrine(bdd-testing): remplacer le caveat poll par la règle « ne jamais poller »
L'ancien caveat_poll-broker-reads érigeait à tort le POLLING en pratique de test.
Remarque utilisateur : le polling est un anti-pattern dans le contexte NextGraph
(par abonnement). Remplacé par rule_no-broker-polling : attendre le push réactif /
la barrière du 1er State ; ne JAMAIS re-interroger le broker en boucle. Fallback
pragmatique admis : un intervalle court qui OBSERVE l'état réactif déjà mis à jour
(pas une re-lecture broker) — au plus près de l'utilisateur qui attend.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 13:20:29 +02:00
Sylvain Duchesne 517045c257 test(@multibrowser): le compteur converge AUSSI côté inscrit B (Q4) + caveat polling
Q4 — le scénario réactif ne vérifiait la convergence de participantCount que du
POV du PROPRIÉTAIRE A. Ajout des assertions symétriques côté INSCRIT B : après que
B rejoint, B voit le compteur passer à 1 réactivement (sans reload) ; après
désinscription, il revient à 0 côté B. Le doc public mis à jour par A (seul
matérialiseur) se propage via le broker jusqu'au doc_subscribe de B. Ferme « A et
B ont-ils tous les deux le compteur incrémenté ? » — oui. Vert wallet frais (16 steps).

Doctrine : nouveau caveat bdd-testing/caveat_poll-broker-reads — asserter les
lectures broker en POLLING borné (lag de sync ~1s), jamais en one-shot ; vaut pour
les lectures à froid (reconnexion) et la propagation réactive (compteur
cross-navigateur). Consolide la doc-debt des features touchées cette session.

Non couvert (suivi) : observateur TIERS (découverte publique, flaky).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 14:09:21 +02:00
Sylvain Duchesne c07150cb27 test: reconnexion même identité — VERT (défaut résolu), retrait de @wip
Le scénario passe désormais (broker réel, 5 steps) : une page fraîche pour la
MÊME identité, sur le wallet persistant (nouveau login → session verifier
fraîche), relit son événement sur l'accueil, sa participation et un count
autoritatif de 1.

Résolution mesurée (investigation opus répétée) : le read à froid de l'index de
scope public est un LAG DE SYNC borné, pas un gap permanent — le doc se liste dès
la 1re tentative, l'accueil converge en ~1 s. Il fallait deux choses :
- les fix lib open-repo + anti-fork de compte (branche fix/session-rehydration-
  on-login, dans node_modules) ;
- et surtout que le TEST attende la convergence : les 3 assertions de la page
  fraîche POLLENT maintenant (jusqu'à ~15 s) au lieu de lire une seule fois — un
  read unique course la fenêtre de premier-open/sync et flakait. L'UI réelle est
  réactive, donc ce polling reflète le vrai comportement utilisateur.

Devient un test @data permanent (retrait de @wip).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 13:14:22 +02:00
Sylvain Duchesne 005c052bc6 test(@wip): reconnexion même identité — documente le défaut de relecture à froid
Scénario @data @wip (exclu du run par défaut) qui documente un défaut RÉEL non
encore corrigé : une PAGE FRAÎCHE pour la MÊME identité, sur le même wallet
persistant (nouveau login broker → session verifier fraîche), relit VIDE ses
propres données (accueil vide, isParticipating=false, count=0).

Mesuré au niveau app sur broker réel. Le fix lib `open-repo` (branche
fix/session-rehydration-on-login, non mergée) fait remonter le PROTECTED
(participation) au cold-start mais PAS l'accueil PUBLIC : `readScopeIndex` de
l'index de scope public rend 0 — observé même côté écrivain même-session — alors
que le code d'index de la lib est prouvé scope-symétrique. Cause exacte encore à
mesurer sous broker (l'hypothèse « mauvais graphe » est déjà réfutée en amont).

Reste @wip tant que le fix n'est pas complet et validé.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 10:45:51 +02:00
Sylvain Duchesne c869c56a17 Diagnostic: activer l'access-log du SDK depuis l'app (toggle runtime)
Câble l'option `debugAccessLog` du SDK @ng-eventually/client dans le point
d'injection `ngSession.configure(...)`, pilotée par un toggle runtime sans
rebuild : `localStorage['festipod.debug.accessLog']==='1'` (ou
`window.__FESTIPOD_ACCESS_LOG__`), off par défaut.

But : VOIR la fuite d'isolation dans l'app RÉELLE. Le harness e2e ne peut pas la
reproduire (les lectures cross-invocation n'y rendent rien), donc on instrumente
l'app : chaque read/write du SDK s'imprime préfixé par l'identité active
(`[urn:festipod:user:<id>] READ <nuri> → N rows`), rendant visible le moment où
un doc est lu sous la mauvaise identité.

tsc propre, build OK. Outillage polyfill-era.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 21:22:40 +02:00
Sylvain Duchesne 65bd67cc20 Isolation deux-identités: test permanent + le créateur ne participe plus
Deux corrections produit/tests demandées, empiriquement validées au broker réel.

1. Créateur ≠ hôte (décision produit). Il n'y a PAS de notion d'hôte : un
   événement est public, simplement signalé par le créateur, qui n'est PAS
   obligé de participer. `createEvent` n'écrit plus de participation-hôte et
   `participantCount` démarre à 0 ; le matérialiseur du propriétaire dérive
   `participantCount = |inscriptions actives|` (plus de base « +1 hôte »).

2. Isolation deux-identités : le trou réel était l'ABSENCE d'un test de
   régression, pas un bug de code actif. Reproduction empirique (DIAG instrumenté,
   retiré) : la fuite n'apparaît QUE si le reset `useEffect([username])` est
   désactivé ET les caps vides (docs persistés d'une session antérieure sur wallet
   gonflé) — le reset en place la neutralise. La sighting live venait d'un état
   wallet pré-fix + identifiant réutilisé. Ajout du test permanent manquant :
   - isolation-deux-identites.feature (@data) : A crée+rejoint E, une identité
     fraîche B sur le même wallet ne voit E ni sur son accueil, ni via
     isParticipating(E,B), et ne lit aucune participation portant le principal de A.
   - us-13 : « Le créateur ne participe pas automatiquement » (count 0,
     isParticipating false autoritatif, puis join→1, leave→0).

Harness: 4 helpers permanents (switchIdentity, currentIdentifier, homeEventTitles,
currentParticipations) pour piloter/observer l'identité en test.
Scénarios @multibrowser/us-7 réalignés (compteur 0→1 au lieu de 1→2).
Doctrine mise à jour (context-internals, actors-and-concepts).

Gates: build OK, tsc propre, @data verts (inscription, désinscription,
idempotence, compteur dérivé, auth ×4), lib @ng-eventually/client non touchée.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 18:55:42 +02:00
Sylvain Duchesne 0f164300f0 refactor(data): canonical event-id matching for the owner-materializer (defensive)
Guard the Option-B owner-materializer against overlay-form drift: match inbox
deposits to owned events on the CANONICAL base repo id (canonicalEventId strips any
✌️<overlay> suffix), applied at the matching boundary in materializeAttendance /
readRegistrationNotifications and to dedup ownedEventIds (ownedKey). The count is
still WRITTEN on the real owned NURI — a stripped id is never a write/anchor target.

Honest framing: this is DEFENSIVE, not a fix for an active bug. On the current tree
create-time, listMyEntityDocs and the read @id already carry the identical NURI
(readUnion pins the subject to the input NURI, 63ecfee) — verified: the count
converges for an event owned via listMyEntityDocs. A prior investigation's 'never
matches' reading was the seeded-but-not-owned artifact (a prior-run identity owned
the seed → reached via discovery, not ownedEventIds — correct behavior).

Un-@wip the @data convergence scenario (asserts the just-joined uid enters the
owner-derived active set — deterministic despite shared-inbox accumulation); it
now passes. Fix authParticipationCount already landed separately. Doctrine:
knowledge_context-internals (canonical id-form invariant). Build + tsc clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 15:14:25 +02:00
Sylvain Duchesne 767a18e98c test(@data): align us-7 inscription tests to Option B; fix authParticipationCount
The three us-7 count assertions encoded the OLD increment model (participantCount =
baseline ± 1 via a fictional 'au départ N' step). Under Option B the count is
owner-derived, not baseline±1 and not the joiner's to write, so those lines were
false. Drop them; keep the real @data contract (join persists + participant + in
list; leave is authoritative + gone). Move count convergence to a @data @wip
scenario with an inline rationale (single-session can't derive the absolute count —
shared-inbox accumulation + create-vs-read NURI-form; the @multibrowser reactive
scenario is the real validation).

Fix a harness bug: authParticipationCount enumerated protected docs via the
all-accounts listEntityDocs (returned 0 for a fresh per-scenario virtual account —
a false 0); use the bounded listMyEntityDocs(currentUser,'protected') (the same
read-by-need path the app's idempotence check uses), and poll to absorb index lag.

Full @data suite green: 18 scenarios / 89 steps. Désinscription contract untouched
(caveat_participation-deletion). Build + tsc clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 14:23:25 +02:00
Sylvain Duchesne 22487ed575 docs(data): drop the phantom-graph justification in entity/registration writes
Comments in entityWrites.ts (writeEntity/updateEntityField) and registration.ts
asserted an explicit GRAPH <plainNuri> writes a distinct named graph the anchored
read never sees (entity 'disappears'). The lib e2e harness disproves it on the
current broker; the '0 entities' symptom was the wallet-bloat hang. Replace with
the minimal 'no-GRAPH is the canonical anchored-default-graph shape; SDK graph
details live in @ng-eventually/client'. No NextGraph internals in the app repo
(boundary); no behavior change (the safe no-GRAPH shape stays).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 09:39:09 +02:00
Sylvain Duchesne cd2a45c254 feat(data): participantCount via Option B (deposit + owner materialization)
Remove the write-isolation violation: joinEvent/leaveEvent no longer write
participantCount on the event doc (a non-owner writing the owner's public doc —
illegitimate in NextGraph). The joiner/leaver only write their own protected
participation doc and DEPOSIT a marker into the event inbox (depositRegistration /
depositLeave).

The event OWNER's session materializes: it subscribes (inbox.watch, doc_subscribe —
no polling) to the inboxes of its OWNED events (ownedEventIds), and on each deposit
recomputes participantCount on its OWN event doc. The count is DERIVED, not
incremented: materializeAttendance derives the SET of distinct active registrations
(new-participant deduped by uid, MINUS leave-participant by regUid/fallback
eventId+userId), count = 1 (host self) + |active set|. A pure function of the inbox
→ broker re-syncs converge, never double-count nor resurrect (idempotent); the write
is guarded (only on change → no loop). Authoritative deleteParticipation preserved
(caveat_participation-deletion).

Because the owner writes its own PUBLIC event doc and every session subscribes to it
(P3), the count round-trips reactively to all — no reload. Owner-offline = eventual
(V1; a future @ng-eventually/service materializes on the owner's behalf).

Real 2-browser e2e (e2e-multibrowser.feature): B registers → A materializes → count
1→2 reactively (no reload) + unknown participant; B leaves → count →1. 14/14 green.
Gates: @data auth 4/4, @data isolation 4/4, build + tsc clean. Doctrine:
knowledge_context-internals (Option B section).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 09:24:55 +02:00
Sylvain Duchesne e62a17e5a2 docs(data-layer): correct the graph-round-trip claim (it was the bloat hang)
The lib e2e harness proves that on the current broker an anchored
INSERT DATA { GRAPH <plainNuri> {…} } DOES round-trip — the earlier 'explicit GRAPH
writes a phantom named graph the read never sees' claim was false; the '0 entity'
symptom was actually the wallet-bloat hang (caveat_wallet-bloat-hang), not a graph
mismatch. Reframe the no-GRAPH default-graph rule as a simplicity/safety convention,
not a round-trip necessity. Lib/app inline comments asserting the phantom-graph
claim remain to reconcile.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 23:56:51 +02:00
Sylvain Duchesne 4e96659bd7 feat(data): reactive cross-session reads (doc_subscribe), + real 2-browser e2e
Wire the app read path to the lib's per-doc reactive subscription so a change made
in ANOTHER session propagates without a reload or local action:
- useNgData subscribes the by-need set via subscribeDocs(allReadDocs, bumpRead) —
  one doc_subscribe per NURI, per-doc error isolation (never the ORM fan-out). Any
  patch (own write or broker-synced from a remote peer) re-runs readUnion.
- Reactive discovery: watchDiscoveredEvents(relist) subscribes the global index →
  a new public event from another session enters the read set (and gets its own sub).
- Loop-safe: the sub effect is keyed on a stable sorted-NURI key (readDocKey); a
  fire→bumpRead→read never changes the doc set, so no re-subscribe loop. Identity
  switch empties the set → clean unsubscribe → rebuild → re-subscribe (no leak).
- readUnion stays the one-shot tolerant reader; subscriptions only trigger re-reads.

Real 2-browser e2e (e2e-multibrowser.feature): B registers → A's EventDetailScreen
shows participantCount 1→2 and an 'unknown' participant WITHOUT A reloading, via A's
doc_subscribe on the public event doc (event-driven). Isolated run 12/12 green.

Count mechanism unchanged (P4/Option-B is next); the joiner still writes the public
event doc's participantCount — which is exactly what the observer sees change live.
Gates: @data auth 4/4, @data isolation 4/4, build + tsc clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 23:40:43 +02:00
Sylvain Duchesne 84bc87d13c docs(data-layer): brief update — P1/P2 done, owner-offline decided, hooks
P1/P2 (lib subscribeDoc + drop polling) landed in @ng-eventually/client c0498a6.
Owner-offline count = eventual for V1, a future @ng-eventually/service takes over
when the owner is disconnected. Reactive hooks are useShape + useDiscrete (no
useQuery); the union-of-N-docs read stays subscribeDocs + re-readUnion (useShape
fan-out hangs). Next: P3 (wire per-doc subscription into the app read path).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 23:07:14 +02:00
Sylvain Duchesne af58667b4f docs(data-layer): brief — reactive reads + option-B attendance
Implementation design brief (grounded in current code): reactive reads via a typed
per-doc doc_subscribe wrapper (no polling, no ORM fan-out -> avoids the historical
hang); participant count via option B (joiner deposits into the event inbox, the
event owner materializes into its own event doc's count; option A ruled out --
non-owner append is impossible in NextGraph). Connection-gated identity (else
'inconnu'). Test plan: polyfill low-level doc_subscribe + real 2-browser e2e
reactivity. Phased P1-P6. Open product question: owner-offline eventual count.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 22:13:54 +02:00
Sylvain Duchesne 01d65238ce docs(data-layer): point to the SDK reference for the reactive read hook
Add a pointer in knowledge_nextgraph-stack: the SDK's recommended read is its
reactive useShape hook (subscribe/push, one-shot is the exception); full contract
in @ng-eventually/client packages/client/docs/sdk-reference.md. No NextGraph
internals copied into the app repo — just the pointer.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 22:02:47 +02:00
Sylvain Duchesne 6ceec5e161 fix(data): reset the read set + emulated caps on identity switch (isolation)
The shared-wallet stopgap keeps ONE React tree across a faux-logout + re-login
under a different identifier (AccountContext.login only rewrites a localStorage
id; AuthGate never remounts, no page reload). FestipodDataContext's by-need read
set accumulates the current identity's scope docs and was never reset on identity
change, so the PREVIOUS identity's PROTECTED docs (its participations) survived in
the new identity's read set and leaked through the union read — the in-memory cap
gate can't filter a doc it doesn't govern this session. Symptom: user B saw A's
participation, and A's event surfaced on B's home (home = getUserEvents(currentUserId)).

Treat every identifier change as a fresh session: a ref-guarded useEffect([username])
clears publicDocs/protectedDocs, resetCaps(), resetRegistryCache(), then bumps the
read tick so the listing effect rebuilds the set bounded to the new identity.
Isolation stays per-document/emulated; the reset only drops cross-identity carryover.
Documented in knowledge_context-internals.

Validated (@data, real broker): after an A→B switch, B does not participate and
does not read A's participation; protected-isolation/read-filter/auth scenarios pass.
tsc + build green; lib untouched.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 17:29:18 +02:00
Sylvain Duchesne 3dfd549af3 docs(tech-stack): correct the dev shared-wallet command (real e2e password + file)
A dummy FESTIPOD_SHARED_WALLET_PASSWORD=1 only makes the screen appear; the import
fails because the displayed password must match the imported .ngw. Document the
working invocation with the real e2e wallet (festipod-e2e-tests) + its file.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 15:52:45 +02:00
Sylvain Duchesne 17543f04c3 fix(auth): land on home after gate entry; align the @humain e2e to the identifier flow
Removing ConnexionScreen dropped its post-login navigate('/home'). Since the
identifier is now entered at the barrier (before the broker round-trip), on return
the app can load at '/' (WelcomeScreen) with a session already open. AuthGate now
redirects welcome→/home once connected AND identified (gate-disabled paths, i.e.
@e2e/@data harness, are exempt).

Update the @humain assisted-import e2e (the real staging flow, the coverage for
this page) to the new UX: the tester types an identifier then clicks « Entrer »
(one act), and lands directly on home — the 'choisir un nom d'utilisateur'
(ConnexionScreen) steps are removed. Step bindings verified; tsc + build green.
Doctrine: knowledge_multibrowser-harness.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 15:34:01 +02:00
Sylvain Duchesne 25b1c033d9 fix(auth): show the shared-wallet flow in dev; hide re-import when already connected
The access barrier's shared-wallet steps are gated on hasSharedWallet(), which
reads a global set only by build.ts's compile-time `define`. The src-served paths
(bun run dev AND bun run start) bundle index.html via Bun's HTML import, which
applies no define and inlines neither `process.env` nor `bun --define` (verified) —
so FESTIPOD_SHARED_WALLET_PASSWORD passed to `bun run dev` never reached the
frontend, and the barrier showed the identifier-only variant.

Expose the config at runtime instead: src/index.ts serves /festipod-config.json
(+ /shared-wallet.ngw), and the entry (frontend.tsx) fetches it, sets the global,
then dynamically imports App so sharedWallet.ts reads it on eval. In a build.ts
bundle the value is inlined via define, so the fetch is skipped (NODE_ENV).
Verified in a headless browser: FESTIPOD_SHARED_WALLET_PASSWORD=1 bun run dev now
renders the download + import steps AND the identifier field, no console errors.

Also: only show the download/import steps when status !== 'connected' — after a
faux-logout the wallet is still open, so re-import must not be offered (just the
identifier). Documents the build-define-vs-runtime-config pitfall in tech-stack.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 15:23:20 +02:00
Sylvain Duchesne e951eaaf96 feat(auth)+refactor(app): identifier at the access barrier; adopt the lib fidelity refactor
Consumer-side of the @ng-eventually/client fidelity pass, plus the identifier UX:

- Identity: the user types an IDENTIFIER at the access barrier (AccessGateScreen),
  in the same act that opens the shared wallet — the separate 'pick a username'
  screen (ConnexionScreen) is removed. The identifier is a technical id (a pseudo
  in practice, not a Festipod username), normalized (trim, @-stripped, lowercased)
  and persisted before the broker redirect, then handed to the SDK as the identity.
  AccountContext keeps its API but its stored value is now this normalized id.
- Relationship/connections are app-owned: new src/shared/utils/connections.ts holds
  the bilateral registry and maps each link to the SDK's directed grantRead(doc,
  grantee); the lib no longer carries a connection concept. Rewired FestipodData
  and the @data harness to it.
- Login removed: accounts use the SDK's IdentityStore (set/clear/get); no faux
  login/logout framing in the SDK boundary.

Doctrine reconciled: app-security (knowledge_authentication flow, knowledge_trust-model
directed grants, decision_2026-07-06_identifier-at-access-barrier), data-layer
(knowledge_context-internals: stable id principal + single-seed), app-architecture
(knowledge_screens auth inventory), bdd-testing (caveat_wallet-bloat-hang).

App gates: tsc no new errors, build OK. @data path unaffected (harness bypasses the
gate and sets identity directly; login() is not on that path).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 14:52:40 +02:00
Sylvain Duchesne 0911b1f9de fix(@data): round-trip the seed/read path against the real broker
Multiple compounding defects kept the connected @data read at 0 entities:
- writeEntity/updateEntityField and registration helpers wrote into an explicit
  GRAPH <plainNuri> named graph, invisible to the anchored default-graph read
  (read-model.readDoc) after the read switched to per-doc anchored. Drop the
  wrapper so writes land in the repo's default graph (matches the read).
- Seed entities are now owned by the CURRENT account, so protected seed docs
  (user profiles) pass the per-document ReadCap gate and round-trip.
- Suppress the double seed (explicit loadTestData + 3s dev auto-seed) and add a
  re-list signal so freshly-seeded protected docs enter the read set.
- @data step awaits the seed result and waits for events AND users > 0.

Documents the anchored-default-graph write pitfall in rule_document-per-entity.

Validated: connexion-nextgraph.feature @data = 4 scenarios / 13 steps green.
NB: the shared test wallet's private store bloats across runs and makes anchored
queries hang (>15s); a fresh .playwright-profile restores ~1.5s — durable wallet
hygiene is a follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 12:46:39 +02:00
Sylvain Duchesne 02cda056b8 test+seed: fresh virtual wallet per @data scenario + seed events reach the index
- @data Before hook sets a UNIQUE virtual-wallet id (username) per scenario so each
  scenario starts on a fresh, empty virtual wallet — isolation without touching the
  physical wallet; "le portefeuille est vide" is now a fast check, not a full scan.
  resetDataState / clearWallet fan-out dropped.
- bootstrapWallet now submits each seeded PUBLIC event to the discovery index
  (mirrors the product createEvent), so a fresh virtual wallet can see seeded events
  through discovery rather than as its own docs.

Note: @data still red — seeded/published events do not surface in the discovery
read (submit→readIndex round-trip against the real broker), and some publish steps
time out. The 75s ORM hang is gone; this is a distinct discovery-index integration
issue, still under diagnosis.
2026-07-06 10:15:06 +02:00
Sylvain Duchesne 8ca79c6d16 refactor(data): per-doc anchored reads over the virtual wallet
Read each by-need entity document with its own anchored query (bounded to the
current account's virtual wallet), never an anchorless scan of the physical shared
wallet. The 75s ORM hang stays gone; a non-empty PHYSICAL wallet now costs nothing
(never scanned). Removed the throwaway anchorless-union probe.

Known remaining (test-infra, not the product): the @data suite still times out
because THIS test account's VIRTUAL wallet is bloated (hundreds of docs
accumulated across this session's many runs) → per-doc reads are O(my docs), and
`clearWallet` still enumerates all accounts. Needs per-scenario test isolation
(fresh/small virtual wallet) + a virtual-wallet-scoped clear to validate green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 22:50:15 +02:00
Sylvain Duchesne 8bb19b687b feat(data): union read model — list via anchorless sparql_query, hang eliminated
Replace the reactive-ORM per-entity fan-out read (which HUNG 75s: orm_start_graph
opened every scope graph and RepoNotFound on any fresh/unsynced doc aborted the
subscription) with the read model:
- readEntities.ts → lib readUnion: resolve the by-need doc set (my own scope docs
  via listMyEntityDocs + public events via the discovery index — NOT all-accounts
  fan-out), then ONE anchorless union sparql_query (GRAPH ?g, VALUES-pinned). Map
  to app types. Re-query on a change signal (no reactive union query).
- countUserParticipations no longer fans out over all accounts (own docs only).
- await loadTestData in the seed step; deleted orphaned useShapeWithDefaults;
  removed the old multistore-stopgap fan-out scenarios; added the read-model-probe.
- Doctrine: rule_document-per-entity read half + _overview rewritten to the union
  model (write half unchanged).

Result: the 75s ORM hang is ELIMINATED (0 hangs; build/tsc/lib-93-tests green;
boundary clean). @data is NOT yet fully green: remaining failures are 90s step
timeouts in the test-harness broker data ops (clearWallet / runUnionProbe / seed)
this run — a harness/broker-op issue, not the read path. To finish separately.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 20:49:01 +02:00
Sylvain Duchesne eafb4403b9 test(data): per-scenario state isolation to bound the read fan-out
@data oscillated 15-20/21 because the persistent test wallet accumulated data
across scenarios, growing the read fan-out. Add a cheap per-scenario reset
(resetDataState): a single SPARQL DELETE on the shim anchor graph clears the
account records, so allAccounts() collapses and the fan-out is bounded to what
the current scenario re-provisions (accounts recreated lazily). O(1) on one
graph — not a fan-out delete (which saturated the browser before). Called in the
@data Before hook, time-boxed so it can't starve the broker login budget.
Test-infra only — product model, boundary and app read path untouched.

Note: not yet re-measured to stable-green — the broker was degraded during the
bounded validation window (DNS/timeout flakiness). To re-measure when the broker
is stable. knowledge_data-layer-broker updated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 13:28:08 +02:00
Sylvain Duchesne 966ba9855c fix(data): restore per-entity write round-trip against the real broker
The per-document isolation refactor (one doc per entity) broke every @data
round-trip against the real broker (0 events readable) — fake-ng unit tests
missed it. Root causes + fixes:
- ngSet.add cannot write to an empty subscription scope ("Set is readonly
  because scope is empty") → write each entity DIRECTLY into its own document via
  SPARQL (new data/entityWrites.ts: writeEntity/updateEntityField), typing each
  field with the correct RDF term per the SHEX shape (else the ORM drops the
  entity on read). Reactive set stays read-only; the doc NURI is registered into
  useShape({graphs}) for reactive reads.
- Current principal made STABLE and username-derived (urn:festipod:user:<name>),
  available immediately at login and invariant — so a Participation's mandatory
  fp:user is never empty and identity/cap-owner/connections all key on the same
  value.
- Discovery deposits AS the current identity (harness sets current user first).
- Idempotence/deregistration checks made authoritative against the broker;
  participantCount persisted via SPARQL. rule_document-per-entity enriched with
  these write/read + stable-principal lessons.

Round-trip restored (seed readable, inscription+notif, persistent deregistration,
public discovery all pass in isolation). NOT yet stably green as a full suite:
@data oscillates 15–20/21 — residual failures are environmental (participation-
read fan-out lag on an accumulating persistent test wallet), same class as the
Chromium saturation; not a logic bug. Durable fix (follow-up): non-fan-out
materialized read + per-scenario test-wallet isolation. app build+tsc + lib 89
tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 17:26:31 +02:00
Sylvain Duchesne 3ad06dfaec feat(data): one document per entity + delegate isolation fully to the SDK
Festipod now follows the correct SDK logic: each entity (event, participation,
profile, notification) is created as its OWN document in its scope
(rule_document-per-entity), via the SDK create call — the store-root write path
and the FESTIPOD_MULTISTORE flag are gone. Reads subscribe the per-entity docs
with instant visibility on create; seed/bootstrap rewritten per-entity.

Removed all app-side access logic: utils/isolation.ts (applyIsolation) deleted.
The app only declares its identity (login) and its own bilateral connections
(sharing act), reads via the SDK, and trusts it — no access filtering in the app.
This makes the SDK's per-document ReadCap the sole, real isolation.

Unit-proven in the lib (89 tests). @data/@e2e validation deferred: the NextGraph
broker is unreachable — to be re-run in T03.d. Follow-up: unify app connection
principals (user IRI) onto the username key used by the SDK's cap owner.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:40:44 +02:00
Sylvain Duchesne 82c2cb5f27 doctrine(data-layer): rule — one document per entity (not store-level)
Festipod persists each entity as its own document (via the SDK), placed in its
scope. The document is the SDK's unit of sharing/permission, so per-document
isolation (private→owner, protected→owner+connections, public→all) is only
possible when each entity has its own document. Writing several entities into a
store-level document defeats per-scope isolation. Framed as SDK usage; the SDK
owns enforcement (app-security/knowledge_trust-model).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 10:21:07 +02:00
Sylvain Duchesne bc3d270bd4 chore: scrub simulation vocabulary from app comments + settle doc-debt
Enforce the boundary in code-comments and doctrine (adversarial-review cleanup):
- App comments in the data plane no longer narrate the SDK's internals: "emulated
  curator"→"the inbox read", "fan-out"→"discovered", removed store-placement
  reasoning and "polyfill/shim/mono-store" wording (FestipodDataContext,
  registration, storeRegistry, ngSession, AccountContext, isolation, sharedWallet,
  AccessGateScreen). Executable logic unchanged.
- Removed dangling references to the dissolved `nextgraph-platform` concept and
  `brief_2026-06-15_shared-wallet-shim` from app code.
- knowledge_nextgraph-stack: dropped "mécanique d'émulation" from the boundary note.
- Settled and deleted all concept _debt.md (confirmatory; target leaves clean).

(Test-infra under workshop/ + generated features.ts still carry some simulation
vocabulary — parked as a separate below-SDK decision.)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 09:58:52 +02:00
Sylvain Duchesne a436c3bd79 feat(data): discover public events via the global index (not fan-out)
On creating a public event, Festipod submits it to the discovery index (an SDK
call); the discovery screen reads the index instead of enumerating accounts. The
app knows nothing of the index's owner, inbox, or materialization — it treats the
lib as a finished SDK whose discovery is a global index. No store ids.

Unit-validated in the lib (79 tests). @data broker validation deferred: the
NextGraph broker (nextgraph.net/eu) was unreachable at run time — to be re-run
in T03.d once the broker recovers.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 09:33:42 +02:00
Sylvain Duchesne 337a1e000d feat(data): activate isolation — declare identity + connections to the SDK
Festipod performs the domain acts that make isolation real: AccountContext
declares the current identity at login/change; FestipodDataContext declares its
connections (friendships) to the data SDK. Reads then discriminate by scope
through the SDK (private→owner, protected→owner+connections, public→all) — no
app-side filtering, no store ids, no awareness that isolation is emulated. New
@data scenario proves an unconnected account can't read another's protected
entity but can after connecting; public stays visible. @data 21/21.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 23:59:03 +02:00
Sylvain Duchesne 619b94ac0e refactor(data): route entities by scope via the SDK — no store ids in the app
Festipod now treats @ng-eventually/client as a finished NextGraph SDK: the app
decides only each entity's logical scope (events/PdR public, profiles/
participations protected, settings private) and calls the lib by scope. The old
mono-store default and the FESTIPOD_MULTISTORE path collapse into ONE scope path.

Removed every physical-store leak from the app data-plane (ngGraph, registration,
FestipodDataContext, NextGraphContext, useShapeWithDefaults): no more
did🆖${store_id} construction. The session is handed to the lib only at the
sanctioned injection point (ngSession/configureStoreRegistry). Product behavior
unchanged. @data 20/20; build + tsc clean.

(_debt.md included; the T03.e doctrine pass settles accumulated doc-debt.)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 23:42:03 +02:00
Sylvain Duchesne db9eb1cf47 doctrine: Festipod treats @ng-eventually/client as a finished NextGraph SDK
Enforce the project boundary: Festipod is written as if NextGraph were a mature,
finished SDK; @ng-eventually/client IS that SDK. NO current-NextGraph-state,
simulation, polyfill, shim, mono-store, store-id or broker-internal knowledge
remains in this repo — it now lives in the @ng-eventually/client repo.

- Dissolved the `nextgraph-platform` concept entirely (12 leaves — all
  current-state/simulation, now in the lib's docs/). Rescued the genuine domain
  parts into functional-domain/knowledge_data-scopes-and-discovery.md (which
  entity → which scope; product-level discovery/notification intent), framed as
  SDK usage with no mechanism.
- data-layer re-anchored to "how Festipod persists via the SDK": stripped
  mono-store/private_store_id/RepoNotFound/DataCloneError/FESTIPOD_MULTISTORE.
  Deleted the current-SDK compensation leaves (private-store-scope, multistore,
  the 2026-03-17 ADRs, conditional-ng-init). Kept/reworded the domain + app
  leaves; caveat_participation-deletion reduced to the domain contract.
- app-security reworded (isolation delegated to the SDK; app trusts it).
- AGENTS.md: dropped the nextgraph-platform row, reworded data-layer/
  functional-domain/app-security, added the "Frontière SDK NextGraph" note.
- Fixed dangling [[links]]; concept lint clean (43 leaves).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 23:23:23 +02:00
Sylvain Duchesne aabb2b77f7 doctrine: reconcile store/document model + T02 features into concepts
- data-layer/caveat_multistore-is-multi-document (new): the recurring store vs
  document confusion. Two axes — (A) which native store, (B) documents within a
  store. FESTIPOD_MULTISTORE toggles axis B (multi-document), not multi-store.
  Isolation (ReadCap) is per-document. As of T02.h the default path writes
  shareable entities to the real protected store (axis A, step 1).
- rule_private-store-scope: rewritten — shareable entities now scope/@graph the
  protected store; private anchors the shim/inbox + settings; "never did:ng:i"
  kept. decision_2026-03-17 marked partially superseded.
- knowledge_stores-permissions: ⚠️ store↔document callout.
- knowledge_entities: MeetingPoint/Notification now persisted (not local-only).
- nextgraph-platform: decision_2026-06-17 records the emulated inbox; fork-inbox
  brief marked short-circuited; discovery-model divergence (shipped fan-out vs
  global-index target) flagged for confirmation.
- functional-domain/knowledge_roadmap, bdd-testing leaves updated. All doc-debt
  settled; lint clean (60 leaves).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 15:51:57 +02:00
Sylvain Duchesne 83604cbc16 test(e2e): multibrowser feature scenarios + @data proofs for T02
- New @data scenarios: inscription-inbox (registration + inbox deposit + notif;
  persistent deregistration), decouverte-publique (cross-account public read),
  protected-store (probe: the native protected store opens for ORM+SPARQL).
- New @multibrowser e2e (e2e-multibrowser.feature): registration+host-notif,
  persistent deregistration, and public discovery across two browser contexts.
- cycle-de-vie: @wip lifted on "Se désinscrire" (fixed).
- harness-ng: bridge helpers for the above; domain sets + ReadCap probe doc
  retargeted to the protected store.
- hooks: defensive AfterAll teardown + Before self-heal on Chromium crash under
  full-suite load. cucumber.json excludes @humain (live nextgraph.eu import,
  non-deterministic; passes standalone). Full suite: 86 passed / 0 failed / 71 skipped.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 15:51:57 +02:00
Sylvain Duchesne aacc2ec3ee feat(data): PdR registration via inbox, notifications, public discovery, protected store
Polyfill-enabled features (T02). All NextGraph I/O goes through
@ng-eventually/client (docs/inbox/storeRegistry); no direct @ng-org.

- Shapes: FpMeetingPoint + FpNotification are now real SHEX shapes with ORM
  bindings (previously app-TS-only, unpersisted).
- Registration (registration.ts, new): joinEvent persists a Participation +
  deposits to the host's inbox + creates a Notification (from = registrant if
  connected, anonymous otherwise). leaveEvent deletes the Participation
  authoritatively via SPARQL DELETE-WHERE (sweep by event+user AND by subject,
  then re-query to confirm) — the désinscription CRDT-resurrection bug is fixed:
  the reactive delete is applied only once the broker confirms 0 remaining.
- Public discovery: useNgData fans out over every account's public docs so a
  user sees others' public events without a connection (dedup union).
- Cap attribution: createEntityDoc declares the ReadCap (open + makePublic/
  grantRead per scope), activating the per-document read filter.
- Protected store (T02.h): the default path now reads/writes shareable domain
  entities in the native protected store (did🆖${protected_store_id}) instead
  of private — verified openable against the broker — matching the per-wallet
  target. Private still anchors the shim/inbox + settings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 15:51:23 +02:00
Sylvain Duchesne 555c670b22 doctrine(nextgraph-platform): shim fully migrated into the lib
Record the completed T01 migration + validation in the two relevant leaves.

- decision_2026-06-17_eventually-library.md: new dated section "Shim migré
  dans la lib — 2026-07-02" — the integration boundary moved from "doc_create
  stays on the real ng / shim still in-app" to "everything in the lib; the app
  touches @ng-org at runtime only via ngSession". TODO "primitive doc_create/
  SPARQL via injected ng" checked done. Namespaces docs/storeRegistry/
  isolation/accounts; isolation<->ReadCap = coexist (distinct axes).
- brief_2026-06-15_shared-wallet-shim.md: Status/summary/Direction "shim
  in-app" -> "shim in the lib".

Validation captured: lib 36/36 + tsc rc=0; app build + harness bundle OK;
full BDD suite 78 passed / 0 failed / 71 skipped (baseline held).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 10:13:29 +02:00
Sylvain Duchesne 3f47ea886f Rewire app onto @ng-eventually/client; drop direct @ng-org runtime imports
Consume the shim mechanics now living in the lib (docs/storeRegistry/
isolation/accounts) and remove the remaining direct @ng-org runtime imports.

- storeRegistry.ts  keeps ONLY the Festipod EntityKind/entityScope mapping,
  injects it via configureStoreRegistry({ getSession, normalizeUser }), and
  re-exports the lib's storeRegistry.* (callers unchanged). Drops
  `import { ng } from '@ng-org/web'`.
- harness-ng.tsx  createSmokeDoc now uses docs.docCreate (real injected ng,
  no DataCloneError) instead of ng.doc_create. Drops the @ng-org import.
- AccountContext.tsx  thin React wrapper over accounts.AccountStore +
  normalizeUsername; historical key `festipod.account.username` pinned →
  zero behavior change. Context/Provider stay in the app.
- isolation.ts  Festipod wrapper over the lib's pure isolation.applyIsolation.

Invariant reached: `grep "from '@ng-org'" src/ | grep -v 'import type'` lists
only ngSession (the configure injection point) + the two documented
test-harness exceptions (auth-setup.tsx, harness.tsx mock). No doc_create
goes through the lib's public proxy. App build + harness-ng bundle OK.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 10:13:11 +02:00
Sylvain Duchesne a54c119b4d chore: gitignore .tasks/ (local big-task tree)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 19:35:15 +02:00
Sylvain Duchesne d69fd7a5f9 Revert doc_create to real ng: lib proxy breaks iframe marshaling (validated)
Full-suite validation of the merge surfaced 4 failures, all multistore: routing
doc_create through the lib's `ng` proxy (685f6d3) breaks @ng-org/web's iframe
postMessage marshaling — DataCloneError "function could not be cloned" (a JS
Proxy over the iframe-RPC proxy = double proxy).

Fix: storeRegistry.ts and harness-ng.tsx (createSmokeDoc) call doc_create /
SPARQL on the real @ng-org/web `ng` directly again. useShape / init / login /
ReadCap still route through the lib. After the fix the 3 multistore scenarios
pass; full suite = 77 passed, 0 merge regressions.

Integration boundary documented in decision_2026-06-17: the in-app shim's
low-level NextGraph calls stay on the real SDK until storeRegistry moves INTO
the lib (where it would use the injected real ng, no double proxy). Lib TODO:
expose a doc_create/SPARQL primitive that uses the injected ng.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 13:39:53 +02:00
Sylvain Duchesne 685f6d379d storeRegistry: route ng through @ng-eventually/client (post-merge integration)
Post-merge audit of main's shared-wallet shim: storeRegistry.ts was the only
runtime path still importing `ng` from @ng-org/web directly, bypassing the lib.
Route it through @ng-eventually/client (the ng proxy forwards doc_create /
sparql_update / sparql_query). Now the only @ng-org runtime imports in the app
are the single injection point (ngSession) + documented exceptions (auth-setup,
mock harness) + generated ORM type-only bindings — the decision_2026-06-17
invariant holds again.

Still in-app, to move into the lib later: storeRegistry, AccountContext, the
isolation filter (distinct from the lib's ReadCap filter).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 13:07:28 +02:00
Sylvain Duchesne c52e581e4f Merge main into ng-eventually: shared-wallet shim + multi-browser e2e
Brings 266e335 (staging shared wallet: file-assisted import + multi-browser
e2e) into the ng-eventually branch. Conflicts resolved so both lines of work
coexist and route through the lib where they overlap:

- harness-ng.tsx: combine ReadCap FilterProbe (ours) with main's SmokeProbe/
  FanoutProbe; useShape + ng imported from @ng-eventually/client.
- ngSession.ts (auto): our single-injection-point configure() + main's hidden
  logoutNg, which uses the lib's ng.
- useShapeWithDefaults.ts (auto): lib useShape + main's { graphs } multistore
  scope.
- cucumber.json: single "tags": "not @wip" (both branches added it).
- brief_2026-06-15_shared-wallet-shim: keep main's implemented status; record
  that the read filter now lives in the lib (decision_2026-06-17) while the
  rest of the shim (storeRegistry/accounts/isolation) is still in-app, slated
  to move into the lib.

Build OK; harness-ng bundles. TODO (next): verify all of main's NextGraph
surface routes through @ng-eventually/client (storeRegistry uses ng directly).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 13:05:21 +02:00
Sylvain Duchesne 98c796054e e2e désinscription: mark @wip (real CRDT bug, not a stale test) + exclude @wip from default run
The "Se désinscrire" e2e wasn't obsolete: verified against the broker that
join reflects in the UI but leave does NOT — the button stays "✓ Je participe"
(>10s). DeepSignalSet.delete() does fire reactivity (touchIterable), so the
real cause is downstream: the deletion doesn't propagate / the item resurrects
via broker sync (the documented CRDT limitation).

- cycle-de-vie-evenement.feature: rewrite the désinscription scenario to be
  self-contained (join → leave → "J'y serai" in one session, no cross-scenario
  / persistence dependency), and tag it @wip with an accurate comment.
- cucumber.json: add tags "not @wip" so known-incomplete scenarios document an
  expectation without failing the suite (default run: 146 scenarios).
- docs: caveat_participation-deletion records the e2e finding (leave doesn't
  reflect in the UI; delete fires reactivity but the item resurrects via sync);
  knowledge_cucumber-setup documents @wip = excluded from the default run.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 12:19:03 +02:00
Sylvain Duchesne 266e33556d feat(auth): staging wallet partagé — import assisté par fichier + e2e multi-navigateur
Stopgap staging multi-user sur wallet partagé (cf. brief_2026-06-15_shared-wallet-shim).

Distribution / import du wallet :
- AccessGateScreen : barrière d'accès ON PAR DÉFAUT (désactivable via
  globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ pour tests/dev). Fournit le FICHIER
  .ngw + le mot de passe + un guide en 3 étapes (import assisté sur nextgraph.eu —
  le broker hébergé n'autorise pas l'import inline pendant l'auth web-app).
- sharedWallet.ts + build.ts : fichier copié en /shared-wallet.ngw, mot de passe gravé.
- Ancien LoginScreen (/login) retiré ; atterrissage post-login -> /home.
- NextGraphContext : dé-piégeage de l'état "connecting" au retour (pageshow/bfcache).

Couche multistore stopgap : storeRegistry, isolation, AccountContext, FestipodDataContext.

Tests e2e multi-navigateur :
- browserPool + world.openBrowser : contextes frais isolés, 2 axes orthogonaux
  (nb de navigateurs × modèle de wallet own/shared).
- @humain : parcours humain complet (télécharge -> importe le fichier sur
  nextgraph.eu -> Entrer -> pseudo -> accueil).
- Bypass de la barrière pour @e2e via context.addInitScript.
- Convention @wip exclue via cucumber.json.

Docs (concepts) : nextgraph-platform (knowledge_broker-import-constraint,
decision_2026-06-17_assisted-wallet-import), bdd-testing (knowledge_multibrowser-harness).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 12:04:02 +02:00
Sylvain Duchesne 073150ef61 ReadCap read filter: consume the lib's per-document model + validate against broker
Align Festipod's @data read-filter scenario and harness bridge with
ng-eventually's grant→ReadCap refactor: the access unit is the document
(an item's `@graph`), not the item.

- harness-ng.tsx: governDocument(reader, user)/setUser via getCaps()/resetCaps()
  (replaces setupReadFilter/setGrantOf); FilterProbe exposes a lazy snapshot()
  reflecting the current user without remount.
- read-filter.feature/steps: validate per-document ReadCap on the real
  DeepSignalSet — govern the wallet document, grant the cap to another user
  → current user sees 0; current user gets the cap → sees all (all-or-nothing
  in mono-store, the faithful behavior). 5/5 steps pass against the broker.
- doctrine: knowledge_stores-permissions records the verified store/document/
  repo/ReadCap model (containment by reference, no read-cap inheritance);
  decision_2026-06-17_eventually-library updates the access-rights + filter
  status to the ReadCap model.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 11:20:12 +02:00
Sylvain Duchesne aec338441c test(data): validate ng-eventually read filter on the real ORM set
Adds a @data scenario (workshop/read-filter) that enables the lib's read filter on the
real reactive ORM set (via a FilterProbe + setupReadFilter harness helper, granting each
participation to its own user) and asserts useShape returns only the target user's
participations. Validates the trickiest piece — filtering a live DeepSignalSet — against the
broker. @data 9/9. Doc: read filter marked implemented & validated.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 10:28:56 +02:00
Sylvain Duchesne e270cc6063 refactor(data): route full NextGraph surface through @ng-eventually/client
The app now takes its NextGraph runtime AND types from @ng-eventually/client; the
only place that imports the real @ng-org SDK is ngSession (the single injection point for
configure()). Lifecycle (init/initNg), data (useShape) and types (ShapeType, DeepSignalSet,
NG…) all go through the lib. Test infra (auth-setup, mock harness) and generated ORM
bindings keep a direct @ng-org import (documented). Validated: build, @ui 4/4, @data 8/8
against the real broker.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 14:54:00 +02:00
Sylvain Duchesne 9af128cb22 feat(data): route useShape through @ng-eventually/client (passthrough)
The reactive ORM data-plane now goes through the @ng-eventually/client wrapper
instead of @ng-org/orm directly; ngSession injects the real SDK into the polyfill via
configure(). Currently a transparent passthrough (lib mechanisms still stubbed) →
behavior unchanged. Validated: build, @ui 4/4, @data 8/8 against the real broker.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 16:35:58 +02:00
Sylvain Duchesne 3ca2d10c49 docs(concepts): NextGraph multi-user design — ng-eventually polyfill, discovery, apps/services
Captures the design worked out this session:
- decision: ng-eventually generic polyfill library (external repo) encapsulates all
  multi-user compensation; @ng-eventually/client is SDK-identical, app depends only on it.
- decision: discovery via a single global index fed through its inbox (owned doc,
  materialized) — no Group store; index owner = open question (singleton app, deferred).
- knowledge: NextGraph apps/services are mono-user with no global data (corrects the
  earlier 'index service with its own wallet' model).
- reconciled shared-wallet-shim brief (per-entity docs, login flow, polyfill terminology),
  authorization-matrix (no Group store), data-layer stack (ng-eventually indirection).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 16:35:58 +02:00
Sylvain Duchesne 222658a75d docs(concepts): shared-wallet-shim — statut d'implémentation (flags OFF)
Couche compte/login + isolation livrées et vérifiées ; couche multi-document
(storeRegistry) livrée derrière FESTIPOD_MULTISTORE/FESTIPOD_STAGING (OFF par
défaut, mono-store reste le défaut), runtime NG à valider sur broker.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 17:05:55 +02:00
Sylvain Duchesne 0294e3992f docs(concepts): migrate project docs into 7 concepts + code-grounded audit
Migrate .project/{knowledge,decisions,briefs} and the always-loaded
AGENTS.md/CLAUDE.md into the in-repo `concept` system (hook-delivered,
typed leaves). Then audit the actual code to verify the migrated doctrine
and capture knowledge that lived only in the source.

Concepts (53 leaves):
- functional-domain — produit : point de rencontre greffé, acteurs, déduplication
- app-architecture — modules, invariant d'imports, routing, écrans, styling-system,
  screen-pattern, cookbook d'ajout d'écran
- tech-stack — Bun-first, APIs, build pipeline, deployment (Dockerfile), commandes
- data-layer — NextGraph mono-store, shapes, modes, règles + caveats (suppression,
  champs non persistés, internals du contexte)
- bdd-testing — Cucumber multi-couches, contrat de couches, harness, cookbook
- app-security — posture actuelle (mono-store, confiance broker), auth wallet,
  brief matrice d'autorisations cible
- nextgraph-platform — NextGraph système externe + briefs (multi-store, shim, fork)

Audit corrections:
- décision SPARQL-delete annulée (superseded) → caveat (le code utilise ngSet.delete,
  persistance possiblement partielle)
- divergences relevées : routing path-based (pas hash), thème moderne sous components/sketchy,
  ConnectScreen hors registre, build:orm au chemin périmé, champs d'event perdus en connecté

Strip migrated sources; AGENTS.md/CLAUDE.md réduits au cœur (but, invariants,
carte des concepts) + pointeurs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 14:58:44 +02:00
Sylvain Duchesne 445a448031 docs: NextGraph multi-user data model — stores, auth matrix, inbox fork plan
Capture the multi-user design exploration as project knowledge + briefs:
- knowledge: NextGraph store types/permissions (+ inbox at protocol, SDK
  exposure, local repo path); integration model (iframe, where the verifier
  runs, generic JS plumbing, ngd stateful, build-time broker target)
- briefs: multi-store refactor; authorization matrix + query inventory +
  derived store partitions; temporary fork to expose the inbox (3 layers:
  SDK fork, Coolify self-hosting, Festipod integration; libs via build:ng)
- fix stale @ng-org versions (alpha.11 -> alpha.13) and a broken
  decision-record link in data-layer.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 17:38:51 +02:00
173 changed files with 17752 additions and 3887 deletions
+40
View File
@@ -0,0 +1,40 @@
# Festipod — variables d'environnement (exemple)
#
# Copier en `.env` (chargé automatiquement par Bun) et renseigner les valeurs.
# En dev (`bun run dev`) ET en prod (`bun run start`), l'app sert depuis src/ et
# lit ces variables au RUNTIME (via l'endpoint /festipod-config.json de src/index.ts).
# Sans elles, l'app tombe en mode dégradé : la barrière d'accès n'affiche que le
# champ identifiant, sans l'assistance de chargement du portefeuille partagé.
# ── Portefeuille partagé (stopgap staging) ─────────────────────────────────
# Mot de passe du portefeuille partagé.
# VIDE => hasSharedWallet() faux => la barrière n'affiche QUE le champ identifiant
# (pas les 3 étapes « télécharger + importer le portefeuille »). REQUIS en staging
# pour l'onboarding d'un appareil qui n'a pas encore de wallet.
FESTIPOD_SHARED_WALLET_PASSWORD=
# Chemin ABSOLU vers le fichier portefeuille partagé (.ngw). Servi en
# téléchargement à /shared-wallet.ngw depuis la barrière d'accès.
FESTIPOD_SHARED_WALLET_FILE=/chemin/absolu/vers/festipod-wallet.ngw
# ── Seed automatique (opt-in) ──────────────────────────────────────────────
# Non vide => l'app amorce des données de démo dans un wallet VIDE au 1er login.
# OFF par défaut : laisser vide en usage normal.
FESTIPOD_AUTO_SEED=
# ── Serveur ────────────────────────────────────────────────────────────────
# Port HTTP du serveur (défaut 3000).
PORT=3000
# NODE_ENV=production bascule `bun run start` (pas de HMR). En dev, laisser vide.
NODE_ENV=
# ── Outillage dev (facultatif) ─────────────────────────────────────────────
# Override du chemin local du polyfill @ng-eventually/client pour `pnpm run
# link:polyfill` (lien local réactif). Défaut = ../nextgraph/ng-eventually-js/packages/client.
NG_EVENTUALLY_LOCAL=
# ── Build only (build.ts / `bun run build`, PAS le runtime) ────────────────
# ACCESS_GATE_DISABLED=1 => build SANS barrière d'accès (l'app démarre directement).
# Réservé à un build de démo/no-gate ; ne pas utiliser pour un déploiement réel.
ACCESS_GATE_DISABLED=
+3
View File
@@ -41,3 +41,6 @@ playwright/.auth/
*storybook.log
storybook-static
dist-staging/
*.ngw
.tasks/
-175
View File
@@ -1,175 +0,0 @@
# Matrice d'autorisations et inventaire des requêtes
**Status:** Incubating — analyse en cours
**Last updated:** 2026-05-18
## Context
Préalable au refactor multi-store ([brief](./multi-store-refactor.md)) et à toute évolution multi-user. La structure de stores NextGraph cible doit être *dérivée* de :
1. Une matrice d'autorisations (qui peut faire quoi sur quel type de donnée).
2. Un inventaire des requêtes nécessaires (lectures, abonnements, écritures par écran).
3. Les partitions naturelles qui en découlent (regroupements de données qui partagent autorisations *et* schéma d'accès).
Ce brief porte cette analyse. Il alimentera la décision finale sur la structure de stores.
## Cadre
### Acteurs (tous authentifiés)
- `Self` — propriétaire de la donnée (varie par type : auteur d'un message, titulaire d'un profil…)
- `D` — Déclarant d'un événement (celui qui a inséré la référence dans Festipod ; pas l'organisateur réel)
- `H` — Hôte d'un point de rencontre (celui qui l'a créé)
- `I` — Inscrit à un point de rencontre
- `C` — Connexion (« ami ») d'un autre acteur lié à la donnée
- `U` — Utilisateur authentifié quelconque, sans relation à la donnée
### Verbes
- `créer`
- `lire` (one-shot)
- `s'abonner` (lecture longue / réactive)
- `modifier`
- `supprimer`
### Conventions
`✓` autorisé · `✗` interdit · `cond` autorisé sous condition (notée) · `—` sans objet
## Décisions cadre (acquises)
- **Tous les utilisateurs sont authentifiés.** Pas d'accès anonyme.
- **Points de rencontre publics universels.** Tout utilisateur peut lire et s'abonner.
- **Création de point de rencontre ouverte à tous.** Pas de prérequis (adhésion, invitation).
- **Hôte = détenteur technique des droits d'écriture** sur un point de rencontre. À ce stade : 1 hôte par PdR, celui qui l'a créé.
- **Adhésion à une communauté : hors périmètre actuel.** Le rôle « Membre de communauté » n'est pas analysé ici.
- **Suivi de communauté ou d'utilisateur : hors périmètre actuel.** À reprendre quand la fonctionnalité de discovery par abonnement sera traitée.
## Matrice par type de donnée
### Point de rencontre
| Verbe | Self (= Hôte) | I (autre inscrit) | D (déclarant de l'événement parent) | U (utilisateur lambda) |
|---|---|---|---|---|
| créer | ✓ (l'acte de créer rend l'utilisateur hôte) | — | ✗ | ✓ (l'acte le rend hôte) |
| lire | ✓ | ✓ | ✓ | ✓ |
| s'abonner | ✓ | ✓ | ✓ | ✓ |
| modifier | ✓ | ✗ | ✗ | ✗ |
| supprimer | ✓ | ✗ | ✗ | ✗ |
**Notes :**
- Pas de différenciation `C` (connexion de l'hôte) — les connexions sont un filtre d'affichage côté UI, pas un droit d'accès, puisque tout est public.
- Le `D` n'a pas de droit particulier sur les PdR greffés sur son événement déclaré — il a juste déclaré la référence.
### Inscription à un point de rencontre
L'objet « Inscription » lie un utilisateur et un point de rencontre. Représente l'engagement à participer.
| Verbe | Self (l'inscrit) | H (hôte du PdR) | I (autre inscrit au même PdR) | U (utilisateur lambda) |
|---|---|---|---|---|
| créer | ✓ (s'inscrire) | ✗ | ✗ | ✓ (l'acte le rend inscrit) |
| lire | ✓ | ✓ | ? **à trancher** | ? **à trancher** |
| s'abonner | ✓ | ✓ | ? **à trancher** | ? **à trancher** |
| modifier | ? **à trancher** (selon les champs modifiables) | ✗ | ✗ | ✗ |
| supprimer | ✓ (se désinscrire) | ? **à trancher** (modération ? blacklist ?) | ✗ | ✗ |
**Questions ouvertes :**
- **Visibilité de la liste des inscrits.** Cohérent avec « tout est public » : tous les utilisateurs voient qui s'est inscrit. Mais à confirmer — y a-t-il un cas où on veut cacher la liste (PdR à inscription confidentielle) ?
- **Champs modifiables d'une inscription.** Booléen seul, ou champs additionnels (commentaire, statut "peut-être", nombre d'accompagnants) ?
- **Modération par l'hôte.** L'hôte peut-il désinscrire un inscrit (= blacklist) ?
### Événement
| Verbe | Self (= D, déclarant) | H (hôte d'un PdR greffé) | U (utilisateur lambda) |
|---|---|---|---|
| créer | ✓ (l'acte rend déclarant) | — | ✓ (l'acte le rend déclarant) |
| lire | ✓ | ✓ | ✓ |
| s'abonner | ✓ | ✓ | ✓ |
| modifier | ? **à trancher** | ? **à trancher** | ? **à trancher** |
| supprimer | ? **à trancher** | ✗ | ✗ |
**Questions ouvertes :**
- **Qui peut modifier un événement déclaré ?** Le déclarant seul (modèle propriétaire) ? Tout utilisateur (modèle wiki, pour compléter/corriger) ? Personne après création (modèle immuable, pour éviter les modifications mal intentionnées) ? Cette question est centrale pour le défi de déduplication évoqué dans le README — un modèle wiki facilite la convergence, un modèle propriétaire complique.
- **Qui peut supprimer ?** Si le déclarant supprime, que deviennent les PdR greffés (orphelins ? supprimés en cascade ? l'événement reste mais marqué supprimé ?) ?
### Profil utilisateur
À déterminer : un seul objet ou split public/privé ?
| Verbe | Self | C (connexion) | U (utilisateur lambda) |
|---|---|---|---|
| créer | ✓ (à l'inscription) | — | — |
| lire (partie publique) | ✓ | ✓ | ? **à trancher** |
| lire (partie privée) | ✓ | ? **à trancher** | ✗ |
| s'abonner | ✓ | ? | ? |
| modifier | ✓ | ✗ | ✗ |
| supprimer | ✓ (auto-destruction du compte) | ✗ | ✗ |
**Questions ouvertes :**
- **Split public/privé ?** Le profil contient-il des champs réservés aux connexions ou à l'utilisateur seul (préférences, paramètres, email) ?
- **Profil entièrement public ?** Cohérent avec « points de rencontre publics » : un visiteur peut voir le profil de l'hôte d'un PdR. Mais le détail (bio, photos, ville…) ?
### Connexion (lien d'amitié)
| Verbe | Self (A, demandeur) | Other (B, l'autre côté de la connexion) | U (utilisateur lambda) |
|---|---|---|---|
| créer (demande) | ✓ | — | — |
| accepter | — | ✓ | ✗ |
| lire (sa propre liste d'amis) | ✓ | — | — |
| lire (la liste d'amis d'un autre) | — | — | ? **à trancher** |
| s'abonner (à sa liste) | ✓ | — | — |
| modifier | — | — | — |
| supprimer (rompre la connexion) | ✓ | ✓ | ✗ |
**Questions ouvertes :**
- **Bilatérale ou unilatérale ?** Le concept « connexion / ami » suggère bilatérale (les deux acceptent). À confirmer ; si oui, il y a deux objets distincts : `DemandeDeConnexion` (unilatérale) et `Connexion` (bilatérale).
- **Visibilité de la liste d'amis.** Une connexion est-elle observable par des tiers ? « Marie est connectée à Bob » est-il public, restreint, ou privé ?
## Hors périmètre actuel
À reprendre quand ces concepts deviendront actifs :
- **Communauté d'intérêt** (membres, modération, création)
- **Adhésion à une communauté**
- **Liste curated** (création, partage, abonnement)
- **Suivi d'utilisateur ou de communauté** pour discovery distribuée
## Inventaire des requêtes par écran
*À remplir une fois la matrice des autorisations stabilisée.*
Schéma prévu :
| Écran | Lectures one-shot | Abonnements | Écritures | Acteur déclencheur |
|---|---|---|---|---|
Écrans à analyser (depuis [AGENTS.md](../../AGENTS.md#routing)) :
- `WelcomeScreen` `/`
- `LoginScreen` `/login`
- `HomeScreen` `/home`
- `EventsScreen` `/events`
- `CreateEventScreen` `/events/new`
- `EventDetailScreen` `/events/:id`
- `UpdateEventScreen` `/events/:id/edit`
- `InviteScreen` `/events/:id/invite` (à voir si encore pertinent)
- `ParticipantsListScreen` `/events/:id/participants`
- `MeetingPointsScreen` `/events/:id/meeting-points`
- `ProfileScreen` `/profile`
- `UpdateProfileScreen` `/profile/edit`
- `FriendsListScreen` `/profile/friends`
- `ShareProfileScreen` `/profile/share`
- `UserProfileScreen` `/users/:id`
- `SettingsScreen` `/settings`
## Partitions naturelles dérivées
*À remplir une fois la matrice + l'inventaire stabilisés.*
Heuristique de dérivation : on regroupe dans un même store les données qui (a) partagent leur cellule d'autorisation pour les verbes d'écriture, et (b) sont accédées ensemble dans la majorité des requêtes (pour éviter de multiplier les abonnements).
## See Also
- [Brief : refactor multi-store](./multi-store-refactor.md) — consommateur principal de cette analyse
- [README §Modèle fonctionnel](../../README.md) — source des acteurs et concepts
- [Knowledge : data layer](../knowledge/data-layer.md) — état actuel mono-store
-126
View File
@@ -1,126 +0,0 @@
# Refactor multi-store NextGraph
**Status:** Incubating — aucun travail démarré
**Last updated:** 2026-05-17
## Context
L'app Festipod est aujourd'hui *mono-store* : tout ce que l'app écrit (events, profils, participations, friendships) atterrit dans le `private_store` de l'utilisateur connecté. C'est un héritage du sample expense-tracker-rdf, formalisé dans [la décision du 2026-03-17](../decisions/2026-03-17-1600-private-store-nuri-scope.md).
Ce choix bloque toute évolution vers du multi-utilisateurs : par construction le `private_store` est non partageable (cf. [data-layer](../knowledge/data-layer.md) et la doc NextGraph officielle — *« It is not possible to share the documents of your private store with anybody else »*). Tant que tout est dans le private_store, Bob ne pourra jamais voir l'event d'Alice.
Le modèle natif NextGraph est *multi-store par utilisateur* (private, protected, public, group, dialog) — chaque type d'information a sa place. Festipod doit s'aligner sur ce modèle avant de pouvoir devenir collaboratif.
**Déclencheur :** discussion du 2026-05-17 sur la suite multi-user. Décision prise : *poser le cap, exécuter plus tard*.
## What We Know
### État actuel du code
Deux fichiers concentrent le hardcoding du store unique :
- `src/shared/utils/ngGraph.ts:30``ensureGraphNuri()` retourne `did:ng:${session.private_store_id}` pour TOUTES les entités, peu importe leur nature.
- `src/shared/hooks/useShapeWithDefaults.ts` — accepte un `storeNuri` mais l'appelant unique (`FestipodDataContext`) lui passe systématiquement le NURI du private_store.
Entités impactées (toutes mélangées dans le même store aujourd'hui) :
- `FpEvent` — devrait vivre dans un store partagé (logique multi-user)
- `FpUserProfile` — devrait être en partie privée, en partie publique
- `FpParticipation` — liée à un event, devrait vivre avec lui
- `FpMeetingPoint` — actuellement local-only côté types ([`src/shared/data/types.ts:106`](../../src/shared/data/types.ts)), pas encore branché à NextGraph
- `FpFriendship` — actuellement local-only, naturellement privée
### Modèle cible proposé
Structure hiérarchique en **4 niveaux de Group stores** (pas de private/public pour le métier collaboratif — tout en Group) :
```
┌─ Group store « index communautaire » ────────────────────┐
│ Référence tous les events visibles dans la communauté │
│ Lecture par tous les membres, sert d'annuaire/discovery │
│ │
│ ┌─ Group store « communauté » ──────────────────────┐ │
│ │ Propriétaire de l'event │ │
│ │ Permissions = qui peut modifier l'event │ │
│ │ (organisateurs / membres de la communauté) │ │
│ │ │ │
│ │ ┌─ Group store « event » ─────────────────────┐ │ │
│ │ │ Tout ce qui se rattache à l'event : │ │ │
│ │ │ participations, infos pratiques, discu… │ │ │
│ │ │ Membres = participants à l'event │ │ │
│ │ │ │ │ │
│ │ │ ┌─ Group store « meeting point » ───────┐ │ │ │
│ │ │ │ Un RDV de l'event = son propre group │ │ │ │
│ │ │ │ Permet participations + discu │ │ │ │
│ │ │ │ scopées au point de rencontre │ │ │ │
│ │ │ └───────────────────────────────────────┘ │ │ │
│ │ └─────────────────────────────────────────────┘ │ │
│ └───────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────┘
```
Mapping entités → store cible :
| Entité | Store cible | Justification |
|---|---|---|
| Event (métadonnées : titre, dates, description) | Group store « communauté » | C'est la communauté qui possède l'event, donc qui contrôle qui peut le modifier |
| Référence d'event (pointeur depuis l'index) | Group store « index communautaire » | Discovery : « voici les events visibles » |
| Participation | Group store « event » | Une participation n'a de sens que dans le contexte de son event |
| MeetingPoint (métadonnées) | Group store « event » | Le RDV appartient à l'event |
| Participation à un MeetingPoint | Group store « meeting point » | RSVP/présence scopés au RDV |
| UserProfile (partie publique) | public_store de l'utilisateur | Modèle natif NextGraph |
| Friendship | private_store de l'utilisateur | Donnée purement personnelle |
### Contrainte SDK bloquante
La création de Group stores et la gestion des invitations/permissions **ne sont pas exposées dans le SDK `@ng-org/web` actuel** (version `0.1.2-alpha.11`). Les méthodes disponibles : `doc_create`, `doc_subscribe`, `sparql_query/update`, `orm_start_*`, `file_get`, `app_request_stream`. Aucune méthode `share_doc`, `invite_user`, `create_group_store`, `accept_invite`. La doc NextGraph annonce qu'*« An API will be provided for permission manipulation »* — pas de date.
**Implication :** le refactor *structurel* (passer d'un store unique à un système de stores par entité) peut commencer sans attendre cette API, en utilisant des placeholders (par ex. continuer à pointer vers `private_store_id` pour les Group stores qui ne peuvent pas encore exister). Mais l'**aboutissement complet** (vrai multi-user, partage entre wallets distincts) dépend de l'arrivée de l'API SDK ou d'un contournement (fork du wallet, accès Rust direct, etc.).
### Implications côté code
Le refactor touche au moins :
1. **Disparition de `ensureGraphNuri()`** comme helper unique. Remplacé par des helpers par entité (`getEventStore(communityId)`, `getParticipationStore(eventId)`, `getProfileStore(scope: 'public' | 'private')`, …) ou par une couche `storeRegistry` qui résout le NURI selon `(entité, contexte)`.
2. **`useShapeWithDefaults` reste un wrapper utile** mais l'appelant choisit explicitement le store. Aujourd'hui un seul appelant ([`FestipodDataContext`](../../src/shared/context/FestipodDataContext.tsx)), demain N appelants ou un appelant qui résout dynamiquement.
3. **Chaque entité de domaine déclare son store cible** — soit via un mapping centralisé, soit via une convention (shape → store).
4. **`bootstrapWallet()`** ([`src/shared/utils/ngBootstrap.ts`](../../src/shared/utils/ngBootstrap.ts)) doit être revu : on ne seed plus dans un unique store, on doit seed dans plusieurs (ou décider que seed ne crée que des données de l'utilisateur courant — ce qui colle mieux à la réalité multi-user).
5. **`FestipodDataContext`** : structurer les hooks par entité, chacun avec son store résolu.
## Open Questions
1. **Quand crée-t-on un Group store de communauté ?** L'API n'existe pas en SDK aujourd'hui. Faut-il que ce soit un acte explicite de l'utilisateur (« créer une communauté ») ou bien tout user a une communauté par défaut à la création de son wallet ?
2. **Comment Bob connaît-il l'index communautaire d'Alice ?** Discovery toujours ouverte — possiblement via le public_store d'Alice qui annonce le NURI de l'index communautaire.
3. **Faut-il vraiment 4 niveaux d'imbrication ?** Le « meeting point comme group store » mérite d'être validé — quel besoin réel justifie une couche de permission supplémentaire vs un simple sous-graphe du group store de l'event ?
4. **Que devient le seed de démo** quand l'app est multi-store et que les Group stores ne peuvent pas encore exister ? Mode dégradé en private_store le temps que le SDK rattrape, ou retirer le seed en mode connecté ?
5. **Migration des wallets existants** : les wallets de test ont déjà des données dans le private_store. Comment on les fait évoluer (script de migration, wipe and reseed, ignore) ?
6. **Bootstrap d'un user vierge** : à la première connexion, faut-il auto-créer un Group store communautaire « par défaut » pour lui ou attendre une action utilisateur ?
## Possible Approaches
Esquisses sans engagement (les arbitrages se feront dans une décision dédiée au moment de l'exécution) :
- **Refactor structurel d'abord, partage ensuite.** Réorganiser l'app en multi-store dès maintenant en utilisant `private_store_id` comme placeholder pour les Group stores manquants. Quand l'API arrive, on remplace les placeholders par de vrais NURIs de Group stores.
- **Registry centralisé** vs **résolution par convention**. Soit un `storeRegistry.ts` qui mappe explicitement `(entité, contexte) → NURI`, soit chaque shape porte sa propre logique de scope.
- **Big-bang** vs **par entité**. Tout migrer en un coup vs migrer entité par entité (commencer par Event qui est le plus stratégique).
- **Maintenir un mode mono-store** parallèle pour le dev/demo tant que les Group stores ne sont pas fonctionnels.
## Out of Scope
Ce brief — et le refactor qui en découlera — **ne traite pas** :
- L'invitation effective d'utilisateurs à un Group store (capability sharing, Nuri d'invitation)
- La gestion des permissions par rôle (organisateur / membre / lecteur)
- La résolution du problème de discovery cross-wallet
- Le contournement éventuel de l'UI wallet (jugée dysfonctionnelle dans cette conversation)
- Le mode P2P direct sans broker
Ces sujets relèvent d'un **second chantier multi-user** dont le refactor multi-store est seulement le *prérequis structurel*.
## Starting Points
- [decision: private_store NURI scope](../decisions/2026-03-17-1600-private-store-nuri-scope.md) — la décision actuelle qu'on viendra modifier
- [knowledge: data-layer](../knowledge/data-layer.md) — état actuel du pattern d'écriture
- [`src/shared/utils/ngGraph.ts`](../../src/shared/utils/ngGraph.ts) — point de hardcoding principal
- [`src/shared/hooks/useShapeWithDefaults.ts`](../../src/shared/hooks/useShapeWithDefaults.ts) — l'autre point de hardcoding
- [`src/shared/context/FestipodDataContext.tsx`](../../src/shared/context/FestipodDataContext.tsx) — l'unique appelant aujourd'hui
- [`src/shared/utils/ngBootstrap.ts`](../../src/shared/utils/ngBootstrap.ts) — le seed à revoir
- NextGraph docs : [Documents et Stores](https://docs.nextgraph.org/en/documents/), [Getting started](https://docs.nextgraph.org/en/getting-started/)
@@ -0,0 +1,25 @@
---
type: _overview
summary: Feature-based architecture of the app — modules per domain, import invariant, provider-stacked app shell, path-based routing, screens and registry
triggers:
keywords: [module, modules, screen, écran, routing, route, navigate, useNavigate, useParams, registry, registre, app shell, shared, import]
paths: ["src/app/**", "src/screens/**", "src/modules/*/screens/**", "src/shared/components/**", "src/shared/context/**"]
---
# App architecture
How the app's code is **structured** and **assembled**. *Feature-based* architecture: the code is organized by **business domain** (module), not by technical layer.
**Read this first:** [[rule_module-imports]] — the central invariant that keeps modules decoupled.
## Links
- [[knowledge_module-structure]] — module tree + `shared/` layer
- [[knowledge_app-shell]] — `src/app/`, provider stack, entry points
- [[knowledge_routing]] — path-based routing (History API), route table, hooks
- [[knowledge_screens]] — screen inventory, registry, component library
- [[knowledge_screen-pattern]] — canonical anatomy of a screen (no props, flex layout, showToast)
- [[caveat_identity-ids-in-screens]] — `currentUserId` (principal) vs `currentUser.id` (profile NURI): two id spaces that are not interchangeable
- [[knowledge_styling-system]] — `src/index.css`, `app-*` classes, vars, pitfalls (Tailwind unused, `user-content` inert)
- [[cookbook_add-screen]] — procedure for wiring up a new screen (registry + router + shell)
- `tech-stack` — build, Bun bundler, commands
@@ -0,0 +1,28 @@
---
type: caveat
summary: A screen juggles TWO ids for the current user that are not interchangeable — currentUserId (principal urn:festipod:user:…) for participation/friendship queries, currentUser.id (profile NURI) to compare against rendered profiles; getting it wrong raises no error, it just yields an empty list or counts you as an unknown participant
last_checked: 2026-07-27
---
# Pitfall: two ids for the current user inside a screen
`useFestipodData()` exposes **two** identifiers for the current user. They live in **different spaces** and are **never equal in connected mode**:
| Value | Space | What it is for |
|---|---|---|
| `currentUserId` | stable **principal** derived from the login identifier (`urn:festipod:user:<key>`) | this is what **participations** and **friendships** store |
| `currentUser.id` | **NURI of the profile document** (`did:ng:…`) | this is what rendered **profiles** carry |
In seed/demo mode the two coincide (`user-1`) — **the pitfall only shows up when connected**, and never as an error: just a wrong result.
## The rule
- Queries that **filter participations/friendships**`getUserEvents(userId)`, `isParticipating(eventId, userId?)`, `getFriends(userId?)` — expect the **principal**. Their default value (`currentUserId`) is correct; **do not pass them** a profile `user.id`, or the list comes back **empty**.
- `getEventParticipants(eventId)` returns **profiles**. Any comparison over its result (typically "remove myself from the list") therefore goes through **`currentUser?.id`**, never `currentUserId`.
## What the mistake costs (observed)
- Comparing `participant.id !== currentUserId` to filter yourself out **removes nothing**: you show up in your own list, and since the row is no longer recognized it renders as « participant inconnu ».
- Symmetrically, a screen displaying **another user's** events from their **profile id** (`getUserEvents(viewedUser.id)`) yields an empty list when connected — same cause.
The participation→profile join itself is **not** the screen's business: it is done in the provider (`resolveParticipantUser`), through the normalized identifier. Full mechanics and the write/read invariant: concept `data-layer`, [[knowledge_context-internals]].
@@ -0,0 +1,20 @@
---
type: cookbook
summary: Procedure for adding a screen — create the component in the module, register it in src/screens/index.ts, add the route in router.tsx, mount it in App.tsx, plus a screenNameMap alias if it is covered by BDD
---
# Cookbook: adding a screen
A screen has to be wired up in **several places** — forgetting one produces silent bugs (see the `ConnectScreen` case, [[knowledge_screens]]).
1. **Create the component**: `src/modules/{module}/screens/MyScreen.tsx`, following [[knowledge_screen-pattern]] (function with no props, `useFestipodData`/`useNavigate`/`useParams`, flex layout, styling via [[knowledge_styling-system]]). Respect [[rule_module-imports]] (import only from `shared/`).
2. **Add it to the registry**: `src/screens/index.ts` — add the import plus the entry (`id`, French `name`, `path`, `component`). **The most frequently forgotten step**: a screen missing from the registry is invisible to Storybook and to the registry's consumers, even though it works as a route.
3. **Add the route**: `src/app/router.tsx` — extend the `Route` type, add the case in `parsePath()` (and the reverse conversion if present).
4. **Mount it in the shell**: `src/app/App.tsx` — add the case in the switch that maps `route.page` → component.
5. **(If covered by BDD)**: add an alias in `screenNameMap` (`src/shared/steps/ui/navigation.steps.ts`) if the French name used in the `.feature` does not resolve trivially to the `id`. See concept `bdd-testing`.
> Check consistency: the `id` must be identical across the registry, the router and `screenNameMap`. A silent mismatch = an unreachable or unrendered screen.
@@ -0,0 +1,50 @@
---
type: knowledge
summary: src/app/ is the app's real shell — App.tsx stacks the providers (Theme > NextGraph > Account > FestipodData > Router), AuthGate keeps every routed screen behind the access barrier, and the shell switches screens according to the route
last_checked: 2026-07-27
---
# App shell
`src/app/` is the **shell of the real app** (mobile web app), not a prototyping tool.
> Migration note: older notes described `src/app/` as a "prototyping tool" using hash routing (`#/`, `#/demo/...`). That is **obsolete** since the restructuring into a real app. The current truth: path-based routing via the History API (see [[knowledge_routing]]).
## Provider stack
`App.tsx` stacks the providers, then switches screens according to the current route:
```
ThemeProvider
└ NextGraphProvider (NextGraph connection cycle — concept data-layer)
└ AccountProvider (current identity = the identifier — concept app-security)
└ FestipodDataProvider (data, connected/demo mode — concept data-layer)
└ RouterProvider (current route + navigate)
└ div.app-container
├ AuthGate (access barrier)
│ └ AppContent (switch route.page → screen)
└ ToastContainer
```
`AppContent` reads `useRouter()` to resolve `route.page` → the screen to render.
### Ordering invariants (what breaks if you move a layer)
- **`AccountProvider` sits ABOVE `FestipodDataProvider`.** The data provider calls `useAccount()` to derive its principal (`currentUserId`) *and* to reset its session when the identity changes. Reversing the order breaks the whole identity resolution, silently.
- **`AuthGate` sits INSIDE the router**: it reads `useRouter()`/`useNavigate()` to leave the logged-out landing route once connected **and** identified. Moving it out of `RouterProvider` breaks it.
- **`AuthGate` wraps EVERY routed screen.** As long as the wallet is not open **or** the identifier is not resolved, `AccessGateScreen` is rendered **instead of** `AppContent`. Consequence: **no screen may assume it is reachable without an identity** — unless the barrier is disabled (see below).
- **`ToastContainer` sits OUTSIDE `AuthGate`** (but inside `.app-container`): it is mounted regardless of the barrier's state.
### Disabling the barrier (two consumers)
`AuthGate` is **ON by default**; it steps aside only if `globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ === true`, set either by `build.ts` (from `ACCESS_GATE_DISABLED=1`, barrier-free build) or by the test harness via `addInitScript` for the `@e2e` tests (which exercise the screens, not the auth flow). **Impact**: the barrier flow is therefore **not** covered by the `@e2e` tests — its guards are `@ui` tests (concept `bdd-testing`).
## Entry points
| File | Role |
|---|---|
| `src/index.ts` | `Bun.serve()` — HTTP server, serves `index.html` + the cucumber report |
| `src/index.html` | HTML entry point, loads `src/app/frontend.tsx` |
| `src/app/frontend.tsx` | React root, renders `<App />` |
The build and the bundler (Bun + Tailwind, alias `@/* → ./src/*`) are documented in the `tech-stack` concept.
@@ -0,0 +1,41 @@
---
type: knowledge
summary: Feature-based tree — business modules (event, user, home, auth, workshop, meeting, notification) and a shared/ layer importable by all of them
---
# Module structure
The code is organized by **business domain**, not by technical layer.
```
src/modules/
event/ # Events: CRUD, discovery, participants, meeting points
user/ # Profiles, connections ("friends"), sharing
home/ # Dashboard, settings
auth/ # Login, welcome/onboarding
workshop/ # Workshop specs (features only, no screens)
meeting/ # Meeting point specs (features only)
notification/ # Notification specs (features only)
```
Each module may contain:
- `screens/` — React screen components
- `features/` — Gherkin `.feature` files (BDD specs, see concept `bdd-testing`)
- `steps/{ui,data,e2e}/` — Cucumber step definitions, one folder per layer
## The `shared/` layer
`src/shared/` holds everything reusable across modules:
| Directory | Contents |
|---|---|
| `components/` | UI component library (see [[knowledge_screens]]) |
| `context/` | `ThemeContext`, `NextGraphContext`, `AccountContext` (current identity — concept `app-security`), `FestipodDataContext` (concept `data-layer`); their **stacking order** is constrained, see [[knowledge_app-shell]] |
| `data/` | User stories, `features.ts` (auto-generated), `seedData.ts`, `types.ts` |
| `hooks/` | `useShapeWithDefaults` (NextGraph) |
| `shapes/` | SHEX + ORM bindings (see concept `data-layer`) |
| `utils/` | `ngSession.ts`, `ngBootstrap.ts`, `ngGraph.ts` |
| `steps/`, `support/` | Shared Cucumber step definitions and hooks (concept `bdd-testing`) |
| `lib/` | Helpers (`cn`, etc.) |
The dependency rule between modules and `shared/` lives in [[rule_module-imports]].
@@ -0,0 +1,35 @@
---
type: knowledge
summary: Path-based routing via the History API (hand-rolled router in src/app/router.tsx) — route table, useNavigate/useParams hooks, no prop drilling
---
# Routing
**Path-based** routing via the History API — hand-rolled router in `src/app/router.tsx` (`window.history.pushState` + `popstate`, `parsePath(pathname)`). No hash routing.
## Route table
| Path | Screen |
|---|---|
| `/` | WelcomeScreen |
| `/home` | HomeScreen |
| `/events` | EventsScreen |
| `/events/new` | CreateEventScreen |
| `/events/:id` | EventDetailScreen |
| `/events/:id/edit` | UpdateEventScreen |
| `/events/:id/invite` | InviteScreen |
| `/events/:id/participants` | ParticipantsListScreen |
| `/events/:id/meeting-points` | MeetingPointsScreen |
| `/profile` | ProfileScreen |
| `/profile/edit` | UpdateProfileScreen |
| `/profile/friends` | FriendsListScreen |
| `/profile/share` | ShareProfileScreen |
| `/profile/connect` | ConnectScreen (`src/modules/user/screens/ConnectScreen.tsx`) — routed and mounted in `App.tsx`, but **absent from the screen registry**, see [[knowledge_screens]] |
| `/users/:id` | UserProfileScreen |
| `/settings` | SettingsScreen |
> This table mirrors `parsePath()` in `router.tsx` — go back to it whenever it changes, that is the source of truth. There is **no** authentication route: the access barrier is not routed, it is rendered *above* the route switch by `AuthGate` (see [[knowledge_app-shell]]).
## Hooks
Screens use the router's `useNavigate()` and `useParams()`**no prop drilling**. The shell intercepts navigation to switch the displayed screen (see [[knowledge_app-shell]]).
@@ -0,0 +1,46 @@
---
type: knowledge
summary: Canonical anatomy of a screen — named function with no props, reads everything through useFestipodData/useNavigate/useParams, flex column layout (Header / scrollable content / BottomNav on hub screens), feedback via showToast, hard-coded French labels
---
# Canonical screen pattern
Every screen follows the same shape. Knowing it avoids reinventing or diverging.
## Shape
```tsx
export function MyScreen() { // named function, NEVER any props
const navigate = useNavigate();
const { eventId, userId } = useParams();
const { getEvent, currentUser, } = useFestipodData();
const [local, setLocal] = useState(); // screen-local state (steps, selections)
const handleAction = () => {
// …mutate through useFestipodData
showToast('Message', 'success'); // feedback
navigate('/path');
};
return (
<div style={{ display:'flex', flexDirection:'column', height:'100%' }}>
<Header title="…" /* left/right optional */ />
<div style={{ flex:1, overflow:'auto' }}>{/* scrollable content */}</div>
<BottomNav active="…" /> {/* only on hub screens */}
</div>
);
}
```
## Invariants
- **Zero props**: a screen receives nothing; everything comes from context/hooks (`useFestipodData`, `useNavigate`, `useParams`). Two exceptions, of different kinds:
- `WelcomeScreen` does not use `useFestipodData` (intro) — but still takes no props. (`LoginScreen`/`ConnexionScreen` no longer exist.)
- **`AccessGateScreen` is the only genuine exception to the zero-prop rule**: it is **not a routed screen**, it is rendered by `src/app/AuthGate.tsx`, which passes it `status`/`error`/`initialIdentifier`/`onEnter`. It therefore sits **outside the registry and outside the route table**, and has access to neither the router nor the data. See [[knowledge_screens]] and [[knowledge_app-shell]].
- **Identity: two id spaces.** `currentUserId` (principal) and `currentUser.id` (profile NURI) are **not** interchangeable depending on the query — see [[caveat_identity-ids-in-screens]] before comparing an id inside a screen.
- **Layout**: full-height flex column; `Header` at the top, content at `flex:1; overflow:auto`, `BottomNav` at the bottom **only for hub screens** (Home, Events, Profile, Friends). Flow screens (creation, editing, detail) have no `BottomNav`.
- **Feedback**: `showToast(message, 'success'|'info'|'error')` (`ToastContainer` mechanism exported by `sketchy/`).
- **Labels**: **French, hard-coded** — no i18n, no translation keys anywhere in the project.
- Styling: see [[knowledge_styling-system]]. Navigation/registry: [[knowledge_routing]], [[knowledge_screens]].
To **create** a screen (the 3+ places to wire up), see [[cookbook_add-screen]].
@@ -0,0 +1,42 @@
---
type: knowledge
summary: Inventory of screens per module, central registry src/screens/index.ts, and the component library under shared/components/sketchy/ — whose NAME is kept but which renders a modern theme (not hand-drawn)
---
# Screens and components
## Component library: `sketchy/` = modern theme
⚠️ **Naming pitfall.** The component library lives under `src/shared/components/sketchy/` (path kept, imported by ~17 screens), **but it no longer renders a "hand-drawn" style**: it was ported to a **modern** theme (DM Sans / orange, `app-*` classes). The *import path* is right, the *"sketchy" visual description* is obsolete. Do not reintroduce hand-drawn aesthetics on the strength of the folder name.
Typical components: `Header`, `BottomNav`, `Button`, `Card`, `Input`, `Badge`, `Avatar`/`AvatarStack`, `Text`/`Title`, `Toggle`, `ListItem`, `Divider`, `Placeholder`, `BrokerBanner`, `NgStatus`.
## Screen registry
`src/screens/index.ts` imports every screen from every module and exposes:
```typescript
export const screenGroups // grouped by domain (home, events, user, general)
export const screens // flat list
export function getScreen(id): Screen | undefined
```
Used notably by Storybook (see concept `tech-stack`) to browse the screens.
## Inventory
Screens per module (IDs = registry keys):
- **home/**: `welcome`, `home`, `settings`
- **event/**: `events`, `event-detail`, `create-event`, `update-event`, `invite`, `participants-list`, `meeting-points`
- **user/**: `profile`, `update-profile`, `user-profile`, `friends-list`, `share-profile`
- **auth/**: `WelcomeScreen` (intro, routed at `/`) and `AccessGateScreen` — the **access barrier** (NextGraph login + identifier entry), rendered by `src/app/AuthGate.tsx`, **outside the registry and outside routing** (it is not a routed screen) and **driven by props** (`status`/`error`/`initialIdentifier`/`onEnter`), the only exception to the zero-prop rule ([[knowledge_screen-pattern]]). The former `LoginScreen`, then `ConnexionScreen`, have been removed (see concept `app-security`, [[knowledge_authentication]]).
Structurally, this screen does **not** render a standard screen layout but a **choice between three mutually exclusive access branches**, driven by `status` + the presence of a shared wallet. **Impact**: a new access case is added as a branch here, **not** as a route. The content and ordering of the branches are `app-security` doctrine ([[knowledge_authentication]]) — do not redefine them from here.
> The path → screen mapping lives in [[knowledge_routing]]. Most screens consume `useFestipodData()` (concept `data-layer`); exceptions: `WelcomeScreen` and the `AccessGateScreen` barrier.
## Pitfall: incomplete registry
The registry must list **every** screen. Observed case, **still true (verified 2026-07-28)**: `ConnectScreen` (`src/modules/user/screens/ConnectScreen.tsx`) exists, is routed at `/profile/connect` (`router.tsx`) and is mounted in `App.tsx` (`case 'connect'`), yet it is **missing from `src/screens/index.ts`** → invisible to Storybook and to the registry's consumers, even though it works as a route. Always check that the screen is registered (see [[cookbook_add-screen]]).
@@ -0,0 +1,32 @@
---
type: knowledge
summary: src/index.css is the styling source of truth — --app-* variables (colors, radii, DM Sans font) and app-* classes rendered by the components; screens combine those classes with inline styles; Tailwind is in the build but screens use no Tailwind utilities; the user-content class is inert
last_checked: 2026-06-15
---
# Styling system
**Source of truth: `src/index.css`** ("Modern clean — DM Sans" theme). That is where the CSS variables and the `app-*` classes live. No per-module CSS files.
## Variables (`:root`)
- Colors: `--app-black #1a1a1a`, `--app-gray #888`, `--app-bg/--app-white #fff`, orange accent `--app-accent #E8590C` (+ `-light #FFF7ED`, `-border`, `-dark #C05621`), green `--app-green #22543D` (+ `-light`, `-border`, `-text`).
- Radii: `--app-radius 16px`, `--app-radius-sm 12px`, `--app-radius-xs 8px`.
- Font: `--font-app: 'DM Sans', …`.
## `app-*` classes
Defined in `index.css`, rendered by the components in `shared/components/sketchy/`: `app-btn` (+ `-primary`/`-green`), `app-input`, `app-card`, `app-title`/`app-subtitle`/`app-text`, `app-badge`, `app-toggle`, `app-checkbox`, `app-header`, `app-navbar`, `app-list-item`, `app-avatar`, `app-placeholder`, `app-divider`, `app-tab`.
## Conventions for writing a screen
- Use the **`sketchy/` components** (which carry the `app-*` classes) for buttons/inputs/cards/typography.
- For **layout** (flex, gaps, paddings, one-off colors), screens use **inline styles** (`style={{…}}`) — that is the normal pattern, not a deviation.
- Icons: **emojis**/Unicode symbols (📅 📍 📝 🎪…), generally no icon imports.
- Width: `.app-container` caps at **`max-width: 768px`, `height: 100dvh`** (mobile-first/portrait tablet). No media queries — no desktop responsiveness.
## Pitfalls
- **Tailwind is in the build** (`bun-plugin-tailwind` plugin, `tailwindcss` dependency), but **screens use no Tailwind utility classes** — the actual styling goes through `app-*` + inline. Do not "tailwindify" a screen thinking you are following the convention.
- **`user-content` is an INERT class**: used on many titles/names across the screens, **with no CSS definition whatsoever**. It is a legacy marker with no effect — do not rely on it for styling, do not assume it does anything.
- No **dark mode**: the "darkMode" toggle in `SettingsScreen` is not wired to anything.
@@ -0,0 +1,24 @@
---
type: rule
summary: A module imports ONLY from shared/ (and the screen registry) — never from another module; this is the invariant that keeps the feature-based architecture real
---
# Rule: a module never imports from another module
**Modules import only from `shared/` — never from each other.**
```
src/modules/event/screens/EventDetailScreen.tsx
✅ import from 'shared/components/...'
✅ import from 'shared/context/FestipodDataContext'
✅ import from 'src/screens' (registry types)
❌ import from 'modules/user/screens/...'
```
## Why
This is what makes the *feature-based* architecture real rather than cosmetic: each domain stays a self-contained block, movable or removable without breaking the others. Any shared need **moves up into `shared/`**; any cross-domain dependency goes through a `shared/` contract (usually `FestipodDataContext` or the screen registry), never through a direct import.
## How to check
`grep -rE "from '\.\./\.\./(event|user|home|auth|workshop|meeting|notification)/" src/modules/` must not surface anything pointing from one module to *another* module. An import that crosses two different module names is a violation.
@@ -0,0 +1,26 @@
---
type: _overview
summary: Festipod's security & privacy — isolation between scopes is enforced by the data SDK, the app trusts it and carries no authorization logic in the screens; wallet-based authentication; target authorization matrix still incubating
triggers:
keywords: [sécurité, security, confidentialité, privacy, accès, "access control", contrôle d'accès, trust, confiance, authz, autorisation, permission, wallet, auth, authentification, anonyme, anonymat, pseudonyme, traçage, corrélation, overlay, cap-less, identité, login, scope, isolation]
paths: ["src/modules/auth/**", "src/shared/context/NextGraphContext.tsx"]
---
# App security
Festipod's **security, privacy and authorization** model.
- **Enforced model** — **isolation between scopes** (public / protected / private) is **enforced by the data SDK** (`@ng-eventually/client`), which exposes to each user only what they are entitled to. The app **trusts** the SDK: no screen carries authorization logic. See [[knowledge_trust-model]].
- **Target authorization matrix** — the detail of *who may do what* per actor × verb (personal data = network, anonymity through the notification inbox): [[brief_2026-05-18_authorization-matrix]]. **Incubating.** It will graduate into `rule_`/`behavior_` as the product settles.
## Pitfalls (read BEFORE designing anything "anonymous")
- [[caveat_stable-overlay-pseudonym]] — a cap-less reference exposes a **permanent pseudonym** of the person; a single cross-reference de-anonymizes their entire history **retroactively**, and no rotation is known
- [[caveat_shared-wallet-global-before-gate-import]] — since the shared wallet is the only mode, a password global set **after** the barrier has been imported makes it unusable (config error screen, no field at all)
## Links
- [[knowledge_trust-model]] — the app delegates isolation to the SDK, no access control in the screens
- [[knowledge_authentication]] — wallet-based auth, everyone authenticated, no anonymous access
- [[brief_2026-05-18_authorization-matrix]] — target authorization matrix (incubating)
- Concept `functional-domain` → [[knowledge_data-scopes-and-discovery]] — which scope for which entity (product fact)
@@ -0,0 +1,126 @@
---
type: brief
summary: Target authorization matrix per data type (meeting point, registration, event, profile, connection) expressed as public/protected/private + dialog scopes; settled framing decisions (everyone authenticated, public meeting points, personal data = network, notification through an identified-or-anonymous inbox); open questions on the event write model and on host identity
last_updated: 2026-05-18
---
# Authorization matrix and query inventory
**Status:** Incubating — target model, not frozen into rules.
## Context
The **target** model of who-may-do-what. Festipod's privacy derives from: (1) an authorization matrix per actor × verb; (2) the inventory of queries per screen; (3) the **scopes** that follow from them — data sharing both an authorization *and* an access pattern. The concrete entity → scope placement is a product fact: concept `functional-domain` → [[knowledge_data-scopes-and-discovery]]. Isolation is **enforced by the data SDK** ([[knowledge_trust-model]]).
## Framing
### Actors (all authenticated)
`Alice` (viewpoint, owner of the data in focus) · `Bob` (second protagonist, bilateral relationships) · `D` (event declarer) · `H` (host of a meeting point) · `I` (registrant) · `C` (connection) · `U` (plain user with no relationship).
### Verbs
`create` · `read` (one-shot) · `subscribe` (reactive read) · `update` · `delete`. Conventions: `✓` allowed · `✗` forbidden · `cond` conditional · `—` not applicable.
## Framing decisions (settled)
- **Everyone is authenticated.** No anonymous access.
- **Meeting points are universally public.** Any user may read and subscribe.
- **Creating a meeting point is open to all.** No prerequisite.
- **Host = holder of the write rights** on a meeting point (1 host, the creator; being the host is public).
- **Personal information = reserved to the network.** Visible only to the holder and their connections: participations, the profile in full, the connection list, and any declarative state whose disclosure would be a leak. "Public" status (meeting point, event) and "personal" status (profile, participations, connections) coexist within the same user.
- **Bilateral connection.** It exists once both sides have accepted. Two objects: `DemandeDeConnexion` (one-sided, transient) and `Connexion` (bilateral, persistent).
- **Registration notification through the meeting point's inbox.** The act of registering is composite: (a) writing an `Inscription` object into the registrant's *protected* scope, (b) dropping a link into the **inbox** of the meeting point document. The sender is **identified if they are one of the host's connections, anonymous otherwise** — a property of the data model.
- **Joining a community / following: out of current scope.**
## Matrix per data type
### Meeting point
| Verb | Alice (= Host) | I (other registrant) | D (parent declarer) | U (plain user) |
|---|---|---|---|---|
| create | ✓ (becomes host) | — | ✗ | ✓ (becomes host) |
| read | ✓ | ✓ | ✓ | ✓ |
| subscribe | ✓ | ✓ | ✓ | ✓ |
| update | ✓ | ✗ | ✗ | ✗ |
| delete | ✓ | ✗ | ✗ | ✗ |
Notes: no `C` differentiation (connections are a UI display filter, not a right, since everything is public). `D` has no special right over the meeting points grafted onto their event.
### Registration to a meeting point
`Inscription` links a user and a meeting point. **Personal data** (registrant + their connections). Composite act (a)+(b) above.
| Verb | Alice (registrant) | C (connection) | H (host) | I (other registrant) | U |
|---|---|---|---|---|---|
| create (composite act) | ✓ | — | ✗ | ✗ | ✓ (becomes registrant) |
| read the content | ✓ | ✓ | cond: ✓ if H ∈ connections(Alice); opaque link otherwise | cond: ✓ if I ∈ connections(Alice) | ✗ |
| subscribe | ✓ | ✓ | cond (same) | cond (same) | ✗ |
| read the meeting point's inbox (raw entries) | — | — | ✓ | ✗ | ✗ |
| update | ? **to be decided** (depends on the fields) | ✗ | ✗ | ✗ | ✗ |
| delete | ✓ (unregister; remove the link from the inbox if possible) | ✗ | cond: inbox moderation only (does not delete the object) | ✗ | ✗ |
**Host visibility: resolved** (identified if a connection, anonymous otherwise). **Open questions:** which fields of a registration are editable (a bare boolean, or + comment/status/companions?); **inbox-side deletion** — can a depositor withdraw their link from a document they do not control?
### Event
| Verb | Alice (= D) | H (host of a grafted meeting point) | U |
|---|---|---|---|
| create | ✓ (becomes declarer) | — | ✓ (becomes declarer) |
| read / subscribe | ✓ | ✓ | ✓ |
| update | ? **to be decided** | ? **to be decided** | ? **to be decided** |
| delete | ? **to be decided** | ✗ | ✗ |
**Open questions:** who may **update** a declared event — the declarer alone (owner)? every user (wiki)? nobody (immutable)? Central to deduplication (concept `functional-domain`, [[brief_2026-06-15_event-deduplication]]). Who may **delete** it, and what becomes of the grafted meeting points (orphaned/cascade/marked deleted)?
### User profile
**Nothing in the profile is public.** Two scopes: the **network profile** (Alice + connections: name, avatar, bio, city, interests); the **private profile** (Alice alone: settings, email, preferences).
| Verb | Alice | C | U |
|---|---|---|---|
| create | ✓ (at sign-up) | — | — |
| read — network | ✓ | ✓ | ✗ |
| read — private | ✓ | ✗ | ✗ |
| subscribe | ✓ | ✓ (network) | ✗ |
| update | ✓ | ✗ | ✗ |
| delete (account) | ✓ | ✗ | ✗ |
**Tension to resolve:** a meeting point is readable by everyone, yet its host should not be identifiable by a plain user. Three positions: (i) **pseudonym through identity alone** (name/avatar resolved only for connections); (ii) **identity denormalized into the offer** (the host picks a "business card" per meeting point, living inside the meeting point object, profile closed); (iii) **host anonymity** (identity revealed only to connections). To be decided. Others: field-by-field composition of each scope; status of the `username` (public/network/dropped?).
### Connection (friendship link)
Bilateral. `DemandeDeConnexion` (one-sided, pending) → `Connexion` (bilateral, upon acceptance; opens access to personal data). Alice's connection list is **personal** (Alice + her connections).
| Verb | Alice (initiator) | Bob (other side) | C | U |
|---|---|---|---|---|
| create the request | ✓ | — | — | — |
| accept | — | ✓ | — | ✗ |
| read Alice's list | ✓ | ✓ | ✓ | ✗ |
| subscribe | ✓ | ✓ | ✓ | ✗ |
| delete (break A↔B) | ✓ | ✓ | ✗ | ✗ |
**Open questions:** granularity on Bob's side (does he see Alice's whole list, or only A↔B? — the principle implies: the whole list); "friends of friends" discoverability (does Alice see Bob↔Carole? — no, unless Carole ∈ connections(Alice)).
## Derived scopes
Heuristic: same scope if (a) same write-authorization cell *and* (b) accessed together. Three **scopes** emerge, plus the bilateral case:
| Scope | Write | Read | Data |
|---|---|---|---|
| **public** | Alice alone | Everyone | Meeting points hosted by Alice; declared events *(subject to the write model)* |
| **protected** (network) | Alice alone | Alice + connections | Network profile; participations; connection index |
| **private** | Alice alone | Alice alone | Private profile (settings, email, preferences) |
| **dialog** (A↔B) | Alice and Bob | Alice and Bob | The bilateral `Connexion` (+ groundwork for future messaging) |
The bilateral **`Connexion`** has *two* writers → a **dialog** scope dedicated to the pair; the **"all of Alice's connections" index** lives in *protected* (it lists the connection references). The **meeting point's inbox** is an attribute of the public document, not a separate scope.
## Query inventory per screen
*To be filled in once the matrix has stabilized.* Planned schema: `| Screen | One-shot reads | Subscriptions | Writes | Triggering actor |`. Screens to analyze: see the route table (concept `app-architecture`).
## See Also
- Concept `functional-domain` → [[knowledge_data-scopes-and-discovery]] — entity → scope placement + discovery
- [[knowledge_trust-model]] — isolation is enforced by the SDK
- `README.md §Modèle fonctionnel` — source of the actors
@@ -0,0 +1,21 @@
---
type: caveat
summary: The shared wallet password is captured at the EVALUATION of src/modules/auth/sharedWallet.ts; now that the shared wallet is the only mode, a value missing at that instant no longer yields a degraded form but a configuration error screen WITHOUT any identifier field — every entry point that renders AccessGateScreen must set the global BEFORE the module is first imported
last_checked: 2026-07-27
---
# Pitfall: set the shared-wallet global BEFORE importing the barrier
**The invariant.** `src/modules/auth/sharedWallet.ts` reads `globalThis.__FESTIPOD_SHARED_WALLET_PASSWORD__` **exactly once, at module evaluation** (the `SHARED_WALLET_PASSWORD` constant, surfaced by `hasSharedWallet()`). A value set *after* that first import is never re-read.
**Why it became blocking.** As long as "no shared wallet" was a fallback mode, a missing global degraded into a still-usable form — evaluation order was cosmetic. Since [[decision_2026-07-20_shared-wallet-only-mode]], `hasSharedWallet() === false` is a **configuration error**: `AccessGateScreen` renders an error block **with no identifier field**. The barrier becomes a dead end, not a degraded login.
## Impact — if I touch X, Y breaks
- **Static import = trap.** A static `import` of `AccessGateScreen` (or of any module that transitively reaches `sharedWallet.ts`) from an entry point that sets the global itself is **hoisted above the assignment** → empty password → error screen, with no JS error to signal it. The remedy is a **dynamic import** (`await import(...)`) executed after setting the global.
- **Entry points concerned today**: the frontend served from `src/` (`src/app/frontend.tsx` fetches `/festipod-config.json`, sets the global, then imports the app dynamically — mechanics detailed in tech-stack → [[knowledge_build-pipeline]]) and the `@ui` harness that renders the barrier (`src/modules/auth/steps/ui/barriere-acces.steps.ts`, same set-then-lazy-import sequence). A bundle produced by `build.ts` is **not** concerned: there the value is inlined by `define`.
- **Operations**: a server without `FESTIPOD_SHARED_WALLET_PASSWORD` serves **no** working barrier at all — by design (fail loudly). Treat it as a configuration outage, not as a screen bug.
**Verified (2026-07-27)**: capture at evaluation time in `sharedWallet.ts`, and the `!hasSharedWallet()` guard as the first branch of `AccessGateScreen`.
> Caveat: the header of `sharedWallet.ts` still describes the old fallback ("the gate falls back to the plain flow") — an obsolete comment; what `AccessGateScreen` actually renders is authoritative.
@@ -0,0 +1,41 @@
---
type: caveat
summary: Any cap-less reference to a person's protected document exposes the `:v:` of their store — a STABLE AND PERMANENT pseudonym, identical everywhere and forever. It does not say who, but a single cross-reference RETROACTIVELY de-anonymizes all of their past and future references. It is the very same bit of information that makes anonymous dedup possible. No known rotation.
last_checked: 2026-07-27
---
# Pitfall: the `:v:` of a cap-less reference is a permanent pseudonym
**Read this before designing anything that circulates cap-less references** (registrations, invitations, mentions, indexes, notifications).
## The fact
A NURI is written `did:ng:o:{document}:v:{overlay}`. The `:v:` segment does **not** come from the document but from **its store** — and a person has **exactly one** *protected* store. Therefore:
> **All** cap-less references to **any** of a person's protected documents carry the **same** `:v:`. Everywhere, and forever.
VERIFIED in `nextgraph-rs` (the details and the pointers live on the polyfill side, `docs/readcap-and-nuri-model.md`): the value injected when a document is created is the overlay of the containing store; a `Repo` carries no overlay of its own, and every block access of a `Store` goes through **its** `overlay_id` — a per-document overlay is therefore structurally impossible, not merely absent.
## Why this is a pitfall and not just a limitation
This `:v:` **does not say who** — it is a non-invertible `BLAKE3` of the store id. The temptation is therefore to treat it as opaque, hence harmless. It is not: it is a **constant handle**.
- **Correlation** — anyone collecting cap-less references can link together all those belonging to one and the same person, without ever identifying them. Recurring presence, memberships, rhythm.
- **Retroactive de-anonymization** — this is the real danger. **One single** cross-reference, **one single time** (a person naming themselves, a channel that leaks, a match against outside data), is enough for `:v:X` to become attached to an identity. At that instant, **all** of the history tied to that `:v:` flips at once — including what was published years earlier in the belief that it was anonymous.
- **No way out** — VERIFIED, along four axes: no overlay rotation (the outer one is a pure hash of the store id, with no secret); the store id is generated once at identity creation and never regenerated; there is no migration path for content towards a new store; and no form of reference allows locating a document without exposing its store's overlay. Renewing capabilities would only change the *inner* overlay — the outer one, the only one present in cap-less NURIs, would survive it. **The only way out is to abandon the entire identity**, which carries none of the content along. Reported upstream as a possible design flaw (`orm-tests/INBOX/2026-07-27-outer-overlay-permanent-pseudonym-no-rotation.md`, see [[rule_nextgraph-inbox]]).
## The coupling you must not hope to break
That very same `:v:` is what makes it possible to **deduplicate without reading** — two references sharing a `:v:` come from the same person, and that is the basis of the anonymous participant counter ([[brief_2026-07-20_attendance-set-model]] on the `data-layer` side).
**It is the same bit of information.** Anonymous dedup and untraceability are not two requirements to be reconciled: they are two readings of one and the same piece of data. You cannot obtain one by removing the other. The only real dial is **how the stores are carved up** — which shifts the trade-off without making it disappear.
And this is **not** an artifact of the polyfill: the property survives into real NextGraph.
## What to do about it
- **Never present an action to the user** as "anonymous" without a caveat if it circulates a cap-less reference. It is **pseudonymous**, and the pseudonym is permanent.
- **Count** the occurrences of a `:v:` that you expose: every additional context in which it appears widens the cross-referencing surface.
- **Recheck** this caveat if NextGraph introduces overlay rotation or an indirect form of reference — it would then become moot, which would be good news.
Links: [[knowledge_trust-model]], [[brief_2026-05-18_authorization-matrix]], data-layer ([[brief_2026-07-20_attendance-set-model]], [[rule_capture-nextgraph-findings]], [[rule_nextgraph-inbox]]).
@@ -0,0 +1,29 @@
---
type: decision
summary: The identifier of the virtual space is entered at the access barrier (AccessGateScreen), in the same act that opens the wallet; the separate "perceived login" screen (ConnexionScreen, « choisissez un nom d'utilisateur ») is removed; the identifier is a lowercase-normalized technical id, not a Festipod username
---
# Decision (2026-07-06): identifier entered at the access barrier
## Context
The earlier stopgap flow (decision of 2026-06-15, a note that disappeared along with the `nextgraph-platform` concept — see `git log`) chained **two screens**: (1) `AccessGateScreen`, the access barrier (the real NextGraph login, opening the shared wallet); (2) `ConnexionScreen`, a "perceived login" where the user picked a **username**. That application-level identity was in fact the key of the **virtual wallet** (shim account / cap owner key), not a product username — so the "username" framing was misleading (confusing `setUsername` logic).
## Decision
The user enters their **identifier** directly in `AccessGateScreen`, **in the same act** that opens the wallet (« Entrer » records the identifier, then triggers `connect()`). `ConnexionScreen` is **deleted**. The identifier:
- is a **technical id** that names the virtual space (a nickname in practice, **not** a Festipod username);
- is **normalized** on entry (trimmed, `@` stripped, **lowercased**) and persisted before the broker redirect (so it survives the round-trip);
- **is** the identity id handed to the SDK (`setCurrentUser`), and the key for the caps and the shim account — no more mixed-case handle to reconcile.
`AuthGate` therefore shows the barrier as long as the wallet is not open **or** the identifier is not set, then the app directly — with no intermediate screen.
## Rejected alternatives
- **Keeping both screens**: the second, "username" screen perpetuated the confusion between product identity and wallet identifier, and added a step with no value.
- **Deriving the identifier from the wallet** (no entry at all): impossible here — there is a single shared wallet; the identifier is precisely what distinguishes the virtual spaces inside that wallet (emulation, see concept `data-layer` and the `@ng-eventually/client` SDK).
## Scope
Supersedes the "screen 2 / perceived login" part of the 2026-06-15 stopgap flow (opening the shared wallet through the broker is unchanged). Current state of the flow: [[knowledge_authentication]].
@@ -0,0 +1,32 @@
---
type: decision
summary: The shared wallet is the ONLY operating mode (the @ng-eventually/client polyfill relies on it as its data backend); the "no shared wallet" fallback is removed — misconfiguration → a blunt error screen, no more bare form. Reaffirms that the barrier's identifier = the wallet/space id, distinct from the profile username.
---
# Decision (2026-07-20) — the shared wallet is the only mode; identifier ≠ profile username
## Context
Observed regression: on opening, the app landed on a **bare form asking for an identifier**, without the wallet-loading assistance. Cause: `FESTIPOD_SHARED_WALLET_PASSWORD` undefined in the server environment → `hasSharedWallet()` false → `AccessGateScreen` switched to its fallback mode. But that mode is a **dead end**: a device with no wallet cannot connect once the import assistance is hidden. In parallel, the old notion of "username" was still lingering to designate the **wallet identity**, which conflated it with the real profile username.
## Decision
1. **The shared wallet is the only supported mode.** Festipod does not work without it — the `@ng-eventually/client` polyfill uses it as its data backend (see [[knowledge_authentication]], `rule_app-uses-sdk-surface-only`). `hasSharedWallet() === false` is therefore **not a functional mode**: it is a **misconfiguration**`AccessGateScreen` displays a **blunt error screen** (« Portefeuille partagé non configuré, définir `FESTIPOD_SHARED_WALLET_PASSWORD` »), never the dead-end bare form.
2. **The barrier's identifier ≠ the profile username.** The identifier entered in `AccessGateScreen` is the **technical id of the wallet/space** (lowercase-normalized, carried by the `?id=` URL param), not a username. The **username** is a distinct concept living in `UserProfile` (`@handle`, predicate `http://festipod.org/username`). Code and tests must no longer label the wallet identity "username/user" (renamed to `identifier`). Reaffirms and extends [[decision_2026-07-06_identifier-at-access-barrier]].
## Consequences
- `AccessGateScreen`: three-branch rendering (config error / assisted import flow when not connected / identifier field alone when already connected).
- `username → identifier` rename of the wallet identity across the test infrastructure (`freshScenarioIdentifier`, `freshIdentifier`), `registration.ts`, `ngSession`, plus comments; **`UserProfile.username` untouched** (profile, seed, display, SHEX).
- `.env.example` added at the root to make the configuration explicit (including `FESTIPOD_SHARED_WALLET_PASSWORD`, `FESTIPOD_SHARED_WALLET_FILE`).
## Rejected alternative
Keeping the wallet-less fallback as a future "own-wallet flow": rejected **for now** — no own-wallet flow in the near term, and the silent fallback created a misleading dead end. To be reintroduced **explicitly** the day an own-wallet mode (each user with their own NextGraph wallet) exists, outside the stopgap.
## Links
- Shared-wallet stopgap: `decision_2026-06-15_shared-wallet-login-flow` (referenced by `AccessGateScreen`/`AccountContext`).
- [[decision_2026-07-06_identifier-at-access-barrier]] — the identifier at the barrier.
- [[knowledge_authentication]], [[knowledge_trust-model]].
@@ -0,0 +1,24 @@
---
type: knowledge
summary: A user's identity = their NextGraph wallet; every user is authenticated (no anonymous access); auth is delegated to the SDK, the app has no application-level accounts or passwords
---
# Authentication
**A user's identity = their NextGraph wallet.** There is **no anonymous access** to the app: every user is authenticated (see concept `functional-domain`). There is **no application-level account/password system** — authentication is **delegated to the data SDK** (`@ng-eventually/client`): opening your session means opening your wallet.
## Flow
- The **access barrier** (`AccessGateScreen`, rendered by `src/app/AuthGate.tsx`) is the real NextGraph login: it opens the shared wallet through the broker redirect. **In the same act**, the user enters an **identifier** that names their virtual space (`onEnter`). There is **no separate "perceived login" screen any more** (the former `ConnexionScreen`, « choisissez un nom d'utilisateur », has been removed — see [[decision_2026-07-06_identifier-at-access-barrier]]; supersedes the two-screen flow of the 2026-06-15 stopgap).
- **The shared wallet is the ONLY supported mode**: `AccessGateScreen` has **three branches** — (1) *configuration error* if no shared wallet is configured (no more dead-end bare form), (2) the **assisted import** flow as long as the session is not connected, (3) the **identifier field alone** once connected. See [[decision_2026-07-20_shared-wallet-only-mode]], and the evaluation-order pitfall [[caveat_shared-wallet-global-before-gate-import]] (the password global must be set before the screen is first imported, otherwise you land on branch 1).
- **Vocabulary in the code**: the wallet identity is called `identifier` everywhere (`registration.ts`, `ngSession`, hooks and test steps) — **never** `username`, which exclusively designates the profile handle `UserProfile.username`. Do not relabel one as the other: they are two distinct identity spaces.
- This **identifier is a technical id** (a nickname in practice, **not** a Festipod username): it is **normalized** (trimmed, `@` stripped, **lowercased**) then persisted (`AccountContext``IdentityStore`), so a reload — or another device reopening the same shared wallet — lands back on the same space. It is this id that is handed to the SDK (`setCurrentUser`) and on which the caps and the shim account are keyed.
- **Carried across the boundary by a URL PARAM `?id=`** (source of truth), NOT by localStorage. The app runs in two contexts — **top-level** (`127.0.0.1:3000` directly, `window.self === window.top`, where the barrier is displayed) and **iframe** (embedded under `nextgraph.net` after the broker round-trip, `window.self !== window.top`). The browser **partitions storage by top-level site**: the top-level's localStorage and the iframe's are **two distinct partitions** → localStorage CANNOT carry the identity from one context to the other (observed symptom: two diverging values depending on the context). The SDK redirects via `location.href = broker + encodeURIComponent(window.location.href)` (embedding the full app URL, query string included, into the `o=` that is reloaded in the iframe), so a **URL param does cross over**. `AuthGate` writes `?id=<identifier>` (`history.replaceState`) **before** `connect()`; `AccountContext` resolves the identifier by priority: **(1) `?id=` from the URL** then **(2) localStorage** (prefill/convenience within the same partition only). localStorage key: `festipod.account.identifier`.
- **Entered ONLY ONCE on first access + prefilled on return.** On a top-level reload the NG session is not restored automatically (`NextGraphContext` starts back at `disconnected`): `AuthGate` shows the barrier again as long as `status !== 'connected'`, but the `AccessGateScreen` field is **prefilled** (`initialIdentifier` prop) — never a bare, empty field. Regressions guarded by `src/modules/auth/features/{barriere-acces-identifiant,identifiant-resolution}.feature` (@ui) — all the more useful because the barrier flow is **disabled** in the @e2e tests (`__FESTIPOD_ACCESS_GATE_DISABLED__`), and therefore invisible at that layer.
- Once the session is open, the current user and their access to the per-scope stores are provided by `NextGraphContext`.
## The test wallet
The `@data`/`@e2e` tests open a real wallet (`festipod-tests`, persistent profile) — see concept `bdd-testing`. These are **plaintext test credentials**, with no security stake, dedicated to staging.
> The authorization model that will build on this identity (bilateral connections, personal data = network, host anonymity) is incubating: [[brief_2026-05-18_authorization-matrix]].
@@ -0,0 +1,21 @@
---
type: knowledge
summary: Isolation between scopes (public/protected/private) is enforced by the data SDK; the app trusts it and only displays what it returns — no access control in the screens, all privacy rests on the SDK
last_checked: 2026-07-06
---
# Trust model
**Stance:** the app reads data through the ORM subscriptions of the `@ng-eventually/client` SDK and displays it **with no app-side authorization logic** (`src/shared/context/FestipodDataContext.tsx`, `useNgData`).
Principles:
1. **Isolation is delegated to the SDK.** Every entity lives in the store of its **scope** (public / protected / private, see concept `functional-domain` → [[knowledge_data-scopes-and-discovery]]); the SDK **exposes to the current user only what they are entitled to**. The app assumes that whatever it receives is already authorized — privacy rests on the SDK, not on Festipod code.
2. **Screens carry no access rules.** No "is this user allowed to see this data" check in the components, nor in the data context. The public / network / private separation is a property of **placement by scope**, not of an application-level filter.
3. **The relationship between users ("connections") is an application-level notion, not an SDK primitive.** NextGraph has no bilateral connection/friendship primitive; on the SDK side there is only a **directed read grant** towards an identity. The app therefore **owns** its relationship graph (`src/shared/utils/connections.ts`) and **translates** it into per-document directed grants handed to the SDK — it does not delegate the notion of a relationship to the SDK, only the **enforcement** of the isolation that follows from it. What the app declares to the SDK stays minimal: **its identity** (the identifier, see [[knowledge_authentication]]) and **those grants**; it still carries no access logic in the screens.
## The point to watch
Because the app **displays everything it receives**, privacy rests entirely on the SDK exposing only what is legitimate. It is a deliberate choice (the app stays thin), but it means **never reintroducing on the screen side a piece of data that the scope should not have let through**.
> To check when in doubt: `useNgData` in `FestipodDataContext.tsx` contains no identity-filtering branch — that is intentional, isolation comes from below.
@@ -0,0 +1,37 @@
---
type: _overview
summary: BDD Cucumber/Gherkin in French across 3 layers (@ui, @data, @e2e) — setup, layer contract (what to test where), real broker harness, and the source-grep leftovers pitfall
triggers:
keywords: [cucumber, gherkin, bdd, feature, scenario, scénario, step, steps, "@ui", "@data", "@e2e", playwright, broker, harness, wallet, world, hooks, renderHelper, multibrowser, multi-navigateur, "@multibrowser", "@private-wallet", "@shared-wallet", storageState, "@wip"]
paths: ["src/modules/*/features/**", "src/modules/*/steps/**", "src/shared/steps/**", "src/shared/support/**", "src/shared/test-harness/**", "cucumber.json"]
---
# BDD testing
BDD tests written in **Cucumber/Gherkin in French** (`Etant donné`, `Quand`, `Alors`) across **3 layers** of increasing cost.
**Read before writing a test:** [[rule_test-layer-contracts]] — each layer answers a distinct question; mixing them produces brittle tests. That is the rule which decides *where* an assertion belongs.
## The 3 layers
```
/\ @e2e real app inside the broker iframe — critical journeys
/ \
/----\ @data mutations & persistence through the real NextGraph broker
/------\
/ @ui \ in-process screen rendering (happy-dom + seed) — the bulk of the volume
/__________\
```
## Links
- [[rule_test-layer-contracts]] — what to test at each layer (the contract)
- [[knowledge_cucumber-setup]] — config, layout, scripts, auto-generated files
- [[knowledge_ui-layer]] — the `@ui` layer: render helper, fixtures, good and bad patterns
- [[knowledge_data-layer-broker]] — the `@data` layer: broker harness, wallet lifecycle, bridge
- [[knowledge_e2e-layer]] — the `@e2e` layer: the real app inside the iframe
- [[knowledge_multibrowser-harness]] — several isolated browsers × wallet model (private/shared), storageState injection
- [[caveat_reconnexion-froide-local-vs-broker]] — a "fresh page" is not a cold start: which setup proves broker durability, and which one just re-reads local
- [[decision_2026-03-12_headless-wallet-creation]] — why the test wallet is created through a headless UI
- [[caveat_source-grep-vestiges]] — leftovers from the "source analysis" era in `world.ts`
- [[cookbook_add-scenario]] — adding a scenario/step (layers, `evaluate` serialization pitfall, `@wip`)
@@ -0,0 +1,54 @@
---
type: caveat
summary: A "fresh page" opened via ctx.newPage() on the PERSISTENT Chromium context NEVER proves broker durability — it re-reads the local IndexedDB of the very same profile. Only a non-persistent context spawned from freshBrowser, seeded solely by the storageState captured at BeforeAll, settles broker-vs-local.
last_checked: 2026-07-27
---
# Pitfall: a "fresh page" is not a cold start (local vs broker)
**Reconnection** scenarios all ask the same question — *does the user get their own data back after closing and reopening?* — but **depending on the browser context chosen, they do not answer the same question**. That is the pitfall: the most natural setup (`ctx.newPage()`) yields a green that proves nothing about the broker.
## The two setups, and what each one proves
| Setup | Where | What it proves | What it does NOT prove |
|---|---|---|---|
| `this.page!.context().newPage()` — fresh page on the **persistent** context (`.playwright-profile`) | `reconnexion.steps.ts` (@data), `reconnexion-persistance.steps.ts` (@e2e) | a new broker login → **fresh verifier session** (empty memory), full remount of the providers | nothing about **broker durability**: the profile **still holds the local repos** in IndexedDB, so a "fresh" reader may well reopen **from local** |
| `spawnContext('shared')`**non-persistent** context spawned from `freshBrowser` | `reconnexion-froide-sans-local.steps.ts` (@data) | that the data **reached the broker** (or did not) | nothing about the real UI journey (this is the harness, not the app) |
**Invariant.** Any assertion of the form "the write is durable broker-side" **requires** the second setup. Making that assertion on a fresh page of the persistent context produces a false green (or a red blamed on the broker when it is really local/timing).
## What makes the "no-local" verdict valid (do not break it)
Three conditions, all met in `reconnexion-froide-sans-local.steps.ts`:
1. **Separate process**`freshBrowser` is a non-persistent `chromium.launch`, distinct from the profile carrying the wallet (see [[knowledge_multibrowser-harness]] for the isolation proven all the way to the broker origin).
2. **Hermetic partition** — every Playwright `newContext()` has its own storage; no IndexedDB shared with the writing page.
3. **The only pre-injected state is `pool.sharedWalletState`**, captured **once at `BeforeAll`**, hence **before** the scenario writes anything → the snapshot **cannot** contain the data under test.
> **Impact if you touch the storageState capture** (`hooks.ts` `BeforeAll` → `pool.sharedWalletState`): moving it later, re-capturing it per scenario, or adding a warm-up that writes data **silently invalidates** the verdict of every "cold, no local" scenario — they would turn green by re-reading the snapshot. The step **fails outright** when `sharedWalletState` is missing (by design: no verdict beats a false verdict).
## Reconnection is not isolation — the identifier decides
`isolation.steps.ts` and `reconnexion.steps.ts` set up **the same machinery** (fresh page plus an identifier injected into `localStorage['festipod.account.identifier']` via `addInitScript`, before any script, on every origin). Only one thing tells them apart:
- **reconnection**: `this.freshIdentifier` is re-injected — **the SAME identity** as the writing page.
- **isolation**: a **new** identifier is minted → a distinct identity B.
Changing that identifier therefore silently turns a reconnection test into an isolation test (and the other way round). `this.freshIdentifier` is set by the `Before` hook in `hooks.ts` for **every** single-browser `@data`/`@e2e` scenario.
## Reads stay reactive, even when "waiting a long time"
The reconnection `Then` steps read the **reactive** state (`homeEventTitles` on the bridge, via `waitForFunction`) — never a broker re-read loop ([[rule_no-broker-polling]]). The long diagnostic step (« … en laissant jusqu'à 60 secondes à la barrière avec rechargements ») does loop, but over the **reactive state already pushed** plus **full page reloads** (each reload = new mount = new sync-barrier attempt): that is the pragmatic fallback the rule explicitly allows, not broker polling. The distinction to keep in mind — *observing the reactive state* versus *re-issuing a broker read*.
## Current state of the scenarios
`reconnexion-froide-sans-local.feature`, the `@reconnexion-pause` scenario of `reconnexion-meme-identite.feature` and `reconnexion-persistance-e2e.feature` are **`@wip`**: they are **diagnostic instruments** (they print a verdict to stdout / as a Cucumber attachment), not regression guards. `@wip` is excluded from the default run (`cucumber.json`) — run them explicitly with `--tags`. The **non-`@wip`** scenario of `reconnexion-meme-identite.feature`, on the other hand, is a genuine guard and must stay green.
> The *why* on the NextGraph side (what a write must clear to be durable, socket behaviour, repo reopening) belongs to the `@ng-eventually/client` SDK — not to this repo. Here we only describe **the test setup that produces a readable verdict**.
## Links
- [[knowledge_data-layer-broker]] — the single-browser `@data` layer (persistent profile).
- [[knowledge_multibrowser-harness]] — `freshBrowser`, `spawnContext`, `pool.sharedWalletState`.
- [[knowledge_e2e-layer]] — the `@e2e` counterpart (real app) of the "close and reopen" setup.
- [[rule_no-broker-polling]] — the red line waiting steps must not cross.
@@ -0,0 +1,21 @@
---
type: caveat
summary: world.ts still carries leftovers from the "source analysis" era (screenFileMap, screenFieldDetectors, screenExpectedContent, screenRequiredFields; hasText/hasField/hasElement with a source fallback) — to be deleted once the @ui migration to the rendered DOM is complete
last_checked: 2026-06-15
---
# Caveat: source-analysis leftovers in `world.ts`
The `@ui` suite **predates** the layer contract ([[rule_test-layer-contracts]]). Remnants of the "grep the source code" era are still around and **must not be extended**:
- `world.ts:screenFileMap`, `screenFieldDetectors`, `screenExpectedContent`, `screenRequiredFields` — mappings from the source-analysis approach.
- `hasText` / `hasField` / `hasElement` — they now **prefer the rendered DOM** but **fall back to the source** so that unmigrated steps keep working during the transition.
## Migration plan (in progress)
1. Rewrite grep-the-source assertions as DOM queries through the render helper.
2. Delete tests that assert implementation details (`/showDuplicateWarning/`, `/importableEvents/`, regexes over JSX).
3. Move behavioural assertions to `@e2e` where they are not already covered.
4. Drop the `@e2e` content checks that duplicate `@ui`.
Once the migration is done, the 4 leftover maps can go away in favour of assertions on the rendered DOM plus seed data. **As long as they exist, do not rely on them for new tests.**
@@ -0,0 +1,21 @@
---
type: caveat
summary: The shared test wallet (.playwright-profile) accumulates data on every run; past a threshold, sparql_query calls anchored to the private store hang (>15s) and the whole @data suite fails during setup — starting from a fresh profile restores ~1s reads
last_checked: 2026-07-06
---
# Pitfall: the test wallet bloats and makes @data reads hang
The persistent Chromium profile `.playwright-profile` (at the root of the working tree) carries the **shared wallet** opened by the whole `@data`/`@e2e` suite. That wallet **accumulates data on every run**: shim accounts (one per scenario, through the fresh identifier `freshScenarioIdentifier`), seeded entity docs, historical inbox deposits… The private store is the **anchor point of the shim** (account resolution) and is queried by **every** read and write (`resolveAccount`, `listMyEntityDocs`, …).
**Symptom.** Past a certain volume (observed around 99 MB of profile), a `sparql_query` **anchored to the private store** stops returning within 15 s — it hangs. Since account resolution sits on the path of **every** read/write, **the entire @data suite fails during setup** (0 events loaded, timeouts), with no explicit error. Verified diagnosis: on a fresh wallet the same query comes back in **~1.5 s** and the seed completes normally.
**Workaround.** Move the bloated profile aside and let the auth hook (beforeAll) recreate a fresh one:
```bash
mv .playwright-profile /tmp/festipod-bloated-$(date +%s)
```
The per-scenario fresh identifier (`freshScenarioIdentifier`) bounds the account *registry* but **not** the physical growth of the shared private store — hence the recurrence. Durable hygiene (periodic purge / throwaway wallet per run) still has to be put in place; until then, if the `resolveAccount failed` errors and timeouts come back, start again from a fresh profile.
> The *why* on the broker side (how an anchored query reaches the private store repo) belongs to the `@ng-eventually/client` SDK, not here — this caveat only describes the consequence on the test side.
@@ -0,0 +1,29 @@
---
type: cookbook
summary: How to add a BDD scenario/step — a tagged French .feature, steps per layer, the appFrame.evaluate serialization pitfall (pass arguments, no closures), add helpers to BOTH harnesses, @wip tag for what is not implemented yet
---
# Cookbook: adding a scenario / a step
1. **Write the `.feature`**: `src/modules/{module}/features/us-N-slug.feature`, `# language: fr`, a header tag `@CATEGORIE @priority-N`, and one layer tag per scenario (`@ui` / `@data` / `@e2e`). French keywords: `Fonctionnalité`, `Contexte` (Background), `Scénario`, `Étant donné`/`Quand`/`Alors`. Tag `@wip` any scenario whose steps are not written yet.
2. **Pick the layer** (see [[rule_test-layer-contracts]]): rendering assertion → `@ui`; mutation/persistence → `@data`; full journey → `@e2e`.
3. **Write the steps** in `src/modules/{module}/steps/{ui,data,e2e}/*.steps.ts` (or `src/shared/steps/ui/` if cross-domain). Signature: `async function (this: FestipodWorld, …)`. Import `FestipodWorld` from `../../../../shared/support/world` (adjust the relative path).
4. **Data access, per layer**:
- `@ui`: `this.renderedDoc` / `this.getDomText()` / `this.hasText(...)` after `navigateTo(...)` (see [[knowledge_ui-layer]]).
- `@data`/`@e2e`: `await this.appFrame!.evaluate(fn, ...args)` on the `window.__testData` bridge (see [[knowledge_data-layer-broker]]).
5. **⚠️ `appFrame.evaluate` serialization pitfall**: the function you pass runs **inside the iframe**, and the step's variables **are not captured** (closures are lost). **Pass every value as an argument**:
```ts
// ❌ const title = eventTitle; await appFrame.evaluate(() => td.getEventByTitle(title)) // title is undefined
// ✅ await appFrame.evaluate((t) => td.getEventByTitle(t), eventTitle)
```
Always `await` (forgetting it means asserting before the promise resolves).
6. **If you add a data operation**: expose the helper on `window.__testData` in **both** harnesses (`src/shared/test-harness/harness.tsx` AND `harness-ng.tsx`) — otherwise the mock fallback drifts away from the real broker.
7. **Wire up a screen under test**: if the French screen name does not resolve to its `id`, add an alias in `screenNameMap` (`src/shared/steps/ui/navigation.steps.ts`).
8. **Run**: `bun run test:cucumber` (everything) or `bun run test:data` (@data). Report: `reports/cucumber-report.html`. `@data`/`@e2e` require the test wallet (`bun run test:auth-setup` on the first go if needed, otherwise it is created automatically — see [[decision_2026-03-12_headless-wallet-creation]]).
@@ -0,0 +1,37 @@
---
type: decision
summary: Decision 2026-03-12 — create the test wallet by automating the broker UI headlessly (Playwright) rather than through the NG API, because it exercises the real auth flow and avoids reverse-engineering the sign-up API
---
# Automated Headless Wallet Creation for CI
**Date:** 2026-03-12 15:00
**Status:** Accepted
## Context
`@data` tests require a NextGraph wallet inside a persistent Chromium profile. Previously, the first run required manual interaction (visible browser, wallet created by hand) → CI was blocked.
## Options Considered
### Option A: create the wallet programmatically through the NG SDK
Call `ng.wallet_create()` from Node/Bun, without any UI.
- **Pros**: faster, no browser needed.
- **Cons**: `@ng-org/web` is browser-only (WASM + postMessage); we would have to reverse-engineer the sign-up API of `account.nextgraph.eu`; it does not exercise the real auth flow.
### Option B: automate the UI flow headlessly
Drive the very same wallet-creation UI with Playwright, in headless mode.
- **Pros**: exercises the real auth/login flow end to end; no reverse-engineering; the same persistent profile is reused; CI-ready with no manual step.
- **Cons**: depends on `nextgraph.eu`/`account.nextgraph.eu` being reachable; brittle to NextGraph UI changes; adds ~27s to the first run.
## Decision
**Option B** — automate the broker UI. The creation flow (navigate → Create Wallet → ToS → username/password → submit) is itself a legitimate test of the auth feature. Depending on external services is acceptable since the tests already depend on the broker being reachable.
## Consequences
**Positive:** fully CI-ready tests (zero interaction); the auth flow gets tested along the way; `bun run test:data` starts from a clean state.
**Negative:** requires internet access (nextgraph.eu, account.nextgraph.eu); brittle to NextGraph UI changes (button texts, form IDs).
**Risk:** rate-limiting from `account.nextgraph.eu` if CI recreates wallets often.
> Detailed lifecycle mechanics: [[knowledge_data-layer-broker]].
@@ -0,0 +1,46 @@
---
type: knowledge
summary: Cucumber config (cucumber.json, fr language, tsx loader), layout of features/steps colocated per module, shared steps under shared/steps/, and the scripts that generate features.ts/testResults.ts/stepDefinitions.ts
---
# Cucumber setup
26 `.feature` files (US-1 to US-26), all in **French**, tagged `@CATEGORIE @priority-N` (categories EVENT, WORKSHOP, USER, MEETING, NOTIF).
## Layout
Features and steps are **colocated with their module**:
```
src/modules/event/features/us-13-creer-evenement.feature
src/modules/event/steps/{ui,data,e2e}/
```
**Shared** (cross-domain) steps live in `src/shared/steps/ui/`:
- `navigation.steps.ts` — navigation, auth, clicks/selections, section/button/field assertions
- `form.steps.ts` — field validation, required fields, import/duplicate
- `screen.steps.ts` — screen content (participants, events, profiles, QR)
The French screen names (`"accueil"`, `"détail événement"`, `"mon profil"`…) map to screen IDs through `screenNameMap`.
Scenario tags: `@ui` / `@data` / `@e2e` (layer) plus **`@wip`** for a scenario whose steps are not implemented yet **or whose application behaviour is not reliable yet** (intended use: flagging a genuine expectation that fails because of a product bug, not marking an obsolete test — historical example: sign-up cancellation not being reflected in the UI, `@wip` **lifted** once it was fixed in T02.c, see [[caveat_participation-deletion]]). **`@wip` is EXCLUDED from the default run** (`cucumber.json: "tags": "not @wip"`): those scenarios document an expectation without breaking the suite; drop the `@wip` once they are reliable. A common `Contexte` (Background) — « Étant donné que je suis connecté » — merely sets an `isAuthenticated` flag, there is no real auth in `@ui`.
## Config
`cucumber.json`: `import` of `src/shared/support/**`, `src/shared/steps/**`, `src/modules/*/steps/**`; `paths` = `src/modules/*/features/**`; `tags: "not @wip"` (excludes WIP scenarios); `language: fr`. **Runner = Node + tsx**, not Bun — the plugins (Playwright, happy-dom) do not load under a native Bun import. Do not "bunify" `cucumber:run`/`test:data`. ⚠️ The runner must point at the package's **actual JS entry** (`node_modules/@cucumber/cucumber/bin/cucumber.js`), **never** at `node_modules/.bin/cucumber-js`: depending on the installer, `.bin/` holds a **shell shim** (not JS) that `node --import tsx/esm` cannot execute.
## The test harness is built on demand
The `@data`/`@e2e` harnesses (`src/shared/test-harness/harness.tsx`, `harness-ng.tsx`) are **not** built by `build.ts`. The `BeforeAll` hook in `hooks.ts` compiles them **on demand** (`bun build``dist/test-harness*.js`). The test wallet can be created ahead of time with `bun run test:auth-setup` (`scripts/setup-test-auth.ts`); otherwise it is created automatically on the first run (see [[decision_2026-03-12_headless-wallet-creation]]).
## Auto-generated files
Scripts under `scripts/` parse features and steps into TS data consumed by the browsing tool:
| Script | Input | Output |
|---|---|---|
| `parse-features.ts` | `*/features/*.feature` | `src/shared/data/features.ts` |
| `parse-test-results.ts` | `reports/cucumber-report.json` | `src/shared/data/testResults.ts` |
| `extract-step-definitions.ts` | `shared/steps/ui/*.ts` | `src/shared/data/stepDefinitions.ts` |
Run: `bun run test:cucumber` (everything), `bun run test:data` (@data). After adding steps: `bun run steps:extract`.
@@ -0,0 +1,42 @@
---
type: knowledge
summary: The @data layer — Playwright drives Chromium (persistent profile), which logs into the real NextGraph broker that loads harness-ng.tsx in an iframe; automated wallet lifecycle (creation + bootstrap login), window.__testData bridge, mock fallback; per-scenario isolation through a fresh virtual identifier (this.freshIdentifier), no more per-scenario purge
last_checked: 2026-07-27
---
# The `@data` layer (real broker)
`@data` exercises the **real NextGraph pipeline** through a broker, not mocked data.
## Architecture
```
Cucumber → Playwright (Chromium, persistent profile)
→ broker wallet login (automated)
→ broker loads the harness in an iframe (http://127.0.0.1:{port})
→ harness-ng.tsx (init → useShape → ORM → broker)
→ window.__testData bridge
```
**Dual mode**: real broker (`harness-ng.tsx`, the default) or mock fallback (`harness.tsx`, standalone DeepSignalSets if the NG build fails).
## Wallet lifecycle (automated, CI-ready)
- **First run**: no `.wallet-ready` marker → headless Chromium creates the wallet (`nextgraph.eu` → Create Wallet → ToS on `account.nextgraph.eu` → username/password → submit), **then logs in** — that initial login is required to bootstrap the session (saved in localStorage); without it, writes would not go through. Marker written.
- **Subsequent runs**: marker found → automated login (click Login → wallet → password → submit) → harness in the iframe → `window.__testData.ready`.
- Wallet credentials: `festipod-tests` / `festipod-tests`.
> The choice of "automating the headless UI rather than creating the wallet through an API" is settled in [[decision_2026-03-12_headless-wallet-creation]].
## Technical details
- **Chromium flags** (`--disable-web-security`, `--allow-insecure-localhost`, Private Network Access turned off): necessary because the public broker loads a `http://127.0.0.1` harness in an iframe.
- **Persistent profile** `.playwright-profile/` (gitignored, wallet in localStorage) — requires the real Chrome binary, not `chrome-headless-shell`.
- **HTTP server** started in `BeforeAll` (auto-assigned port), serving the HTML plus `/harness.js` (separate files — an inline script breaks because of special characters in the bundle).
- **The bridge is the real app path (per entity).** Since the move to *one document per entity* (concept `data-layer`, [[rule_document-per-entity]]), the `window.__testData` bridge (`events`/`users`/`participations`, `joinEvent`/`leaveEvent`/`isParticipating`/`getEventParticipants`, `loadTestData`) **delegates to the app's data context** (`appData` through `FestipodDataProvider`) — this is the real per-entity path the screens use, not a read at root-store level. The harness therefore mounts the **`AccountProvider`** and logs in by default (`@mariedupont`) to establish the current identity (without it the ReadCap filter would only let public data through). It reads `appData` through a **live ref** (a captured snapshot goes stale after a seed re-render).
- Low-level probe paths are kept (root-store scope `protectedNuri`) for the ReadCap/isolation scenarios that *govern* that document: `rawJoin`/`rawParticipations`, `governDocument`/`governProtected`/`documentNuri`, `FilterProbe`/`FanoutProbe`.
- **Identity before writing.** A `Participation` has a mandatory `fp:user`; since reading the profile can lag behind the public events, the steps wait for `ensureCurrentUser()` before `joinEvent` (otherwise a participation is written without a user → dropped on read, and never makes the round trip) and then wait (`waitForFunction`) for the participation to be read back.
- **Per-scenario isolation = a fresh virtual identifier, NOT a purge.** The @data `Before` hook mints a unique identifier per scenario (`freshScenarioIdentifier` in `hooks.ts`), exposes it as `this.freshIdentifier` on the World, and injects it via `addInitScript` into `localStorage['festipod.account.identifier']` **on every origin** (including the harness iframe on 127.0.0.1) — before any script. The shim then serves a **fresh, empty virtual account**, whose registry starts empty *by construction*: **nothing to purge**. The old per-scenario reset (`window.__testData.resetDataState()`, a SPARQL DELETE of the `urn:ng-eventually:shim:Account` records on the anchor graph) is **no longer called** — it cost up to 10 s taken out of the 60 s budget of the `Before` hook, already eaten by the broker login. The helper still exists on the bridge (`harness-ng.tsx`) but is no longer on the default path: do not put it back into the `Before` hook without measuring.
- **What the fresh identifier does NOT bound**: the *physical* growth of the shared wallet — see [[caveat_wallet-bloat-hang]] (profile to be moved aside when anchored reads start to hang).
- `this.freshIdentifier` is also what distinguishes a **reconnection** test (same identifier re-injected) from an **isolation** test (new identifier) — see [[caveat_reconnexion-froide-local-vs-broker]].
- The connected seed stays **lightweight** (few docs) because each `docCreate` is a serial broker round trip of about 2s.
@@ -0,0 +1,77 @@
---
type: knowledge
summary: The @e2e layer — Playwright boots the REAL app (not a harness) inside the broker iframe, interacts through appFrame.evaluate()/locator(), reuses setupBrokerPage() from @data; tests navigation/redirects/clicks, no mock fallback; per-scenario identity (this.freshIdentifier) plus the access barrier disabled by init script; "close and reopen" idiom for reconnection scenarios
last_checked: 2026-07-27
---
# The `@e2e` layer (real app)
`@e2e` tests the **UI of the real app** running inside the broker iframe — unlike `@data`, which loads a test harness.
## Architecture
```
Cucumber → Playwright (Chromium, persistent profile)
→ https://nextgraph.net/redir/#/?o=http://127.0.0.1:{appPort}
→ broker login (automated, same machinery as @data)
→ broker loads the REAL APP in an iframe
→ app renders with a self-connecting NextGraphProvider
→ steps through appFrame.evaluate() + Playwright locators
```
**App server**: started in `BeforeAll` (`spawn('bun', ['src/index.ts'], { env: { PORT } })`, polled until it answers over HTTP, killed in `AfterAll`). It reuses the `setupBrokerPage()` helper from `@data` (redirect, login, iframe discovery).
## Step definitions
Inside the modules (e.g. `src/modules/auth/steps/e2e/connexion.steps.ts`):
- `this.appFrame!.evaluate()` — JS inside the app iframe (hash/path navigation, content checks)
- `this.appFrame!.locator()` — DOM elements
- `this.appFrame!.waitForFunction()` — poll for an expected state
- `SCREEN_MARKERS` — map from screen ID to a unique verification text
Navigation: `window.history.pushState` plus a `popstate` dispatch (path-based routing, see `app-architecture`).
## Differences from `@data`
| Aspect | `@data` | `@e2e` |
|---|---|---|
| Loaded in the iframe | harness (`harness-ng.tsx`) | real app (`src/index.ts`) |
| Ready signal | `window.__testData.ready` | `root.innerHTML.length > 100` |
| Interaction | `evaluate()` bridge | `evaluate()` + locators |
| Mock fallback | yes | **no** (real broker required) |
| Tests | data operations | UI behaviour (nav, redirects, clicks) |
> **Do not re-check in `@e2e` what `@ui` already covers** — `@e2e` must break when the *collaboration* between layers breaks, not when an icon changes (see [[rule_test-layer-contracts]]).
## Scenario identity + access barrier
Two settings applied by the `Before` hook in `hooks.ts` govern **every** `@e2e` scenario:
- **`this.freshIdentifier`** — a virtual identifier **unique to each scenario**, injected via `addInitScript` into `localStorage['festipod.account.identifier']` on **every** origin before any script. The real app therefore boots straight into that identity, and each scenario starts from an empty space. This is the **same** machinery as in `@data` (same World field).
- **Access barrier disabled** — `browserContext.addInitScript` sets `globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ = true` on the **persistent** context: `@e2e` sees the app, not the `AccessGateScreen`. **Fresh** contexts (`@humain`, see [[knowledge_multibrowser-harness]]) do not inherit that setting → the barrier is ON for them.
> **Impact:** any page opened by hand inside a step (`ctx.newPage()`) must **re-apply both init scripts itself** — the context's `addInitScript` only applies to pages of that context, and the identifier must be written **before** the app's first script.
## The "close and reopen" idiom (reconnection scenarios)
`reconnexion-persistance-e2e.feature` / `src/modules/event/steps/e2e/reconnexion-persistance.steps.ts` reproduce the "I create, I close, I come back" journey inside the REAL app:
1. **Creation through the real form** — the step drives the actual creation wizard at DOM level (3-step wizard, selection by *placeholder*: event name, venue; submit button by its label). ⚠️ **These steps are coupled to the French labels of the creation screen**: renaming a placeholder or the submit button breaks the scenario, not the app.
2. **Reopening** — a second page on the **same** persistent context, with the **same** `this.freshIdentifier` and the barrier disabled, then `pool.setupBrokerPage(page, pool.appUrl!)` → new broker login, fresh verifier session.
3. **Proof** — the step captures the console of **both** pages and publishes a summary through `this.attach` (Cucumber attachment) plus stdout; a raw dump of the connection/sync lines is **opt-in** through the `RECO_RAW_DUMP=1` environment variable (noisy, off by default).
> **Limitation to know about**: this setup proves the reconnection *of the journey*, **not** the broker durability of the write — the second page shares the IndexedDB of the persistent profile. See [[caveat_reconnexion-froide-local-vs-broker]] for the setup that does settle broker-vs-local.
The scenario is **`@wip`** (diagnostic instrument, excluded from the default run).
## `@smoke` — guarding the "blank page once connected" class
`@e2e @smoke` (`src/modules/home/features/accueil-connecte-rend.feature`) guards a CLASS of regression: a rendering crash that happens ONLY once the app is connected and mounted on real data (symptom: only the broker iframe banner shows, `#root` stays empty). The smoke test reuses the boot from the @e2e `Before` hook, navigates to the connected home screen and asserts TWO things:
1. **HomeScreen really mounted** — presence of strong markers (`.app-navbar` plus the `[aria-label="Relayer un événement"]` button), absent from a spinner or from the broker banner. A `throw` inside a component/provider mounted after connection unmounts the tree (there is no `ErrorBoundary`) → those markers disappear → red.
2. **Zero runtime errors**`this.pageErrors` (see below) must be empty.
The @e2e `Before` hook now **collects** the app page's `pageerror` and `console.error` events into the World (field `pageErrors`, reset per scenario) — that is what makes the "no error" assertion possible. The default run of `bun run validate` executes `@smoke and not @wip` (not all of `@e2e`, to stay fast). **Detection proof**: a `throw` at the top of `HomeScreen` turns the smoke test red; without it, green.
## Key files
`src/shared/support/hooks.ts` (Playwright lifecycle + `pageErrors` collection), `world.ts` (fields `page`/`appFrame`/`pageErrors`), `scripts/debug-browser.ts` (headed debugging), `.playwright-profile{,-debug}/` (gitignored).
@@ -0,0 +1,70 @@
---
type: knowledge
summary: Multi-browser harness along TWO orthogonal axes — number of browsers (the machinery, isolated fresh contexts spawned from a non-persistent freshBrowser) AND wallet model (own/@private-wallet vs shared/@shared-wallet); shared is provisioned by storageState injection (test-only); an @humain e2e validates the REAL product mechanism through the real staging app (.ngw file downloaded from the screen → nextgraph.eu "Import a Wallet File" → Entrer → connected); @wip convention excluded through cucumber.json
last_checked: 2026-06-16
---
# Multi-browser harness (private-wallet vs shared-wallet)
The ability of the `@data`/`@e2e` harness to drive **several isolated browsers** within a single scenario, along **two orthogonal axes**. It makes it possible to test both the "everyone has their own wallet" model (`@private-wallet`) and the "wallet shared between browsers" model (`@shared-wallet`).
## The two axes (orthogonal)
| Axis | What it decides | Expressed by |
|---|---|---|
| **Number of browsers** (machinery) | 1..N isolated named contexts | `openBrowser(name, …)` + steps `… dans le navigateur "X"` |
| **Wallet model** | distinct vs shared NG identity | **step phrasing + tag** (see below) |
Do **not** confuse `@multibrowser` (several browsers) with `@shared-wallet` (same wallet): we run multibrowser **in private** (everyone with their own wallet) **and in shared** (shared wallet), and compare both setups with the **same** behavioural steps.
## Wallet model: phrasing + tags
- `Étant donné un navigateur "A" avec son propre wallet`**own** model, tag `@private-wallet`.
- `Étant donné un navigateur "A" avec le wallet partagé`**shared** model, tag `@shared-wallet`.
- Umbrella tag `@multibrowser` (whole feature).
## Architecture (where things live)
- **`src/shared/support/browserPool.ts`** — shared state + factory. Outside the **persistent** Chromium context that carries the shared wallet (legacy single-browser `@data`/`@e2e`, **unchanged**, see [[knowledge_data-layer-broker]]), the harness launches a **non-persistent** browser `freshBrowser` (`chromium.launch`) which mints fresh isolated contexts on demand (`spawnContext(wallet)`). The module is imported by `hooks.ts` (lifecycle) and `world.ts` (per-scenario use) — no import cycle.
- **`world.ts`** — API: `openBrowser(name, wallet)`, `browser(name)`, `loadAppInBrowser(name, 'app'|'harness')`, `closeBrowsers()`; registry `browsers: Map<name, NamedBrowser>`. Named browsers are closed in `After`, `freshBrowser` in `AfterAll`.
- **`hooks.ts`** — a scenario tagged `@multibrowser` **does not get** the legacy single page; the steps open the browsers themselves. Requires the real broker mode (`freshBrowser` is unavailable in the mock fallback).
## Wallet provisioning
- **own**: empty `newContext()` → distinct NG identity / no wallet.
- **shared**: `newContext({ storageState })`, where `storageState` is **captured once** at `BeforeAll` from the persistent profile (warm-up through `setupBrokerPage`, then `browserContext.storageState()`), exposed as `pool.sharedWalletState`. **Empirically verified (2026-06-16)**: the `nextgraph.eu` and `nextgraph.net` origins round-trip into the fresh contexts, and two **shared** browsers both reach the app **connected** to NextGraph (`window.__testData.ready`) **without any manual login**.
> This provisioning is **test-only** — distinct from the **product** mechanism (FILE-assisted import). The shared-wallet scenario using storageState **bypasses the import**; to validate the REAL mechanism, see the `@humain` e2e below.
## Human journey — e2e of the product mechanism (green)
The `@humain` scenario validates the REAL wallet distribution flow **end to end, through the real app**, not through test injection. A blank browser opens the staging app → the `AccessGateScreen` offers the **file** and the **password** → the file is downloaded **from the screen**, the displayed password is checked to **equal** the wallet's own → import on `nextgraph.eu` "Import a Wallet File" → back to the app → an **identifier is typed in**, then a click on « Entrer » (naming the space and opening the wallet are a single act, see concept `app-security` [[decision_2026-07-06_identifier-at-access-barrier]]) → app connected, landing straight on the home screen (no more separate « nom d'utilisateur » screen).
- **e2e wallet**: a `.ngw` file (`festipod-e2e-tests`, password = identifier) placed **at the root of the worktree**; `findE2eWalletFile()` locates it (`*.ngw`). Gitignored → each environment has to add it (otherwise a clear error is raised).
- `pool.ensureStagingApp()` (`hooks.ts`) — an **isolated** build `bun run build.ts --outdir=dist-staging` (access barrier **ON by default**; password baked in and the **file copied** to `/shared-wallet.ngw`, see `build.ts`), served statically. Memoized and lazy (only `@humain` pays for it).
- **Barrier bypass for `@e2e`**: the harness calls `browserContext.addInitScript` on the **persistent** context to set `globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ = true` (which applies to the app iframe before its scripts) → `@e2e` sees the app directly, not the barrier. Fresh contexts (`@humain`) leave it alone → barrier ON. The old `/login` `LoginScreen` has been removed.
- `pool.importWalletViaFile(page, filePath, password)``nextgraph.eu/#/wallet/login``setInputFiles('input[type=file]')` (wait for the SPA to render, otherwise `EncryptionError`) → password field → unlock.
- `pool.completeBrokerLogin(page, appUrl, walletPassword?)` — the "broker login" half extracted from `setupBrokerPage`. **Robust waiting**: after the (multi-hop) redirect, it waits for either the app iframe or the "Click here to login with your wallet" link, then unlocks with the password. Since the broker session is **not** persisted between launches, this wallet login is required on every run (warm-up + `@e2e` + `@humain`).
> **The e2e is what guarantees it works for a real human**: Festipod hands out the RIGHT file plus password, and importing that file yields a working wallet on a blank device. The `@shared-wallet` scenario (storageState) remains a test provisioning shortcut, it does not validate the import.
## Isolation (guaranteed at 3 levels, proven by the scenarios)
1. `freshBrowser` runs in a **separate process** from the persistent profile carrying the wallet → an **own** browser starts **with no wallet**.
2. Every `newContext()` is a **hermetic storage partition** (Playwright guarantee).
3. Isolation is proven not only on the **local** origin (`127.0.0.1`) but also on the **broker origin** `nextgraph.net` **where the wallet actually lives** (a localStorage probe written in A is absent from B).
## Files
- Feature: `src/modules/workshop/features/multibrowser-harness.feature`.
- Steps: `src/modules/workshop/steps/data/multibrowser.steps.ts`.
- A `/blank` route added to the harness server (`hooks.ts`): a minimal page **with no NG stack**, for the localStorage isolation checks.
## The `@wip` convention (now enforced)
`cucumber.json` (profile `default`) carries `"tags": "not @wip"`. `cookbook_add-scenario` prescribed `@wip` for anything unimplemented, but it was **excluded nowhere**; now `not @wip` is **AND**ed with the CLI filters (e.g. `--tags @data``(not @wip) and @data`, verified).
## Links
- [[knowledge_data-layer-broker]] — the single-browser `@data` layer (persistent profile) that this capability extends.
- [[cookbook_add-scenario]] — the `@wip` convention, step pitfalls.
@@ -0,0 +1,47 @@
---
type: knowledge
summary: The @ui layer — renderHelper.tsx renders any screen inside LocalDataProvider + happy-dom, world.renderCurrentScreen() invokes it on every navigateTo, assertions run against the rendered DOM with the deterministic seed fixtures; pitfall of screens reading a global injected at build time (access barrier → lazy import mandatory)
last_checked: 2026-07-27
---
# The `@ui` layer
`@ui` renders a screen with `LocalDataProvider` (seed) plus `RouterProvider` through happy-dom, then asserts on the **rendered DOM**.
- Helper: `src/shared/test-harness/renderHelper.tsx` (installs the happy-dom globals, wraps the screen). Invoked from `world.ts:renderCurrentScreen()` on every `navigateTo(...)`.
- Deterministic fixtures (`src/shared/data/seedData.ts`, see concept `data-layer`): `Marie Dupont`/`@mariedupont` = currentUser, `Jean Durand`/`@jeandurand` exists, 5 events, and so on.
## Good assertion patterns
```ts
// Visible text
expect(this.getDomText()).to.include('Marie Dupont');
// Element present, by class/role
expect(this.renderedDoc!.querySelector('.app-avatar')).to.not.be.null;
// Conditional rendering (filled vs empty)
expect(this.renderedDoc!.querySelectorAll('.app-card').length).to.be.greaterThan(0);
// Required field rendered with a label and an asterisk
const labels = Array.from(this.renderedDoc!.querySelectorAll('p')).map(p => p.textContent ?? '');
expect(labels.some(t => t.includes("Nom de l'événement *"))).to.be.true;
```
## `FestipodWorld` fields & helpers (`src/shared/support/world.ts`)
- `renderedDoc: Document | null` — the rendered happy-dom DOM (populated by `renderCurrentScreen()`, called on every `navigateTo(...)`).
- `currentScreenId: string | null` — the current screen.
- Assertion helpers: `getDomText()` (DOM text), `hasText(t)`, `hasField(name)`, `hasElement(selector)` — they **prefer the rendered DOM** but **fall back to the screens' source** for unmigrated steps (a leftover, see [[caveat_source-grep-vestiges]]).
## ⚠️ Screens that read a global injected at **build** time (access barrier)
`src/modules/auth/sharedWallet.ts` **captures, at module evaluation time**, a global set by `build.ts` (`__FESTIPOD_SHARED_WALLET_PASSWORD__`). The `@ui` harness runs under Node **without going through the build** → that global is missing, `hasSharedWallet()` returns false, and since the **shared wallet is the only supported mode** (concept `app-security`), `AccessGateScreen` renders its **configuration error** branch: **no identifier field at all** in the DOM → every barrier step fails with a misleading message ("field not found").
**The mandatory setup** (applied in `src/modules/auth/steps/ui/barriere-acces.steps.ts`):
1. set the global **at the top of the steps module**, before any import of the screen;
2. **import the screen lazily** (memoized `await import(...)`) — a static `import` would be **hoisted above** the assignment and `sharedWallet.ts` would capture an empty value.
> **Impact if you touch this:**
> - Adding a static `import` of `AccessGateScreen` (or of any module that reaches `sharedWallet.ts`) in **any** `@ui` steps file re-introduces the bug — Cucumber loads every steps module, so the screen would be evaluated before the global is set.
> - The current determinism relies on **this file being the only** `@ui` module that reaches `sharedWallet.ts`. A second entry point would make the evaluation order unguaranteed → the global injection would then have to move into the shared support, not be duplicated.
> The `app-*` classes confirm the modern theme (see `app-architecture`). Anti-patterns (regexes over the source, implementation details) are banned by [[rule_test-layer-contracts]]. To write a new scenario, see [[cookbook_add-scenario]].
@@ -0,0 +1,27 @@
---
type: rule
summary: NEVER poll the broker (re-reading in a loop "is it there yet?"). NextGraph is subscription-based — data arrives by PUSH, and the first `State` of a `doc_subscribe` is the deterministic sync barrier (after it — presence guaranteed, absence definitive). Tests AND app wait for the push / for the reactive state to settle, never a broker re-read loop.
last_checked: 2026-07-09
---
# Never poll the broker — wait for the subscription
NextGraph is **subscription-based (reactive)**. A read is NOT "query in a loop until it shows up"; it is "subscribe, react to the push". The **first `State`** of a `doc_subscribe` marks the end of the initial synchronization (a synchronous barrier): after it, the **presence** of a piece of data is **guaranteed** and its **absence** is **definitive**. Contract verified empirically on the SDK side (`@ng-eventually/client`, e2e test « CONTRAT 3 »).
## The anti-pattern to ban
```
for (i = 0; i < N; i++) { if (await authParticipationCount(...) === X) break; sleep(500); }
```
Any loop that **re-queries the broker** (repeated `authParticipationCount`, `listMyEntityDocs`, `sparql_query`) in order to "wait" for data is forbidden: it hides the real mechanism, makes the test brittle (guessed timeout), and directly contradicts the NextGraph model. That remark is what caused the deletion of the old caveat which wrongly held polling up as a practice.
## What to do instead
Wait for the **reactive push**. In practice (app AND test): the reactive state (`AD().*` fed by `subscribeDoc` in the data context) updates **on push**. We wait for THAT state to reflect the expectation — we **observe the settled reactive state**, we do NOT re-issue a broker read. The data mechanism is the subscription; waiting only **observes the reactive result**.
- App: the screen is already reactive (`subscribeDoc` → re-render on push) — no application-level polling, no spinner driven by a guessed timeout (if a waiting state is wanted, it comes from the native subscription barrier, not from an added signal).
- Test: **a helper that reliably waits for the push/barrier is welcome** (it makes things reliable without making them brittle). What is banned is the **re-read loop**, not waiting for a signal.
- **Pragmatic fallback**: if strictly waiting for the push/signal turns out to be brittle one way or another, a **short interval** (`setInterval` / closely spaced re-checks) that **observes the ALREADY updated reactive state** (the local state fed by the subscription — NOT a broker re-read) is acceptable: it is as close as it gets to what the user experiences, simply **waiting** for the (reactive) screen to update. The red line is invariant: **never re-query the broker in a loop**; observing the settled reactive state, yes.
See also [[caveat_wallet-bloat-hang]] (another source of @data flakiness, orthogonal to this one). The non-polling mechanism on the library side (`open-repo`: subscribe + wait for the first State + read) lives in the `@ng-eventually/client` repo, not here.
@@ -0,0 +1,29 @@
---
type: rule
summary: Each BDD layer answers a distinct question — @ui = rendering (DOM + seed), @data = broker mutations/persistence, @e2e = collaboration of the layers over a journey; push every assertion down to the lowest layer that can answer it
---
# Rule: the test layer contract
Each layer answers **one distinct question**. Mixing concerns produces brittle tests that break on refactors without catching any real regression. **Push every assertion down to the lowest layer that can answer it.**
- **`@ui` — display layer.** Renders a screen with `LocalDataProvider` (seed) plus happy-dom and asserts on the DOM. Checks that *given known data, the screen shows the expected text and elements*. **Does not test** navigation, mutations or persistence.
- **`@data` — data layer.** Drives ORM mutations through the **real NextGraph broker** (headless harness, no app UI). Checks that *shape operations are persisted and observable in the wallet*. No DOM here — use the `window.__testData` bridge.
- **`@e2e` — integration layer.** Boots the real app inside the broker iframe (Playwright/Chromium). Checks that *the layers collaborate to deliver a journey* (create → list → edit → reload → still there). **Rare**: 1 scenario per critical path; **never duplicate** a `@ui` content check.
## Why cost dictates the pyramid
`@ui` runs in-process (instant); `@data` boots a broker (~50s); `@e2e` boots broker + app + browser (~2min). A rendering claim belongs to `@ui`, not to `@e2e`.
## `@ui` anti-patterns to ban
```ts
// ❌ regex over the source: couples the test to the structure of the code
expect(/<Title[^>]*>Marie Dupont<\/Title>/.test(source)).to.be.true;
// ❌ implementation details
expect(/showDuplicateWarning/.test(source)).to.be.true;
```
Prefer assertions on the **rendered DOM** plus seed data (see [[knowledge_ui-layer]]). The source-analysis helpers and maps are leftovers on their way out: [[caveat_source-grep-vestiges]].
+40
View File
@@ -0,0 +1,40 @@
---
type: _overview
summary: How Festipod persists its data through the @ng-eventually/client SDK — entities stored as documents placed by scope, direct SPARQL writes + union-model reads, SHEX stack, connected/demo modes, seed
triggers:
keywords: [nextgraph, "@ng-eventually", polyfill, union, readUnion, readEntities, SHEX, shape, scope, "@graph", NURI, overlay, ReadCap, WriteCap, cap-less, sparql, seed, wallet, FestipodData, ngSession, ngGraph, bootstrap, document, entité, déconnexion, reconnexion, durabilité, outbox, SerializationError]
paths: ["src/shared/shapes/**", "src/shared/data/readEntities.ts", "src/shared/data/entityWrites.ts", "src/shared/context/NextGraphContext.tsx", "src/shared/context/FestipodDataContext.tsx", "src/shared/utils/ng*", "src/shared/data/seedData.ts"]
---
# Data layer
How Festipod **persists its data** through NextGraph (P2P, local-first, end-to-end encrypted). The data SDK is **`@ng-eventually/client`**: we treat it as a finished NextGraph SDK — every entity is a **document** placed in the store of its **scope** (public / protected / private). A **write** is direct SPARQL into the entity's own document; a **read** is the **union model** (resolve the documents on demand → open/sync → **one** unanchored `sparql_query` over the union → re-query on signal), not a fan-out reactive ORM subscription (which *hangs*). See [[rule_document-per-entity]]. The mapping *which entity → which scope* is a **product** fact (concept `functional-domain`, [[knowledge_data-scopes-and-discovery]]); this concept describes the **persistence mechanics**.
> **SDK boundary.** Festipod's data SDK is `@ng-eventually/client` — initialized/injected **exactly once** through `ngSession.configure(...)`. We write against it as a **finished** NextGraph SDK: never document NextGraph's current state here (constraints, workarounds, broker internals) — that lives in the `@ng-eventually/client` repo. See [[knowledge_nextgraph-stack]].
## Model & data
- [[knowledge_sdk-surface]] — **the data contract**: the `@ng-eventually/client` surface the app codes against (reads, writes, documents, inbox, discovery, capabilities, identity) and what may / may not be assumed of each
- [[knowledge_nextgraph-stack]] — the `@ng-eventually/client` SDK, SHEX shapes, reactive ORM, `build:orm`, injection through `ngSession`
- [[knowledge_data-modes]] — connected (SDK) vs disconnected/demo (seeded local state), how the provider is chosen
- [[knowledge_entities]] — the `Fp*` types and their SHEX shapes
- [[knowledge_seed-data]] — seed data, `CURRENT_USER_ID`
- [[knowledge_context-internals]] — pitfalls of `FestipodDataContext` (currentUser, **two id spaces** principal ↔ profile NURI, dev auto-seed, `participantCount` cache, reset on identity change, local no-op)
## Write rules
- [[rule_document-per-entity]] — every entity gets **its own document** (per scope), never one at store level; this is what makes the SDK's per-document isolation possible
- [[rule_app-uses-sdk-surface-only]] — the app behaves as if NextGraph were finished; every workaround lives in the polyfill
## What leaves this repo (two destinations, don't confuse them)
- [[rule_capture-nextgraph-findings]] — established **knowledge** about how NextGraph actually works → the **polyfill**'s reference docs, at the moment of discovery
- [[rule_nextgraph-inbox]] — a NextGraph **malfunction**, or a **gap** we need and emulate in the meantime → a note in `orm-tests/INBOX/`, which tracks upstream progress and says what to remove from the polyfill
## Pitfalls (read before touching deletions / event fields)
- [[caveat_participation-deletion]] — withdrawal must be **authoritative** and must not come back
- [[caveat_event-fields-not-persisted]] — `startTime`/`themes`… not covered by the Event shape → lost when connected
- [[caveat_write-durability-across-disconnect]] — a write made just before an idle period / socket drop can be **lost** (no broker durability); the account survives. Open incident → post-mortem in the polyfill
> Confidentiality (scope isolation, trusting the SDK): concept `app-security`. Product scopes per entity + discovery: concept `functional-domain`.
@@ -0,0 +1,186 @@
---
type: brief
summary: Implementation design (historical) — make reads REACTIVE via doc_subscribe (per-document, without the ORM fan-out that hangs) and replace the mutated-in-place participantCount with the Option-B flow (the participant deposits into the event's inbox, the owner materializes and increments their own doc). READ IN THIS LIGHT — the app-side doc_subscribe wiring was later SUPERSEDED by the SDK's watchShape/useShapeQuery surface, and the « reactive with no reload » framing was RETRACTED for « the owner processes their inbox at their next connection »; Option B (P4-P5) is still pending
---
# Reactive reads + correct participant count (Option B)
Implementation brief, anchored in the current code. Goal: two coupled evolutions of Festipod's data layer (connected mode / `@ng-eventually/client`).
1. **Cross-session reactive reads** — replace the one-shot `readUnion` + `bumpRead` (manual re-query, local-only) with real broker-pushed reactivity, **never polling** and **without the ORM fan-out that hangs**.
2. **Correct participant count (Option B)** — remove the current isolation violation (the participant writes `participantCount` on the event doc, which is not theirs) and replace it with the inbox-deposit → owner-materialization flow.
This brief describes **what to build and in what order**. No code change is made here.
Cross-cutting references: [[knowledge_context-internals]], [[rule_document-per-entity]], [[caveat_participation-deletion]], `functional-domain/knowledge_data-scopes-and-discovery`, `app-security/knowledge_trust-model`, and the `@ng-eventually/client` SDK contract (`docs/sdk-reference.md`, `docs/read-model.md`, `docs/nextgraph-current-state.md`).
---
## 0. Current state (the starting point, file:function)
### Reads (one-shot, manual re-query)
`src/shared/context/FestipodDataContext.tsx``useNgData()`:
- The set of docs to read **on demand** is two `useState`s: `publicDocs` / `protectedDocs` (lines 232-233). It is fed by (a) the listing effect (lines 302-332) which calls `listMyEntityDocs(owner, 'public'|'protected')` (bounded to my own account) + `readDiscoveredEvents()` (the global index), and (b) `registerDoc(scope, nuri)` (lines 251-255) which adds a freshly created doc.
- The **actual read** (lines 347-364): `readEntities(allReadDocs)``readModel.readUnion(docs)` (one `sparql_query` anchored per doc, in parallel, per-doc tolerant). It **re-runs** when `allReadDocs` changes **or** when `readTick` changes.
- `readTick`/`bumpRead` (lines 236-237) = a **manual re-query signal**, bumped after every mutation. **There is NO signal coming from the broker**: a write made by ANOTHER session never increments this session's `readTick`**no cross-session reactivity**. That is the gap this brief fills.
- `listTick`/`relist` (lines 246-247) replays the listing effect after a seed.
### Writing the counter (the violation to remove)
- `joinEvent` (lines 597-668): after writing its own `Participation` (protected doc, lines 621-631), it calls `updateEntityField(eventId, eventId, 'participantCount', int(next))` on **the event's doc** (lines 635-640) — but that doc belongs to the **event's owner**, not to the participant. That is an out-of-scope write. It *also* deposits into the inbox via `depositRegistration` (line 652) — that deposit is the right channel; it is the direct `participantCount` write that must go.
- `leaveEvent` (lines 670-712): symmetrically, decrements `participantCount` on the event's doc (lines 705-710) after the authoritative DELETE of the participation.
- `caveat_participation-deletion`: the participation DELETE must remain **authoritative** (SPARQL DELETE-WHERE via `deleteParticipation`, `src/shared/data/registration.ts` lines 260-334, verified `remaining === 0`) — this brief does not change that contract.
- [[knowledge_context-internals]] already documents that `participantCount` is a **cache mutated in place**, never recomputed, and "not a source of truth". Option B turns it into a value **derived and owned by the owner**.
### Display (already "count + anonymous", to be kept)
`src/modules/event/screens/EventDetailScreen.tsx`:
- `joined = isParticipating(eventId)` (line 20).
- `participants = getEventParticipants(eventId)` (line 21) → in the context, `getEventParticipants` (FestipodDataContext lines 108-111) filters the known `participations` by `eventId` and joins the **readable** `users` (so only my connections, per the protected cap).
- `knownParticipants = participants.filter(p => p.id !== currentUserId)` (line 33).
- The label **« Participants ({event.participantCount}) »** (line 146) displays the **derived count**, and `knownParticipants.length < event.participantCount` renders the **« voir tous les participants » placeholders** (lines 163-170) — exactly the intended "count + anonymous" model. **This display does not change**: Option B only makes `participantCount` correct and reactive, and `knownParticipants` remains governed by the protected read cap.
### The lib's polling watchers (to be replaced)
Confirmed by reading the lib (`packages/client/src/`):
- `inbox.watch(target, onDeposits, {intervalMs=1000})` (`inbox.ts:195-223`) = **`setInterval` polling**, firing only when `deposits.length` changes.
- `discovery.watchIndex(onEntries, {intervalMs=1000})` (`discovery.ts:163-187`) = the same **`setInterval` polling**.
- `useShape` (`use-shape.ts:12`) IS push-based/reactive, but **only safe on ONE already-open document** — the `graphs:[…]` fan-out hangs (§2).
- **No `doc_subscribe` wrapper is exposed today** in `docs.ts` (which only exposes `docCreate` / `sparqlUpdate` / `sparqlQuery`). The `ng.doc_subscribe` primitive is reachable *untyped* through the `ng` proxy (`ng-proxy.ts:54-56` passthrough), but there is **no typed layer****the lib must add one** (§A).
---
## 1. The platform primitives (nextgraph-rs, verified)
- `doc_subscribe(repo_o: String, session_id, callback)` (`sdk/js/lib-wasm/src/lib.rs:1907`) is **per-document**: a single repo NURI, a single callback. It mounts a subscription on **one branch** of the doc (`verifier.rs:352` `create_branch_subscription`), first pushes a `TabInfo` + initial `State` (`verifier.rs:470-477`), then a stream of `Patch`es on every commit.
- The push: on every verified transaction on a branch B, the verifier calls `push_app_response(&B, AppResponse::…)` (`verifier.rs:252`) on the `Sender` registered in `branch_subscriptions[B]` (`verifier.rs:115`). **Unit of subscription = one branch of one doc.**
- The **ORM fan-out** lives elsewhere: `orm_start_graph(scope.graphs[], …)` (a single call over an array). There, a **single** unsynchronized repo in the array makes `open_for_target → resolve_target` return `RepoNotFound` (`request_processor.rs:147-171`, and above all the `initialize.rs:125-128` loop where the `?` **aborts the whole subscription**). The `readyPromise` then never resolves → **~75s hang** (`nextgraph-current-state.md` § *The ORM fan-out hang*, quoted in `read-model.md:93-98` and the header of `read-model.ts:24-31`). **Corollary: per-doc `doc_subscribe` does NOT have this flaw** — it is not subject to fan-out, so a missing doc only breaks its own subscription.
- **Writes are membership-bound, with no append** (confirmed, `repo.rs:584` `verify_permission`: a non-member author → `PermissionDenied`; `commit.rs`: a transaction requires `WriteAsync`/`WriteSync`, obtainable only via a grant from the owner; **there is no `Append` variant in `PermissionV0`**). ⇒ **Option A is impossible**: a participant cannot write to / increment a counter on someone else's public doc. Hence Option B through the inbox.
- **The inbox is a real platform primitive** (`server_broker.rs:826` `inbox_post`: no membership check on the sender; the message is sealed to the inbox's key, readable only by the registered *readers*). That is exactly the "anyone deposits, only the owner drains" channel. Today the lib emulates it over the shared wallet (`inbox.ts` post/read RDF), the native one being deferred.
---
## A. Reactive reads — the design
### Principle: per-doc `doc_subscribe` as a **change signal**, `readUnion` remains the reader
We do **not** make `readUnion` reactive and we do **not** introduce an ORM fan-out. We keep the documented pattern (`read-model.md:100-110`):
> a lightweight reactive subscription (`doc_subscribe`, or the ORM on a single already-open store — never a per-entity fan-out) on the synchronized docs; on its change signal, replay the bounded set of per-doc `sparql_query` calls (`readUnion`).
Concretely:
1. **The lib exposes a typed `doc_subscribe` wrapper.** It does not exist today. Add to `packages/client/src/docs.ts` (or a new `subscribe.ts`) a function, e.g.:
```ts
// returns an unsubscribe; onChange called on the initial State then on every Patch
export function subscribeDoc(nuri: Nuri, onChange: (r: AppResponse) => void): () => void
```
which wraps `ng.doc_subscribe(nuri, sessionId, cb)` and normalizes the AppResponse (initial + patches) plus stream teardown. It is **per-document** (a single NURI), hence immune to the fan-out hang.
- Also expose a helper to subscribe to **a set** of docs by mounting **one subscription per doc** (a `nuri → unsubscribe` map), with **per-doc error isolation**: a `RepoNotFound` / unsynchronized doc only fails ITS OWN subscription (retry/skip), never the others. That is the key point that avoids reproducing the fan-out. The SDK contract (`sdk-reference.md`) will need to document this wrapper.
2. **The data context (FestipodDataContext) mounts a per-doc subscription over the set it already reads.** The `allReadDocs` set (union of `publicDocs` `protectedDocs`) is already bounded and on-demand. A new effect in `useNgData()`:
```
useEffect(() => {
const unsubs = allReadDocs.map(nuri => subscribeDoc(nuri, () => bumpRead()));
return () => unsubs.forEach(u => u());
}, [allReadDocs]);
```
→ on **any** patch of a subscribed doc (written by THIS session OR another one), `bumpRead()` re-triggers the existing `readUnion` (lines 347-364). **`readTick`/`bumpRead` stay** — they stop being "manual after my own mutation" and become "pushed by the broker". The shape of the context (`events`/`users`/`participations` values in `useState`) **does not change**; screens keep reading through `useFestipodData()` unmodified.
3. **NEW docs entering the subscribed set, without a fan-out hang:**
- **A newly discovered event**: reactive discovery replaces `discovery.watchIndex` (setInterval) with a **`doc_subscribe` subscription on the global index doc** (the index inbox, a single doc — `resolveInboxAnchor`-style). On every patch of the index → re-read `readDiscoveredEvents()` → the new `doc` NURIs enter `publicDocs` (via `setPublicDocs`), which **grows `allReadDocs`**, which **remounts the per-doc subscription** (the new `useEffect` above) → the new event is read AND from then on subscribed. No fan-out: each doc is subscribed **individually**, as it enters.
- **A new inbox deposit** (new participant, host notification): likewise, replace `inbox.watch` (setInterval) with a **`doc_subscribe` subscription on the relevant inbox doc** (a single doc). A patch → re-materialize (§B).
- **A doc I just created**: `registerDoc` keeps adding it to `publicDocs`/`protectedDocs` → it enters `allReadDocs` → it gets subscribed. (An immediate `bumpRead` keeps perceived local latency at zero.)
4. **The lib replaces its polling watchers**: `inbox.watch` and `discovery.watchIndex` become `doc_subscribe` wrappers on the inbox doc / index doc respectively (one doc each — no fan-out). The public signature is preserved (callback + unsubscribe) so callers do not break; the implementation moves from `setInterval(read)` to `subscribeDoc(anchor, () => read().then(onX))`.
### What does NOT change
- `readUnion` stays one-shot, per-doc, tolerant (a failing doc → `[]`, never an abort).
- The `readEntities` mapping (`src/shared/data/readEntities.ts`) is unchanged.
- **No per-entity `useShape({graphs:[…]})` is introduced** — the only remaining `useShape` is the test harness's `FanoutProbe` (whose very purpose is to *demonstrate* the hang), not an application path.
---
## B. Participant count — Option B (deposit → owner materialization)
### The documents / inboxes involved
- **The participant's participation doc**: protected, **owned by the participant** (already created by `joinEvent`, `createEntityDoc(owner,'protected')` + `writeEntity(ENTITY_TYPE.participation, …)`). Readable in plaintext only by the participant's **connections** (protected cap + `declareConnections`).
- **The event's inbox**: resolved by `hostInboxNuri(eventId)` → `resolveInboxAnchor()` (today a single anchor; after migration, one inbox doc per event — `hostInboxNuri` already reserves the `eventId` param). That is where the participant **deposits the participation link**.
- **The event's doc**: public, **owned by the owner**. It is **the owner** who writes `participantCount` there — never the participant.
- **A (reference) recorded by the owner**: an entry linking the incremented count to the deposit (idempotence + audit); it can live in the event's doc (reference to an already-materialized deposit) or in a protected doc of the owner's.
### The flow (who writes what)
1. **Participant — `joinEvent`** (modified):
- Writes its own `Participation` (protected, theirs) — **unchanged**.
- **Deposits into the event's inbox** a `{ kind:'new-participant', eventId, participationDoc, participantId, uid }` payload via `depositRegistration` (today `inbox.post(target, {from:null, payload})`, `registration.ts:110-125`). `from` stays anonymous at the transport level (the SDK binds `from` to the identity and rejects a spoof — see `registration.ts:106-108`); the domain identity travels in the payload. **The deposit carries the NURI of the participation doc** (`participationDoc`) so that the owner, if they are a connection, can read it in plaintext.
- **REMOVES the `participantCount` write on the event's doc** (current lines 635-640). The participant never writes to someone else's doc again.
2. **Owner — materialization (when connected)**: the owner's session is subscribed (`doc_subscribe`, §A.3) to their event's inbox doc. On a new `new-participant` deposit:
- dedup via `uid` (idempotence: do not re-count an already materialized deposit — check the recorded (reference));
- **increments `participantCount` on THEIR OWN event doc** (`updateEntityField(eventDoc, eventDoc, 'participantCount', int(next))`) — **the owner writing their own doc**, not a read privilege nor an out-of-scope write;
- records the **(reference)** of the materialized deposit (idempotence marker).
- This logic replaces/extends the existing **notification materialization** effect (FestipodDataContext lines 443-479, `readRegistrationNotifications`): today it only surfaces notifications; it also becomes the point where the counter is incremented. The trigger moves from implicit polling to the `doc_subscribe` subscription on the inbox.
3. **Other sessions see the count change**: the event's doc is **public**, so **every** session that has it in its `allReadDocs` is subscribed to it (§A). The owner's write produces a patch → `bumpRead()` → `readUnion` re-reads → `event.participantCount` updated → `EventDetailScreen` re-renders « Participants (N) » **with no reload and no user action**. That is the complete reactive path, cross-session.
### Withdrawal (symmetric, authoritative)
- `leaveEvent`: keeps the **authoritative DELETE** of the participation (`deleteParticipation`, verified `remaining === 0`) — [[caveat_participation-deletion]] intact (it must not come back to life).
- **Removes the direct decrement** of `participantCount` by the participant (lines 705-710). Instead, the participant **deposits a `leave`** (`{ kind:'leave-participant', eventId, uid }`) into the event's inbox; the owner materializes → **decrements their own doc** (idempotent via `uid`, `max(0, n-1)`, and refuses to re-decrement an already processed `uid` so as not to "resurrect" a wrong count).
- **Owner-offline case = eventual behaviour, ACCEPTED**: if the owner is not connected, the deposit stays in the inbox; the count is **not** updated until they reconnect and materialize. **This is accepted behaviour** (eventual consistency, local-first). Others see the count correct itself when the owner comes back. To be stated as such in the product contract.
### Identity (C)
- A participant is shown **by name** only if the viewer is a **connection** of that participant: the participation doc + the participant's profile are protected, so they are readable in plaintext only through the cap granted by `declareConnections` (`src/shared/utils/connections.ts` → `grantRead(protectedDocsOf(owner), neighbour)`). Otherwise the doc stays unreadable → the participant does **not** appear in `getEventParticipants` (which joins on the `users`/`participations` that were read) → they fall into the **« inconnu » placeholders** of `EventDetailScreen` (lines 163-170), the derived count remaining visible through `participantCount`.
- **No privileged read for the host**: the owner does not read participations; they only **count deposits** and write their own counter. They see a named participant only if they are a connection of theirs — exactly like any other viewer. This matches `functional-domain/knowledge_data-scopes-and-discovery` ("identified if known, anonymous otherwise") and `app-security/knowledge_trust-model` (no application-level access control; isolation is per-document and delegated to the SDK).
---
## D. Test plan (real e2e, no polling)
### D.1 — POLYFILL low-level: `doc_subscribe` really does react
Goal: prove the reactive primitive works, independently of Festipod.
- Location: a unit/integration test of the lib (`packages/client`) — or a Festipod `@data` test if the broker harness is required.
- Setup: two "views" of the **same** doc (two subscriptions, or one subscription plus a write through another path). Mount `subscribeDoc(nuri, onChange)`, write to the doc via `sparqlUpdate`.
- **Assertion**: `onChange` is called (initial State) **and then** called again after the write, **without polling** (no `setInterval`; the assertion waits on an event, not on a timeout). Check that a write on **another** doc does NOT trigger `onChange` (per-branch isolation). Check that an unsynchronized doc which fails **does not abort** the other subscriptions (per-doc).
### D.2 — FESTIPOD app-level: 2 real browsers, with no reload and no action from A
Goal: B signs up → A's `EventDetailScreen` shows `participantCount` incremented **and** an "unknown participant", **without A reloading or acting**.
- Extend `src/modules/event/features/e2e-multibrowser.feature` (`@multibrowser @shared-wallet`) and `src/modules/event/steps/e2e/multibrowser-features.steps.ts`.
- New scenario (French Gherkin sketch):
```
Scénario: Un participant apparaît réactivement dans l'autre navigateur sans reload
Étant donné un navigateur "A" avec le wallet partagé
Et un navigateur "B" avec le wallet partagé
Et le navigateur "A" charge l'application via le broker
Et le navigateur "B" charge l'application via le broker
Et le navigateur "A" est connecté à NextGraph
Et le navigateur "B" est connecté à NextGraph
Et le navigateur "A" crée l'événement "Apéro réactif"
Et le navigateur "A" ouvre le détail de l'événement "Apéro réactif"
Et le compteur de participants affiché dans "A" pour "Apéro réactif" vaut 1
Quand le navigateur "B" s'inscrit à l'événement "Apéro réactif"
Alors sans recharger, le compteur de participants affiché dans "A" pour "Apéro réactif" passe à 2
Et le navigateur "A" affiche un participant "inconnu" pour "Apéro réactif"
```
- **Exact assertions**:
1. `participantCount` **on A's side** goes from 1 to 2 — asserted via `frame.waitForFunction` on the context's reactive state (`__testData.events` → the event → `participantCount === 2`) **and then** confirmed on the rendered DOM (the « Participants (2) » label of `EventDetailScreen`), **with no `loadAppInBrowser`/reload call** between B's join and A's assertion.
2. **Unknown placeholder**: `knownParticipants.length < participantCount` → assert the presence of the « Voir tous les participants » block (or an anonymous count = `participantCount knownParticipants.length ≥ 1`), B not being a connection of A → not named.
3. **Negative, no-polling**: the 1→2 transition arrives through the subscription (event-driven); the test waits on the event, and must not depend on a fixed `waitForTimeout` as the *source* of the update (a guard timeout remains tolerated to let the broker sync, as in the existing withdrawal scenario, line 131).
- **Harness helpers required** (in `harness-ng.tsx`, exposed on `window.__testData`, and replicated in BOTH harnesses — see `bdd-testing/cookbook_add-scenario`):
- a getter for an event's reactive `participantCount` (already reachable via `__testData.events`).
- a way to reach A's **rendered** `EventDetailScreen` **without manual navigation**: either mount the real app on the detail route (the @e2e path), or expose `knownParticipants` / the anonymous count. Reuse `createEventReal` (line 232), `appJoinEvent` (line 245), `readInboxDeposits` (line 283), `authParticipationCount` (line 302).
- a "the owner has materialized" hook: since A is the owner AND connected, their inbox subscription must increment their own doc — the test observes the outcome (count 2) without driving materialization by hand.
- **Withdrawal symmetry**: extend the existing scenario « la désinscription ne ressuscite pas » (lines 36-48) with a reactive assertion: after B's leave, `participantCount` on A's side **goes back to 1 without a reload**, and `authParticipationCount === 0` (already covered).
---
## E. Risks / open questions
1. **The fan-out hang** (risk #1). The design avoids it **by construction**: **per-document** subscription (`doc_subscribe`), never `orm_start_graph(graphs:[…])`. To be kept as an invariant: every new doc enters through an **individual** subscription with per-doc error isolation — an unsynchronized doc must never be able to abort the other subscriptions nor block `readUnion` (which stays per-doc tolerant). Residual risk: the **volume** of per-doc subscriptions (one per doc read) — to be validated against the real broker; failing that, cap/prioritize the subscribed docs (current event + its inbox + my own docs) rather than the whole union.
2. **Owner-offline count = eventual — DECIDED (2026-07-06).** As long as the owner is not connected, no deposit is materialized → `participantCount` stays stale for everyone else (the participation itself is persisted broker-side — nothing is lost, only the aggregate waits for the host to reconnect). Accepted for V1. **Later, a SERVICE will take over** when the owner is disconnected (the deferred `@ng-eventually/service` package — the "curator" mentioned in the lib's inbox docs): an always-available actor will materialize the inbox in the host's stead. No « N+ en attente » fallback in V1.
3. **Per-doc `doc_subscribe` — DONE (lib `c0498a6`).** The lib now exposes `subscribeDoc`/`subscribeDocs` (per-doc error isolation, no ORM fan-out), `inbox.watch`/`discovery.watchIndex` have moved to `doc_subscribe` (no more polling), and the contract is in `sdk-reference.md`. Validated against the real broker (the callback crosses the iframe RPC and fires on change). Remaining: wire the subscription into the app's read path (P3).
> **The SDK's reactive hooks** (clarification): NextGraph's React adapter exposes `useShape` (reactive RDF shapes) and `useDiscrete` (discrete CRDT docs) — there is no `useQuery`. The lib re-exposes `useShape`. For a UNION read over N docs (Festipod's case), `useShape`/the ORM in fan-out *hangs*; the app's reactive path therefore goes through `subscribeDocs` (per-doc) + a re-`readUnion`, possibly wrapped into a reactive read hook on the lib side (to be decided in P3).
Other points to settle:
> ⚠️ **REFRAMED + CORRECTED (2026-07-13).** The claim below, "Proven by the D.2 e2e … with no reload", was **FALSE** (the "green" came from a bloated wallet). But more importantly the framing "reactive / no reload / cross-session push" was an **OVER-FRAMING**: the real spec is **"the owner reliably processes their inbox at their NEXT CONNECTION"** (not a live real-time notification between two connected users). The bug fixed under that framing: the materializer read the inbox **before it had synced** (→ a memoized 0). Fix = inbox read **gated on a barrier** (`inbox.readSynced` = `ensureRepoOpen` + `read`) + triggering on connection + a single source of truth, `event.participantCount`. The `event/e2e-multibrowser.feature` scenario was **reframed as "at the next connection" and un-`@wip`'d, GREEN on a fresh profile** (a reconnection/re-materialization by A is the accepted mechanism). Details: [[knowledge_context-internals]] §participantCount. The phasing plan below must be re-read in that light ("no reload" is no longer the requirement).
- **Phasing order:** ~~(P1) lib: `subscribeDoc` + multi-doc variant + D.1 tests~~ **DONE (`c0498a6`)**; ~~(P2) lib: replace `inbox.watch`/`discovery.watchIndex` with `doc_subscribe`~~ **DONE (`c0498a6`)**; ~~(P3) app: wire the per-doc subscription into `useNgData` (pushed bumpRead) + reactive discovery~~ **DONE, then SUPERSEDED** — P3 first wired an app-side `subscribeDocs(allReadDocs, …)` effect + a reactive discovery effect on top of the one-shot `readUnion`. That app-side wiring **no longer exists**: the read path has since moved entirely behind the SDK surface (`watchShape` bound by `useShapeQuery`), with no doc set, no `bumpRead` and no per-doc subscription left in the app (verified 2026-07-28 — see [[rule_app-uses-sdk-surface-only]] and [[rule_document-per-entity]] §Reads). **Validation — the earlier « proven by the D.2 e2e, with no reload » claim is RETRACTED**: per the REFRAMED + CORRECTED box above, that green came from a bloated wallet, and « live cross-session push with no reload » was never the spec. What `e2e-multibrowser.feature` covers is the reframed contract — **the owner reliably processes their inbox at their NEXT CONNECTION** (un-`@wip`'d, green on a fresh profile). So P3 is delivered as *the app reads through a reactive SDK surface*, **not** as *a proven reload-free live push*. ; (P4) app: Option B join (remove the participant's counter write, owner materialization); (P5) app: symmetric Option B leave; ~~(P6) e2e D.2~~ **DONE with P3** (the reactive scenario above; the reactive withdrawal symmetry remains to be added with P5). P1→P3 deliver reactivity; P4→P6 the correct counter. P1P3 can ship before P4P6.
- **Materialization idempotence**: the per-deposit `uid` (`RegistrationPayload.uid`, `registration.ts:56`) is the pivot; the (reference) recorded by the owner must be consulted before any increment/decrement so as never to double-count (sync replay) nor "resurrect" a count.
- **Native inbox migration**: today the inbox is emulated over the shared wallet (`inbox.ts` post/read RDF). On migration to the native broker inbox (`inbox_post`/`inbox_pop_for_user`, sealed), the Option B flow **remains valid** (non-member deposits allowed, reads reserved to the *readers* = the owner), but the `subscribeDoc` wrapper on the inbox will have to target the native deposit-notification mechanism. To be checked at migration time.
@@ -0,0 +1,104 @@
---
type: brief
summary: Target model for sign-ups — a Participation READABLE by everyone (event ref + `active` boolean + cap-less did to the participant's profile), deposited into the event's inbox; the creator processes the inbox, dedups on the overlay without knowing who, files the reference into a Set on the event and PURGES the cancelled ones; count = Set.size with no filtering (accepted upper bound); only connections hold the profile cap and recognize the person. Supersedes Option-B (mutated counter + plaintext userId).
---
# Brief (2026-07-20, revised 2026-07-27) — Set-based sign-ups
## The model
Laid down and refined by the PO on 2026-07-27. Everything is **keys and URLs** — no roles, no membership, no allow-list.
1. The participant creates a **Participation** object, **readable by everyone**, holding: the **reference to the event**, an **`active` boolean**, and a **cap-less did to their *protected* profile**. **Nothing else** — no description for now.
2. They deposit the **Participation's did** into the **event's inbox**.
3. The **creator** processes their inbox **automatically**, as soon as they are online.
4. They **dedup** (see below) — **without knowing who the participant is**: they hold the profile's did, not its cap.
5. They file a **reference** to the Participation into a **Set** carried by the event's document.
6. Anyone reads **`Set.size`** → the number of participants.
7. Someone **connected** to the participant holds their profile's cap, reads it, and **recognizes** the person.
**Withdrawal**: the participant sets `active` to false **on their own object**. The creator sees it when reading, and **purges** — removing the reference from the Set.
Three properties follow: **anonymous attendance by default** (even the creator cannot see who); **nobody modifies anyone else's sign-up** (only the participant holds the write key to their own object); **no plaintext `userId`** ever travels.
### The principle that holds it all together: the truth is in the object, messages are only hints
The object **controlled by the participant** is what counts. Any message — an inbox deposit, a purge notification — is only a **hint** that triggers a check, never an authority.
Consequence: **forgery becomes structurally harmless**. A fake « purge X » leads the creator to read X, find it still active, and do nothing. That is why inbox deposits **need not be signed** — which is just as well, since NextGraph does not offer that (see table).
### Why a flag rather than a deletion
A **deletion** is **not detectable** without the read key (VERIFIED: append-only, encrypted tombstone). A **readable** object carrying a **flag** transforms the problem: the cancellation no longer has to be *detected*, it is simply *read*. The blocker disappears instead of being worked around with a forgeable message.
### Why the identity pointer targets the existing profile
No need for a second document per participation: the participant's **protected profile** already plays that role, and their connections **already** hold its cap — that is the very definition of being connected. A third party sees an opaque did.
The advantage over an encrypted field inside the Participation: **adding a connection rewrites nothing**. The profile's cap is sealed to them once, durably. An encrypted field would require re-sealing to N recipients and rewriting the Participation on every new connection. *(Incidentally, an encrypted field is not a NextGraph primitive: the encryption granularity is the document, all-or-nothing.)*
## What this rests on — facts established in NextGraph
Verified by reading `nextgraph-rs`. Details and pointers live on the polyfill side (`docs/readcap-and-nuri-model.md`) — see [[rule_capture-nextgraph-findings]].
| Fact | Status | Role here |
|---|---|---|
| The **overlay** (`:v:`) is **store-scoped**, never document-scoped | VERIFIED | **The dedup key** |
| A cap-less NURI **names without granting read access** | VERIFIED | The profile's did points without disclosing |
| A cap is **sealed durably** to a recipient (no ACL re-declared) | VERIFIED | The profile's cap, sealed once to the connections |
| Without the key, blocks remain **ciphertext** | VERIFIED | The creator genuinely cannot read the profile |
| A **deletion** is **NOT** detectable without the key | VERIFIED | **Why this is a flag, not a deletion** |
| An inbox deposit is **NOT authenticated** (anonymous sealed box) | VERIFIED | **Why messages must stay hints** |
| Author signature verification **is not implemented** at runtime, and would require decrypting | VERIFIED | Rules out the « signed inbox deposit » alternative |
## The dedup: on exactly what
**Validated by the PO (2026-07-27).**
A NURI's `:v:` segment comes **not from the document** but from **its store**. And a person has a single store per scope. So **all their Participations carry the same `:v:`**, however many objects they create. That is what the creator dedups on: two references with the same `:v:` in the Set of a single event = the same person. **Without ever knowing who.**
This is the **robust** criterion — more so than the profile's did, which a participant could multiply by creating several profile documents in their store.
Design consequence: the Set is **keyed by `:v:`** — at most one reference per `:v:`. `Set.size` = the number of distinct `:v:` = the number of distinct people.
### The trade-off — a standing reservation, not to be lost
> **It lives in `app-security/`[[caveat_stable-overlay-pseudonym]]**, not here. This brief is meant to be dissolved when it graduates; the reservation must outlive it.
In short: this `:v:` is a **stable, permanent pseudonym** for the person, present in every cap-less reference to their documents. It does not say *who*, but a **single** cross-reference de-anonymizes their whole history **retroactively** — and **no way out exists** (no rotation is possible, VERIFIED). It is **the same bit of information** that makes it possible to dedup without reading and to trace from one event to the next: the two cannot be separated. Making the Participation public **increases the collection surface** for this pseudonym.
## Trade-offs deliberately accepted (PO, 2026-07-27)
- **No filtering on read.** The count is `Set.size`, **without** checking the `active` flags. We accept the **staleness risk**: a cancelled participation still counts until the creator has purged. `Set.size` is therefore an **upper bound**, exact once purged. *Rationale: keep reads simple and O(1).*
- **Purging is the creator's job.** No curator service, no catch-up by readers.
- **No description** in the Participation for now. *(To be reopened when the need arises: whatever we put there would become public.)*
- **Creator offline**: the Set does not move until they have processed their inbox. Accepted.
## What changes vs the current implementation (Option-B)
What exists today ([[brief_2026-07-06_reactive-reads-and-attendance]]) derives a `participantCount` **mutated in place** from inbox markers carrying the **plaintext `userId`**.
- **Drop the `userId`** from inbox deposits → only the **Participation's did** remains.
- **Count distinct references** (by `:v:`), no longer `userId`s.
- **The mutated `event.participantCount` goes away**, replaced by `Set.size`.
- **Identity resolution** now goes through **reading the profile** (hence through its cap), no longer through the marker.
- **Withdrawal stops being a deletion** → `active` set to false + a purge by the creator. See [[caveat_participation-deletion]], whose requirement (« authoritative, must not come back ») still holds but changes mechanism.
Still valid as-is: **reactive reads**, **re-arming on reconnection**, and the **id-space fix** already shipped.
## Open points
- **Participation scope** — it becomes **public**, whereas current product doctrine places it in *protected* ([[knowledge_data-scopes-and-discovery]], concept `functional-domain`). That leaf describes **what is implemented**: do not change it until this brief has graduated, but **do update it at that point**.
- **Recognition by connections** (step 7) — how the profile's cap gets sealed, and what happens to a broken connection (revocation is a coarse, non-retroactive re-key). Explicitly deferred to a second stage.
- **Public reads are not recursive** — this is the principle the whole model rests on, and it deserves to be stated on its own: *an item in the **public** store is public — whoever has the URL reads the content.* But **not recursively**: public content may **reference** private content, and **that is exactly our case**. So the creator reads the Participation (public) and **cannot** follow the reference to the profile (protected). That is what yields both readability by the creator and anonymity towards them — with no additional mechanism.
## Dependencies
- **Blocking**: the **polyfill's caps emulation**. Today `caps.ts` models an **ACL** (a set of principals per document) where the reality is **key possession**, and the content stays readable in plaintext (`sparqlQuery` and `inbox.read` bypass the filter). Until that is fixed, coding anonymity on the Festipod side would produce code that **claims** to isolate without isolating. Polyfill brief `2026-07-20-caps-emulation-alignment`, batch P1.
- **Parked**: **identity terminology** (wallet / user / profile) — see `.project/to-discuss.md`.
## Status: model settled, implementation gated
The model is **settled** (PO, 2026-07-27) and its foundations are **verified**. What remains gated is the **implementation**: it is waiting on the polyfill's P1 batch. **Do not remove Option-B** in the meantime.
Links: [[brief_2026-07-06_reactive-reads-and-attendance]] (superseded), [[caveat_participation-deletion]], [[rule_capture-nextgraph-findings]], [[rule_document-per-entity]], app-security ([[caveat_stable-overlay-pseudonym]], [[brief_2026-05-18_authorization-matrix]], [[knowledge_trust-model]]), polyfill `readcap-and-nuri-model.md` + `docs/vision.md`.
@@ -0,0 +1,17 @@
---
type: caveat
summary: The FpEventData type and the seed carry startDate/endDate/startTime/endTime/themes, but the Event SHEX does not define them — these fields are silently lost in connected mode (NextGraph)
last_checked: 2026-06-15
---
# Caveat: event fields not persisted in connected mode
The app type `FpEventData` (`src/shared/data/types.ts`) and the seed (`seedData.ts`) carry the fields **`startDate`, `endDate`, `startTime`, `endTime`, `themes`** — but the **SHEX `Event` shape** (`src/shared/shapes/shex/festipodShapes.shex`) does **not** define them. The shape only covers: `title, description, date, location, distance, participantCount, coverImage, hostName, hostInitials` (to be checked in the `.shex`).
## Consequence
In **connected mode** (SDK), the mapping (`mapEvent` in `FestipodDataContext.tsx`) only reads/writes the shape's fields. Fields outside the shape are **silently lost**: filled with defaults, or empty. Yet screens **do display them** (e.g. `startTime`/`endTime` in `EventDetailScreen`) — so in demo mode (the local seed) they show up, but when connected they vanish. The discrepancy is only observable in actual use.
## To fix it (if we want them persisted)
Add the fields to `festipodShapes.shex`, then `bun run build:orm`, and extend `mapEvent`. Until that is done, **do not rely on the date/time/theme fields in connected mode**.
@@ -0,0 +1,15 @@
---
type: caveat
summary: Withdrawing from a meeting point must be AUTHORITATIVE — once the Participation is deleted, it must not come back; after a real refresh, check that the sign-up is really gone on the data side
last_checked: 2026-07-03
---
# Caveat: withdrawal must be authoritative
Business contract: when a user **withdraws** from a meeting point (`leaveEvent` in `src/shared/context/FestipodDataContext.tsx`), the `Participation` must be **durably deleted**. It must **not come back to life** after a resynchronization.
## The pitfall
Reflecting the deletion only in the UI's reactive state is not enough: the sign-up can reappear if the deletion is not **persisted** on the data side. Withdrawal must therefore be **authoritative at the document level**, not merely at the display level.
**To check after any change to `leaveEvent`**: sign up, then withdraw, do a **real refresh**, and confirm that the participation is indeed gone (the button must not stay on « ✓ Je participe »). Covered by the `@e2e` scenario « Se désinscrire d'un événement » (`src/modules/event/features/cycle-de-vie-evenement.feature`) and a `@data` one, « désinscription persistante » (`inscription-inbox.feature`).
@@ -0,0 +1,17 @@
---
type: caveat
summary: An entity written just before an idle period / socket drop can be silently lost (never made durable broker-side); the account survives (no fork). Observed on Firefox. The SDK neither confirms durability nor reconnects on its own.
last_checked: 2026-07-14
---
# Pitfall: a write made just before a disconnect is not guaranteed durable
**Product symptom.** The user creates an entity (an event), it appears to succeed, then a **period of inactivity** follows; on reload / reconnection, the entity has **disappeared**. The scope reads back **empty**. The **identity/account survives** — this is NOT a fork, it is a write that was never made durable.
**Mechanism (summary, not settled).** The broker socket can die spontaneously while idle (`SOCKET IS CLOSED … SerializationError`). The write was in the local outbox; on return, the replay fails (`Err(TopicNotFound)`) and the entity is abandoned. **Observed on Firefox only** so far. A cold @data test (2026-07-14) also showed that a **fresh** session (no local state, same account A) does **not** recover A's own scope from the broker: the @data reconnection test that "passed" was in fact re-reading the **local** IndexedDB. Still to be settled: **loss at write time** vs **failure to rehydrate from cold** (two distinct mechanisms) — see the post-mortem in the polyfill.
**Why the app does not see it.** `NgStatus` is derived from the initial session **exactly once** → blind to drops that happen mid-session. The SDK's `disconnections_subscribe` channel does fire on the failure but **is not consumed** (neither by the polyfill nor by the app). No API confirms that a write reached the broker.
**Do not document NextGraph internals here.** SDK boundary (see [[knowledge_nextgraph-stack]]): the root cause, the causal chain (socket, reconnection still TODO) and the fix leads live in the `@ng-eventually/client` repo → `docs/incidents/2026-07-14-write-loss-on-disconnect.md`. This note keeps only the **consumer-side impact** + the pointer.
**Status: open, not addressed (2026-07-14).** To revisit when the core/SDK addresses reconnection or exposes a durability confirmation — this caveat will then fall away. See also the cold-read vs real-loss debate in [[brief_2026-07-06_reactive-reads-and-attendance]] (@data's `BARRIER timed-out` is a distinct signature, not confirmed to be this bug).
@@ -0,0 +1,98 @@
---
type: knowledge
summary: Internal pitfalls of FestipodDataContext — currentUserId = a stable principal derived from the identifier, TWO id spaces joined through the normalized identifier (resolveParticipantUser / USER_PRINCIPAL_PREFIX), OPT-IN auto-seed (FESTIPOD_AUTO_SEED, OFF by default), Option-B derived participantCount (reliable at the owner's connection because it reads under the synced-view contract; single source = event.participantCount), session reset on identity change (overlay + caps), useShapeQuery instrumentation (spinner + timing) + identity-first logs, mutations that are no-ops in local mode despite the toast
last_checked: 2026-07-27
---
# Internals & pitfalls of `FestipodDataContext`
Non-obvious behaviours of `src/shared/context/FestipodDataContext.tsx` to know about before touching the data context.
## Resolving `currentUser` (NG mode)
In connected mode, the currentUser's **principal** (`currentUserId`) is **not** `CURRENT_USER_ID` ('user-1', local mode), nor the IRI of the profile that was read. When an identifier is logged in, it is an id **derived from that identifier and stable**: `urn:festipod:user:<normalized-identifier>`, available immediately (without depending on reading the protected profile) and invariant for the session — the same key used by `setCurrentUser`, the owner cap and the shim account (see [[rule_document-per-entity]], identity corollary). Remaining pitfalls:
- The `currentUser` object (the displayed profile), by contrast, is resolved by `users.find(u => normalizeIdentifier(u.username) === identifiant)` with a **fallback** to `@mariedupont` then `users[0]` — a silent fallback if the identifier matches no profile (the identifier is a space id, not necessarily the `username` of a seeded profile).
- With no identifier logged in (dev/demo), `currentUserId` falls back to the IRI of the profile that was read (or `''` if the wallet is empty → a `Participation` with `user: ''`, which is invalid): only create a participation once the principal is resolved.
## TWO id spaces meet — joining a participation to its profile
**Invariant.** A `Participation` stores its user as a **principal** (`urn:festipod:user:<normalized-identifier>`, = `currentUserId`), whereas a `UserProfile` has as its `id` the **NURI of its document** (`did:ng:…`). In connected mode, **these two values are never equal**. So a raw `participation.userId === profile.id` join **never** matches — a symptom that shipped and was then fixed (2026-07-27): every participant displayed as « participant inconnu ». Every participation→profile join goes through **`resolveParticipantUser`** (`FestipodDataContext`), never through a direct comparison.
The **bridge** between the two spaces is the **normalized identifier**: `principal prefix` == `normalizeIdentifier(profile.username)` (the same equality that resolves `currentUser`). Hence the order in which `resolveParticipantUser` tries: (1) a **direct match** `u.id === userId` — the demo seed's space, where both sides hold the same bare id (`user-1`) and where the seeded username `@mariedupont` would *not* normalize to that id, so the direct match must come first; (2) failing that, a **match on the normalized identifier** after stripping the prefix.
**`USER_PRINCIPAL_PREFIX` is the single source of the prefix**, shared by the **write** side (deriving `currentUserId`) and the **read** side (`resolveParticipantUser`). If you change the shape of the principal, change it **there**: otherwise write and read drift apart silently and the join falls back to « inconnu » without raising an error.
A **third** id space exists and takes **no** part in this join: the inbox deposit `uid` (`mint…`) — it identifies a **deposit** for the counter, never a user.
> **Horizon.** This paragraph describes **what is implemented** (Option-B). The target model drops the plaintext `userId` and routes identity resolution through **reading the profile** — see [[brief_2026-07-20_attendance-set-model]], whose implementation is gated. The id-space fix is explicitly noted there as **still valid**: do not undo it in anticipation of the target.
### Which space each query expects (the `buildQueries` contract)
| Query | What it expects / returns |
|---|---|
| `getUserEvents(userId)`, `isParticipating(eventId, userId?)`, `getFriends(userId?)` | **expect the principal** (they filter on `participation.userId` / `friendship.userId`) — their default is `currentUserId`, which is correct |
| `getEventParticipants(eventId)` | **returns profiles** (`FpUserData``id` = NURI), the join being done internally |
**Screen-side impact**: filtering yourself out of a participant list compares against **`currentUser?.id`** (the profile NURI, the same space as the rendered items), **not** against `currentUserId` (the principal) — otherwise you do not remove yourself and you see yourself appear as one more participant. Conversely, passing a **profile id** to `getUserEvents`/`isParticipating` returns an **empty** list in connected mode. See `app-architecture`, [[caveat_identity-ids-in-screens]].
## Reads = `watchShape` (the SDK surface), no more bespoke machinery
**Since 2026-07-10**: `useNgData` reads through `useShapeQuery(shape, scope)` (a `useSyncExternalStore` binding over the polyfill's `watchShape`) — THREE useQuery-shaped reads (events/public, users/protected, participations/protected) + Fp adapters (`shapeAdapters.ts`). Removed: `readEntities`, `subscribeDocs`+`bumpRead`+`readTick`, the manual listing (`publicDocs`/`protectedDocs`/`registerDoc` for reads), and `relist`. `ready` = the combination of the `isSuccess` flags. See [[rule_app-uses-sdk-surface-only]].
**Immediate visibility of mutations = an OPTIMISTIC overlay** (no `registerDoc`): `createEvent`/`joinEvent`/`leaveEvent` feed `pendingAddEvents`/`pendingAddParticipations`/`pendingRemoveIds`; the exposed state = merge(reactive, adds) minus removes, deduped by id (id = the doc's NURI). Reconciliation happens automatically on push (an add that shows up in the reactive state, or a remove that disappears from it, is dropped) — never a poll ([[rule_no-broker-polling]]). Cleared on identity change.
## Dev auto-seed
**Since 2026-07-13 the auto-seed is OPT-IN and OFF by default**: it only fires if the `FESTIPOD_AUTO_SEED` env var is set (`=1`), no longer off `NODE_ENV`. Var absent → **no automatic seed at all**, even in dev (`autoSeedEnabled()`/`shouldAutoSeed()`, `src/shared/utils/autoSeed.ts`; delivered in dev through the `/festipod-config.json` runtime route + a compile-time `define` in `build.ts`, the same mechanism as the shared wallet — see `tech-stack/knowledge_build-pipeline`). The **explicit** seed (`loadTestData()`, @data tests) is unchanged. Rationale: the repeated auto-seed was bloating the wallet (slow reads, see [[caveat_wallet-bloat-hang]]).
When it is enabled, the auto-seed fires if events AND users are both empty — **gated on `isSuccess`** (`watchShape`'s readiness), NO LONGER on a 3s `setTimeout`: we only decide "the wallet is empty" once the sync is **confirmed** (`isSuccess`), otherwise a not-yet-finished read was taken for an empty wallet → a re-seed on every reconnection (bug fixed). Remaining pitfalls:
- **One seed at a time**: `loadTestData()` sets `hasTriedAutoSeed`, and the auto-seed re-checks it → an explicit load cancels the pending auto-seed (otherwise two concurrent `bootstrapWallet` calls write everything twice).
- The seed is **owned by the current identity** (`bootstrapWallet(…, owner)`): the seeded protected entities go through the owner's per-document read cap.
- **No retry**: if the seed fails, you get an empty screen + a `console.error`.
## `participantCount` — derived and owned by the owner (Option B)
> ✅ **CORRECTED (2026-07-13).** The requirement is **"reliable at the owner's NEXT CONNECTION"** (the creator processes their inbox when they connect), NOT a live real-time cross-user notification. The bug was: the owner-materializer materialized **too early** (before the participant's deposit had synced) → read `active=0` → wrote 0 → **memoized that 0** → never re-processed. Fix: (1) read under the **synced-view contract** — `inbox.readSynced` instead of `inbox.read`, so a deposit already synced by another identity IS seen from a cold session (the two differ by contract, see [[knowledge_sdk-surface]]); (2) the materializer fires **directly on connection** (`[ready, ownedKey]`), no longer only on a push; (3) `materializedCountRef` no longer locks in a premature 0 (its sole role = loop guard: only write when the derived value changes); (4) **the single source of the NUMBER = `event.participantCount`** (the `participantCount: 1` literal in `CreateEventScreen` is removed → it starts at 0; the display no longer computes a local number). Kept GREEN (on a fresh profile) by `event/e2e-multibrowser.feature` « Le compteur converge chez le propriétaire à sa prochaine connexion » (un-`@wip`'d). No polling ([[rule_no-broker-polling]]).
**Since Option B (2026-07-07)**: `participantCount` is no longer mutated in place by the participant. The flow is inbox-deposit → owner-materialization:
- `joinEvent`/`leaveEvent` **no longer** write `participantCount` on the event's doc (that would be an isolation violation — the participant writing someone else's doc; NextGraph writes are membership-bound, with no append). The participant only writes their **own** participation doc (protected), then **deposits** a marker into the event's inbox (`depositRegistration` on join, `depositLeave` on leave, `src/shared/data/registration.ts`).
- The event **owner's** session does the materializing: it is subscribed (`inbox.watch`, `doc_subscribe`, no polling) to the inbox of the events it owns (`ownedEventIds` = `listMyEntityDocs(owner,'public')` + freshly created events), and on every deposit it **recomputes** `participantCount` on **its own** event doc (`updateEntityField` on its own doc). It is the counter's only writer.
- **The counter is DERIVED, not incremented**: `materializeAttendance` (registration.ts) reads the inbox and computes the **set** of distinct active sign-ups (`new-participant` deposits deduped by `uid`, MINUS those cancelled by a `leave-participant` — by exact `regUid` or by the `(eventId, userId)` fallback). `participantCount = |active set|`**no host baseline**: the creator does not attend automatically (there is no notion of host, see concept `functional-domain`), so the counter starts at **0** on creation and only moves on real sign-ups. `createEvent` **no longer writes** a participation at creation time (it used to write a host participation and set the counter to 1); the creator sees « J'y serai » and can join/leave their own event like anyone else. Because it is a **pure function of the inbox**, a broker sync replay converges — never double-counting nor a phantom decrement (idempotence). The write is guarded (it only writes when the value changes), a loop guard. Covered by the `@data` scenario « Le créateur ne participe pas automatiquement à son événement » (us-13): counter 0 + `isParticipating(E)===false` at creation, then join→true / leave→false.
- **Owner offline = eventual**: only the owner's session materializes; while they are disconnected, the counter does not move for anyone else (the participations/deposits stay persisted — nothing is lost; a future service will materialize in their stead).
- The counter nevertheless remains an **aggregate**, not the list of named participants: `getEventParticipants` (named identity) is still governed by the protected read cap ([[caveat_participation-deletion]] for the authoritative deletion, unchanged). See the brief `brief_2026-07-06_reactive-reads-and-attendance` §B.
### Id-form invariant: match on the CANONICAL form of the event id
An event's `@id` **is** its document NURI (`did:ng:o:<repo>[:v:<overlay>]`). The owner's materializer matches the inbox **deposits** to the owned events **by event id**: `ownedEventIds` (what the materializer iterates over), the **deposit key** (`payload.eventId`, what the participant deposits under) and the counter's **write target** must all designate the same event.
**Measured finding (2026-07-07)**: on the current tree these three paths carry the **same** NURI (the `:v:<overlay>` suffix included) — create-time, `listMyEntityDocs` and the `@id` read back all coincide, because `readUnion` **pins the subject to the input NURI** (lib `read-model.ts`, `63ecfee`). So matching already works, **including** for an owned event reached through `listMyEntityDocs` (validated by the @data scenario « …fait converger le compteur dérivé »). The canonicalization below is **defensive**, not the fix for an active bug. (The mismatch one investigation thought it had seen was the **seeded-but-not-owned** artifact: on a persistent wallet, the seed belonged to a `test-*` identity from an earlier run → the current session reaches it through discovery, not through `ownedEventIds` — correct behaviour.)
**Rule**: match the event id on its **canonical form** — the base repo id, with any `:v:<overlay>` suffix stripped (`canonicalEventId`, `src/shared/data/registration.ts`). This canonical form is used for **matching** in `materializeAttendance` / `readRegistrationNotifications`, and for **deduplicating** `ownedEventIds` (`ownedKey`, FestipodDataContext) so that one and the same event reached through two paths is not materialized twice. **Careful**: only the **matching** uses the stripped form; the counter is always **written** to the real owned NURI (a live, openable doc) — a stripped id must never serve as a write target or an anchor. This is an **app-side** invariant (not a NextGraph detail): however the lib makes the overlay vary, the app matches on the common base.
## Identity change = a fresh session (isolation)
> **History of the symptom** (the paragraph that follows describes the setup of the time — the bespoke read set `publicDocs`/`protectedDocs`/`readTick` **no longer exists** since the move to `watchShape`). It is kept because it explains *why* the reset rule exists; the **current mechanism** is described further down.
The on-demand read set (`publicDocs`/`protectedDocs`) **accumulated** the current identity's scope docs (so as not to lose a just-created doc before the re-listing). But the shared-wallet stopgap keeps **a single React tree** across a fake logout + re-login under a **different identifier** (no page reload — `AccountContext.login` merely rewrites the identifier in localStorage, and `AuthGate` remounts nothing). Without a reset, **the previous identity's PROTECTED docs (its participations) survive in the new identity's read set and leak** through the union read: the cap gate cannot filter them out when the (in-memory) cap registry does not govern that doc in *this* session (a doc persisted from an earlier run, or a fresh load where the caps are empty). Symptom observed: a user B saw A's participation (and A's event appeared on B's **home screen**, since home = `getUserEvents(currentUserId)`, see concept `app-architecture`).
**Rule**: treat **any identifier change** as a **fresh session**. A `useEffect([identifier])`, **ref-guarded** (it does not fire on first mount, only on a genuine value change), resets **all session state carried by the app**. Isolation remains per-document/emulated (concept `app-security`, [[knowledge_trust-model]]); this reset only removes the carry-over of state between identities.
**Current mechanism** (since reads go through `watchShape`): the **read** side has nothing left to reset — `watchShape` re-resolves its scope against the new `getCurrentUser()` on the next push. What the effect clears is the **app-side** state: `ownedEventIds` (the owner materializer's set), the `joinUids` map (the current session's deposit uids), the **optimistic overlay** (`pendingAddEvents`/`pendingAddParticipations`/`pendingRemoveIds` — otherwise the old identity's mutations bleed into the new one's reads), then `resetCaps()` + `resetRegistryCache()`.
> **Impact — the invariant not to break**: **any new session state** added to the provider (a cache, a `useRef`, the overlay, a doc set) must be added to that effect. Forgotten state **leaks from one identity to the next** with no error — exactly the class of bug the regression guard below covers.
**Mechanism confirmed empirically (2026-07-07)**: the leak reproduces ONLY when TWO conditions coincide — (a) the read set still carries A's PROTECTED doc across the switch (no reset), AND (b) the in-memory cap registry does not govern that doc (`resetCaps()` already fired / caps empty for a doc persisted from a session earlier than the reload). Then A's participation makes it through B's union read (the per-document filter has no cap to check). With the reset fired, A's doc left B's read set BEFORE the cap-less read could expose it → no more leak whatever the state of the caps (at the time via `setProtectedDocs([])`; today it is `watchShape` that re-resolves the scope, and the reset now carries only the app-side state listed above). **Regression guarded** by the `@data` scenario « Une identité fraîche ne voit pas la participation d'une autre » (event/isolation-deux-identites.feature): A creates E and signs up to it, B (a fresh page on the same wallet, with a distinct identifier) has NEITHER E on their home screen (`getUserEvents(B)`), NOR `isParticipating(E,B)`, AND reads NO participation carrying A's principal. The historical symptom « B voit "Je participe" » mostly occurred when B **reused an identifier already used by A** (the same normalized principal) on a **bloated** wallet (docs persisted from an earlier run, empty caps).
## `useShapeQuery` instrumentation — global spinner + timing
`useShapeQuery` (a `useSyncExternalStore` binding over `watchShape`) instruments **every query cycle**: at the start of a cycle it registers itself in a module-level store `src/shared/data/pendingQueries.ts` (`beginQuery`/`resolveQuery`, a Set of ids — idempotent, safe under StrictMode), and on the first `isPending → isSuccess|isError` transition (the "first result", the readPromise equivalent) it resolves AND logs the delay: `[FestipodData] <shape>/<scope> premier résultat en <N>ms (n=<len>)` (so the delay for Event/public events is visible by name). The `cycleId` is memoized on `[shapeKey, scope]` → an identity/scope switch recreates the observable AND starts a new cycle (a fresh `beginQuery`), and the cleanup resolves on unmount (never stuck). The `usePendingQueries()` hook exposes the number of pending queries; `HomeScreen` renders a `Spinner` (sketchy, `.app-spinner` + `@keyframes app-spin` in `index.css`) next to the « Festipod » title as long as the count is > 0 → it only stops once **all** in-flight queries have received their first result. Any future `useShapeQuery` contributes to it automatically. The measurement lives on the app side (React-perceived delay), **not** in the polyfill.
## Logging convention — identity-first prefix, and counter before→after
Every DATA log from the provider goes through **`logPrefix`**: `[<currentUserId>][app][data]` when the principal is resolved, `[app][data]` otherwise (a transient connection state). Reason: with the shared wallet, **two identities share the same console** (two tabs / a multi-browser run) — an unprefixed line does not say *whose* it is and becomes useless for diagnosing a leak or a stuck counter. **Adding a DATA log = reusing `logPrefix`**, not a bare `console.log`.
Two measurement points are laid down **as a pair** and serve together: the owner's materializer logs `participantCount` **before → after** its write, and the display read logs the value **as exposed to the render**. Comparing them tells a stuck counter apart between a **DATA** problem (never incremented) and a **DISPLAY** problem (incremented but not re-read until the next session). Do not remove one without the other — on their own they diagnose nothing.
## Mutations are no-ops in local mode
In local/demo mode (`useLocalData`), `createEvent`/`joinEvent`/`leaveEvent`/`updateEvent` are **no-ops** (a `console.log`, the state does not change) — yet the screens still show a **success toast** (« Tu participes »). Potentially misleading UX: the user believes they signed up when nothing has changed. See [[knowledge_data-modes]] for how the provider is chosen based on status.
@@ -0,0 +1,28 @@
---
type: knowledge
summary: Two modes (connected = the @ng-eventually/client SDK, disconnected/demo = seeded local state); FestipodDataContext picks the provider based on connection status, and every screen goes through useFestipodData()
---
# Data modes & contexts
The app has **two modes**, both consumed through the `useFestipodData()` hook:
1. **Connected** — ORM shapes from the `@ng-eventually/client` SDK (P2P, encrypted, local-first)
2. **Disconnected / Demo** — local React state seeded from `seedData.ts` (see [[knowledge_seed-data]])
## NextGraphContext (`src/shared/context/NextGraphContext.tsx`)
- Connection cycle: `disconnected``connecting``connected` | `error`.
- Provides the session (the current user and their access to the per-scope stores).
## FestipodDataContext (`src/shared/context/FestipodDataContext.tsx`)
- Reads the shapes reactively through **`useShapeQuery()`** (`src/shared/data/useShapeQuery.ts`), the app's React binding over the SDK's `watchShape(shape, scope)` observable — three scoped reads: events (`public`), profiles and participations (`protected`), mapped to the `Fp*` domain types by `shapeAdapters.ts` (see [[rule_document-per-entity]] §Reads). There is no `useShapeWithDefaults` — that name is obsolete (verified 2026-07-28).
- Exposes `useFestipodData()` (consumed by every screen) + CRUD (`createEvent`, `updateEvent`, `joinEvent`, `leaveEvent`, etc.).
- **Provider chosen by connection status**:
- `disconnected``LocalDataProvider` with the seed (demo)
- `connecting` → an **empty** `LocalDataProvider` (avoids flashing the seed before the wallet loads)
- `connected``NgDataProvider` (real wallet data)
- `error``LocalDataProvider` with the seed (graceful fallback)
> Mutations are **genuinely persisted** in connected mode (`joinEvent` writes a Participation and notifies the meeting point's host, `leaveEvent` deletes authoritatively — see [[caveat_participation-deletion]]). In local/demo mode they are no-ops (see [[knowledge_context-internals]]).
@@ -0,0 +1,24 @@
---
type: knowledge
summary: The Fp* data types — Event, UserProfile, Participation, MeetingPoint and Notification are persisted in NextGraph (SHEX shapes + ORM); only Friendship stays local-only (app-TS)
last_checked: 2026-07-03
---
# Data entities
`src/shared/data/types.ts`:
| Type | Persistence | Key fields |
|---|---|---|
| `FpEventData` | SDK (Event shape) | id, title, date, location, distance, themes |
| `FpUserData` | SDK (UserProfile shape) | id, name, username, bio, city, counts |
| `FpParticipationData` | SDK (Participation shape) | eventId + userId + confirmed |
| `FpMeetingPointData` | SDK (MeetingPoint shape) | eventId, location, time, host |
| `FpNotificationData` | SDK (Notification shape) | kind, target, source |
| `FpFriendshipData` | **local-only** | userId + friendId |
`MeetingPoint` and `Notification` do have real **SHEX shapes** (`src/shared/shapes/shex/festipodShapes.shex`) with generated ORM bindings (`festipodShapes.shapeTypes.ts`: `FpMeetingPointShapeType`, `FpNotificationShapeType`) and **are persisted**. A `Notification` is created in particular when signing up to a meeting point (`joinEvent`).
`Friendship` has **no** SHEX shape and no persistence — it stays app-TS-only (see [[knowledge_nextgraph-stack]]).
> Pitfall: even for `FpEvent` (which is persisted), several fields of the app type are **not** in the shape and are lost when connected — see [[caveat_event-fields-not-persisted]].
@@ -0,0 +1,36 @@
---
type: knowledge
summary: The data SDK is @ng-eventually/client (treated as a finished NextGraph SDK) — injected exactly once through ngSession.configure; reactive useShape ORM over the festipodShapes SHEX shapes, bindings regenerated with build:orm; never document NextGraph's current state here
---
# Data stack (the `@ng-eventually/client` SDK)
Festipod persists through **`@ng-eventually/client`** — the NextGraph SDK the app consumes. We treat it as a **finished, mature SDK**: documents per entity placed by scope, capabilities, inboxes, a reactive ORM.
> **It is a polyfill, and that word carries its whole job**: closing the gap between the SDK **as it should be** and what NextGraph provides **today**. The app codes against the target and **ignores the current state entirely**; the polyfill absorbs the difference. The contract itself — which surfaces exist and what may be assumed of them — is written down in this repo: [[knowledge_sdk-surface]]. See [[rule_app-uses-sdk-surface-only]].
```
@ng-eventually/client # THE app's data SDK (reactive useShape ORM, docs, scopes, inbox)
```
## SDK boundary (the golden rule)
- The app **depends on `@ng-eventually/client` only** for data.
- The SDK is **initialized/injected exactly once** through `ngSession.configure(...)` (`src/shared/utils/ngSession.ts`) — a single injection point. Everything else in the app (data plane, lifecycle, login, types) goes through the lib.
- **Never document NextGraph's current state in this repo** (constraints of the underlying SDK, workarounds, broker/verifier internals): that lives in the `@ng-eventually/client` repo. Here we describe only **how Festipod uses that SDK**.
## ORM & SHEX shapes
The reactive ORM (`useShape`) is built on **SHEX shapes**: `src/shared/shapes/shex/festipodShapes.shex` defines:
- **Event** — title, description, dates, location, themes, participants
- **UserProfile** — name, username, bio, city, visibility
- **Participation** — links an event and a user, confirmation status
- **MeetingPoint** — a meeting point (location, time, host)
- **Notification** — a notification (created in particular when signing up to a meeting point)
The ORM bindings are generated in `src/shared/shapes/orm/` (`*.schema.ts`, `*.shapeTypes.ts`, `*.typings.ts`). **Regenerate** with `bun run build:orm` after any `.shex` change.
> **Recommended way to read = the SDK's reactive hook.** The canonical way to read is `useShape`: you subscribe to a shape on a scope, you get the current value, and the component re-renders on every change (local **or** remote once synchronized) — subscription/push, never polling; one-shot reads are the exception. The SDK's full reference (read/reactivity contract + where the current emulation still diverges) lives on the lib side: `packages/client/docs/sdk-reference.md` in `@ng-eventually/client`. Do not copy NextGraph internals here.
> `Friendship` has **no** SHEX shape and no persistence — it stays app-TS-only (see [[knowledge_entities]]).
@@ -0,0 +1,95 @@
---
type: knowledge
summary: The `@ng-eventually/client` contract Festipod is written against, as a FINISHED NextGraph SDK — reactive reads (`watchShape`, `useShape`), document writes (`docs`), per-scope placement (`storeRegistry`), `inbox`, `discovery`, capabilities (`capFor` / `inbox.shareCap` / `publishRepoLink`), identity — with what the app MAY and MAY NOT assume of each, so no agent ever needs to open the SDK's own repo.
---
# The SDK surface Festipod codes against
This is Festipod's **data contract**: what `@ng-eventually/client` offers, and what the app is entitled to rely on. It describes the SDK **as it should be** — a finished NextGraph SDK — because that is what the app is written against ([[rule_app-uses-sdk-surface-only]]). It says **nothing** about NextGraph's or the package's implementation state, on purpose: the app ignores that entirely, and any gap is the package's to absorb, never the app's.
Everything below is exported from the SDK entry `@ng-eventually/client`, **except** the few items explicitly marked `/polyfill` — the bootstrap subpath `@ng-eventually/client/polyfill`, the one part that disappears at migration. Injection happens exactly once, in `ngSession` ([[knowledge_nextgraph-stack]]).
## Reactive reads — the canonical path
**`watchShape(shapeType, scope) -> ShapeObservable`** — the read Festipod uses. It observes one SHEX shape over one **logical scope** (`'public' | 'protected' | 'private'`) and yields a `useQuery`-shaped snapshot: `{ data, isPending, isSuccess, isError, error }`. Bind it with `useSyncExternalStore` (`src/shared/data/useShapeQuery.ts`).
May assume:
- `data` is **always an array**, never `undefined`; its items are `UnionSubject` (`{ subject, graph, props }`) — raw per-subject property bags, mapped to `Fp*` types by `src/shared/data/shapeAdapters.ts` ([[knowledge_entities]]).
- `isPending` and `isSuccess` are **mutually exclusive**, and a synchronized-but-empty scope is `isSuccess` with `data: []` — the distinction the surface exists for. Never guess emptiness with a timer.
- The snapshot reference is **stable** until the value actually changes (safe for `useSyncExternalStore`).
- Reactivity is **push**: the snapshot updates on any change in scope, local or remote, and on any change to what the current identity may read. Never polling.
- The observable is **inert until first `subscribe()`** (or `refetch()`); the last unsubscribe tears everything down. `refetch()` forces a re-resolve and is idempotent w.r.t. subscriptions.
- `isError` fires **only** on a real thrown exception, never on a slow or absent peer.
**`useShape(shapeType, scope) -> DeepSignalSet<T>`** — the ORM hook, for **one already-known document NURI** as scope. Returns a live reactive set that re-renders on every change. Festipod uses it in the `@data` harness; screens go through `watchShape`.
May not assume: any ordering of `data`; that a value seen once stays; that a document the identity holds no capability for will ever appear (it silently does not).
## Writes — one document at a time
**`docs.docCreate(sessionId, crdt, cls, dest, store?)`** creates one document and returns its NURI. **`docs.sparqlUpdate(sessionId, query, anchor)`** writes into it: a SPARQL `INSERT`/`DELETE` scoped to the **anchor document's** graph. **`docs.sparqlQuery(sessionId, query, base?, anchor?)`** is the one-shot, non-reactive read.
May assume:
- One document = one repo = one entity ([[rule_document-per-entity]]); a write is a change on that document, and every observer of it is pushed.
- A write **targets exactly one document**. There is no "write to the union", and no primitive by which a non-owner appends to someone else's document — surfacing data to another identity goes through the **inbox**, or through each identity owning its own document.
May not assume: that `sparqlQuery` is reactive (it is a snapshot — to stay live, use `watchShape`); that an unanchored update means anything.
## Placement by scope — `storeRegistry`
**`storeRegistry.createEntityDoc(id, scope)`** — create the entity's own document in the right scope, and record it as the identity's. **`storeRegistry.listEntityDocs(scope)`** / **`listMyEntityDocs(id, scope)`** enumerate documents in a scope, all or mine. **`resolveWriteGraph(id, scope)`**, **`resolveScopeGraph(scope)`**, **`resolveReadGraphs(scope)`**, **`resolveInboxAnchor()`** resolve the NURIs a call needs. **`ensureAccount(id)`**, **`resolveAccount(id)`**, **`allAccounts()`** yield `AccountRecord`s (`{ id, docPublic, docProtected, docPrivate }`).
Festipod's own glue (`src/shared/utils/storeRegistry.ts`) adds only the **domain mapping** entity kind → scope; placement itself belongs to the SDK.
May assume: the SDK owns NURI construction and placement. May not assume: that the app may build a NURI by hand, or read/write a scope's container document directly.
## Inbox — delivery to an identity
**`inbox.post(targetInbox, { payload, from?, ts? })`** deposits into a document's inbox. `from` omitted defaults to the current identity; **`from: null` is an explicit anonymous deposit**, and naming another identity is rejected as a spoof. **`inbox.read(targetInbox)`** returns every `Deposit` (`{ from, payload, ts }`) sorted by ascending `ts`. **`inbox.watch(targetInbox, onDeposits)`** fires once on the initial state and again on every change; it returns an unsubscribe. **`inbox.readSynced`** is the same read under a stronger contract: it returns once the deposits synced to that inbox are visible, where `read` returns what is known locally right now. **Choose by need, not by habit**: `read` inside a session already watching the inbox, `readSynced` whenever correctness depends on a cold session seeing another identity's deposit. `inbox.materialize` is an alias of `read`.
May assume:
- **Any identity — even anonymous — can deposit** into an inbox it knows. That is the only way data reaches an identity that cannot write your documents. See [[rule_nextgraph-inbox]].
- `watch` is **push, never polling**; its `intervalMs` option exists for signature compatibility and is ignored.
- `payload` is **opaque to the SDK** — Festipod defines its own kinds (`src/shared/data/registration.ts`).
May not assume: exactly-once delivery semantics, or that a deposit is removed once read.
## Discovery — the global index
**`discovery.submitToIndex(ref, opts?)`** makes a reference discoverable; `SubmitOptions.from` follows the same identified/anonymous rule as `inbox.post`, and `SubmitOptions.doc` names the document being announced. **`discovery.readIndex()`** returns `IndexEntry[]` (`{ ref, from, ts }`, deduplicated). **`discovery.watchIndex(onEntries)`** is the push-based observer.
May assume: the index admits a document only if it was **published** as a repo link — announcing something past the reach you chose for it is refused. May not assume: that `ref` means anything to the SDK (it is app-defined), or that being indexed grants any read.
## Capabilities — reading is key possession
The model has **no authorization list**. You hold a document's `ReadCap` (a NURI carrying a `:k:` segment) and you read it, or you do not. A bare `Nuri` **names** a document without granting anything.
- **`capFor(nuri): ReadCap | undefined`** (`/polyfill`, also `getCaps().capFor`) — do I hold this document's key? Nothing derives a key from a bare reference; it is either in your keyring because you created the document, or it was delivered to you.
- **`inbox.shareCap(cap, toInbox)`** — the act of sharing: **one document, to one recipient inbox**. Several recipients means several calls. Recipients are addressed as **inboxes**, never as principals.
- Receiving a capability needs **no dedicated call**: it arrives as an inbox deposit, is applied inline by `inbox.read`/`watch`, and the resulting keyring change **re-triggers the reads that were empty for want of it** — a `watchShape` view fills in on its own.
- **`getCaps().publishRepoLink(nuri)`** (`/polyfill`) — publish a document as a shareable link; that link, not the bare NURI, is what goes into anything discoverable. **`getCaps().open(nuri, scope)`** records a document as mine in a scope (publishing it when `public`).
- **Public is readable by whoever has the link, and NOT recursive**: a public document may *reference* a private one without disclosing it. Festipod relies on exactly that.
- Key rotation **redelivers** through the same inbox channel; access is deferred to the next connection, never lost. The app implements nothing to "keep" an access.
May not assume: that a store-level key grants its documents (it does not — isolation is per document); that `Nuri`/`ReadCap` are compile-time-branded (they are plain strings, checked at runtime); that revocation is retroactive.
## Identity and lifecycle
**`accounts.IdentityStore`** / **`accounts.browserIdentityStore(key?)`** persist the current identity id over an injected `AccountStorage`; it is an opaque id, with no notion of password or login step. `/polyfill` adds **`setCurrentUser(id)`**, **`getCurrentUser()`**, **`resetCaps()`**, **`configure(...)`** and **`configureStoreRegistry(...)`** — the bootstrap. **`init` / `initNg`** are the lifecycle entry points, and **`ng`** is the raw SDK object, both re-exported from the SDK entry.
May assume: switching identity **switches** keyrings, it does not wipe them — a delivered capability is durable across sessions.
## SPARQL safety
**`escapeLiteral(value)`**, **`escapeIri(value)`**, **`assertNuri(nuri)`** — the app reuses the SDK's own escaping whenever it builds SPARQL by interpolation. Any untrusted value crossing into a query goes through one of them; never hand-roll quoting.
## Types re-exported for the app
`Nuri`, `ReadCap`, `Scope`, `PrincipalId`, `UnionSubject`, `ShapeQuery`, `ShapeObservable`, `IndexEntry`, `SubmitOptions`, `Deposit`, `PostOptions`, `AccountRecord`, `RegistrySession`, `AccountStorage`, `DocChange`, `Unsubscribe` — plus `ShapeType`, `BaseType`, `Schema`, `DeepSignalSet` and `NG`, so the app never imports from `@ng-org/*` directly.
## Exported, but not for the app
`readModel.readUnion`, `subscribeDoc` / `subscribeDocs` / `docChangeType`, and `docs.sparqlQuery` used as a listing primitive are **lower-level** surfaces. Festipod reads through `watchShape` and does **not** assemble its own reactivity on top of them ([[rule_app-uses-sdk-surface-only]]). In demo mode none of this is reached at all ([[knowledge_data-modes]]).
@@ -0,0 +1,17 @@
---
type: knowledge
summary: seedData.ts provides deterministic fixtures (10 users, events, participations) with CURRENT_USER_ID = 'user-1' (Marie Dupont); used in demo mode and by the @ui tests
---
# Seed data
`src/shared/data/seedData.ts` provides **deterministic** fixtures:
- 10 users — **Marie Dupont = the current user**, `user-1`
- Several events (dates, locations, themes)
- Participations, meeting points, friendships
- `CURRENT_USER_ID = 'user-1'`
These fixtures serve (a) **demo mode** (`LocalDataProvider`, see [[knowledge_data-modes]]) and (b) the **`@ui`** tests, which render the screens against this predictable data (`Marie Dupont`/`@mariedupont` = currentUser, `Jean Durand`/`@jeandurand` exists, etc. — see concept `bdd-testing`).
> `bootstrapWallet()` (`src/shared/utils/ngBootstrap.ts`) seeds this data into the wallet in connected mode — triggered only by an explicit user action (« Charger données de test »).
@@ -0,0 +1,35 @@
---
type: rule
summary: The app IGNORES NextGraph's implementation state entirely and is coded against the SDK as it SHOULD BE — the contract written down in this repo ([[knowledge_sdk-surface]]). @ng-eventually/client is a POLYFILL whose mission is to COMPENSATE THE GAP between that target SDK and what NextGraph provides today (the virtual wallet being the largest piece, not the whole mission). When something breaks, the question is never "how do we work around it in the app" but "what must the polyfill compensate".
---
# The app uses the SDK surface only — never the polyfill's internals
## The rule
The Festipod app treats `@ng-eventually/client` as a **finished, flawless NextGraph SDK**. Concretely:
1. **Reactive reads = `useShape`** (the SDK-shaped surface provided by the polyfill, **scoped to the virtual wallet**). The app does NOT read through the polyfill's internals (`readModel.readUnion`, `subscribeDoc`, a home-made read model…), and does NOT mount its own reactivity (a re-run on a signal).
2. **The app NEVER reasons about NextGraph's current state**: no code and no comment of the kind "we do X because the ORM fan-out hangs / because a cold read returns 0". From the app's point of view, those problems do not exist.
## The contract is the SDK as it SHOULD BE — written down here, in this repo
The app is coded against the SDK **as it should be**, and that contract lives in Festipod's own doctrine: [[knowledge_sdk-surface]]. That is what an agent reads to know what it may rely on. It never needs to open the polyfill's repo, and it never needs to know what NextGraph does or does not implement today.
**Ignore NextGraph's implementation state — entirely.** Not "mostly", not "except when it bites". The app's code and comments must contain **nothing** of the form "we do X because NextGraph does Y today". From the app's point of view, that state does not exist.
## The polyfill's mission: COMPENSATE THE GAP
`@ng-eventually/client` is a **polyfill**, and its mission is exactly that of any polyfill: **close the gap between the target SDK and what the underlying platform currently provides**.
The **virtual wallet** (several identities on one physical wallet) is the largest piece of that gap, and historically the reason the polyfill was created — but it is **one piece, not the whole mission**. Emulating capabilities, the union read-model, `open-repo`, readiness mirroring, reconnection: all of it is gap-compensation, all of it is legitimately the polyfill's job, and **none of it surfaces in the app**.
**The operative consequence.** When something does not work, the question is never *"how do we work around NextGraph in the app?"* — it is *"what does the polyfill have to compensate?"*. An app-side workaround is a doctrine violation even when it works, because it hard-codes a temporary state of NextGraph into code that must outlive it.
## Status (deviation resolved)
**Resolved**: `FestipodDataContext` now reads through `useShapeQuery` (a `useSyncExternalStore` binding over the polyfill's `watchShape`) + Fp adapters (`src/shared/data/shapeAdapters.ts`). **Removed**: `readEntities.ts`, the bespoke reactivity (`subscribeDocs`+`bumpRead`+`readTick`), the manual listing (`publicDocs`/`protectedDocs`/`registerDoc` for reads), and the comments reasoning about the ORM hang. The auto-seed is gated on `isSuccess` (no more 3s timer). The app consumes nothing but the SDK surface.
**Target (design reminder)**: the polyfill exposes a `useShape` that is **reactive and scoped to the virtual wallet**, whose **shape follows TanStack `useQuery`**`{ data, isPending/isLoading, isSuccess, isError, … }`**in anticipation of the PLANNED update of `useShape` by NextGraph** (which is going to adopt that behaviour). So this is not an invention: it is a future NextGraph API, emulated ahead of time, that will align once NextGraph ships it. It **natively distinguishes** `isPending` (sync in progress) from `isSuccess` + empty `data` (synchronized, genuinely empty) — exactly what is needed. Internally, the hook encapsulates readUnion over `subscribeDoc` plus the identity scoping (invisible to the app). The app **removes** its bespoke machinery (`readEntities`/`subscribeDocs`/`bumpRead`) and reads through that hook.
The auto-seed bug (the 3s timer) is a **symptom**: with `isSuccess`, the auto-seed decides "empty" only once the sync is confirmed, instead of guessing a delay. See [[rule_no-broker-polling]] and [[knowledge_nextgraph-stack]].
@@ -0,0 +1,33 @@
---
type: rule
summary: Any important knowledge established about how NextGraph ACTUALLY works (a core/broker/verifier mechanism, a primitive's semantics, a shape property) → record it AT THE MOMENT of discovery in the polyfill's reference docs `../../nextgraph/ng-eventually-js/docs/`, never in the Festipod repo; distinguish VERIFIED from INFERRED, and never deduce the TARGET shape from the source's CURRENT state
---
# Rule: record NextGraph knowledge the moment you establish it
When an investigation establishes an **important fact about how NextGraph actually works** — a primitive's mechanism, a structure's semantics, a shape property ("the overlay is *store*-scoped, never document-scoped"), an access guard, what an operation does or does not require — **write it down straight away** in the polyfill's reference documentation:
`../../nextgraph/ng-eventually-js/docs/` (from this repo's root) — typically the reference note for the subject (caps/NURI model, current state, SDK reference).
**Never in the Festipod repo.** `AGENTS.md` forbids it explicitly: Festipod doctrine describes *how Festipod uses the SDK*, not the state of NextGraph. See [[rule_app-uses-sdk-surface-only]].
## At the moment of discovery — not at the end
"I will write it up at the end of the session" does not work: the context is compacted before that, and the fact is lost. This knowledge is **very expensive** to establish (several agent investigations through the Rust source, often contradicting each other before they converge) and **impossible to verify from memory** — a second session will pay full price again for the same answer, or worse, will settle for a wrong intuition.
## The central pitfall: current state ≠ target shape
**Never read `nextgraph-rs`'s current state to DEDUCE the target shape from it.** The source contains **unfinished scaffolding** that looks like model: you can find membership and permission types in it that are **inert at runtime** (never called outside unit tests, structures built empty). Deducing a "membership" primitive from that and shaping it into the polyfill means carving in a shape that will never exist — exactly the failure mode the polyfill exists to prevent.
The source is there to **verify an existing mechanism**, never to **infer an intention**. Intentions are to be asked of NextGraph's designer.
## Shape of the note
- **Distinguish VERIFIED** (a path read end to end, or better: observed at runtime) from **INFERRED** (deduced, not traced). A load-bearing fact left unmarked silently turns into a certainty.
- **Point at symbols**, not line numbers (which are volatile) — and date the note.
- Write down the fact's **consequence** too, not just the fact: that is what will be re-read.
- A fact that **contradicts** an existing note → fix the note, do not pile on.
## Sibling rule
This one covers **knowledge** — what *is*; [[rule_nextgraph-inbox]] covers what must be **reported upstream or waited for** — the malfunctions and the gaps (→ `../../nextgraph/orm-tests/INBOX/`). One and the same investigation often produces both: file each half in its own place. See [[knowledge_nextgraph-stack]].
@@ -0,0 +1,48 @@
---
type: rule
summary: Festipod persists EVERY entity as ITS OWN document (through the SDK), placed in its scope (public/protected/private) — never several entities written into a store-level document. The document is the unit of sharing and of rights: the SDK's isolation is PER-DOCUMENT, so one document per entity is what makes it possible.
---
# Rule: one document per entity (never at store level)
When Festipod creates an entity (event, meeting point, profile, participation, notification), it writes it as **its own document**, through the data SDK's "create a document" call ([[knowledge_nextgraph-stack]]), stating its **scope** (`public` / `protected` / `private`). The entity is then read from and written to **that** document.
**Never** write several entities into a shared "store-level" document (e.g. putting everything into a single root document). That is an anti-pattern that breaks isolation.
## Why
The **document is the SDK's unit of sharing and of rights**: isolation (who can read what) is enforced **per document**. `private` → the owner; `protected` → the owner + their connections; `public` → everyone. That discrimination is possible **only if each entity has its own document**: putting several entities (or worse, several owners) into a single document makes sharing all-or-nothing and defeats scope-based isolation.
Isolation itself is **entirely handled by the SDK** ([[knowledge_trust-model]] in the `app-security` concept) — the app carries no access logic; it only declares its identity (at login) and its connections (an act of sharing), then trusts whatever the SDK returns. The "one document per entity" granularity is the write-side counterpart of that trust.
## How to apply it
- At creation time: ask the SDK for **a document for the entity, in its scope** (`createEntityDoc(scope)`); write the entity into it. Do not reuse a document from another scope, nor a store-level document.
- For reads: go through the SDK's **reactive shape surface** (see below) — the app names a SHEX shape and a **logical scope**, and the SDK resolves that scope to the documents to read (the discovery index for public events; its own scope documents for its own entities), opens/synchronizes them and pushes changes. No NURI resolution, no document listing and no query written on the app side.
- The *entity → scope* mapping (event/meeting point → public, network profile/participation → protected, settings → private) is a product fact (concept `functional-domain`, [[knowledge_data-scopes-and-discovery]]).
## Reads: the SDK's reactive shape surface (`watchShape` / `useShapeQuery`)
**Reads go through the SDK surface only** ([[rule_app-uses-sdk-surface-only]]). The app names a shape and a scope, and gets a live, `useQuery`-shaped result back:
1. `watchShape(shapeType, scope)` (SDK) returns an **observable**`{ data, isPending, isSuccess, isError }` — which resolves the scope against the current identity's wallet (its own scope documents, plus the discovery index for `public`), waits for the sync barrier, and **pushes** on every change. `data` is always an array; a synced-but-empty scope reads `{ data: [], isPending: false, isSuccess: true }`, which is what distinguishes "still syncing" from "genuinely empty".
2. `useShapeQuery(shapeType, scope)` (`src/shared/data/useShapeQuery.ts`) is the app's **only** React binding over it (`useSyncExternalStore`), memoized per (shape, scope) so the underlying document subscriptions are not churned on every render.
3. `FestipodDataContext` mounts exactly three of them — events (`public`), profiles (`protected`), participations (`protected`) — and maps the SDK's `UnionSubject` property bags onto the app's `Fp*` domain types through `src/shared/data/shapeAdapters.ts`.
**The app resolves, lists, registers and re-queries nothing.** There is no app-side document set, no manual re-read signal and no per-document subscription: reactivity is the SDK's own push. The single app-side layer laid over the read is a **pure optimistic overlay** (`pendingAdd*` / `pendingRemoveIds` in `FestipodDataContext`), auto-reconciled the moment the reactive set catches up — it hides the broker's push latency, it is not a read path.
> **Removed (verified 2026-07-28).** An earlier version of this rule described reads as a bespoke union model: an on-demand document set (`publicDocs`/`protectedDocs` fed by `listMyEntityDocs` + `registerDoc`), a one-shot `readEntities` → `readModel.readUnion`, and a manual re-query signal (`bumpRead`/`readTick`). **None of those read symbols exist in `src/` any more** — `src/shared/data/readEntities.ts` is gone, and the surviving mentions are historical code comments. Do not code against them ([[rule_app-uses-sdk-surface-only]]).
## Direct writes (the round-trip pitfall)
**Writing** an entity happens **directly into its own document** (through the SDK's SPARQL call — `src/shared/data/entityWrites.ts`, `writeEntity`), **not** by adding to a reactive set. Reason: a reactive set is only *writable* if the target document is **already** within its subscription scope; but registering the freshly created document is React state that only takes effect on the **next** render → you cannot create-then-add in a single synchronous pass (seed loop, first creation). Against the real broker, an `add` on an empty scope raises "Set is readonly because scope is empty" (the fake-ng unit tests do not catch it).
So: **write = direct SPARQL into the entity's document** (immediate, per-document); **read = the SDK's reactive shape surface** (above).
**Graph convention (write into the anchored default graph).** A write passes the document's NURI as the **anchor** of `docs.sparqlUpdate` and writes the SPARQL body **without** an explicit `GRAPH <…>` clause; the SDK's shape read queries that same anchored default graph. This is the **canonical, always-safe** form — to be kept for `writeEntity`, `updateEntityField` and `registration.ts`.
> **Correction (2026-07-06).** An earlier comment (and an earlier version of this paragraph) claimed that an explicit `GRAPH <docNuri>` body writes into a *distinct named graph* that an anchored read would not see → the entity would "disappear". **That is false on the current broker** (`@ng-org/web 0.1.2-alpha.13`): the lib's real e2e harness (`packages/client/e2e/`) verifies that an `INSERT DATA { GRAPH <plainNuri> {…} }` **anchored** to the doc round-trips (read back both from the default graph and from `GRAPH <plainNuri>`). The "0 entities" symptom we had attributed to that "pitfall" in fact came from the **bloated-wallet hang** (see `bdd-testing/caveat_wallet-bloat-hang`), not from a graph mismatch. So the "no `GRAPH` wrapper" rule remains a choice of **simplicity/safety**, not a round-trip necessity. (The *why* on the SDK side lives in `@ng-eventually/client`, not here.)
The same goes for **mutating an existing field** (e.g. `participantCount`): mutating a value in memory does not hold — the reactive read re-reads the **persisted** value from the broker (reverting to the old value) → persist through SPARQL (`updateEntityField`: DELETE then INSERT of the triple) so that the change sticks and the re-read agrees. Each field is written with the **right RDF term** according to the SHEX shape (xsd:integer / float / boolean, or an IRI for the `Participation.event`/`.user` references) — a missing or mistyped mandatory field makes the read **discard the entity** (it never round-trips). The entity's **subject** = its document's **NURI** (one entity = one document), which yields an `@id` of the form `did:ng:…`.
Identity corollary: a `Participation` carries a **mandatory** `fp:user` — never write it with an empty principal (the entity would be discarded on read). The current user's principal is **stable and derived from the username** (`urn:festipod:user:<normalized-username>`), available **immediately** after login (no dependency on reading the protected profile, which may lag) and **invariant** (it does not flip from a fallback to the profile IRI mid-session, which would desynchronize a participation written under one value from a check made under the other). It is the same principal that the SDK identity (`setCurrentUser`) and the owner cap derive from the username; bilateral connections (`declareConnections`) are declared with those same username keys (not profile IRIs) so that "protected = my connections" discriminates.
@@ -0,0 +1,42 @@
---
type: rule
summary: The shared NextGraph inbox `../../nextgraph/orm-tests/INBOX/` takes TWO families of notes — malfunctions (a primitive misbehaves) AND gaps (a primitive we need, not yet implemented, which we emulate in the polyfill in the meantime). It doubles as a tracker of NextGraph's progress: when a gap is filled upstream, its note says what to REMOVE from the polyfill.
---
# Rule: the NextGraph inbox takes malfunctions AND gaps
The shared NextGraph inbox is `../../nextgraph/orm-tests/INBOX/` (from this repo's root) — in the sibling repo `nextgraph/orm-tests`, which hosts the ORM integration tests against a real broker (`tests/standalone/` for repros).
It is **not** just a bug tracker. It has **two inputs** and **one feedback loop**.
## Input 1 — malfunctions
A NextGraph primitive exists but **misbehaves**: a socket that dies (`SerializationError`), no automatic reconnection, a `doc_subscribe` that does not deliver or delivers late, a slow repo cold-open, a write that is not durable broker-side, a reachable panic.
## Input 2 — the gaps we need
A primitive **is not implemented yet** (or is only inert scaffolding) while our model depends on it. File it too, with the three pieces of information that make it valuable:
- **what we need** and why — the model that depends on it;
- **what the polyfill does in the meantime** — the emulation that fills the hole;
- **what will have to be removed** from the polyfill the day it lands upstream.
It is that third point that turns the note into a **cleanup ticket**. Without it, the emulation outlives its reason for existing and the polyfill starts drifting away from the target — exactly what it exists to prevent.
## What does NOT qualify
An **app** bug (a badly wired React effect, an effect's gating) or a **polyfill wiring** issue (wrong NURI, subscription not re-armed). Those are fixed **on our side**. The distinction is crucial: first prove that the primitive is at fault — ideally with a test — not our integration. See [[rule_app-uses-sdk-surface-only]].
## The loop: the inbox tracks NextGraph's progress
The notes do not only travel upstream, they are also **re-read**: taken together, they say where NextGraph stands relative to what Festipod needs. When a note is resolved upstream, the polyfill update follows — often by **removing** emulation that has become useless, not by adding code.
## Note format
Name: `YYYY-MM-DD-<slug>.md`. Contents: nature (**malfunction** or **gap**), symptom or need, **verbatim evidence** (logs, measurements, source pointers marked "to re-verify"), a repro when it is a malfunction (ideally a standalone in `orm-tests/tests/standalone/`), expected vs observed, and — for a gap — the **polyfill workaround** and **what will have to be removed**. Severity + status.
The inbox receives the **report that is actionable for the NextGraph maintainers**; a longer post-mortem can live on the polyfill side.
## Sibling rule
This one covers what must be **reported upstream or waited for**; [[rule_capture-nextgraph-findings]] covers established **knowledge** about how things actually work (→ the polyfill's reference docs). One and the same investigation often produces both: file each half in its own place. See [[knowledge_nextgraph-stack]].
@@ -0,0 +1,29 @@
---
type: _overview
summary: Festipod's product model — the meeting point grafted onto a public event as the unit of value, its actors, its business concepts, and the confidentiality scopes (public/protected/private) per entity
triggers:
keywords: [point de rencontre, rencontre, greffe, greffer, événement, déclarant, hôte, inscrit, inscription, communauté, connexion, festival, déduplication, découverte, périmètre, scope, public, protected, privé]
paths: ["src/modules/*/features/**"]
---
# Functional domain
Festipod's **functional domain**: what the product promises and the business vocabulary that describes it. Original source: `README.md §Modèle fonctionnel`.
**Read this first:** [[knowledge_business-model]] — without it, you conflate the event (the anchor) with the meeting point (the value), and you model things backwards.
## Pivotal idea
Festipod lets users create **meeting points** that *graft* themselves onto existing **public events**. The event (festival, conference…) is only a *pretext* and a space-time anchor; the value produced is the meeting point. **You sign up to a meeting point, never to an event.**
## Scope & confidentiality
The product model of **who sees what** — personal data reserved to one's network, public events/meeting points, identified-or-anonymous sign-up notification — is a business fact: see [[knowledge_data-scopes-and-discovery]]. The detailed authorization matrix (actor × verb) and its incubation live in the `app-security` concept ([[brief_2026-05-18_authorization-matrix]]).
## Links
- [[knowledge_business-model]] — the event / meeting point inversion
- [[knowledge_actors-and-concepts]] — reference for actors and business concepts
- [[knowledge_data-scopes-and-discovery]] — public/protected/private scopes per entity + discovery
- [[knowledge_roadmap]] — current features vs upcoming evolutions
- [[brief_2026-06-15_event-deduplication]] — open challenge of deduplicating events in P2P
@@ -0,0 +1,23 @@
---
type: brief
summary: Open challenge — on a P2P infrastructure, two users can declare the same public event and fragment the meeting points grafted onto it; leads not yet settled
---
# Deduplicating events on a decentralized infrastructure
**Status:** Open challenge — not settled
**Captured:** 2026-06-15 (from `README.md §Défis ouverts`)
## Problem
Since NextGraph is P2P, nothing prevents two users from **independently declaring the same public event** (e.g. "Eurockéennes 2027") and producing two distinct entries. The resulting dispersion **fragments the meeting points grafted onto it** and reduces their visibility — which runs against the app's primary purpose (see [[knowledge_business-model]]).
## Leads considered (not settled)
- **Search before create** — when declaring, offer the user the events already declared within their network / their communities that match what they are typing.
- **Canonical external identifier** — use an official event URL, Wikidata, or `schema.org/Event` to recognize duplicates and present them as a single event on display.
- **Curation** — let curators (human or community-run) merge / vet the canonical entries.
## Link with the write model
This challenge is coupled to an open question in [[brief_2026-05-18_authorization-matrix]]: **who may modify a declared event** (owner / wiki / immutable). A *wiki* model would make convergence easier; an *owner* model makes it harder. To be decided together.
@@ -0,0 +1,31 @@
---
type: knowledge
summary: Reference for the actors (user, connection, declarer, host, participant, member) and the business concepts (meeting point, event, community, curated list, connection)
---
# Actors and business concepts
Vocabulary reference. Every actor is a specialization of an authenticated **user** in a given context — not a separate account role.
## Actors
| Actor | Definition |
|---|---|
| **User** | Anyone with an account (a NextGraph wallet). The root of all the others. |
| **Connection ("friend")** | Another user I am connected to. Used to scope lists ("my friends who are attending…") and trust. Bilateral (accepted on both sides). |
| **Declarer of an event** | The user who inserted the event into Festipod. *Not necessarily the real organizer*: just whoever references it. **There is NO notion of "event host"**: the event is public, merely flagged by its declarer, who **is NOT required to attend** — at creation no participation is written, the counter starts at 0, and the declarer can join/leave like anyone else (a product decision; on the data side see data-layer/[[knowledge_context-internals]] §participantCount). The "host" remains an actor at the **meeting point** level (next row), not at the event level. |
| **Host of a meeting point** | The user who created a meeting point attached to an event. |
| **Participant in a meeting point** | A user signed up to a meeting point; in effect they become an attendee of the parent event. |
| **Member of an interest community** | A user subscribed to a community in order to discover the events it references. |
## Business concepts
| Concept | Definition |
|---|---|
| **Meeting point** | *The app's unit of value.* A moment of meeting proposed by a host at a given place and time, grafted onto a public event. It is what you sign up to. |
| **Event** | The anchor. A real public event referenced in Festipod to serve as a support for meeting points. A mere pretext (title, dates, location, themes). |
| **Interest community** | A thematic grouping of users. Used mainly to discover events (through subscription) and to delimit referencing scopes. |
| **Curated list** | An editorialized list of events (by a user or a community), distinct from "the events I declared". Allows organizing/recommending. |
| **Connection** | A bilateral trust link between two users (the equivalent of "friend"). |
> Communities, curated lists and subscriptions are largely **prospective** (see [[knowledge_roadmap]]). The detailed authorization matrix by data type lives in [[brief_2026-05-18_authorization-matrix]].
@@ -0,0 +1,26 @@
---
type: knowledge
summary: The meeting point is the unit of value, grafted onto an event that is only a pretext; you sign up to the meeting point, not to the event
---
# Business model: the grafted meeting point
> Festipod lets users create **meeting points** that come to be "grafted" onto **existing public events**. The goal: encourage people to meet around those events.
## The inversion to grasp
The **public event** (festival, conference, trade show, exhibition…) is **only a pretext** and a *temporal and geographical anchor point*. The value the app produces is the **meeting point** that users come and graft onto it.
Direct consequences for modelling:
- **You sign up to a meeting point, not to an event.** Without meeting points, a Festipod event is of no interest whatsoever.
- The **declarer** of an event is *not* (necessarily) its real organizer — just someone who inserted the reference into Festipod so that others can attach meeting points to it.
- The **host** of a meeting point is whoever created it; the act of creating makes you the host. Likewise the act of declaring an event makes you its declarer.
## Authentication
**Every user is authenticated** (each one owns a NextGraph wallet) — there is no anonymous access to the app. The various "actors" (declarer, host, participant, connection…) are *specializations of a user in a given context*, not separate accounts. See [[knowledge_actors-and-concepts]].
## Underlying stack
A mobile-first web app, Bun + React + **NextGraph** (P2P, local-first, end-to-end encrypted). The P2P choice has a strong business consequence: see the challenge in [[brief_2026-06-15_event-deduplication]].
@@ -0,0 +1,44 @@
---
type: knowledge
summary: The product model of confidentiality and discovery — every entity lives in a SCOPE (public / protected / private) depending on who must see it; events & meeting points = public, network profile & participations = protected (network), settings = private; bilateral connections = the dialog scope; discovery reads a global event index
---
# Data scopes and discovery
The **product** model of who sees what, and of how events are found. This is **domain**: the technical *how* (documents, capabilities, index) is handled by the `@ng-eventually/client` data SDK — the app only states **the business intent**.
## Three scopes per piece of data
Every entity is stored in the **scope** matching who must be able to read it:
| Entity | Scope | Who reads it |
|---|---|---|
| Event (the anchor) | **public** | everyone |
| Meeting point | **public** | everyone |
| Network profile (name, avatar, bio, city, interests) | **protected** | the holder + their connections |
| Participation / sign-up to a meeting point | **protected** | the participant + their connections |
| Connection index | **protected** | the holder + their connections |
| Private profile (settings, email, preferences) | **private** | the holder alone |
| Connection A↔B (bilateral link, + future messaging) | **dialog** | both users |
Guiding principle: **the "public" side (meeting point, event) and the "personal" side (profile, participations, connections) coexist within a single user.** Personal information is reserved to the **network** (bilateral connections), never visible to an ordinary user.
- **Meeting points / events are universally public.** Any user can read them and subscribe; creating a meeting point makes you its host, declaring an event makes you its declarer (no prerequisite).
- **The host is the sole holder of write rights** on their meeting point; the declarer has no particular right over the meeting points grafted onto their event.
- **Bilateral connection**: `DemandeDeConnexion` (unilateral, transient) → `Connexion` (bilateral, persistent) — the latter opens access to the other person's *protected* data.
Festipod **places each entity in the store of its scope**; isolation between scopes is **handled by the data SDK**, not by application code (see concept `app-security`).
## Event discovery
A user discovers the events they did not create through a **global index**: the SDK reads that index, which yields the references (NURIs) of the event documents, then synchronizes and queries locally. **Primary** discovery goes through that index; a **secondary**, relational axis is layered on top (the connections' *protected* participations: "my friends are attending…").
> **Sign-up notification (product intent).** Signing up to a meeting point notifies its host: identified if the participant is one of the host's connections, **anonymous otherwise**. This "identified if known, anonymous otherwise" is a property of the data model — the app relies on it, the mechanism is provided by the SDK.
## Open questions (business)
- **Event write model**: owner (the declarer alone) / wiki (everyone) / immutable? Central to deduplication ([[brief_2026-06-15_event-deduplication]]).
- **The host's identity towards an ordinary user**: a meeting point is readable by all, but should its host be identifiable? (pseudonym by default, a business card per meeting point, or anonymity lifted only for connections.)
- **Which fields of a sign-up can be edited**; **"friends of friends" discoverability**.
> The detailed authorization matrix by actor × verb lives in the `app-security` concept ([[brief_2026-05-18_authorization-matrix]]).
@@ -0,0 +1,27 @@
---
type: knowledge
summary: What is implemented today (event + meeting point lifecycle, profiles, connections) vs the evolutions identified but not built (communities, subscriptions, curated lists, multi-user)
---
# Current features vs upcoming evolutions
## Implemented (screens reachable through the router)
- Authentication through a NextGraph wallet
- Event lifecycle (declaration, viewing, update)
- Meeting point lifecycle (attached to an event)
- Signing up to / withdrawing from a meeting point
- List of an event's participants
- User profile, profile update, profile sharing
- Friends list (connections), another user's profile
> Signing up to / withdrawing from a meeting point is **genuinely wired** on the data side: `joinEvent` persists a Participation, notifies the meeting point's host and creates a Notification; `leaveEvent` deletes the Participation authoritatively (see concept `data-layer`, [[caveat_participation-deletion]] on the data-layer side). Public discovery — a user seeing another user's public event — works too.
> **Product reservation — persistence is not guaranteed end to end.** An event that was created can **disappear** after a period of inactivity followed by a reconnection under the same identity (same wallet). This is an **open defect**, not a property of the product model: impact and pointer on the `data-layer` side → [[caveat_write-durability-across-disconnect]]. Consequence for the domain: "my events / my sign-ups" behave as *implemented* but **not yet as durable** — do not build any product promise (reminders, history, commitment) on top of them while this caveat is open. The `src/modules/event/features/reconnexion-*.feature` scenarios of the `event` module are the non-regression guard for that promise (execution status: concept `bdd-testing`).
## Identified evolutions (not implemented)
- **Subscribing to an interest community** in order to discover its events (distributed discovery).
- **Subscribing to a user** in order to follow their declarations without being a friend.
- **Curated lists** — creating/sharing editorialized selections.
- **Collaborative multi-user**: actually sharing a meeting point seen by several users, resting on the public/protected/private scopes (see [[knowledge_data-scopes-and-discovery]]).
+21
View File
@@ -0,0 +1,21 @@
---
type: _overview
summary: Stack and tooling — Bun-first (runtime, bundler, native APIs), build pipeline, and the project's commands
triggers:
keywords: [bun, bunx, build, bundler, vite, webpack, jest, npm, storybook, "bun.serve", hmr, tailwind, package.json]
paths: ["build.ts", "package.json", "bunfig.toml", "tsconfig.json", "src/index.ts", "src/index.html", ".storybook/**", "scripts/**"]
---
# Tech stack
The project's stack and tooling. Guiding principle: **Bun-first** — Bun replaces Node/npm/vite/webpack/jest and provides the native server APIs.
**Read this first:** [[rule_bun-first]] — the convention that decides which tool to use.
## Links
- [[rule_bun-first]] — use Bun, not Node/npm/vite/jest/express/ws/pg…
- [[knowledge_bun-apis]] — native Bun APIs (serve, sqlite, redis, sql, file, shell)
- [[knowledge_build-pipeline]] — build.ts, bundler, server, harness built separately, Storybook
- [[knowledge_stack-and-commands]] — stack components + the real scripts (plus quirks)
- [[knowledge_deployment]] — Dockerfile, prod served from src/, no CI, `portless` in dev
@@ -0,0 +1,26 @@
---
type: caveat
summary: Firefox 151+ blocks (Local Network Access) the hosted broker embedding the local dev app in its iframe → blank iframe, zero app logs, no error at all. This is NOT a code bug. Browser-side fix — about:config network.lna.enabled=false.
last_checked: 2026-07-13
---
# Firefox LNA blocks the broker's app iframe in local dev
## Symptom
In local dev, the app runs INSIDE the hosted broker's iframe (`nextgraph.eu`/`nextgraph.net` over HTTPS embeds `festipod.localhost``127.0.0.1`). On **Firefox 151+**, the iframe stays **blank**: **no `[FestipodData]`/`[NG]` log at all** (the app's JS never runs), and **no red error** either (the block is a network policy decision, not a throw). Easy to mistake for a Festipod rendering crash — it is NOT one.
## Cause
**Local Network Access (LNA)**: Firefox 151+ (on by default, see the 149→151 rollout) forbids a **public site** (the HTTPS broker) from reaching a **local network resource** (`127.0.0.1`) — including embedding it in an iframe. The telltale console log:
`Local Network Access detected: ... accessing target "…festipod.localhost…" (127.0.0.1) … prompt action: auto_deny`.
Two corollaries that mislead:
- **The top level loads just fine**: navigating directly to `https://festipod.localhost:1355` (the AccessGateScreen barrier) is NOT subject to LNA. Only **iframe embedding** by the broker is. So "the cert is already accepted / the app starts up" before the iframe does not mean the iframe will go through.
- **HTTPS changes nothing**: LNA targets the **local destination address**, not the protocol. Switching to `portless proxy start --https` (app on `https://festipod.localhost`) does not unblock it.
## Fix (browser, not code)
`about:config`**`network.lna.enabled` = `false`** (master flag: disables every LNA check). Targeted alternative: **`network.lna.skip-domains`** with `nextgraph.eu`, `nextgraph.net` (keeps the protection everywhere else). Other LNA prefs: `network.lna.blocking`, `network.lna.block_trackers`.
Do NOT go hunting for a Festipod rendering bug as long as there is **no `[FestipodData]` log** in the console: with no app logs, the app never ran → it is the environment (LNA, untrusted cert, dev server down), not the code. The `@e2e` smoke test CANNOT catch this: Playwright does not enforce LNA the way a real Firefox does.
@@ -0,0 +1,37 @@
---
type: knowledge
summary: Dev runs on bun --hot, prod builds through build.ts (Bun bundler + Tailwind plugin) into dist/, path alias @/* → ./src/*
---
# Build pipeline
- **Dev**: `bun --hot src/index.ts` (through `bun run dev`) — HMR, port 3000.
- **Prod**: `bun run build``build.ts` (Bun bundler + Tailwind plugin) → `dist/`.
- **Path alias**: `@/* → ./src/*` (declared in `tsconfig.json`).
The server serves `src/index.html`, which loads `src/app/frontend.tsx` (see `app-architecture` §app-shell). The bundler transpiles the TSX and bundles the CSS without any external tool — no Vite/webpack/esbuild (see [[rule_bun-first]]).
## Details of `build.ts` and of the server
- `build.ts` scans `src/**/*.html` for entrypoints (today just one: `src/index.html`), `target: 'browser'`, minify plus linked sourcemap, `bun-plugin-tailwind` plugin. Adding a second `.html` would create a second bundle.
- `src/index.ts` (`Bun.serve`) serves: `/reports/cucumber` (HTML report), `/api/hello*` stubs, `/festipod-config.json` plus `/shared-wallet.ngw` (runtime config, see below), and a **catch-all `/*` → `src/index.html`** (SPA routing, which must stay last). HMR when `NODE_ENV !== 'production'`, port from `PORT`.
## Build-time globals vs runtime config (the shared wallet pitfall)
`build.ts` injects **compile-time globals** through `define` (e.g. `__FESTIPOD_SHARED_WALLET_PASSWORD__` from `FESTIPOD_SHARED_WALLET_PASSWORD`, `__FESTIPOD_ACCESS_GATE_DISABLED__`, and `__FESTIPOD_AUTO_SEED__` from `FESTIPOD_AUTO_SEED` — the dev auto-seed, OFF when absent). **Pitfall**: the `src/index.ts` server (used by `bun run dev` AND `bun run start`) bundles `index.html` through Bun's HTML import, which **applies no `define`** — neither `bun --define` nor `process.env` propagates there (verified). So an environment variable passed to `bun run dev` never reaches the frontend bundle along that path.
For those paths served from `src/`, the configuration therefore goes through the **runtime**: `src/index.ts` exposes `/festipod-config.json` (read from the environment), and the `src/app/frontend.tsx` entry **fetches it first**, sets the global, **then imports the app dynamically** (`await import('./App')`) — so that `sharedWallet.ts` reads the value when it is evaluated. In a `build.ts` bundle the value is already inlined by `define`, so the fetch is skipped (`NODE_ENV === 'production'`). Practical consequence: to exercise the "shared wallet" flow in dev **end to end** (download plus a working import), pass the REAL password of the e2e wallet **and** the file — the password shown on screen must match the imported `.ngw`, otherwise the import fails (a dummy value such as `1` merely makes the screen appear):
```
FESTIPOD_SHARED_WALLET_PASSWORD=festipod-e2e-tests \
FESTIPOD_SHARED_WALLET_FILE=./festipod-e2e-tests.ngw \
bun run dev
```
## The test harness is built separately
⚠️ `build.ts` does **not** build the test harnesses. The Cucumber hooks (`src/shared/support/hooks.ts`) run a `bun build` **on demand** for `src/shared/test-harness/harness.tsx` (and `harness-ng.tsx`) → `dist/test-harness*.js`. It is an entrypoint separate from the app build — see concept `bdd-testing`.
## Storybook
`storybook dev -p 6006`**webpack5 + SWC** (not Vite). The decorators (`.storybook/`) inject the full provider stack (Theme > NextGraph > FestipodData > Router) and import `src/index.css`; mobile viewport by default. Tightly coupled to the project context (not reusable outside Festipod).
@@ -0,0 +1,41 @@
---
type: knowledge
summary: Native Bun APIs used by the project — Bun.serve (HTTP/WS/routes), bundled HTML imports, bun:sqlite, Bun.redis, Bun.sql, Bun.file, Bun.$
---
# Native Bun APIs
Reference for the Bun APIs to favour (see [[rule_bun-first]]). Full documentation: `node_modules/bun-types/docs/**.mdx`.
## Server — `Bun.serve()`
Supports WebSockets, HTTPS and routes. No need for `express`/`ws`.
```ts
import index from "./index.html"
Bun.serve({
routes: {
"/": index,
"/api/users/:id": { GET: (req) => new Response(JSON.stringify({ id: req.params.id })) },
},
websocket: { open: (ws) => ws.send("hello"), message: (ws, m) => ws.send(m), close: (ws) => {} },
development: { hmr: true, console: true },
})
```
This is the mechanism behind `src/index.ts` (see concept `app-architecture` §app-shell).
## HTML imports (frontend)
`Bun.serve()` serves HTML imports; the Bun bundler automatically transpiles and bundles `.tsx`/`.jsx`/`.js` and the CSS (Tailwind included). A `<script type="module" src="./frontend.tsx">` in the HTML is enough — no Vite.
## Storage & shell
- **`bun:sqlite`** for SQLite (not `better-sqlite3`)
- **`Bun.redis`** for Redis (not `ioredis`)
- **`Bun.sql`** for Postgres (not `pg`/`postgres.js`)
- **`WebSocket`** built in (not `ws`)
- **`Bun.file`** rather than `node:fs` readFile/writeFile
- **`Bun.$\`ls\`** rather than `execa`
Bun loads `.env` automatically → do not use `dotenv`.
@@ -0,0 +1,32 @@
---
type: knowledge
summary: Deployment — multi-stage Bun Alpine Dockerfile; install through pnpm (git+node inside the image) but bun at runtime; runs `bun run start` from src/ (not dist/), EXPOSE 3000, env PORT/NODE_ENV; no CI/CD committed; dev goes through the portless wrapper
last_checked: 2026-07-14
---
# Deployment & infra
## Dockerfile
A `Dockerfile` exists (multi-stage Bun Alpine). **Installation goes through pnpm, but runtime/build/test stay on bun** (see [[knowledge_stack-and-commands]]):
- `FROM oven/bun:1-alpine`, `install` stage: `apk add --no-cache git nodejs npm` then `npm install -g pnpm@10.26.0` (the bun image has neither Node nor pnpm; Alpine's `apk nodejs` does not ship corepack), `COPY package.json pnpm-lock.yaml`, then `pnpm install --frozen-lockfile`. `git` is required because `@ng-eventually/client` is a public **git+https** dependency (Gitea, no auth). `release` stage: copies `node_modules` plus the source.
- `ENV NODE_ENV=production`, `USER bun`, `EXPOSE 3000/tcp`, `ENTRYPOINT ["bun","run","start"]`.
**`bun` peer pitfall**: `bun-plugin-tailwind` declares `bun` as a peerDependency → pnpm materializes the npm `bun` package and **creates a `node_modules/.bin/bun` shim** that shadows the `bun` from the PATH under `bun run`/`pnpm run`. Its postinstall is ignored by default → broken shim → `bun run start` fails. Fixed by approving the build: `pnpm.onlyBuiltDependencies: ["bun"]` in `package.json` (the postinstall then downloads the real binary). Without that, the whole pnpm migration breaks startup.
**Quirk**: `start` = `NODE_ENV=production bun src/index.ts` → the container **runs the TypeScript source directly** (Bun transpiles on the fly), it **does not use `dist/`**. `bun run build` (→ `dist/`) is therefore **not** on the default production path. Serving the build would require changing the entrypoint.
## CI/CD
**No** pipeline is committed (`.github/workflows/` absent, no Coolify config in the repo). A knowingly accepted blind spot. To host the Bun app, the `coolify-hosting` skill applies.
## Environment variables
- `PORT` (default 3000), `NODE_ENV` (enables/disables HMR and the dev auto-seed — see concept `data-layer`).
- No `.env*` is committed (`.env` is gitignored). No secret management in the repo.
## Dev
`bun run dev` = **`portless festipod bun --hot src/index.ts`** — it goes through the **`portless`** wrapper (an external port-management tool), not a bare `bun --hot`. HMR is active outside production.
**Reactive local link to the polyfill**: in production the `@ng-eventually/client` dependency comes from Gitea (git+https, pinned by `pnpm-lock.yaml`). To edit the polyfill locally and see the changes live, `pnpm run link:polyfill` (script `scripts/link-polyfill.ts`, strategy S2) replaces `node_modules/@ng-eventually/client` with a **real copy** of the local source (`…/ng-eventually-js/packages/client`) — **without** its own `node_modules/@ng-org` — and resyncs `src/` on every edit. That is what guarantees **a single `@ng-org/web` instance** (a single verifier): a symlink to the monorepo checkout would carry its own `@ng-org` → a 2nd instance → broken SDK. To go back to the committed state: `pnpm install`.
@@ -0,0 +1,43 @@
---
type: knowledge
summary: Stack components (Bun runtime/build/test, install through pnpm, React, NextGraph, Storybook, Cucumber, Tailwind-inside-the-build) and the real list of package.json scripts, quirks included (cucumber through node+tsx, build:ng for the local fork, link:polyfill for the reactive local link)
---
# Stack & commands
## Components
| Layer | Technology |
|---|---|
| Runtime / bundler / test | **Bun** (see [[rule_bun-first]]) |
| **Dependency installation** | **pnpm** (`pnpm install`, `pnpm-lock.yaml`) — **only** installation moves to pnpm; runtime/build/test stay on bun. Reason: `@ng-eventually/client` is resolved from Gitea over **git+https** (pnpm handles `git+…#main&path:/packages/client` cleanly, along with deduplication of the `@ng-org` peers). Do not switch installation back to bun/npm. |
| UI | **React** (mobile-first, max width 768px — styling covered by concept `app-architecture`) |
| Data | **NextGraph** P2P local-first (concept `data-layer`) |
| CSS build | **Tailwind** (`tailwindcss` + `bun-plugin-tailwind`) — present in the build, but the screens style themselves with `app-*`/inline, no Tailwind utilities (see concept `app-architecture`) |
| UI exploration | **Storybook** (webpack5 + SWC, port 6006) |
| Tests | **Cucumber/Gherkin** in French, multi-layer, plus Playwright, happy-dom and chai (concept `bdd-testing`) |
## `package.json` scripts (the real ones)
| Script | Command / role |
|---|---|
| `dev` | `portless festipod bun --hot src/index.ts` — dev with HMR through the `portless` wrapper (see [[knowledge_deployment]]) |
| `start` | `NODE_ENV=production bun src/index.ts` — production, served from `src/` (not `dist/`) |
| `build` | `bun run build.ts` — Bun bundler + Tailwind → `dist/` ([[knowledge_build-pipeline]]) |
| `test:cucumber` | chains `cucumber:run``cucumber:report``features:parse``steps:extract` |
| `cucumber:run` | `node --import tsx/esm node_modules/@cucumber/cucumber/bin/cucumber.js`**through Node+tsx, not Bun** (Playwright/happy-dom plugin compatibility), and through the package's **actual JS entry**, not the `.bin/` shim (see Pitfalls) |
| `test:data` | same, with `--tags @data` |
| `test:auth-setup` | `bun scripts/setup-test-auth.ts` — bootstraps the persistent test wallet |
| `cucumber:report` | `bun scripts/parse-test-results.ts``cucumber-report.json` → HTML |
| `features:parse` | `bun scripts/parse-features.ts``features.ts` |
| `steps:extract` | `bun scripts/extract-step-definitions.ts` |
| `build:orm` | `rdf-orm build --input ./src/shared/shapes/shex --output ./src/shared/shapes/orm` |
| `build:ng` | `bash scripts/build-ng-packages.sh` — (re)builds the NextGraph packages from a local source (optional tool) |
| `link:polyfill` | `bun scripts/link-polyfill.ts`**reactive** local link to the `@ng-eventually/client` polyfill (strategy S2: copy-overlay + watcher), preserving the single `@ng-org` instance. Details in [[knowledge_deployment]]. |
| `storybook` / `build-storybook` | Storybook dev (6006) / static build |
## Pitfalls
- **`cucumber:run`/`test:data` run under Node+tsx**, not Bun — the test plugins do not load under a native Bun import. Do not "bunify" these scripts.
- **Never point a script at `node_modules/.bin/*`.** Installation goes through pnpm ([[rule_bun-first]] §exception), which puts **shell shims** there rather than JS entries: `node --import tsx/esm node_modules/.bin/cucumber-js` fails. Invoke the package's **actual JS entry** (`node_modules/@cucumber/cucumber/bin/cucumber.js`). This holds for any npm script that would launch a dependency's binary under `node`.
- **`build:orm` was broken until 2026-07-28**: it targeted `./src/shapes/`, which does not exist (the shapes live under `src/shared/shapes/`), so the command exited with an error. **Fixed in `package.json`** — it now runs. Beware of a side effect: the generator has moved on since the committed bindings were produced, so a run reformats them and drops the `: Schema` annotation. That regeneration is a **tool-version bump, not a content fix** — treat it as its own validated change, do not let it ride along.
@@ -0,0 +1,39 @@
---
type: rule
summary: By default use Bun and its native APIs, never the Node equivalents — bun instead of node/ts-node, bun test/build, bunx, and no express/ws/pg/dotenv. EXCEPTION — package installation goes through pnpm (in both repos), not bun install
---
# Rule: Bun-first
By default, use **Bun** and its native APIs rather than the Node.js equivalents.
| Instead of… | Use |
|---|---|
| `node <file>`, `ts-node` | `bun <file>` |
| `jest`, `vitest` | `bun test` |
| `npm/yarn install`, `bun install` | **`pnpm install`** (see the exception below) |
| `npm run <script>` | `bun run <script>` |
| `npx <pkg>` | `bunx <pkg>` |
| `webpack`, `esbuild`, `vite` | `bun build` / the Bun bundler (HTML imports) |
| `express` | `Bun.serve()` |
| `better-sqlite3` | `bun:sqlite` |
| `ioredis` | `Bun.redis` |
| `pg`, `postgres.js` | `Bun.sql` |
| `ws` | `WebSocket` (built in) |
| `node:fs` readFile/writeFile | `Bun.file` |
| `execa` | `Bun.$\`...\`` |
| `dotenv` | (pointless — Bun loads `.env` automatically) |
API details: [[knowledge_bun-apis]].
## Exception: package installation goes through pnpm
**Dependencies are installed with `pnpm install` — not `bun install` — in BOTH repos** (Festipod *and* the `@ng-eventually/client` polyfill). Everything else stays on Bun: **runtime, build, test, scripts** (`bun run dev`, `bun build`, `bun test`, `bunx`). Only the installation step changes package manager.
**Why.** In production the polyfill is installed from a Gitea repository as a **subdirectory** git dependency: `git+https://…/ng-eventually.git#main&path:/packages/client`. pnpm (≥ 10.26) resolves that `#<ref>&path:/…` format and guarantees a **single** instance of `@ng-org/*` (a single verifier); `bun install` does not handle this workflow cleanly. The reference lockfile is therefore `pnpm-lock.yaml`, and the reactive local link to the polyfill goes through `pnpm run link:polyfill` (see [[knowledge_deployment]]).
**Practical consequence.** npm scripts that relied on `node_modules/.bin/*` may break (pnpm puts shell shims there, not JS entries) — call the package's actual JS entry (e.g. `node_modules/@cucumber/cucumber/bin/cucumber.js`) rather than the `.bin/` shim.
## Why (Bun for everything else)
The project is all-Bun (runtime, bundler, test, server). Reintroducing a redundant Node tool adds a dependency, diverges from the repo's conventions, and breaks the native integration (HMR, automatic TS transpilation, `.env` loading). This is a consistency choice, not a cosmetic preference. The installation exception above is the only deviation, and it is motivated by the subdirectory git dependency.
@@ -1,54 +0,0 @@
# Automated Headless Wallet Creation for CI
**Date:** 2026-03-12 15:00
**Status:** Accepted
## Context
Data-layer BDD tests (`@data` scenarios) require a NextGraph wallet in a persistent Chromium profile. Previously, the first run required manual interaction: a visible browser opened and the user had to create a wallet and close the browser. This blocked CI execution.
## Options Considered
### Option A: Programmatic wallet creation via NG SDK
Call `ng.wallet_create()` directly from Node/Bun, bypassing the UI entirely.
**Arguments for:**
- Fastest execution
- No browser needed for wallet creation
**Arguments against:**
- `@ng-org/web` is browser-only (WASM + postMessage)
- Would need to reverse-engineer the registration API at `account.nextgraph.eu`
- Doesn't test the real auth flow
### Option B: Automate the browser UI flow headlessly
Use Playwright to drive the same wallet creation UI a real user would use, but in headless mode.
**Arguments for:**
- Tests the real auth/login feature end-to-end
- No API reverse-engineering needed
- Same persistent profile used for subsequent test runs
- CI-ready with no manual steps
**Arguments against:**
- Depends on `nextgraph.eu` and `account.nextgraph.eu` being reachable
- UI changes in NextGraph could break the automation
- Adds ~27s to first run
## Decision
Option B — automate the browser UI. The wallet creation flow (navigate to `nextgraph.eu` → "Create Wallet" → accept ToS at `account.nextgraph.eu` → fill username/password → submit) is itself a legitimate test of the app's auth feature. The dependency on external services is acceptable since the tests already depend on the broker being reachable.
## Consequences
**Positive:**
- Tests are fully CI-ready (no human interaction)
- Auth/login flow is tested as a side effect
- Single command `bun run test:data` works from a clean state
**Negative:**
- Requires internet access (nextgraph.eu, account.nextgraph.eu)
- Fragile to NextGraph UI changes (button text, form IDs)
**Risks:**
- `account.nextgraph.eu` rate limiting could block CI runs that frequently recreate wallets
@@ -1,48 +0,0 @@
# Conditional NextGraph Init Based on Broker Iframe Detection
**Date:** 2026-03-13 14:00
**Status:** Accepted
## Context
`@ng-org/web`'s `initNgWeb()` checks `window.self === window.top`. When the app runs standalone (not in an iframe), it redirects the entire page to `nextgraph.net/redir/` to trigger broker authentication. This caused the app to redirect on every load — even during development or when the user hadn't clicked "Se connecter".
## Options Considered
### Option A: Always auto-init NG on mount
**Arguments for:**
- Simpler code — no branching logic
**Arguments against:**
- Causes immediate redirect to broker when loaded standalone
- Breaks development workflow
- User sees broker login page instead of the app
### Option B: Conditional auto-init based on iframe detection
**Arguments for:**
- When in iframe, the broker has already authenticated — safe to auto-init
- When standalone, user must explicitly click "Se connecter" to trigger the redirect
- Preserves standalone demo/development experience
- Matches `@ng-org/web`'s own detection logic
**Arguments against:**
- Relies on `window.self !== window.top` heuristic (could theoretically be wrong if embedded in non-broker iframe)
## Decision
Option B. `NextGraphContext` checks `const isInsideBroker = typeof window !== 'undefined' && window.self !== window.top` at module level. `useEffect` only auto-calls `initNg()` when `isInsideBroker` is true. The `connect()` callback remains available for explicit user-initiated connection.
Additionally, `FestipodDataContext` now renders empty data (not seed data) during the `connecting` phase to avoid flashing demo content before the wallet loads.
## Consequences
**Positive:**
- App loads without redirecting — works standalone for development and demo
- In broker iframe, connection is seamless and automatic
- No seed data flash during wallet connection
**Negative:**
- None significant
**Risks:**
- If `@ng-org/web` changes its detection logic, our guard may diverge — keep them aligned
@@ -1,67 +0,0 @@
# Use private_store_id as useShape scope and @graph
**Date:** 2026-03-17 16:00
**Status:** Accepted
## Context
Clicking "Charger données de test" loaded data in-memory (via ORM signals) but produced `RepoNotFound` errors from `doc_create` and `orm_frontend_update`. Data disappeared after page reload because SPARQL writes never reached the broker. The NextGraph verifier's `self.repos` HashMap didn't contain the private store repo, so `resolve_target()` failed.
## Options Considered
### Option A: `did:ng:i` scope + `doc_create` for @graph
Use "entire user site" scope for reads, create a new document for writes.
**Arguments for:**
- `did:ng:i` is well-documented as a valid subscription scope
- `doc_create` returns a real document NURI
**Arguments against:**
- `did:ng:i` uses a special code path (`NuriTargetV0::UserSite`) that doesn't open individual repos
- `doc_create` calls `resolve_target(NuriTargetV0::PrivateStore)` which needs the repo in `self.repos` — fails if repo wasn't opened
- Requires complex retry logic / timing workarounds
### Option B: `private_store_id` as both scope AND @graph
Mirror the expense-tracker-rdf example: `useShape(type, `did:ng:${session.private_store_id}`)` and `@graph: `did:ng:${session.private_store_id}``.
**Arguments for:**
- Proven pattern: expense-tracker-rdf uses exactly this and works
- `orm_start_graph` with private store NURI opens the repo in the verifier's `self.repos` HashMap
- Subsequent writes via `orm_frontend_update` find the repo because it's now in the cache
- Simple, no retry logic needed
**Arguments against:**
- Slightly less flexible than `did:ng:i` (scoped to one store)
- Requires passing session to `useShapeWithDefaults`
### Option C: `did:ng:i` scope + reuse existing entity @graph
Subscribe with `did:ng:i`, then reuse `@graph` from any existing entity for writes.
**Arguments for:**
- Works for returning users who already have data
**Arguments against:**
- Fails for empty wallets (no existing entities to reuse)
- Still needs `doc_create` fallback which hits the same `RepoNotFound` issue
## Decision
**Option B**: Use `did:ng:${session.private_store_id}` as both `useShape` scope and `@graph` for writes. This matches the official expense-tracker-rdf example exactly.
The `useShapeWithDefaults` hook accepts a `storeNuri` parameter. `FestipodDataContext.useNgData()` gets the session from `useNextGraph()` and passes `did:ng:${session.private_store_id}`.
`ensureGraphNuri()` simplified: checks existing entities first (optimization), then falls back to `did:ng:${session.private_store_id}`.
## Consequences
**Positive:**
- Writes work immediately after connection (no retries needed)
- Data persists across page reloads
- Pattern matches official NextGraph examples
- All 7 e2e scenarios pass including data persistence
**Negative:**
- `useShapeWithDefaults` signature changed (added `storeNuri` parameter)
**Risks:**
- If NextGraph changes the private store behavior, this would break
@@ -1,81 +0,0 @@
# Use SPARQL DELETE instead of ORM ngSet.delete() for object removal
**Date:** 2026-03-17 18:00
**Status:** Accepted
## Context
Leaving an event requires deleting the user's `Participation` object from the NextGraph store. The ORM's `DeepSignalSet.delete()` method updates the local reactive state (UI reflects the change immediately) but the deletion does not persist to the broker — after page refresh, the participation reappears.
## Options Considered
### Option A: ORM `ngSet.delete(item)`
The ORM README shows `dogs.delete(aDog)` as the intended API. Internally, `.delete()` generates a `{ op: "remove", path: "/<syntheticId>" }` patch, delivered via microtask to `OrmSubscription.onSignalObjectUpdate`, which calls `ng.graph_orm_update()`.
**Arguments for:**
- Official ORM API, shown in README examples
- Immediate local reactive update (instant UI feedback)
**Arguments against:**
- Does not persist in practice: `delete()` returns `true`, local set updates, but after refresh the object is back
- The `graph_orm_update` WASM call may not correctly handle "remove" patches for top-level set objects (possible engine bug)
- No error is thrown — fails silently
### Option B: `ng.sparql_update()` with SPARQL DELETE
Bypass the ORM patch mechanism entirely. Use `DELETE WHERE { GRAPH <graph> { <subject> ?p ?o } }` to remove all RDF triples for the object.
**Arguments for:**
- Works: deletion persists across page refresh
- The broker confirms via `TORMO became invalid` + `GraphOrmUpdate` remove, which reactively removes the item from the ORM set
- Direct control over RDF triple removal
**Arguments against:**
- Not instant: UI update waits for the SPARQL round-trip + broker `GraphOrmUpdate` callback (near-instant in practice, ~50ms)
- Must not combine with `ngSet.delete()` — running both causes CRDT conflicts where the item reappears
### Option C: `ngSet.delete()` + `ng.sparql_update()` together
Use `.delete()` for instant UI and SPARQL for persistence.
**Arguments for:**
- Instant UI feedback + guaranteed persistence
**Arguments against:**
- **Does not work**: the ORM `.delete()` patch and the SPARQL DELETE backend update conflict in the CRDT, resulting in neither UI change nor persistence
## Decision
**Option B: SPARQL DELETE only.** The broker sends back a `GraphOrmUpdate` with `op: "remove"` that reactively removes the item from the ORM set, so the UI still updates — just not synchronously.
Do NOT call `ngSet.delete()` alongside `sparql_update()` — they conflict.
## Implementation
```typescript
// In FestipodDataContext.tsx leaveEvent():
const session = await sessionPromise;
await ng.sparql_update(
session.session_id,
`DELETE WHERE { GRAPH <${partGraph}> { <${partId}> ?p ?o } }`,
partGraph,
);
```
Imports: `ng` from `@ng-org/web`, `sessionPromise` from `../utils/ngSession`.
## Consequences
**Positive:**
- Deletion actually persists
- Single source of truth (broker → ORM → UI)
**Negative:**
- Slight UI delay (~50ms) vs instant for property mutations
- Pattern diverges from ORM README examples
**Risks:**
- If `ng.sparql_update` API changes, this breaks
- Other delete operations (if added) must follow the same pattern
- The ORM `ngSet.delete()` bug may be fixed in a future version — revisit when upgrading `@ng-org/orm`
-84
View File
@@ -1,84 +0,0 @@
# Architecture
Feature-based architecture where code is organized by business domain (module), not by technical layer.
## Module Structure
```
src/modules/
event/ # 7 screens, 5 features — events CRUD, discovery, participants, meeting points
user/ # 5 screens, 11 features — profiles, friends, sharing
home/ # 2 screens — dashboard, settings
auth/ # 2 screens — login, welcome/onboarding
workshop/ # 0 screens, 6 features — workshop/atelier specs (future)
meeting/ # 0 screens, 1 feature — meeting point specs
notification/ # 0 screens, 3 features — notification specs
```
Each module can contain:
- `screens/` — React screen components
- `features/` — Gherkin `.feature` files (BDD specs)
- `steps/{ui,data,e2e}/` — Cucumber step definitions by layer
## Import Rules
**Modules only import from `shared/` — never from each other.**
```
src/modules/event/screens/EventDetailScreen.tsx
✅ import from '../../../shared/components/sketchy'
✅ import from '../../../shared/context/FestipodDataContext'
✅ import from '../../../screens' (registry types)
❌ import from '../../user/screens/...'
```
## Shared Layer
`src/shared/` contains everything reusable across modules:
| Directory | Contents |
|-----------|----------|
| `components/sketchy/` | Hand-drawn UI library (Button, Card, Avatar, Header, NavBar, etc.) |
| `components/ui/` | Shadcn/Radix components (used only in prototyping tool) |
| `context/` | ThemeContext, NextGraphContext, FestipodDataContext |
| `data/` | User stories (`index.ts`), auto-generated `features.ts`, `testResults.ts`, `seedData.ts`, `types.ts` |
| `hooks/` | `useShapeWithDefaults` (NextGraph) |
| `shapes/` | SHEX definitions + ORM TypeScript bindings |
| `utils/` | `ngSession.ts`, `ngBootstrap.ts` |
| `steps/ui/` | Shared BDD step definitions (navigation, screen, form) |
| `support/` | Cucumber `world.ts`, `hooks.ts` |
| `types/` | `gherkin.ts` (ParsedFeature, ParsedScenario types) |
| `lib/` | `utils.ts` (cn helper for Tailwind) |
## App Shell
`src/app/` is the prototyping tool — not part of the Festipod app itself:
- `App.tsx` — Root: ThemeProvider > NextGraphProvider > FestipodDataProvider > RouterProvider
- `router.tsx` — Hash-based routing: `#/` (gallery), `#/demo/{screenId}`, `#/specs/{featureId}`
- `frontend.tsx` — React entry point (referenced from `src/index.html`)
- `components/Gallery.tsx` — Screen preview grid
- `components/DemoMode.tsx` — Interactive mockup viewer with sidebar navigation
- `components/specs/` — BDD specs browser (SpecsPage, FeatureView, GherkinHighlighter)
## Screen Registry
`src/screens/index.ts` is the central registry that imports all screens from all modules and exports:
- `screenGroups` — Grouped by domain (Accueil, Evenements, Utilisateur, General)
- `screens` — Flat list
- `getScreen(id)` — Lookup by ID
- `ScreenProps` interface — `{ navigate: (screenId: string) => void }`
## Entry Points
| File | Purpose |
|------|---------|
| `src/index.ts` | Bun.serve() — HTTP server, serves index.html + cucumber report |
| `src/index.html` | HTML entry, loads `src/app/frontend.tsx` |
| `src/app/frontend.tsx` | React root, renders `<App />` |
## Build
- Dev: `bun --hot src/index.ts` (via `bun run dev`)
- Prod: `bun run build.ts` — Bun bundler + Tailwind plugin → `dist/`
- Path alias: `@/*``./src/*` (tsconfig)
-113
View File
@@ -1,113 +0,0 @@
# BDD Testing
Cucumber/Gherkin BDD specs in French with multi-layer step definitions.
## Overview
- 26 feature files (US-1 to US-26), all in French
- Categories: EVENT, WORKSHOP, USER, MEETING, NOTIF
- Priorities: 0 (Impossible), 1 (Haute), 2 (Moyenne), 3 (Basse)
- Current results: 51 passed, 7 failed, 75 skipped (133 scenarios total)
## Multi-Layer BDD
Each module has step directories for three test layers:
```
src/modules/event/steps/
ui/ # UI/screen assertions (source analysis)
data/ # Data layer assertions (Playwright + broker)
e2e/ # E2E assertions (Playwright + broker + real app UI)
```
Shared steps (cross-domain) live in `src/shared/steps/ui/`.
## Feature Files
Collocated with their module:
```
src/modules/event/features/us-13-creer-evenement.feature
src/modules/user/features/us-23-connexion-utilisateurs.feature
src/modules/workshop/features/us-1-visualiser-atelier-termine.feature
...
```
Tagged with `@CATEGORY @priority-N` for filtering.
## Step Definitions
### Shared Steps (`src/shared/steps/ui/`)
| File | Purpose |
|------|---------|
| `navigation.steps.ts` | Screen navigation, authentication, click/select actions, section/button/field assertions |
| `form.steps.ts` | Form field validation, required fields, import/duplicate detection |
| `screen.steps.ts` | Screen content assertions (participants, events, profiles, QR codes) |
### How UI Steps Work
`@ui` steps render the screen with `LocalDataProvider` (seed data) and `RouterProvider` via happy-dom, then assert on the rendered DOM. The render helper lives in `src/shared/test-harness/renderHelper.tsx` and is invoked from `world.ts:renderCurrentScreen()` on every `navigateTo(...)`.
See [test-layer-contracts](./test-layer-contracts.md) for what `@ui` is allowed to test and the patterns to follow (and avoid).
Legacy: `screenFileMap`, `screenFieldDetectors`, `screenExpectedContent`, `screenRequiredFields` in `world.ts` are vestiges of an earlier source-code-grep approach. `hasText`/`hasField`/`hasElement` now prefer the rendered DOM and fall back to source so unmigrated steps keep working during the transition.
### Screen Name Resolution
French names in `.feature` files map to screen IDs via `screenNameMap`:
- `"accueil"``home`
- `"détail événement"``event-detail`
- `"mon profil"``profile`
- `"relayer un événement"``create-event`
## Cucumber Configuration
`cucumber.json`:
```json
{
"default": {
"import": [
"src/shared/support/**/*.ts",
"src/shared/steps/**/*.ts",
"src/modules/*/steps/**/*.ts"
],
"paths": ["src/modules/*/features/**/*.feature"],
"language": "fr"
}
}
```
Requires `tsx` loader: `node --import tsx/esm node_modules/.bin/cucumber-js`
## Auto-Generated Files
Scripts in `scripts/` parse features and steps into TypeScript data files consumed by the prototyping tool:
| Script | Input | Output |
|--------|-------|--------|
| `parse-features.ts` | `src/modules/*/features/*.feature` | `src/shared/data/features.ts` |
| `parse-test-results.ts` | `reports/cucumber-report.json` | `src/shared/data/testResults.ts` |
| `extract-step-definitions.ts` | `src/shared/steps/ui/*.ts` | `src/shared/data/stepDefinitions.ts` |
Run all: `bun run test:cucumber`
## Data-Layer Testing
`@data` scenarios test through the real NextGraph broker. See [data-layer-testing](./data-layer-testing.md) for full architecture.
## E2E Testing
`@e2e` scenarios test the real app running in the broker iframe. See [data-layer-testing](./data-layer-testing.md#e2e-layer) for architecture. Key differences from `@data`:
- Uses the **real app** (not a test harness) served on a local HTTP port
- Interacts via Playwright locators and `evaluate()` on the app iframe
- Tests actual UI behavior: navigation, redirects, button clicks, screen content
- Requires real broker mode (fails with `Error` if broker unavailable)
## Adding New Steps
1. **Module-specific**: Create in `src/modules/{module}/steps/ui/`
2. **Cross-domain**: Add to `src/shared/steps/ui/`
3. Import `FestipodWorld` type from `../../support/world` (shared) or adjust relative path
4. Run `bun run steps:extract` to regenerate tooltip data
-177
View File
@@ -1,177 +0,0 @@
# Data-Layer Testing
BDD scenarios tagged `@data` test the real NextGraph data pipeline through a broker, not mocked data.
## Overview
`@data` scenarios run Cucumber steps against a real NextGraph broker. Playwright drives a Chromium instance that authenticates with the broker, which loads our test harness in an iframe. The harness uses real `useShape`/ORM subscriptions and exposes a `window.__testData` bridge for step definitions.
## Architecture
```
Cucumber steps → Playwright (Chromium, persistent profile)
https://nextgraph.eu/auth/#/?o=http://127.0.0.1:{port}
Broker wallet login (automated)
Broker loads app in iframe → http://127.0.0.1:{port}
harness-ng.tsx (init → useShape → ORM → broker)
window.__testData bridge
```
## Dual Mode
- **Real broker** (default): `harness-ng.tsx` with NextGraph ORM through broker iframe
- **Mock fallback**: `harness.tsx` with standalone DeepSignalSets (if NG harness build fails)
## Wallet Lifecycle
Fully automated — no manual interaction required. CI-ready.
### First Run (wallet creation + bootstrap)
1. `BeforeAll` detects no `.wallet-ready` marker in `.playwright-profile/`
2. Launches headless Chromium with persistent profile
3. Navigates to `https://nextgraph.eu/` → clicks "Create Wallet"
4. Redirected to `account.nextgraph.eu` → clicks "I accept" (ToS)
5. Redirected back → fills username/password form → submits
6. Wallet created in localStorage
7. **Logs in to the wallet** — this triggers the verifier bootstrap from the remote broker, populating localStorage with repo data
8. Waits 10s for bootstrap to complete, then closes context
9. Marker written
Step 7 is critical: the NextGraph verifier starts with an empty `repos` HashMap. On first login, `verifier.sync()` bootstraps from the remote broker, downloading repo data (including store repos). This data is saved to localStorage via `session_save`. Without this initial login, subsequent sessions would have empty repos and all writes would fail with `RepoNotFound`.
### Subsequent Runs (automated login)
1. Marker found → skip wallet creation
2. Headless Chromium with persistent profile
3. Automated login: click "Login" → click wallet link → fill password → submit
4. Broker authenticates, loads app harness in iframe
5. Harness initializes NG, creates ORM subscriptions, seeds data if needed
6. `window.__testData.ready` → steps execute via `appFrame.evaluate()`
### Wallet Credentials
- Name: `festipod-tests`
- Password: `festipod-tests`
## Key Technical Details
### Chromium Flags
```
--disable-features=PrivateNetworkAccessRespectPreflightResults,BlockInsecurePrivateNetworkRequests,...
--allow-insecure-localhost
--disable-web-security
```
Required because broker at `nextgraph.eu` (public) loads harness from `http://127.0.0.1:{port}` (local) in an iframe — Chromium's Private Network Access blocks this by default.
### Persistent Profile (`.playwright-profile/`)
- Stores NG wallet in localStorage (`ng_wallets` on `nextgraph.eu`, `ng_bootstrap` on `nextgraph.net`)
- Gitignored
- Must use full Chrome binary, not `chrome-headless-shell`
### HTTP Server
- Started in `BeforeAll` on auto-assigned port (`127.0.0.1:0`)
- Serves harness HTML at `/` and JS bundle at `/harness.js` (separate files — inline script breaks due to special characters in bundle)
- Shut down in `AfterAll`
### ORM Subscriptions
Harness creates subscriptions for all three shapes with scope `did:ng:${session.private_store_id}` (opens the store repo for reads AND writes):
- `FpEventShapeType` → events
- `FpUserProfileShapeType` → users
- `FpParticipationShapeType` → participations
### Test Bridge (`window.__testData`)
Exposed by the harness, consumed by steps via `appFrame.evaluate()`:
- `events`, `users`, `participations` — live DeepSignalSets
- `currentUserId` — IRI of the test user
- `getEvent(id)`, `getEventByTitle(title)` — lookups
- `joinEvent(eventId, userId)`, `leaveEvent(eventId, userId)` — mutations
- `isParticipating(eventId, userId)`, `getEventParticipants(eventId)` — queries
- `updateEvent(eventId, updates)` — field updates
## E2E Layer (`@e2e`)
`@e2e` scenarios test the real app UI running inside the broker iframe. Unlike `@data` which loads a test harness, `@e2e` loads the actual app.
### Architecture
```
Cucumber steps → Playwright (Chromium, persistent profile)
https://nextgraph.net/redir/#/?o=http://127.0.0.1:{appPort}
Broker wallet login (automated, same as @data)
Broker loads REAL APP in iframe → http://127.0.0.1:{appPort}
App renders with NextGraphProvider auto-connecting
Steps interact via appFrame.evaluate() and Playwright locators
```
### App Server
Started in `BeforeAll` alongside the harness server:
1. Find a free port
2. `spawn('bun', ['src/index.ts'], { env: { PORT: appPort } })`
3. Poll until the server responds to HTTP GET
4. Killed in `AfterAll`
### Shared Infrastructure
`@e2e` reuses the same `setupBrokerPage()` helper as `@data` — handles broker redirect URL construction, wallet login automation, and iframe discovery.
### Step Definitions
E2E steps live in module directories (e.g., `src/modules/auth/steps/e2e/connexion.steps.ts`). They use:
- `this.appFrame!.evaluate()` — run JS in the app iframe (hash navigation, content checks)
- `this.appFrame!.locator()` — find and interact with DOM elements
- `this.appFrame!.waitForFunction()` — poll for expected state (screen content, URL changes)
- `SCREEN_MARKERS` — map screen IDs to unique text content for verification
### Before Hook (`@e2e`)
```
1. Open new Playwright page
2. setupBrokerPage(page, realAppUrl) → automated login → find app iframe
3. Wait for React render (root.innerHTML.length > 100)
4. Wait 3s for NG connection + provider stabilization
```
### Differences from `@data`
| Aspect | `@data` | `@e2e` |
|--------|---------|--------|
| What loads in iframe | Test harness (`harness-ng.tsx`) | Real app (`src/index.ts`) |
| Ready signal | `window.__testData.ready === true` | `root.innerHTML.length > 100` |
| Interaction | `evaluate()` on test bridge | `evaluate()` + Playwright locators |
| Mock fallback | Yes (standalone DeepSignalSets) | No — requires real broker |
| Tests | Data operations (CRUD, queries) | UI behavior (navigation, redirects, clicks) |
## Files
| File | Purpose |
|------|---------|
| `src/shared/test-harness/harness-ng.tsx` | Real broker harness (useShape through broker iframe) |
| `src/shared/test-harness/harness.tsx` | Mock harness (DeepSignalSets, no broker) |
| `src/shared/support/hooks.ts` | Playwright lifecycle (wallet creation, login automation, iframe detection, app server) |
| `src/shared/support/world.ts` | World with `page`/`appFrame` fields |
| `src/modules/event/steps/data/inscription.steps.ts` | Inscription data steps |
| `src/modules/auth/steps/e2e/connexion.steps.ts` | Auth/connection e2e steps |
| `.playwright-profile/` | Persistent Chromium profile (gitignored) |
| `scripts/debug-browser.ts` | Manual browser debug tool — launches headed Chromium to inspect broker interactions |
| `.playwright-profile-debug/` | Chromium profile created by debug-browser.ts (gitignored) |
## Commands
```bash
bun run test:data # Run @data scenarios (real broker if wallet exists, mock fallback)
bun run test:cucumber # Run all scenarios (UI + data + e2e)
```
## See Also
- [BDD Testing](./bdd-testing.md) — general Cucumber setup, UI-layer steps
- [Data Layer](./data-layer.md) — NextGraph stack, shapes, context providers
-115
View File
@@ -1,115 +0,0 @@
# Data Layer
NextGraph-backed local-first data with fallback to local state for demo/disconnected mode.
## Overview
The app has two data modes:
1. **Connected** — NextGraph ORM shapes (P2P, encrypted, local-first)
2. **Disconnected/Demo** — Local React state seeded from `seedData.ts`
All screens use `useFestipodData()` hook regardless of mode.
## NextGraph Stack
```
@ng-org/web # Browser WASM runtime
@ng-org/orm # RDF shape-based ORM
@ng-org/shex-orm # SHEX → TypeScript code generation
@ng-org/alien-deepsignals # Reactive signals bridge
```
Packages installed from npm (`@ng-org/*` alpha versions). For local development against an unreleased `nextgraph-rs` build, `scripts/build-ng-packages.sh` packs the monorepo into `.ng-tarballs/` and updates `package.json` to point at those paths.
## SHEX Shapes
`src/shared/shapes/shex/festipodShapes.shex` defines:
- **Event** — title, description, dates, location, themes, participants
- **UserProfile** — name, username, bio, city, visibility
- **Participation** — links event + user, confirmation status
ORM bindings in `src/shared/shapes/orm/`:
- `festipodShapes.schema.ts` — Schema registration
- `festipodShapes.shapeTypes.ts` — Shape type constants
- `festipodShapes.typings.ts` — TypeScript interfaces
Regenerate with `bun run build:orm`.
## NextGraph Read/Write Pattern
The app follows the same pattern as the official expense-tracker-rdf example:
- **Scope**: `useShape(shapeType, `did:ng:${session.private_store_id}`)` — opens the private store repo in the verifier
- **@graph**: `did:ng:${session.private_store_id}` — writes target the same NURI
This is critical: `orm_start_graph` with the private store NURI explicitly opens the repo in the verifier's `self.repos` HashMap. Without this, `orm_frontend_update` fails with `RepoNotFound`.
**Do NOT use `did:ng:i` as scope** — it subscribes to the entire user site via a special code path that doesn't open individual repos, breaking all writes.
### Deleting Objects
`ngSet.delete(item)` updates the local reactive set but does **not** persist to the broker. Use `ng.sparql_update()` with SPARQL DELETE instead:
```typescript
import { ng } from '@ng-org/web';
import { sessionPromise } from '../utils/ngSession';
const session = await sessionPromise;
await ng.sparql_update(
session.session_id,
`DELETE WHERE { GRAPH <${item["@graph"]}> { <${item["@id"]}> ?p ?o } }`,
item["@graph"],
);
```
The broker sends back a `GraphOrmUpdate` with `op: "remove"` that reactively removes the item from the ORM set. **Do NOT combine with `ngSet.delete()`** — the two operations conflict in the CRDT.
See [decision record](../decisions/2026-03-17-1800-sparql-delete-for-orm-objects.md) for details.
### Key files
- `src/shared/hooks/useShapeWithDefaults.ts` — Accepts `storeNuri` param, passes to `useShape`
- `src/shared/utils/ngGraph.ts``ensureGraphNuri()` returns `@graph` for entity creation
- `src/shared/utils/ngBootstrap.ts` — Seeds test data using `ensureGraphNuri()` for `@graph`
See [decision record](.project/decisions/2026-03-17-1600-private-store-nuri-scope.md) for why.
## Context Providers
### NextGraphContext (`src/shared/context/NextGraphContext.tsx`)
- Connection lifecycle: `disconnected``connecting``connected` | `error`
- Provides session with store IDs (private, protected, public)
- **Conditional auto-init**: Only auto-calls `initNg()` when running inside the broker iframe (`window.self !== window.top`). Outside the iframe, `initNgWeb()` would redirect the page to the broker — so connection waits for explicit `connect()` call.
- `connect()`: Called by user clicking "Se connecter". When outside broker, triggers the redirect flow.
#### `@ng-org/web` redirect behavior
`initNgWeb()` checks `window.self === window.top`. If the app is NOT in an iframe, it redirects to `nextgraph.net/redir/` with the current URL encoded as a return parameter. The broker then loads the app back in an iframe after auth. This means the app must NOT auto-init NG when loaded standalone.
### FestipodDataContext (`src/shared/context/FestipodDataContext.tsx`)
- Wraps NextGraph shapes with `useShapeWithDefaults()` hook
- CRUD: `createEvent()`, `updateEvent()`, `joinEvent()`, `leaveEvent()`, etc.
- Exposes `useFestipodData()` hook consumed by all screens
- `selectedEventId` state for cross-screen event navigation
- `loadTestData()`: Calls `bootstrapWallet()` to seed test data into NG wallet — only triggered by explicit user action
- **Provider states based on NG status**:
- `disconnected``LocalDataProvider` with seed data (demo mode)
- `connecting``LocalDataProvider` with **empty data** (avoids flashing seed data before wallet loads)
- `connected``NgDataProvider` with real wallet data
- `error``LocalDataProvider` with seed data (graceful fallback)
## Data Types
`src/shared/data/types.ts`:
- `FpEventData` — id, title, date, location, distance, themes, etc.
- `FpUserData` — id, name, username, bio, city, counts
- `FpParticipationData` — eventId + userId + confirmed
- `FpMeetingPointData` — eventId, location, time, host (local-only)
- `FpFriendshipData` — userId + friendId (local-only)
## Seed Data
`src/shared/data/seedData.ts`:
- 10 users (Marie Dupont = current user, `user-1`)
- Multiple events with dates, locations, themes
- Participations, meeting points, friendships
- `CURRENT_USER_ID = 'user-1'`
-94
View File
@@ -1,94 +0,0 @@
# Screens
16 mobile mockup screens using the sketchy hand-drawn component library.
## Screen Inventory
### Home Module (`src/modules/home/screens/`)
| ID | Name | File | Description |
|----|------|------|-------------|
| `welcome` | Bienvenue | WelcomeScreen.tsx | Onboarding/welcome page |
| `home` | Accueil | HomeScreen.tsx | Dashboard with upcoming events, quick actions |
| `settings` | Parametres | SettingsScreen.tsx | Notifications, privacy, location settings |
### Event Module (`src/modules/event/screens/`)
| ID | Name | File | Description |
|----|------|------|-------------|
| `events` | Decouvrir | EventsScreen.tsx | Event discovery/search |
| `event-detail` | Detail evenement | EventDetailScreen.tsx | Event info, participants, join/leave |
| `create-event` | Relayer evenement | CreateEventScreen.tsx | Create/relay event, import from Mobilizon/Transiscope |
| `update-event` | Modifier evenement | UpdateEventScreen.tsx | Edit existing event |
| `invite` | Inviter des amis | InviteScreen.tsx | Invite contacts to event |
| `participants-list` | Liste des participants | ParticipantsListScreen.tsx | Event participant list |
| `meeting-points` | Points de rencontre | MeetingPointsScreen.tsx | Carpooling/meeting coordination |
### User Module (`src/modules/user/screens/`)
| ID | Name | File | Description |
|----|------|------|-------------|
| `profile` | Mon profil | ProfileScreen.tsx | Current user profile |
| `update-profile` | Modifier mon profil | UpdateProfileScreen.tsx | Edit profile form |
| `user-profile` | Profil d'un utilisateur | UserProfileScreen.tsx | View another user's profile |
| `friends-list` | Mon reseau | FriendsListScreen.tsx | Network/friends list |
| `share-profile` | Partager mon profil | ShareProfileScreen.tsx | QR code + link sharing |
### Auth Module (`src/modules/auth/screens/`)
| ID | Name | File | Description |
|----|------|------|-------------|
| `login` | Connexion | LoginScreen.tsx | Login (NextGraph + email fallback) |
## Screen Registry
`src/screens/index.ts` imports all screens and exports:
```typescript
export interface ScreenProps {
navigate: (screenId: string) => void;
}
export const screenGroups: ScreenGroup[] // Grouped: home, events, user, general
export const screens: Screen[] // Flat list
export function getScreen(id: string): Screen | undefined
```
## Sketchy Component Library
`src/shared/components/sketchy/` — hand-drawn UI with custom font:
| Component | Usage |
|-----------|-------|
| `Header` | Screen header with back button |
| `NavBar` | Bottom tab navigation |
| `Button` | Action buttons |
| `Card` | Content cards |
| `Input` | Text inputs |
| `Title`, `Subtitle`, `Text` | Typography |
| `Avatar` | User avatars with initials |
| `Badge` | Status/category badges |
| `Toggle`, `Checkbox` | Form controls |
| `ListItem` | List row items |
| `Divider` | Section separators |
| `Placeholder` | Image/content placeholders |
| `PhoneFrame` | Phone device frame wrapper |
| `BrokerBanner` | NextGraph connection status banner |
| `NgStatus` | Connection indicator dot |
## Screen Patterns
All screens follow the same pattern:
```typescript
import { Header, Button, ... } from '../../../shared/components/sketchy';
import { useFestipodData } from '../../../shared/context/FestipodDataContext';
import type { ScreenProps } from '../../../screens';
export function MyScreen({ navigate }: ScreenProps) {
const { events, currentUser, ... } = useFestipodData();
// render with sketchy components
}
```
Navigation between screens uses `navigate(screenId)` — the prototyping tool intercepts this to switch the displayed screen.
@@ -1,90 +0,0 @@
# Test Layer Contracts
Each BDD test layer (`@ui`, `@data`, `@e2e`) answers a distinct question. Mixing concerns produces brittle tests that fail on refactors without catching real regressions.
## Overview
```
/\ @e2e ~10 scénarios, parcours utilisateur critiques
/ \
/----\
/ @data\ ~10 scénarios, mutations & persistance NG
/--------\
/ @ui \ ~60 scénarios, 1-5 par état d'écran × 15 écrans
/____________\
```
The pyramid reflects cost: `@ui` runs in-process (instant), `@data` boots a broker (~50s for the suite), `@e2e` boots broker + real app + navigates a real browser (~2min). Move every assertion to the lowest layer that can answer the question — UI rendering claims belong in `@ui`, not `@e2e`.
## Key Concepts
- **`@ui` — display layer.** Renders a screen with `LocalDataProvider` (seed data) + happy-dom and asserts on the resulting DOM. Verifies that *given known data, the screen shows the expected text and elements*. Does **not** test navigation outcomes, mutations, or data persistence.
- **`@data` — data layer.** Drives ORM mutations through the real NextGraph broker via a headless test harness. No app UI involved. Verifies that *operations on shapes are correctly persisted and observable in the wallet*. See [data-layer-testing](./data-layer-testing.md).
- **`@e2e` — integration layer.** Boots the real app inside the broker iframe with a Playwright-controlled Chromium. Verifies that *layers collaborate to deliver a user journey* (e.g. create → list → modify → reload → still there). Sparse: 1 scenario per critical path; never duplicate `@ui` content checks here.
## Implementation
### `@ui` — rendering helper
`src/shared/test-harness/renderHelper.tsx` installs happy-dom globals and renders any screen wrapped in `LocalDataProvider` + `RouterProvider`. Called from `world.ts:renderCurrentScreen()` on every `navigateTo(...)`. Seed data (`src/shared/data/seedData.ts`) provides predictable fixtures — `Marie Dupont`/`@mariedupont` is `currentUser`, `Jean Durand`/`@jeandurand` exists in `users`, 5 seed events, etc.
**Good `@ui` assertion patterns:**
```ts
// Text visible to the user
expect(this.getDomText()).to.include('Marie Dupont');
// Element presence by class/role
expect(this.renderedDoc!.querySelector('.app-avatar')).to.not.be.null;
// Conditional rendering (filled state vs empty state)
const cards = this.renderedDoc!.querySelectorAll('.app-card');
expect(cards.length).to.be.greaterThan(0);
// Required form fields rendered with their label + asterisk
const labels = Array.from(this.renderedDoc!.querySelectorAll('p'))
.map(p => p.textContent ?? '');
expect(labels.some(t => t.includes("Nom de l'événement *"))).to.be.true;
```
**Anti-patterns to remove:**
```ts
// ❌ Regex on source: couples test to code structure, fails on refactor
expect(/<Title[^>]*>Marie Dupont<\/Title>/.test(source)).to.be.true;
// ❌ Testing implementation details
expect(/showDuplicateWarning/.test(source)).to.be.true;
expect(/importableEvents/.test(source)).to.be.true;
// ❌ Testing JSX structure rather than rendered output
expect(/<Avatar[^>]*initials="MD"[^>]*size="lg"/.test(source)).to.be.true;
```
### `@data` — broker-only
Already isolated correctly. See [data-layer-testing](./data-layer-testing.md). Don't touch the DOM here; use the test harness bridge (`window.__testData`).
### `@e2e` — full stack
Path-based routing: navigate via `window.history.pushState` + `popstate` dispatch (`src/modules/auth/steps/e2e/connexion.steps.ts`). Assert on actual DOM text after `appFrame.waitForFunction`. **Do not** re-verify here what `@ui` already covers — `@e2e` should fail when *collaboration* between layers breaks, not when an icon changes.
## Migration Consequences
The current `@ui` suite predates this contract. The migration plan:
1. **Rewrite source-grep assertions** → DOM queries via the helper. The `world.ts:hasText/hasField/hasElement` methods already prefer the rendered DOM and fall back to source — so unmigrated steps still work during the transition.
2. **Delete tests on implementation details** (`/showDuplicateWarning/`, `/importableEvents/`, regex on JSX). They protect nothing the user sees.
3. **Move behavioral assertions to `@e2e`** when not already covered ("clicking Suivant advances the wizard" — exercise it via Playwright if it's not redundant with existing journeys).
4. **Drop redundant `@e2e` content checks** that duplicate `@ui` (e.g. "screen contains 'Découvrir'" — let `@ui` own that).
`world.ts:screenFileMap`, `screenFieldDetectors`, `screenExpectedContent`, `screenRequiredFields` are vestiges of the source-analysis era. Once the migration is complete, they can be removed in favor of seed-data assertions on the rendered DOM.
## See Also
- [BDD Testing setup](./bdd-testing.md) — Cucumber config, file layout, scripts
- [Data Layer](./data-layer.md) — NextGraph shapes, seed data, contexts
- [Data-Layer Testing](./data-layer-testing.md) — broker harness, wallet setup, Playwright
- [Architecture](./architecture.md) — module structure
+4
View File
@@ -0,0 +1,4 @@
# To discuss
- [ ] revoir l'implémentation des ReadCap et WriteCap, aligner avec NextGraph et vérifier que le polyfill enforce bien la logique de droits d'accès en attendant que cela soit implémenté
- [ ] clarifier la terminologie identité NextGraph (wallet = liste de clés ; user = données + username ; profils = identités contenues dans le user) et réconcilier avec decision_2026-07-06 (« identifiant = wallet »), decision_2026-07-20 (« username dans le profil ») et le modèle principal/identity du polyfill
+27 -62
View File
@@ -1,75 +1,40 @@
# Festipod
Mobile-first web app for discovering and sharing festival/event recommendations through trusted networks.
Web app mobile-first où les utilisateurs créent des **points de rencontre** qui se *greffent* sur des **événements publics** existants, pour favoriser les rencontres. L'événement n'est qu'un prétexte/ancrage ; la valeur, c'est le point de rencontre — **on s'inscrit à un point de rencontre, pas à un événement**. Stack : Bun + React + NextGraph (P2P, local-first, chiffré).
## Architecture
## Invariants à toujours garder
Feature-based: code organized by business domain, not technical layer. See [architecture](.project/knowledge/architecture.md).
- **Architecture feature-based** : le code est organisé par domaine métier, pas par couche technique.
```
src/modules/{event,user,home,auth,workshop,meeting,notification}/
src/shared/ # Composants, context, data — importable par tous les modules
src/app/ # App shell (router, providers, entrée)
src/screens/index.ts # Registre d'écrans (utilisé par Storybook)
```
- **Un module n'importe QUE depuis `shared/` — jamais d'un autre module.** C'est l'invariant qui rend l'archi réelle.
- **Bun-first** : `bun` / `bun install` / `bun test` / `bun build`, jamais node/npm/vite/jest. `bun run dev` (port 3000).
```
src/modules/{event,user,home,auth,workshop,meeting,notification}/
src/shared/ # Components, context, data — importable by all modules
src/app/ # App shell (router, providers, entry point)
src/screens/index.ts # Screen registry (used by Storybook)
```
## Frontière SDK NextGraph
## Routing
Le SDK de données de Festipod est **`@ng-eventually/client`** — traité comme un **SDK NextGraph fini et mature** (documents par entité placés par scope public/protected/private, capabilities, inboxes). Il est injecté une seule fois via `ngSession.configure(...)`.
Path-based routing with History API (custom router in `src/app/router.tsx`).
**`@ng-eventually/client` est un POLYFILL**, et ce mot dit toute sa mission : **compenser l'écart** entre le SDK **tel qu'il devrait être** et ce que NextGraph fournit **aujourd'hui**. Le wallet virtuel (plusieurs identités sur un wallet physique) en est la plus grosse pièce, pas la totalité.
| Path | Screen |
|------|--------|
| `/` | WelcomeScreen |
| `/login` | LoginScreen |
| `/home` | HomeScreen |
| `/events` | EventsScreen |
| `/events/new` | CreateEventScreen |
| `/events/:id` | EventDetailScreen |
| `/events/:id/edit` | UpdateEventScreen |
| `/events/:id/invite` | InviteScreen |
| `/events/:id/participants` | ParticipantsListScreen |
| `/events/:id/meeting-points` | MeetingPointsScreen |
| `/profile` | ProfileScreen |
| `/profile/edit` | UpdateProfileScreen |
| `/profile/friends` | FriendsListScreen |
| `/profile/share` | ShareProfileScreen |
| `/users/:id` | UserProfileScreen |
| `/settings` | SettingsScreen |
**L'app ignore ENTIÈREMENT l'état d'implémentation de NextGraph.** Elle est codée contre le SDK cible, dont le contrat est écrit **dans ce repo** (concept `data-layer`, fiche `knowledge_sdk-surface`). Aucun code ni commentaire du type « on fait X parce que NextGraph fait Y aujourd'hui ». Quand quelque chose ne marche pas, la question n'est jamais « comment contourner dans l'app » mais **« qu'est-ce que le polyfill doit compenser »**.
Screens use `useNavigate()` and `useParams()` hooks from the router — no prop drilling.
**Ne jamais documenter dans ce repo l'état courant de NextGraph** (contraintes du SDK sous-jacent, contournements, internes broker/verifier) : cela vit dans le repo `@ng-eventually/client`. La doctrine Festipod décrit uniquement *le contrat SDK cible* + *comment Festipod l'utilise* + le domaine + l'architecture + le contrat BDD.
## Data Layer
## Doctrine du projet — concepts (livrée automatiquement)
NextGraph (P2P/local-first) with SHEX shapes and ORM. See [data-layer](.project/knowledge/data-layer.md).
La connaissance détaillée vit dans `.project/concepts/` (système *concept*) : fiches courtes, typées, **livrées par un hook quand tu touches leur territoire** — tu n'as pas à les charger d'avance. Les 6 concepts :
## BDD Testing
| Concept | Couvre |
|---|---|
| `functional-domain` | Modèle produit : point de rencontre, acteurs, concepts métier, périmètres public/protected/private par entité, découverte, défi déduplication |
| `app-architecture` | Modules, invariant d'imports, app shell, routing path-based, écrans |
| `tech-stack` | Bun-first, APIs Bun, build pipeline, commandes |
| `data-layer` | Persistance via le SDK `@ng-eventually/client` : entités-documents par scope, shapes SHEX/ORM, modes connected/demo, pièges |
| `bdd-testing` | Cucumber multi-couches FR, contrat `@ui`/`@data`/`@e2e`, harness broker, cookbook |
| `app-security` | Isolation déléguée au SDK (pas de contrôle d'accès dans les écrans), auth wallet, matrice d'autorisations cible |
Multi-layer Cucumber/Gherkin in French. See [bdd-testing](.project/knowledge/bdd-testing.md) for the setup and [test-layer-contracts](.project/knowledge/test-layer-contracts.md) for what each layer is allowed to test.
`@ui` scenarios render screens in-process (happy-dom + seed data) and assert on the DOM. `@data` scenarios test data operations through the real NextGraph broker. `@e2e` scenarios test the real app UI in the broker iframe. See [data-layer-testing](.project/knowledge/data-layer-testing.md).
## Quick Start
```bash
bun run dev # Dev server with HMR (port 3000)
bun run build # Production build to dist/
bun run storybook # Browse screens and components
bun run test:cucumber # Run all BDD tests
bun run features:parse # Regenerate features.ts from .feature files
bun run steps:extract # Extract step definitions for tooltips
bun run build:orm # Regenerate ORM from SHEX shapes
```
## Documentation
- [Architecture](.project/knowledge/architecture.md) — module structure, import rules, app shell
- [Data Layer](.project/knowledge/data-layer.md) — NextGraph, shapes, context, seed data
- [BDD Testing](.project/knowledge/bdd-testing.md) — Cucumber setup, step layers, feature files
- [Test Layer Contracts](.project/knowledge/test-layer-contracts.md) — what each of `@ui`/`@data`/`@e2e` is allowed to test
- [Screens](.project/knowledge/screens.md) — screen inventory, registry, sketchy components
- [Data-Layer Testing](.project/knowledge/data-layer-testing.md) — real broker testing, wallet setup, Playwright harness, e2e layer
## Briefs (work not yet started)
- [Multi-store refactor](.project/briefs/multi-store-refactor.md) — passer du mono-store actuel à une structure de Group stores par communauté/event/RDV (prérequis multi-user)
- [Matrice d'autorisations et requêtes](.project/briefs/authorization-matrix.md) — analyse qui doit guider la structure de stores cible
Pour **documenter** un fait projet : `/concept document <sujet>` (ne pas écrire en libre dans `.project/`).
+4 -191
View File
@@ -2,195 +2,8 @@
# Festipod Project
Mobile-first web app for discovering and sharing festival/event recommendations through trusted networks. Uses a sketchy hand-drawn UI style.
Le cœur toujours-chargé (but produit, invariants, conventions Bun-first, carte des concepts) vit dans `@AGENTS.md` ci-dessus. Toute la doctrine détaillée est dans `.project/concepts/` et **livrée automatiquement par le hook concept** quand tu touches le territoire concerné — ne la recopie pas ici.
## Architecture
Feature-based architecture: code is organized by business domain (module), not by technical layer. A module can only import from `shared/` — never from another module.
Multi-layer BDD: each module has `steps/ui/`, `steps/data/`, `steps/e2e/` directories. Shared step definitions live in `src/shared/steps/`.
## Project Structure
```
src/
modules/ # Business domain modules
event/ # Events (create, discover, detail, update, invite, participants, meeting points)
screens/ # EventsScreen, EventDetailScreen, CreateEventScreen, etc.
features/ # Gherkin .feature files for this domain
steps/ # BDD step definitions
ui/ # UI-layer steps
data/ # Data-layer steps
e2e/ # E2E steps
user/ # User profiles, friends, sharing
screens/ # ProfileScreen, FriendsListScreen, ShareProfileScreen, etc.
features/
steps/
home/ # Home dashboard, settings
screens/ # HomeScreen, SettingsScreen
auth/ # Authentication, onboarding
screens/ # LoginScreen, WelcomeScreen
workshop/ # Workshop/atelier specs (no screens yet)
features/
steps/
meeting/ # Meeting point specs
features/
steps/
notification/ # Notification specs
features/
steps/
shared/ # Shared code (importable by all modules)
components/
sketchy/ # Hand-drawn UI components (Button, Card, Avatar, etc.)
ui/ # Shadcn/Radix components
context/ # ThemeContext, NextGraphContext, FestipodDataContext
data/ # User stories, features.ts (auto-generated), testResults.ts
hooks/ # Custom hooks (useShapeWithDefaults)
shapes/ # SHEX shapes + ORM bindings (NextGraph)
utils/ # ngSession, ngBootstrap
steps/ # Shared BDD step definitions (cross-domain)
ui/ # navigation.steps.ts, form.steps.ts, screen.steps.ts
data/
support/ # Cucumber hooks.ts, world.ts
types/ # TypeScript type definitions
lib/ # Utility functions (cn, etc.)
app/ # App shell
App.tsx # Root component with providers + route switch
router.tsx # Path-based routing (History API)
frontend.tsx # React entry point
screens/
index.ts # Screen registry (used by Storybook)
scripts/ # Build scripts for parsing features
docs/ # Documentation
.storybook/ # Storybook configuration
```
## Key Commands
```bash
bun run dev # Start dev server with HMR
bun run storybook # Browse screens and components in Storybook
bun run test:cucumber # Run Cucumber tests
bun run features:parse # Regenerate features.ts from .feature files
bun run steps:extract # Extract step definitions for tooltips
```
## Routing
Path-based routing via `src/app/router.tsx`. Screens use `useNavigate()` and `useParams()` hooks. See AGENTS.md for the full route table.
## Conventions
- Gherkin specs are in French (Etant donne, Quand, Alors)
- UI labels are in French
- User stories are prefixed US-1 to US-26
- Screens use the sketchy component library, not Tailwind
- Max app width: 768px (tablet portrait)
---
Default to using Bun instead of Node.js.
- Use `bun <file>` instead of `node <file>` or `ts-node <file>`
- Use `bun test` instead of `jest` or `vitest`
- Use `bun build <file.html|file.ts|file.css>` instead of `webpack` or `esbuild`
- Use `bun install` instead of `npm install` or `yarn install` or `pnpm install`
- Use `bun run <script>` instead of `npm run <script>` or `yarn run <script>` or `pnpm run <script>`
- Use `bunx <package> <command>` instead of `npx <package> <command>`
- Bun automatically loads .env, so don't use dotenv.
## APIs
- `Bun.serve()` supports WebSockets, HTTPS, and routes. Don't use `express`.
- `bun:sqlite` for SQLite. Don't use `better-sqlite3`.
- `Bun.redis` for Redis. Don't use `ioredis`.
- `Bun.sql` for Postgres. Don't use `pg` or `postgres.js`.
- `WebSocket` is built-in. Don't use `ws`.
- Prefer `Bun.file` over `node:fs`'s readFile/writeFile
- Bun.$`ls` instead of execa.
## Testing
Use `bun test` to run tests.
```ts#index.test.ts
import { test, expect } from "bun:test";
test("hello world", () => {
expect(1).toBe(1);
});
```
## Frontend
Use HTML imports with `Bun.serve()`. Don't use `vite`. HTML imports fully support React, CSS, Tailwind.
Server:
```ts#index.ts
import index from "./index.html"
Bun.serve({
routes: {
"/": index,
"/api/users/:id": {
GET: (req) => {
return new Response(JSON.stringify({ id: req.params.id }));
},
},
},
// optional websocket support
websocket: {
open: (ws) => {
ws.send("Hello, world!");
},
message: (ws, message) => {
ws.send(message);
},
close: (ws) => {
// handle close
}
},
development: {
hmr: true,
console: true,
}
})
```
HTML files can import .tsx, .jsx or .js files directly and Bun's bundler will transpile & bundle automatically. `<link>` tags can point to stylesheets and Bun's CSS bundler will bundle.
```html#index.html
<html>
<body>
<h1>Hello, world!</h1>
<script type="module" src="./frontend.tsx"></script>
</body>
</html>
```
With the following `frontend.tsx`:
```tsx#frontend.tsx
import React from "react";
import { createRoot } from "react-dom/client";
// import .css files directly and it works
import './index.css';
const root = createRoot(document.body);
export default function Frontend() {
return <h1>Hello, world!</h1>;
}
root.render(<Frontend />);
```
Then, run index.ts
```sh
bun --hot ./index.ts
```
For more information, read the Bun API docs in `node_modules/bun-types/docs/**.mdx`.
- Specs Gherkin et libellés UI en **français** (`Etant donné`, `Quand`, `Alors`).
- Conventions techniques (Bun, APIs, build) : concept `tech-stack`. Architecture et écrans : concept `app-architecture`.
- Documenter un fait projet : `/concept document <sujet>`.
+12 -4
View File
@@ -1,11 +1,19 @@
# Use the official Bun image
# Use the official Bun image (runtime stays Bun; only install moves to pnpm)
FROM oven/bun:1-alpine AS base
WORKDIR /app
# Install dependencies
# Install dependencies with pnpm.
# - git: the @ng-eventually/client polyfill is a git+https (public Gitea) dependency → no auth.
# - nodejs + npm: pnpm is a Node CLI; we pin the exact pnpm version via `npm i -g`
# (Alpine's nodejs package does not bundle corepack).
# The `bun` npm peer (pulled by bun-plugin-tailwind) is approved to build in package.json
# (pnpm.onlyBuiltDependencies) so node_modules/.bin/bun is a real binary — required because
# `bun run start` puts node_modules/.bin ahead of PATH.
FROM base AS install
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile
RUN apk add --no-cache git nodejs npm \
&& npm install -g pnpm@10.26.0
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile
# Copy source code and build assets
FROM base AS release
+4 -6
View File
@@ -40,7 +40,7 @@ Implémentées dans le code (écrans visibles via le router) :
- Liste d'amis (connexions)
- Profil d'un autre utilisateur
Voir le tableau des routes dans [AGENTS.md](./AGENTS.md#routing) et l'inventaire des écrans dans [.project/knowledge/screens.md](./.project/knowledge/screens.md).
Voir l'inventaire des routes et des écrans dans le concept [app-architecture](./.project/concepts/app-architecture/).
### Défis ouverts
@@ -56,7 +56,7 @@ Identifiées comme nécessaires (notamment pour la scalabilité et la découvert
- **Abonnement à une communauté d'intérêt** pour découvrir ses événements (mécanisme de discovery distribué).
- **Abonnement à un utilisateur** pour suivre les événements qu'il déclare (sans nécessairement être ami).
- **Listes curated** — créer et partager des sélections d'événements éditorialisées.
- **Multi-utilisateurs collaboratif** : aujourd'hui chaque utilisateur a ses données isolées dans son wallet. Le passage en mode collaboratif (un point de rencontre vu par plusieurs personnes) suppose un refactor de la couche données vers les Group stores NextGraph. Voir [brief multi-store-refactor](./.project/briefs/multi-store-refactor.md).
- **Multi-utilisateurs collaboratif** : aujourd'hui chaque utilisateur a ses données isolées dans son wallet. Le passage en mode collaboratif (un point de rencontre vu par plusieurs personnes) suppose un refactor de la couche données. Voir le concept [nextgraph-platform](./.project/concepts/nextgraph-platform/) (briefs multi-store, matrice d'autorisations, wallet partagé, fork inbox).
## Quick Start
@@ -78,7 +78,5 @@ bun run build:orm # Régénérer l'ORM depuis les SHEX shapes
## Documentation
- [AGENTS.md](./AGENTS.md) — architecture, routes, points d'entrée pour contribuer
- [.project/knowledge/](./.project/knowledge/) — comment les choses fonctionnent (data layer, BDD, écrans…)
- [.project/decisions/](./.project/decisions/) — choix techniques figés
- [.project/briefs/](./.project/briefs/) — chantiers à venir, recherche préparatoire
- [AGENTS.md](./AGENTS.md) — cœur : but produit, invariants, carte des concepts
- [.project/concepts/](./.project/concepts/) — toute la doctrine projet (savoir, règles, décisions, briefs), typée et livrée par hook au moment pertinent. 6 concepts : `functional-domain`, `app-architecture`, `tech-stack`, `data-layer`, `bdd-testing`, `nextgraph-platform`.
+22
View File
@@ -133,10 +133,32 @@ const result = await Bun.build({
sourcemap: "linked",
define: {
"process.env.NODE_ENV": JSON.stringify("production"),
// Access gate (ON by default) + shared wallet password, baked into the
// browser bundle as globals (see src/app/AuthGate.tsx, sharedWallet.ts). The
// wallet FILE is copied into the outdir below (served at /shared-wallet.ngw).
"globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__": JSON.stringify(
process.env.ACCESS_GATE_DISABLED === "1",
),
"globalThis.__FESTIPOD_SHARED_WALLET_PASSWORD__": JSON.stringify(
process.env.FESTIPOD_SHARED_WALLET_PASSWORD ?? "",
),
// Auto-seed gate (OFF by default): only seed a genuinely-empty wallet with
// demo data when FESTIPOD_AUTO_SEED is set (see src/shared/utils/autoSeed.ts).
"globalThis.__FESTIPOD_AUTO_SEED__": JSON.stringify(
process.env.FESTIPOD_AUTO_SEED ?? "",
),
},
...cliConfig,
});
// Staging: copy the shared wallet FILE into the bundle so the access gate can
// offer it for download (served at /shared-wallet.ngw). See sharedWallet.ts.
if (process.env.FESTIPOD_SHARED_WALLET_FILE) {
const { copyFileSync } = await import("fs");
copyFileSync(process.env.FESTIPOD_SHARED_WALLET_FILE, path.join(outdir, "shared-wallet.ngw"));
console.log(`📦 Copied shared wallet → ${path.join(outdir, "shared-wallet.ngw")}`);
}
const end = performance.now();
const outputTable = result.outputs.map(output => ({
-1380
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -6,6 +6,7 @@
"src/modules/*/steps/**/*.ts"
],
"paths": ["src/modules/*/features/**/*.feature"],
"tags": "not @wip and not @humain",
"format": [
"progress-bar",
"json:reports/cucumber-report.json",
+13 -4
View File
@@ -8,18 +8,21 @@
"start": "NODE_ENV=production bun src/index.ts",
"build": "bun run build.ts",
"test:cucumber": "bun run cucumber:run && bun run cucumber:report && bun run features:parse && bun run steps:extract",
"cucumber:run": "node --import tsx/esm node_modules/.bin/cucumber-js --config cucumber.json",
"test:data": "node --import tsx/esm node_modules/.bin/cucumber-js --config cucumber.json --tags @data",
"cucumber:run": "node --import tsx/esm node_modules/@cucumber/cucumber/bin/cucumber.js --config cucumber.json",
"test:data": "node --import tsx/esm node_modules/@cucumber/cucumber/bin/cucumber.js --config cucumber.json --tags @data",
"test:auth-setup": "bun scripts/setup-test-auth.ts",
"cucumber:report": "bun scripts/parse-test-results.ts",
"features:parse": "bun scripts/parse-features.ts",
"steps:extract": "bun scripts/extract-step-definitions.ts",
"build:orm": "rdf-orm build --input ./src/shapes/shex --output ./src/shapes/orm",
"build:orm": "rdf-orm build --input ./src/shared/shapes/shex --output ./src/shared/shapes/orm",
"validate": "bun scripts/validate.ts",
"build:ng": "bash scripts/build-ng-packages.sh",
"link:polyfill": "bun scripts/link-polyfill.ts",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
},
"dependencies": {
"@ng-eventually/client": "git+https://gitea.reconnexion.apps.gueraud.net/Reconnexion/ng-eventually.git#main&path:/packages/client",
"@ng-org/alien-deepsignals": "0.1.2-alpha.11",
"@ng-org/orm": "0.1.2-alpha.18",
"@ng-org/shex-orm": "0.1.2-alpha.8",
@@ -56,5 +59,11 @@
"@storybook/addon-a11y": "^10.3.5",
"@storybook/addon-docs": "^10.3.5",
"@storybook/addon-onboarding": "^10.3.5"
}
},
"pnpm": {
"onlyBuiltDependencies": [
"bun"
]
},
"packageManager": "pnpm@10.26.0+sha512.3b3f6c725ebe712506c0ab1ad4133cf86b1f4b687effce62a9b38b4d72e3954242e643190fc51fa1642949c735f403debd44f5cb0edd657abe63a8b6a7e1e402"
}
+6408
View File
File diff suppressed because it is too large Load Diff
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env bun
/**
* link-polyfill.ts — Reactive local link for the @ng-eventually/client polyfill (S2).
*
* WHY S2 (copy-overlay) and not a symlink (S1):
* The committed prod dependency installs @ng-eventually/client from Gitea (git+https)
* into pnpm's store WITHOUT its own node_modules/@ng-org → @ng-org/web resolves up to
* Festipod → ONE @ng-org instance (one verifier). The local polyfill CHECKOUT, however,
* carries its own node_modules/@ng-org/* (symlinks into the ng-eventually-js monorepo
* store). Symlinking node_modules/@ng-eventually/client to that checkout puts the
* checkout's @ng-org in the resolution path → a SECOND @ng-org instance → broken SDK
* (two verifiers). So we overlay a real directory that contains ONLY the polyfill's
* source (no node_modules) and keep it in sync by copying — @ng-org still resolves to
* Festipod, single instance preserved.
*
* WHAT IT DOES:
* 1. Replaces node_modules/@ng-eventually/client (the pnpm store symlink) with a real
* directory holding the local polyfill's package.json + src (NO node_modules).
* 2. Asserts the single-instance invariant (same @ng-org/web realpath from Festipod and
* from the overlay) — aborts if it would break.
* 3. Watches the local polyfill src and copies each change into the overlay, so
* `bun --hot` (bun run dev) reloads the edited file live.
*
* USAGE (reactive dev):
* Terminal 1: pnpm run link:polyfill # overlays local source, then watches
* Terminal 2: bun run dev # portless festipod bun --hot src/index.ts
* Edit files under packages/client/src → they land in node_modules → bun --hot reloads.
*
* pnpm run link:polyfill --once # overlay + verify, no watch (CI / one-shot)
* Return to the committed git-installed dependency: pnpm install
*
* Override the local checkout path with NG_EVENTUALLY_LOCAL=/path/to/packages/client.
*/
import { existsSync, lstatSync, mkdirSync, rmSync, cpSync, copyFileSync, realpathSync } from "node:fs";
import { watch } from "node:fs";
import { join, dirname } from "node:path";
const FESTIPOD = realpathSync(join(import.meta.dir, ".."));
const LOCAL =
process.env.NG_EVENTUALLY_LOCAL ??
"/home/sylvain/projects/nextgraph/ng-eventually-js/packages/client";
const TARGET = join(FESTIPOD, "node_modules", "@ng-eventually", "client");
const SRC_LOCAL = join(LOCAL, "src");
const SRC_TARGET = join(TARGET, "src");
const ONCE = process.argv.includes("--once");
function fail(msg: string): never {
console.error(`✖ link:polyfill — ${msg}`);
process.exit(1);
}
if (!existsSync(join(LOCAL, "package.json"))) {
fail(`local polyfill not found at ${LOCAL} (set NG_EVENTUALLY_LOCAL to override)`);
}
// 1. Replace the pnpm store symlink with a real overlay dir (metadata + src, NO node_modules).
console.log(`→ overlaying local polyfill: ${LOCAL}`);
if (existsSync(TARGET) || lstatSync(TARGET, { throwIfNoEntry: false })) {
rmSync(TARGET, { recursive: true, force: true });
}
mkdirSync(TARGET, { recursive: true });
for (const meta of ["package.json", "tsconfig.json", "README.md"]) {
const from = join(LOCAL, meta);
if (existsSync(from)) copyFileSync(from, join(TARGET, meta));
}
// Copy src fresh (NEVER a node_modules dir — that is what guarantees single @ng-org instance).
cpSync(SRC_LOCAL, SRC_TARGET, { recursive: true });
// 2. Assert the single-instance invariant.
const fromFestipod = realpathSync(Bun.resolveSync("@ng-org/web", FESTIPOD));
const overlayReal = realpathSync(TARGET);
const fromPolyfill = realpathSync(Bun.resolveSync("@ng-org/web", overlayReal));
console.log(` @ng-org/web (Festipod): ${fromFestipod}`);
console.log(` @ng-org/web (overlay) : ${fromPolyfill}`);
if (fromFestipod !== fromPolyfill) {
fail(
"single-instance invariant BROKEN — @ng-org/web resolves to two different realpaths.\n" +
" The overlay must not contain its own node_modules/@ng-org. Aborting.",
);
}
console.log("✓ single @ng-org/web instance preserved");
if (ONCE) {
console.log("✓ overlay ready (--once, not watching)");
process.exit(0);
}
// 3. Watch and copy on change so `bun --hot` sees live edits.
console.log(`👀 watching ${SRC_LOCAL}${SRC_TARGET} (Ctrl-C to stop)`);
watch(SRC_LOCAL, { recursive: true }, (_event, filename) => {
if (!filename) return;
const from = join(SRC_LOCAL, filename);
const to = join(SRC_TARGET, filename);
try {
if (existsSync(from)) {
mkdirSync(dirname(to), { recursive: true });
copyFileSync(from, to);
console.log(`${filename}`);
} else if (existsSync(to)) {
rmSync(to, { force: true });
console.log(`${filename} (removed)`);
}
} catch (err) {
console.error(` ! failed to sync ${filename}:`, err);
}
});
+490
View File
@@ -0,0 +1,490 @@
#!/usr/bin/env bun
/**
* validate.ts — Validation matrix (broker-level tests only, no @ui/@e2e).
*
* Default run (no flags) — key subset only, fast:
* (a) Polyfill unit tests (@ng-eventually/client — bun test)
* (b) Polyfill e2e real-broker (@ng-eventually/client — bun run e2e/run.ts)
* (c) Festipod @data KEY SUBSET (cucumber --name regex covering terrain bugs)
* (d) Festipod @multibrowser (cucumber --tags @multibrowser)
* (e) Festipod @smoke (cucumber --tags @smoke — boot connecté rend)
* (f) Festipod @wip [informational only, non-blocking]
*
* With --full flag:
* (c) becomes full @data suite (cucumber --tags @data)
*
* Each step runs even if the previous one failed (--bail mode is OFF).
* Exit code is non-zero if any non-informational step has failures.
*
* Profile rotation: both Playwright profiles are rotated before @data and
* @multibrowser when their size exceeds BLOAT_THRESHOLD_MB (default 50 MB),
* to avoid the sparql_query hang described in caveat_wallet-bloat-hang.
*/
import { spawnSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
// ─── Config ────────────────────────────────────────────────────────────────
const FESTIPOD_DIR = "/home/sylvain/projects/festipod/festipod";
const POLYFILL_DIR =
"/home/sylvain/projects/nextgraph/ng-eventually-js/packages/client";
const FESTIPOD_PROFILE = path.join(FESTIPOD_DIR, ".playwright-profile");
const POLYFILL_PROFILE = path.join(
POLYFILL_DIR,
"e2e",
".playwright-profile-lib",
);
/** Rotate profile when it exceeds this many MB (caveat_wallet-bloat-hang). */
const BLOAT_THRESHOLD_MB = 50;
/**
* Per-step timeouts:
* - polyfill unit/e2e: short steps, keep 10 min
* - @data key subset: generous — BeforeAll + 8 scenarios, ~15 min margin
* - @data full: full suite, ~35 min margin
* - @multibrowser: 7 scenarios, ~10 min margin
* - @wip: informational, 10 min
*/
const TIMEOUT_POLYFILL_UNIT_MS = 10 * 60 * 1000; // 10 min
const TIMEOUT_POLYFILL_E2E_MS = 10 * 60 * 1000; // 10 min
const TIMEOUT_DATA_KEY_MS = 15 * 60 * 1000; // 15 min (key subset)
const TIMEOUT_DATA_FULL_MS = 35 * 60 * 1000; // 35 min (--full)
const TIMEOUT_MULTIBROWSER_MS = 10 * 60 * 1000; // 10 min
const TIMEOUT_SMOKE_MS = 10 * 60 * 1000; // 10 min (1 @e2e boot scenario)
const TIMEOUT_WIP_MS = 10 * 60 * 1000; // 10 min
/**
* Key-subset --name regex: matches exactly the 8 scenarios that cover the
* known terrain bugs (inscription, désinscription, isolation, reconnexion,
* compteur dérivé, créateur ne participe pas, auth vide, auth distinctes).
*
* Uses a single cucumber invocation so BeforeAll (broker login) runs once.
*
* French accent chars must be URL-safe in the regex — cucumber uses JS
* RegExp, which handles unicode natively; we pass the literal string.
*/
const DATA_KEY_NAME_REGEX = [
"S'inscrire à un événement",
"Se désinscrire d'un événement$",
"Une identité fraîche ne voit pas la participation d'une autre",
"Une page fraîche pour la même identité relit ses propres données",
"Le créateur ne participe pas automatiquement à son événement",
"L'inscription fait converger le compteur dérivé du propriétaire",
"Un portefeuille connecté est vide par défaut",
"Les données du portefeuille sont distinctes des données par défaut",
].join("|");
// ─── Helpers ───────────────────────────────────────────────────────────────
function dirSizeMB(dir: string): number {
if (!fs.existsSync(dir)) return 0;
try {
const result = spawnSync("du", ["-sm", dir], { encoding: "utf-8" });
const line = result.stdout.trim().split("\n")[0] ?? "";
return parseInt(line.split("\t")[0] ?? "0", 10);
} catch {
return 0;
}
}
/**
* Remove any stale Chromium singleton files from `profilePath`. Chromium refuses
* to launch (ProcessSingleton error) if SingletonLock, SingletonCookie, or
* SingletonSocket are left over from a previous crashed run. Idempotent — safe to
* call even when the profile does not exist yet.
*/
function cleanSingletons(profilePath: string, label: string): void {
if (!fs.existsSync(profilePath)) return;
const singletons = ["SingletonLock", "SingletonCookie", "SingletonSocket"];
for (const name of singletons) {
const p = path.join(profilePath, name);
if (fs.existsSync(p)) {
try {
fs.rmSync(p, { force: true });
console.log(`[rotate] ${label}: removed stale ${name}.`);
} catch {
// Non-fatal: if we can't remove it, launch will fail with a clear error
}
}
}
}
function rotateProfile(profilePath: string, label: string): void {
const sizeMB = dirSizeMB(profilePath);
if (sizeMB > BLOAT_THRESHOLD_MB) {
console.log(
`[rotate] ${label}: ${sizeMB}MB > ${BLOAT_THRESHOLD_MB}MB — rotating profile...`,
);
try {
fs.rmSync(profilePath, { recursive: true, force: true });
console.log(`[rotate] ${label}: profile removed. Will be recreated.`);
} catch (e) {
console.warn(`[rotate] ${label}: failed to remove profile: ${e}`);
}
} else {
// Even if we keep the profile, remove any stale Chromium singleton files left
// by a previous crashed run — Chromium refuses to launch if they exist.
cleanSingletons(profilePath, label);
console.log(
`[rotate] ${label}: ${sizeMB}MB — below threshold, keeping profile.`,
);
}
}
interface StepResult {
label: string;
status: "passed" | "failed" | "error";
/** Lines to show in the summary (failed scenario names, FAIL lines, etc.) */
failures: string[];
/** Raw exit code */
exitCode: number;
durationMs: number;
}
/**
* Run a command and capture its output. Returns the result with parsed
* pass/fail summary. Never throws — all errors are captured in StepResult.
*/
function runStep(
label: string,
cmd: string,
args: string[],
cwd: string,
timeoutMs: number,
extraEnv: Record<string, string> = {},
): StepResult {
const t0 = Date.now();
console.log(`\n${"═".repeat(60)}`);
console.log(`${label}`);
console.log(` ${cmd} ${args.join(" ")} (cwd: ${cwd})`);
console.log(` timeout: ${Math.round(timeoutMs / 60000)}min`);
console.log(`${"═".repeat(60)}`);
const env = { ...process.env, ...extraEnv };
const result = spawnSync(cmd, args, {
cwd,
env,
encoding: "utf-8",
timeout: timeoutMs,
maxBuffer: 20 * 1024 * 1024, // 20MB
});
const durationMs = Date.now() - t0;
const stdout = result.stdout ?? "";
const stderr = result.stderr ?? "";
const combined = stdout + "\n" + stderr;
// Print output in real-time equivalent (post-hoc since spawnSync)
if (stdout) process.stdout.write(stdout);
if (stderr) process.stderr.write(stderr);
if (result.error) {
console.error(`[${label}] process error:`, result.error.message);
return {
label,
status: "error",
failures: [`Process error: ${result.error.message}`],
exitCode: result.status ?? 1,
durationMs,
};
}
const exitCode = result.status ?? 1;
const failures = extractFailures(combined, label);
const status = exitCode === 0 ? "passed" : "failed";
return { label, status, failures, exitCode, durationMs };
}
/**
* Extract meaningful failure lines from combined stdout+stderr.
* Heuristics per step type (cucumber scenario names, FAIL lines, etc.).
*/
function extractFailures(output: string, label: string): string[] {
const lines = output.split("\n");
const failures: string[] = [];
if (label.includes("polyfill:unit")) {
// bun test output: lines starting with "✗" or "FAIL" or "fail"
for (const line of lines) {
const l = line.trim();
if (/^(✗|✕|FAIL|fail)\s/.test(l) || l.includes("tests failed")) {
failures.push(l);
}
}
// Also capture summary line "N passed, M failed"
const summary = lines.find(
(l) => l.includes("passed") && l.includes("failed"),
);
if (summary) failures.push(summary.trim());
} else if (label.includes("polyfill:e2e")) {
// e2e/run.ts output: lines starting with " [FAIL]"
for (const line of lines) {
const l = line.trim();
if (l.startsWith("[FAIL]")) failures.push(l);
}
// Summary: "N passed / M failed" style
const summary = lines.find(
(l) => l.includes("passed") || l.includes("failed"),
);
if (summary && !failures.includes(summary.trim()))
failures.push(summary.trim());
} else {
// Cucumber steps: look for "✗" scenario lines, "FAILED" scenario names,
// or lines beginning with "✖" / "×" / "Scenario:" after a failure tag
for (const line of lines) {
const l = line.trim();
if (
/^(✗|✕|×|✖)\s/.test(l) ||
l.startsWith("✘") ||
l.includes("# Scénario:") ||
l.includes("# Scenario:") ||
(l.startsWith("F") && l.length === 1) // progress-bar failure tick
) {
if (l.length > 1) failures.push(l);
}
}
// Cucumber "N scenarios (M failed)" summary
const summary = lines.find((l) =>
/\d+ sc[eé]narios?.*(failed|undefined)/.test(l),
);
if (summary) failures.push(summary.trim());
// Individual scenario fail lines: "✗ Scenario name (features/...)"
for (const line of lines) {
const l = line.trim();
if (l.startsWith("✗") || l.startsWith("✕")) {
if (!failures.includes(l)) failures.push(l);
}
}
}
return failures.filter(Boolean);
}
function fmtDuration(ms: number): string {
if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
const m = Math.floor(ms / 60_000);
const s = ((ms % 60_000) / 1000).toFixed(0);
return `${m}m${s}s`;
}
function printMatrix(
steps: StepResult[],
wipResult: StepResult | null,
fullMode: boolean,
): void {
console.log("\n");
console.log("╔══════════════════════════════════════════════════════════╗");
console.log("║ VALIDATION MATRIX ║");
if (fullMode) {
console.log("║ (mode: --full, @data complet) ║");
} else {
console.log("║ (mode: défaut, sous-ensemble clé) ║");
}
console.log("╚══════════════════════════════════════════════════════════╝");
console.log("");
const maxLabel = Math.max(...steps.map((s) => s.label.length));
for (const step of steps) {
const icon = step.status === "passed" ? "✅" : step.status === "failed" ? "❌" : "⚠️ ";
const pad = step.label.padEnd(maxLabel + 2);
console.log(` ${icon} ${pad} [${fmtDuration(step.durationMs)}]`);
for (const f of step.failures) {
console.log(`${f}`);
}
}
if (wipResult) {
console.log("");
console.log(" ── @wip (informational, non-blocking) ──────────────────");
const icon =
wipResult.status === "passed"
? "✅"
: wipResult.status === "failed"
? "❌"
: "⚠️ ";
const pad = wipResult.label.padEnd(maxLabel + 2);
console.log(` ${icon} ${pad} [${fmtDuration(wipResult.durationMs)}]`);
for (const f of wipResult.failures) {
console.log(`${f}`);
}
}
console.log("");
const allPassed = steps.every((s) => s.status === "passed");
const totalMs = steps.reduce((sum, s) => sum + s.durationMs, 0) +
(wipResult?.durationMs ?? 0);
if (allPassed) {
console.log(" 🟢 ALL STEPS PASSED");
} else {
const failed = steps.filter((s) => s.status !== "passed");
console.log(` 🔴 ${failed.length} STEP(S) FAILED: ${failed.map((s) => s.label).join(", ")}`);
}
console.log(` ⏱ Total: ${fmtDuration(totalMs)}`);
if (!fullMode) {
console.log(" ️ Pour @data complet : bun run validate -- --full");
}
console.log("");
}
// ─── Cucumber command builder ───────────────────────────────────────────────
function cucumberArgsByTags(tags: string): string[] {
return [
"--import",
"tsx/esm",
"node_modules/.bin/cucumber-js",
"--config",
"cucumber.json",
"--tags",
tags,
];
}
function cucumberArgsByName(nameRegex: string): string[] {
return [
"--import",
"tsx/esm",
"node_modules/.bin/cucumber-js",
"--config",
"cucumber.json",
"--tags",
"@data",
"--name",
nameRegex,
];
}
// ─── Main ──────────────────────────────────────────────────────────────────
async function main(): Promise<void> {
const args = process.argv.slice(2);
const fullMode = args.includes("--full");
if (fullMode) {
console.log("🔍 Festipod — Full Validation Run (--full : @data complet)");
} else {
console.log("🔍 Festipod — Validation Run (sous-ensemble clé)");
console.log(" Pour @data complet : bun run validate -- --full");
}
console.log(` Festipod: ${FESTIPOD_DIR}`);
console.log(` Polyfill: ${POLYFILL_DIR}`);
console.log("");
// ── Profile rotation AVANT les étapes broker ──────────────────────────────
console.log("── Profile rotation check (avant @data et @multibrowser) ────");
rotateProfile(FESTIPOD_PROFILE, "festipod");
rotateProfile(POLYFILL_PROFILE, "polyfill-lib");
const steps: StepResult[] = [];
// ── (a) Polyfill unit tests ───────────────────────────────────────────────
steps.push(
runStep(
"polyfill:unit",
"bun",
["test"],
POLYFILL_DIR,
TIMEOUT_POLYFILL_UNIT_MS,
),
);
// ── (b) Polyfill e2e real broker ──────────────────────────────────────────
// Clean singleton files immediately before launching Chromium — guards against
// any file left by polyfill:unit (unlikely but defensive) or by a previous
// interrupted run that the initial rotateProfile call ran before.
cleanSingletons(POLYFILL_PROFILE, "polyfill-lib (pre-e2e)");
steps.push(
runStep(
"polyfill:e2e",
"bun",
["run", "e2e/run.ts"],
POLYFILL_DIR,
TIMEOUT_POLYFILL_E2E_MS,
),
);
// ── (c) Festipod @data ────────────────────────────────────────────────────
if (fullMode) {
// --full : lance tout @data
steps.push(
runStep(
"festipod:@data (complet)",
"node",
cucumberArgsByTags("@data"),
FESTIPOD_DIR,
TIMEOUT_DATA_FULL_MS,
),
);
} else {
// défaut : sous-ensemble clé en UNE invocation (BeforeAll partagé)
steps.push(
runStep(
"festipod:@data (clé)",
"node",
cucumberArgsByName(DATA_KEY_NAME_REGEX),
FESTIPOD_DIR,
TIMEOUT_DATA_KEY_MS,
),
);
}
// ── (d) Festipod @multibrowser ────────────────────────────────────────────
// Exclude @wip: a scenario tagged @wip @multibrowser (e.g. the reactive
// cross-session scenario, blocked by the shared-wallet structural limit) must
// not gate the baseline — it flows into the informational @wip pass below.
steps.push(
runStep(
"festipod:@multibrowser",
"node",
cucumberArgsByTags("@multibrowser and not @wip"),
FESTIPOD_DIR,
TIMEOUT_MULTIBROWSER_MS,
),
);
// ── (e) Festipod @smoke — boot connecté rend / page blanche ───────────────
// Un seul scénario @e2e : boote le VRAI App, se connecte au broker, et vérifie
// que l'accueil connecté rend du contenu d'app réel SANS erreur runtime. Garde
// la CLASSE « crash de rendu une fois connecté » (page blanche). On ne lance
// QUE @smoke (pas tout @e2e) pour garder le run par défaut rapide.
// Nettoie les singletons Chromium juste avant, comme les autres étapes broker.
cleanSingletons(FESTIPOD_PROFILE, "festipod (pre-@smoke)");
steps.push(
runStep(
"festipod:@smoke",
"node",
cucumberArgsByTags("@smoke and not @wip"),
FESTIPOD_DIR,
TIMEOUT_SMOKE_MS,
),
);
// ── (f) Festipod @wip [informational] ────────────────────────────────────
console.log("\n── @wip informational pass (non-blocking) ──────────────────");
const wipResult = runStep(
"festipod:@wip",
"node",
cucumberArgsByTags("@wip"),
FESTIPOD_DIR,
TIMEOUT_WIP_MS,
);
// ── Matrix ────────────────────────────────────────────────────────────────
printMatrix(steps, wipResult, fullMode);
// ── Exit code ─────────────────────────────────────────────────────────────
const anyFailed = steps.some((s) => s.status !== "passed");
process.exit(anyFailed ? 1 : 0);
}
main().catch((e) => {
console.error("validate.ts: unhandled error:", e);
process.exit(1);
});
+14 -10
View File
@@ -1,12 +1,13 @@
import { RouterProvider, useRouter } from './router';
import { ThemeProvider } from '../shared/context/ThemeContext';
import { NextGraphProvider } from '../shared/context/NextGraphContext';
import { AccountProvider } from '../shared/context/AccountContext';
import { FestipodDataProvider } from '../shared/context/FestipodDataContext';
import { AuthGate } from './AuthGate';
import { ToastContainer } from '../shared/components/sketchy';
// Auth
import { WelcomeScreen } from '../modules/auth/screens/WelcomeScreen';
import { LoginScreen } from '../modules/auth/screens/LoginScreen';
// Home
import { HomeScreen } from '../modules/home/screens/HomeScreen';
@@ -34,7 +35,6 @@ function AppContent() {
switch (route.page) {
case 'welcome': return <WelcomeScreen />;
case 'login': return <LoginScreen />;
case 'home': return <HomeScreen />;
case 'events': return <EventsScreen />;
case 'create-event': return <CreateEventScreen />;
@@ -57,14 +57,18 @@ export function App() {
return (
<ThemeProvider>
<NextGraphProvider>
<FestipodDataProvider>
<RouterProvider>
<div className="app-container">
<AppContent />
<ToastContainer />
</div>
</RouterProvider>
</FestipodDataProvider>
<AccountProvider>
<FestipodDataProvider>
<RouterProvider>
<div className="app-container">
<AuthGate>
<AppContent />
</AuthGate>
<ToastContainer />
</div>
</RouterProvider>
</FestipodDataProvider>
</AccountProvider>
</NextGraphProvider>
</ThemeProvider>
);
+91
View File
@@ -0,0 +1,91 @@
/**
* AuthGate — the stopgap access flow (see decision_2026-06-15_shared-wallet-login-flow):
* 1. Access barrier + identifier (AccessGateScreen) → the user names their
* virtual space (an identifier) and opens the SHARED wallet via the broker
* redirect (with the wallet file + guide it hands the user). Naming the
* space and opening it are ONE act.
* 2. The app.
*
* The gate is ON BY DEFAULT (Festipod never functions without NextGraph). It is
* disabled only when `globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ === true` —
* injected by `build.ts` (from ACCESS_GATE_DISABLED=1) for a no-gate build, or
* by the test harness via `context.addInitScript` for @e2e (which exercises the
* screens, not the auth flow). Absent → gate ON.
*/
import { useEffect, type ReactNode } from 'react';
import { useNextGraph } from '../shared/context/NextGraphContext';
import { useAccount, normalizeIdentifier } from '../shared/context/AccountContext';
import { AccessGateScreen } from '../modules/auth/screens/AccessGateScreen';
import { useRouter, useNavigate } from './router';
declare global {
// eslint-disable-next-line no-var
var __FESTIPOD_ACCESS_GATE_DISABLED__: boolean | undefined;
}
const GATE_DISABLED = globalThis.__FESTIPOD_ACCESS_GATE_DISABLED__ === true;
export function AuthGate({ children }: { children: ReactNode }) {
const { status, error, connect } = useNextGraph();
const { identifier, login } = useAccount();
const { route } = useRouter();
const navigate = useNavigate();
// Once connected AND identified, leave the disconnected welcome screen for the
// app home. The identifier is now set at the barrier (before the broker
// round-trip), so on return the app can land on '/' with a session already
// open; the removed ConnexionScreen used to do this navigate on login.
useEffect(() => {
if (!GATE_DISABLED && status === 'connected' && identifier && route.page === 'welcome') {
navigate('/home');
}
}, [status, identifier, route.page, navigate]);
// Gate explicitly disabled (no-gate build / @e2e harness) → straight to app.
if (GATE_DISABLED) {
return <>{children}</>;
}
// Access barrier — shown until BOTH the wallet is open AND the space is named.
// "Entrer" records the identifier (persisted to localStorage AND written into
// the `?id=` URL param, which is what actually survives the broker redirect
// across the partitioned frontier) and, if the wallet isn't open yet, triggers
// the connect.
//
// On return (reload / broker round-trip) the identifier is already stored, so
// we PREFILL the field with it (`initialIdentifier`) — the user never sees a
// bare empty prompt they must re-type. It is captured ONCE, at first access.
if (status !== 'connected' || !identifier) {
const onEnter = (entered: string) => {
login(entered);
// Carry the identifier across the broker frontier via the URL. localStorage
// is partitioned by top-level site, so the value written here (127.0.0.1)
// is NOT what the app reads inside the broker iframe (nextgraph.net). The
// `@ng-org/web` redirect embeds the FULL app URL (query included) in the
// broker `o=`, which is reloaded in the iframe — so writing the normalized
// id into `?id=` BEFORE connect() makes it travel. `history.replaceState`
// (not push) keeps a single history entry. See AccountContext resolution.
if (typeof window !== 'undefined') {
try {
const url = new URL(window.location.href);
url.searchParams.set('id', normalizeIdentifier(entered));
window.history.replaceState(window.history.state, '', url.toString());
} catch {
/* URL construction can't fail for a real page URL; ignore defensively */
}
}
if (status !== 'connected') connect();
};
return (
<AccessGateScreen
status={status}
error={error}
initialIdentifier={identifier ?? ''}
onEnter={onEnter}
/>
);
}
// The app.
return <>{children}</>;
}
+50 -15
View File
@@ -3,24 +3,59 @@
* element and renders the App component to the DOM.
*
* It is included in `src/index.html`.
*
* Before loading the app tree it pulls the RUNTIME shared-wallet config (dev
* server + `bun run start`, which serve from src/ and so miss build.ts's
* compile-time `define`), sets the global, then dynamically imports `App` so
* `sharedWallet.ts` reads the value on evaluation. In a build.ts bundle the
* password is already inlined via `define`, so this step is skipped (NODE_ENV).
*/
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./App";
const elem = document.getElementById("root")!;
const app = (
<StrictMode>
<App />
</StrictMode>
);
if (import.meta.hot) {
// With hot module reloading, `import.meta.hot.data` is persisted.
const root = (import.meta.hot.data.root ??= createRoot(elem));
root.render(app);
} else {
// The hot module reloading API is not available in production.
createRoot(elem).render(app);
/** Fetch the runtime shared-wallet config and set the global (dev/start only). */
async function loadRuntimeConfig(): Promise<void> {
if (process.env.NODE_ENV === "production") return; // build.ts define provides it
try {
const res = await fetch("/festipod-config.json");
if (!res.ok) return;
const cfg = (await res.json()) as { sharedWalletPassword?: string; autoSeed?: string };
// Bracket access so build.ts's `define` (which matches the dotted global)
// never rewrites this assignment. Only set when the env actually carries one.
const g = globalThis as Record<string, unknown>;
if (cfg.sharedWalletPassword && g["__FESTIPOD_SHARED_WALLET_PASSWORD__"] == null) {
g["__FESTIPOD_SHARED_WALLET_PASSWORD__"] = cfg.sharedWalletPassword;
}
// Auto-seed gate (see src/shared/utils/autoSeed.ts): only set the global when
// the env var carries a truthy value; absent → stays undefined → seed OFF.
if (cfg.autoSeed && g["__FESTIPOD_AUTO_SEED__"] == null) {
g["__FESTIPOD_AUTO_SEED__"] = cfg.autoSeed;
}
} catch {
// No runtime config endpoint (static build) → rely on the compile-time define.
}
}
async function main(): Promise<void> {
await loadRuntimeConfig();
// Dynamic import AFTER the global is set, so sharedWallet.ts reads it on eval.
const { App } = await import("./App");
const elem = document.getElementById("root")!;
const app = (
<StrictMode>
<App />
</StrictMode>
);
if (import.meta.hot) {
// With hot module reloading, `import.meta.hot.data` is persisted.
const root = (import.meta.hot.data.root ??= createRoot(elem));
root.render(app);
} else {
// The hot module reloading API is not available in production.
createRoot(elem).render(app);
}
}
void main();
-3
View File
@@ -6,7 +6,6 @@ import React, { createContext, useContext, useState, useEffect, useCallback } fr
type Route =
| { page: 'welcome' }
| { page: 'login' }
| { page: 'home' }
| { page: 'events' }
| { page: 'create-event' }
@@ -38,7 +37,6 @@ function parsePath(pathname: string): Route {
const path = pathname.replace(/\/+$/, '') || '/';
if (path === '/' || path === '') return { page: 'welcome' };
if (path === '/login') return { page: 'login' };
if (path === '/home') return { page: 'home' };
if (path === '/events') return { page: 'events' };
if (path === '/events/new') return { page: 'create-event' };
@@ -73,7 +71,6 @@ function parsePath(pathname: string): Route {
export function routeToPath(route: Route): string {
switch (route.page) {
case 'welcome': return '/';
case 'login': return '/login';
case 'home': return '/home';
case 'events': return '/events';
case 'create-event': return '/events/new';
+11
View File
@@ -333,6 +333,17 @@ body {
min-height: 0;
}
/* Global data-query spinner (near the "Festipod" title) */
@keyframes app-spin {
to { transform: rotate(360deg); }
}
.app-spinner {
animation: app-spin 0.8s linear infinite;
flex-shrink: 0;
vertical-align: middle;
}
/* Online indicator on avatar */
.app-avatar .online-dot {
position: absolute;
+22
View File
@@ -41,6 +41,28 @@ const server = serve({
});
},
// Shared-wallet config, exposed at RUNTIME for the dev server + `bun run start`
// (both serve from src/, so they miss build.ts's compile-time `define`). The app
// entry (frontend.tsx) fetches this before it loads the app tree, so
// `sharedWallet.ts` sees the password. Empty env → '' → no shared wallet.
"/festipod-config.json": () =>
Response.json({
sharedWalletPassword: process.env.FESTIPOD_SHARED_WALLET_PASSWORD ?? "",
// Auto-seed gate (OFF by default): only set when the env var is present, so
// the front seeds an empty wallet only on explicit opt-in (see autoSeed.ts).
autoSeed: process.env.FESTIPOD_AUTO_SEED ?? "",
}),
// The shared wallet file (download target of the access barrier), when configured.
"/shared-wallet.ngw": async () => {
const p = process.env.FESTIPOD_SHARED_WALLET_FILE;
if (p) {
const file = Bun.file(p);
if (await file.exists()) return new Response(file);
}
return new Response("No shared wallet file configured.", { status: 404 });
},
// Serve index.html for all unmatched routes (must be last)
"/*": index,
},
@@ -0,0 +1,27 @@
# language: fr
@AUTH @priority-1
Fonctionnalité: Barrière d'accès — l'identifiant se saisit une seule fois
En tant qu'utilisateur qui revient dans Festipod
Je veux retrouver l'identifiant que j'ai déjà choisi, pré-rempli
Afin de ne jamais avoir à le retaper à l'arrivée
# Garde-fou contre la régression rapportée : au retour (rechargement / round-trip
# broker) la barrière re-demandait un identifiant NU et VIDE alors qu'il était
# déjà stocké. L'identifiant est capturé UNE FOIS au premier accès, persisté,
# puis pré-rempli. Voir AuthGate + AccessGateScreen.
@ui
Scénario: Le champ identifiant est pré-rempli avec la valeur déjà stockée
Étant donné que la barrière d'accès s'affiche avec l'identifiant stocké "alice"
Alors le champ identifiant contient "alice"
@ui
Scénario: Un premier accès sans identifiant stocké affiche un champ vide
Étant donné que la barrière d'accès s'affiche sans identifiant stocké
Alors le champ identifiant est vide
@ui
Scénario: Entrer remonte l'identifiant saisi
Étant donné que la barrière d'accès s'affiche avec l'identifiant stocké "alice"
Quand je clique sur "Entrer" dans la barrière
Alors l'identifiant remonté à l'application est "alice"
@@ -6,29 +6,10 @@ Fonctionnalité: Connexion NextGraph et chargement des données
Et charger les données de test dans mon portefeuille
Afin d'utiliser l'application avec mes propres données
# --- UI layer: écran de connexion ---
@ui
Scénario: L'écran de connexion affiche le bouton NextGraph
Étant donné je suis sur la page "connexion"
Alors l'écran contient un bouton "Se connecter avec NextGraph"
@ui @wip
# Behavioral: requires simulating an NG status change. Better tested at the
# @e2e layer where a real connected session triggers the redirect.
Scénario: L'écran de connexion redirige automatiquement quand connecté
Étant donné je suis sur la page "connexion"
Alors l'écran gère la redirection automatique après connexion
@ui
Scénario: L'état initial est "en cours" quand une connexion est en attente
Étant donné je suis sur la page "connexion"
Alors l'écran gère l'état de connexion en cours
@ui
Scénario: Aucune donnée de démonstration n'est visible pendant la connexion
Étant donné je suis sur la page "connexion"
Alors l'écran n'importe pas de données de démonstration
# NB : l'ancien écran /login (LoginScreen) a été retiré — l'accès NextGraph
# passe désormais par l'AccessGateScreen (barrière ON par défaut), cf.
# decision_2026-06-17_assisted-wallet-import. Les scénarios @ui qui testaient
# le LoginScreen ont été supprimés en conséquence.
# --- Data layer: comportement du portefeuille ---
@@ -59,11 +40,6 @@ Fonctionnalité: Connexion NextGraph et chargement des données
# --- E2E layer: comportement réel dans le navigateur ---
@e2e
Scénario: L'écran de connexion redirige vers l'accueil si déjà connecté
Quand l'utilisateur navigue vers l'écran "login"
Alors l'application affiche l'écran "home"
@e2e
Scénario: La navigation interne met à jour l'URL
Quand l'utilisateur navigue vers l'écran "events"
@@ -0,0 +1,42 @@
# language: fr
@AUTH @priority-1
Fonctionnalité: Résolution de l'identifiant — le param d'URL prime sur localStorage
En tant qu'application relancée dans l'iframe du broker après le round-trip
Je veux résoudre l'identifiant depuis le param d'URL "?id="
Afin qu'il traverse la frontière top-leveliframe (que localStorage ne franchit pas)
# Le flux wallet-partagé fait tourner l'app dans DEUX contextes avec DEUX
# partitions localStorage distinctes (top-level 127.0.0.1 vs iframe
# nextgraph.net). localStorage ne traverse pas la frontière ; le param "?id="
# embarqué dans le redirect broker (o=) la traverse. AccountContext résout donc
# dans l'ordre : (1) param d'URL "?id=" (source de vérité) ; (2) sinon
# localStorage (préremplissage même-partition). Voir AccountContext + AuthGate.
@ui
Scénario: Le param d'URL est la source de vérité quand il est présent
Étant donné que localStorage contient l'identifiant "alice"
Et que l'URL porte le param id "bob"
Quand le contexte de compte résout l'identifiant
Alors l'identifiant résolu est "bob"
@ui
Scénario: Le param d'URL prime même sur une valeur localStorage différente et est persisté
Étant donné que localStorage contient l'identifiant "alice"
Et que l'URL porte le param id "carol"
Quand le contexte de compte résout l'identifiant
Alors l'identifiant résolu est "carol"
Et localStorage contient désormais l'identifiant "carol"
@ui
Scénario: Sans param d'URL, localStorage sert de repli
Étant donné que localStorage contient l'identifiant "dave"
Et que l'URL ne porte aucun param id
Quand le contexte de compte résout l'identifiant
Alors l'identifiant résolu est "dave"
@ui
Scénario: Le param d'URL est normalisé (minuscules, @ retiré)
Étant donné que localStorage ne contient aucun identifiant
Et que l'URL porte le param id "@Erin"
Quand le contexte de compte résout l'identifiant
Alors l'identifiant résolu est "erin"
@@ -0,0 +1,183 @@
/**
* AccessGateScreen the *technical access barrier* of the stopgap.
*
* SHARED WALLET IS THE SOLE SUPPORTED MODE. Festipod does not function without
* the shared wallet (the SDK polyfill runs on it). "No shared wallet configured"
* is therefore NOT an offered flow it is a loud MISCONFIGURATION error
* (`!hasSharedWallet()` a config-error block, no functional form). Configure it
* via FESTIPOD_SHARED_WALLET_PASSWORD.
*
* STOPGAP (see decision_2026-06-15_shared-wallet-login-flow). This is the
* REAL NextGraph login, shown before the app renders. Because it precedes the
* app, the user reads it as "access to the test environment", not as an app
* login. The user also types an IDENTIFIER here the id that names their
* virtual space (a technical id, a pseudo in practice, NOT a Festipod profile
* handle like `@mariedupont`).
* Clicking "Entrer" records that identifier and triggers `connect()`, which
* redirects to the broker to open the SHARED wallet. After return the identity
* is already set (persisted before the redirect), so NG auto-connects straight
* into the app there is no separate "choose a handle" screen.
*
* ASSISTED IMPORT (see decision_2026-06-17). The hosted broker can't import a
* wallet inline during
* web-app auth: a first-time device has no wallet, so the broker redirect would
* dead-end. We therefore HAND the user the shared wallet FILE (download) + the
* shared password and guide a one-time import on nextgraph.eu ("Import a Wallet
* File"), BEFORE they click "Entrer". The wallet FILE is the correct static
* primitive a TextCode is a transient 5-min transfer, unusable to embed. This
* assisted flow is the default whenever the shared wallet is open pending.
*/
import { useState, type ReactNode } from 'react';
import { Button, Input, Title, Text } from '../../../shared/components/sketchy';
import { SHARED_WALLET_PASSWORD, SHARED_WALLET_FILE_URL, WALLET_IMPORT_URL, hasSharedWallet } from '../sharedWallet';
interface AccessGateScreenProps {
status: 'disconnected' | 'connecting' | 'connected' | 'error';
error?: string;
/**
* The identifier already stored for this space (the persisted one), used to
* PREFILL the field so a returning user never re-types it. Empty on a truly
* first access. Normalized upstream; shown verbatim.
*/
initialIdentifier?: string;
/** Enter the space: the raw identifier the user typed (normalized upstream). */
onEnter: (identifier: string) => void;
}
// One numbered step: a badge + a title + the action for that step.
function Step({ n, title, children }: { n: number; title: string; children: ReactNode }) {
return (
<div style={{ display: 'flex', gap: 12, marginBottom: 18 }}>
<div style={{
flexShrink: 0, width: 26, height: 26, borderRadius: '50%', background: '#E8590C',
color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 14,
}}>{n}</div>
<div style={{ flex: 1, minWidth: 0 }}>
<Text style={{ margin: '2px 0 8px', fontWeight: 600, fontSize: 14 }}>{title}</Text>
{children}
</div>
</div>
);
}
export function AccessGateScreen({ status, error, initialIdentifier, onEnter }: AccessGateScreenProps) {
const connecting = status === 'connecting';
const [copied, setCopied] = useState(false);
// The identifier that names this virtual space (a technical id — a pseudo in
// practice, but not a Festipod profile handle). Entered HERE, at wallet access, so a
// single act both names the space and opens it. Normalized (lowercased) upstream.
// PREFILLED from the stored identifier so a returning user (reload / broker
// round-trip) sees the value they already chose and never re-types it.
const [identifier, setIdentifier] = useState(initialIdentifier ?? '');
const copyPassword = async () => {
try {
await navigator.clipboard.writeText(SHARED_WALLET_PASSWORD);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
// clipboard may be blocked — the password stays selectable
}
};
const canEnter = !connecting && identifier.trim().length > 0;
const enter = () => { if (canEnter) onEnter(identifier); };
// Identifier field + Entrer: naming the space and opening it are one act.
const entrer = (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<Input
data-testid="identifier-input"
placeholder="votre identifiant"
value={identifier}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setIdentifier(e.target.value)}
onKeyDown={(e: React.KeyboardEvent) => { if (e.key === 'Enter') enter(); }}
/>
<Text style={{ margin: 0, fontSize: 12, color: '#999' }}>
Il identifie votre espace (mis en minuscules).
</Text>
<Button
variant="primary"
onClick={enter}
disabled={!canEnter}
style={{ width: '100%', opacity: canEnter ? 1 : 0.6 }}
>
{connecting ? 'Accès en cours…' : 'Entrer'}
</Button>
</div>
);
return (
<div style={{ padding: 24, display: 'flex', flexDirection: 'column', height: '100%' }}>
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
<Title style={{ textAlign: 'center', fontSize: 30, marginBottom: 4 }}>Festipod</Title>
<Text style={{ textAlign: 'center', marginBottom: 24, color: '#888' }}>Espace de test</Text>
{!hasSharedWallet() ? (
// SOLE-MODE guard: Festipod cannot run without the shared wallet, so a
// missing one is a misconfiguration, NOT a functional login form.
<Text style={{ textAlign: 'center', fontSize: 14, color: '#c92a2a', lineHeight: 1.5, margin: '0 0 12px' }}>
Portefeuille partagé non configuré. Festipod ne fonctionne pas sans
(définir <code>FESTIPOD_SHARED_WALLET_PASSWORD</code>).
</Text>
) : status !== 'connected' ? (
<>
<Text style={{ textAlign: 'center', fontSize: 14, color: '#666', margin: '0 0 20px', lineHeight: 1.5 }}>
Première connexion sur cet appareil ?<br />Chargez le portefeuille partagé, une seule fois.
</Text>
<Step n={1} title="Téléchargez le portefeuille">
<a
data-testid="shared-wallet-download"
href={SHARED_WALLET_FILE_URL}
download="festipod-wallet.ngw"
style={{
display: 'block', textAlign: 'center', textDecoration: 'none',
padding: 10, borderRadius: 10, background: '#E8590C', color: '#fff', fontWeight: 600, fontSize: 14,
}}
>
Télécharger le portefeuille
</a>
</Step>
<Step n={2} title="Importez-le sur NextGraph">
<Text style={{ margin: '0 0 8px', fontSize: 13, lineHeight: 1.6, color: '#666' }}>
<a href={WALLET_IMPORT_URL} target="_blank" rel="noopener noreferrer" style={{ color: '#E8590C', fontWeight: 600 }}>
Ouvrir la page d'import
</a>{' '}(nouvel onglet) « Import a Wallet File » choisissez le fichier mot de passe :
</Text>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<code
data-testid="shared-wallet-password"
style={{ flex: 1, padding: '6px 10px', background: '#fff', border: '1px solid #eee', borderRadius: 8, fontSize: 13, userSelect: 'all' }}
>
{SHARED_WALLET_PASSWORD}
</code>
<Button variant="accent-outline" onClick={copyPassword} style={{ padding: '6px 10px', fontSize: 12 }}>
{copied ? 'Copié ✓' : 'Copier'}
</Button>
</div>
</Step>
<Step n={3} title="Revenez ici, choisissez un identifiant et entrez">
{entrer}
</Step>
</>
) : (
entrer
)}
{status === 'error' && (
<Text style={{ textAlign: 'center', fontSize: 12, color: '#c92a2a', marginTop: 12 }}>
{error || "Accès à l'environnement impossible. Réessayez."}
</Text>
)}
</div>
<Text style={{ textAlign: 'center', fontSize: 12, color: '#bbb' }}>
Version beta
</Text>
</div>
);
}
@@ -1,14 +0,0 @@
import type { Meta, StoryObj } from '@storybook/react-webpack5';
import { LoginScreen } from './LoginScreen';
import { withProviders } from '../../../../.storybook/decorators';
const meta: Meta<typeof LoginScreen> = {
title: 'Screens/Auth/LoginScreen',
component: LoginScreen,
decorators: [withProviders],
};
export default meta;
type Story = StoryObj<typeof LoginScreen>;
export const Default: Story = {};
-95
View File
@@ -1,95 +0,0 @@
import { useEffect } from 'react';
import { Button, Input, Title, Text, Divider } from '../../../shared/components/sketchy';
import { useNextGraph } from '../../../shared/context/NextGraphContext';
import { useNavigate } from '../../../app/router';
export function LoginScreen() {
const navigate = useNavigate();
const { status, connect } = useNextGraph();
useEffect(() => {
if (status === 'connected') {
navigate('/home');
}
}, [status]);
const handleNgLogin = () => {
if (status === 'connected') {
navigate('/home');
} else {
connect();
}
};
return (
<div style={{ padding: 24, display: 'flex', flexDirection: 'column', height: '100%' }}>
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
<Title style={{ textAlign: 'center', fontSize: 32, marginBottom: 8 }}>Festipod</Title>
<Text style={{ textAlign: 'center', marginBottom: 32, color: '#888' }}>Créez et rejoignez des événements entre amis</Text>
{/* NextGraph login */}
<div style={{ marginBottom: 24 }}>
{status === 'connected' ? (
<div style={{ textAlign: 'center', marginBottom: 8 }}>
<Text style={{ color: '#22543D', fontWeight: 'bold', margin: '0 0 8px 0' }}>
Connecté via NextGraph
</Text>
<Button variant="primary" onClick={() => navigate('/home')} style={{ width: '100%' }}>
Continuer vers l'accueil
</Button>
</div>
) : status === 'connecting' ? (
<Button disabled style={{ width: '100%', opacity: 0.6 }}>
Connexion NextGraph en cours...
</Button>
) : (
<div>
<Button
variant="primary"
onClick={handleNgLogin}
style={{ width: '100%' }}
>
Se connecter avec NextGraph
</Button>
{status === 'error' && (
<Text style={{ textAlign: 'center', fontSize: 12, color: '#888', marginTop: 8 }}>
NextGraph non disponible mode démonstration
</Text>
)}
</div>
)}
</div>
<Divider />
<Text style={{ textAlign: 'center', fontSize: 14, color: '#888', margin: '16px 0' }}>
ou connexion classique (démo)
</Text>
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div>
<Text style={{ marginBottom: 4, fontSize: 13, color: '#888' }}>Email</Text>
<Input type="email" placeholder="vous@exemple.com" />
</div>
<div>
<Text style={{ marginBottom: 4, fontSize: 13, color: '#888' }}>Mot de passe</Text>
<Input type="password" placeholder="••••••••" />
</div>
<Button variant="primary" onClick={() => navigate('/home')}>
Se connecter
</Button>
<Text style={{ textAlign: 'center', fontSize: 14, color: '#E8590C' }}>
Mot de passe oublié ?
</Text>
</div>
</div>
<Text style={{ textAlign: 'center', fontSize: 14, color: '#888' }}>
Pas encore de compte ? <span style={{ color: '#E8590C', cursor: 'pointer' }}>S'inscrire</span>
</Text>
</div>
);
}
+12 -2
View File
@@ -1,8 +1,18 @@
import { useEffect } from 'react';
import { Button, Title, Text } from '../../../shared/components/sketchy';
import { useNavigate } from '../../../app/router';
import { useNextGraph } from '../../../shared/context/NextGraphContext';
export function WelcomeScreen() {
const navigate = useNavigate();
const { status } = useNextGraph();
// Onboarding is for NOT-connected users. A connected user landing on '/'
// (e.g. a returning tester past the access gate) goes straight to the app.
useEffect(() => {
if (status === 'connected') navigate('/home');
}, [status]);
return (
<div style={{ padding: 24, display: 'flex', flexDirection: 'column', height: '100%' }}>
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
@@ -41,12 +51,12 @@ export function WelcomeScreen() {
</div>
</div>
<Button variant="primary" onClick={() => navigate('/login')} style={{ marginBottom: 12 }}>
<Button variant="primary" onClick={() => navigate('/home')} style={{ marginBottom: 12 }}>
Rejoindre la communauté
</Button>
<Text style={{ textAlign: 'center', fontSize: 13, color: '#888' }}>
Déjà membre ? <span onClick={() => navigate('/login')} style={{ color: '#E8590C', cursor: 'pointer', fontWeight: 600 }}>Connexion</span>
Déjà membre ? <span onClick={() => navigate('/home')} style={{ color: '#E8590C', cursor: 'pointer', fontWeight: 600 }}>Connexion</span>
</Text>
</div>
+38
View File
@@ -0,0 +1,38 @@
/**
* Shared wallet material for the staging stopgap.
*
* STOPGAP: the hosted broker can't auto-import a wallet, so Festipod HANDS the
* user the shared wallet and guides a one-time import on nextgraph.eu.
*
* The correct primitive is the **wallet FILE** (.ngw), NOT a TextCode: a
* TextCode is a transient device-to-device transfer (5 min, source device
* online, single use) useless to embed. A wallet file is STATIC and reusable.
* So Festipod serves the file (download) + shows the shared password; the user
* imports it via nextgraph.eu "Import a Wallet File".
*
* ZERO-SECURITY shared credential (friendly users) embedding the file +
* password is consistent with the posture.
*
* `build.ts` copies the file (from FESTIPOD_SHARED_WALLET_FILE) to the bundle as
* `/shared-wallet.ngw`, and `define`s the password global from
* FESTIPOD_SHARED_WALLET_PASSWORD. Empty password no shared wallet configured
* the gate falls back to the plain flow.
*/
// Build-injected global (not `process.env`, absent in the browser); any path
// that doesn't inject it reads `undefined` → '' safely (no ReferenceError).
declare global {
// eslint-disable-next-line no-var
var __FESTIPOD_SHARED_WALLET_PASSWORD__: string | undefined;
}
export const SHARED_WALLET_PASSWORD: string = globalThis.__FESTIPOD_SHARED_WALLET_PASSWORD__ ?? '';
/** URL of the shared wallet file in the bundle (copied by build.ts). */
export const SHARED_WALLET_FILE_URL = '/shared-wallet.ngw';
/** Standalone NextGraph wallet app — where the import actually happens. */
export const WALLET_IMPORT_URL = 'https://nextgraph.eu/#/wallet/login';
/** Whether Festipod has a shared wallet to hand over (drives the assisted UI). */
export const hasSharedWallet = (): boolean => SHARED_WALLET_PASSWORD.trim().length > 0;

Some files were not shown because too many files have changed in this diff Show More